Commit 9c202aa8 by zxw

init

parents
## Ignore Visual Studio temporary files, build results, and
## files generated by popular Visual Studio add-ons.
# User-specific files
*.suo
*.user
*.sln.docstates
# Build results
[Dd]ebug/
[Dd]ebugPublic/
[Rr]elease/
[Rr]eleases/
x64/
build/
bld/
[Bb]in/
[Oo]bj/
# Roslyn cache directories
*.ide/
# MSTest test Results
[Tt]est[Rr]esult*/
[Bb]uild[Ll]og.*
#NUNIT
*.VisualState.xml
TestResult.xml
# Build Results of an ATL Project
[Dd]ebugPS/
[Rr]eleasePS/
dlldata.c
*_i.c
*_p.c
*_i.h
*.ilk
*.meta
*.obj
*.pch
*.pdb
*.pgc
*.pgd
*.rsp
*.sbr
*.tlb
*.tli
*.tlh
*.tmp
*.tmp_proj
*.log
*.vspscc
*.vssscc
.builds
*.pidb
*.svclog
*.scc
# Chutzpah Test files
_Chutzpah*
# Visual C++ cache files
ipch/
*.aps
*.ncb
*.opensdf
*.sdf
*.cachefile
# Visual Studio profiler
*.psess
*.vsp
*.vspx
# TFS 2012 Local Workspace
$tf/
# Guidance Automation Toolkit
*.gpState
# ReSharper is a .NET coding add-in
_ReSharper*/
*.[Rr]e[Ss]harper
*.DotSettings.user
# JustCode is a .NET coding addin-in
.JustCode
# TeamCity is a build add-in
_TeamCity*
# DotCover is a Code Coverage Tool
*.dotCover
# NCrunch
_NCrunch_*
.*crunch*.local.xml
# MightyMoose
*.mm.*
AutoTest.Net/
# Web workbench (sass)
.sass-cache/
# Installshield output folder
[Ee]xpress/
# DocProject is a documentation generator add-in
DocProject/buildhelp/
DocProject/Help/*.HxT
DocProject/Help/*.HxC
DocProject/Help/*.hhc
DocProject/Help/*.hhk
DocProject/Help/*.hhp
DocProject/Help/Html2
DocProject/Help/html
# Click-Once directory
publish/
# Publish Web Output
*.[Pp]ublish.xml
*.azurePubxml
## TODO: Comment the next line if you want to checkin your
## web deploy settings but do note that will include unencrypted
## passwords
*.pubxml
# NuGet Packages
packages/*
*.nupkg
## TODO: If the tool you use requires repositories.config
## uncomment the next line
#!packages/repositories.config
# Enable "build/" folder in the NuGet Packages folder since
# NuGet packages use it for MSBuild targets.
# This line needs to be after the ignore of the build folder
# (and the packages folder if the line above has been uncommented)
!packages/build/
# Windows Azure Build Output
csx/
*.build.csdef
# Windows Store app package directory
AppPackages/
# Others
sql/
*.Cache
ClientBin/
[Ss]tyle[Cc]op.*
~$*
*~
*.dbmdl
*.dbproj.schemaview
*.pfx
*.publishsettings
node_modules/
# RIA/Silverlight projects
Generated_Code/
# Backup & report files from converting an old project file
# to a newer Visual Studio version. Backup files are not needed,
# because we have git ;-)
_UpgradeReport_Files/
Backup*/
UpgradeLog*.XML
UpgradeLog*.htm
# SQL Server files
*.mdf
*.ldf
# Business Intelligence projects
*.rdl.data
*.bim.layout
*.bim_*.settings
# Microsoft Fakes
FakesAssemblies/
/.vs
/JmpModel/CodeTemplates
/JunmpPoliceStation/appsettings.json
/JunmpPoliceStation/internal-nlog.txt
/JunmpPoliceStation/JunmpPoliceStation.xml
namespace JmpZbModel
{
public class BaseInfo
{
public string Id { get; set; }
public string ModelType { get; set; }
}
}
namespace JmpZbModel
{
public enum ConnectType
{
USB,
COM,
Net
}
}
namespace JmpZbModel
{
public class DeviceInfo
{
public ConnectType ConnectType { get; set; }
public PrintType PrintType { get; set; }
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace JmpUhfService
{
public class InitalizeCmdInfo
{
public InitializeCmdType CmdType { get; set; }
public string Content { get; set; }
}
}
using JmpUhfService;
namespace JmpZbModel
{
public class InitializeCmdInfo
{
public string Content { get; set; }
public InitializeCmdType CmdType { get; set; }
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace JmpUhfService
{
public enum InitializeCmdType
{
StartInventory,
StopInventory,
InventoryInfo,
ErrorMsg,
Initialize,
Linked,
Busy,
ReadInventorySingle,
InitializeV2,
ReadInventorySingleError
}
}
<?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>{7E4C3E44-3418-43D0-915B-57F76CF4CAB4}</ProjectGuid>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>JmpZbModel</RootNamespace>
<AssemblyName>JmpZbModel</AssemblyName>
<TargetFrameworkVersion>v4.5</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<Deterministic>true</Deterministic>
<TargetFrameworkProfile />
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>..\Programe\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<PlatformTarget>x86</PlatformTarget>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>..\Programe\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|x86'">
<DebugSymbols>true</DebugSymbols>
<OutputPath>bin\x86\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<DebugType>full</DebugType>
<PlatformTarget>x86</PlatformTarget>
<LangVersion>7.3</LangVersion>
<ErrorReport>prompt</ErrorReport>
<CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|x86'">
<OutputPath>bin\x86\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<Optimize>true</Optimize>
<DebugType>pdbonly</DebugType>
<PlatformTarget>x86</PlatformTarget>
<LangVersion>7.3</LangVersion>
<ErrorReport>prompt</ErrorReport>
<CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet>
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
<Reference Include="System.Net.Http" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="BaseInfo.cs" />
<Compile Include="InitializeCmdType.cs" />
<Compile Include="InitalizeCmdInfo.cs" />
<Compile Include="InitializeCmdInfo.cs" />
<Compile Include="PrintCmdInfo.cs" />
<Compile Include="PrintCmdType.cs" />
<Compile Include="ConnectType.cs" />
<Compile Include="DeviceInfo.cs" />
<Compile Include="PrintMessage.cs" />
<Compile Include="PrintType.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="SingleInfo.cs" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
</Project>
\ No newline at end of file
namespace JmpZbModel
{
public class PrintCmdInfo
{
public string Message { get; set; }
public PrintCmdType CmdType { get; set; }
public bool Success { get; set; }
}
}
namespace JmpZbModel
{
public enum PrintCmdType
{
devQuery,
printMsg,
startPrint,
printNotice,
printError,
printUsed
}
}
namespace JmpZbModel
{
public class PrintMessage
{
public MessageType MessageType { get; set; }
public string MessageContent { get; set; }
public string MessageCode { get; set; }
}
public enum MessageType
{
,
通知,
异常
}
}
namespace JmpZbModel
{
public enum PrintType
{
东芝,
斑马
}
}
using System.Reflection;
using System.Runtime.InteropServices;
// 有关程序集的一般信息由以下
// 控制。更改这些特性值可修改
// 与程序集关联的信息。
[assembly: AssemblyTitle("JmpZbModel")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Microsoft")]
[assembly: AssemblyProduct("JmpZbModel")]
[assembly: AssemblyCopyright("Copyright © Microsoft 2020")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// 将 ComVisible 设置为 false 会使此程序集中的类型
//对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型
//请将此类型的 ComVisible 特性设置为 true。
[assembly: ComVisible(false)]
// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID
[assembly: Guid("7e4c3e44-3418-43d0-915b-57f76cf4cab4")]
// 程序集的版本信息由下列四个值组成:
//
// 主版本
// 次版本
// 生成号
// 修订号
//
//可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值
//通过使用 "*",如下所示:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.21")]
[assembly: AssemblyFileVersion("1.0.0.21")]
namespace JmpZbModel
{
public class SingleInfo : BaseInfo
{
public string Info1 { get; set; }
public string Info2 { get; set; }
public string Info3 { get; set; }
public string Info4 { get; set; }
public string Info5 { get; set; }
public string Info6 { get; set; }
public string Info7 { get; set; }
public string Info8 { get; set; }
public string Info9 { get; set; }
}
}

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 16
VisualStudioVersion = 16.0.29911.84
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "JmpZbService", "JmpZbPrintService\JmpZbService.csproj", "{4EA469D8-1A2C-4B3C-965F-DBE85C4414BC}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "JmpZbPrint", "JmpZbPrint\JmpZbPrint.csproj", "{AF8CBDF8-6713-4E88-A2CD-A5ED53AAE26F}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "JmpZbModel", "JmpZbModel\JmpZbModel.csproj", "{7E4C3E44-3418-43D0-915B-57F76CF4CAB4}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "JmpUhfService", "RepairService\JmpUhfService.csproj", "{111435B9-7C04-4AE7-A9E0-FF7052D9F196}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
Debug|x64 = Debug|x64
Debug|x86 = Debug|x86
Release|Any CPU = Release|Any CPU
Release|x64 = Release|x64
Release|x86 = Release|x86
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{4EA469D8-1A2C-4B3C-965F-DBE85C4414BC}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{4EA469D8-1A2C-4B3C-965F-DBE85C4414BC}.Debug|Any CPU.Build.0 = Debug|Any CPU
{4EA469D8-1A2C-4B3C-965F-DBE85C4414BC}.Debug|x64.ActiveCfg = Debug|x64
{4EA469D8-1A2C-4B3C-965F-DBE85C4414BC}.Debug|x64.Build.0 = Debug|x64
{4EA469D8-1A2C-4B3C-965F-DBE85C4414BC}.Debug|x86.ActiveCfg = Debug|Any CPU
{4EA469D8-1A2C-4B3C-965F-DBE85C4414BC}.Debug|x86.Build.0 = Debug|Any CPU
{4EA469D8-1A2C-4B3C-965F-DBE85C4414BC}.Release|Any CPU.ActiveCfg = Release|Any CPU
{4EA469D8-1A2C-4B3C-965F-DBE85C4414BC}.Release|Any CPU.Build.0 = Release|Any CPU
{4EA469D8-1A2C-4B3C-965F-DBE85C4414BC}.Release|x64.ActiveCfg = Release|x64
{4EA469D8-1A2C-4B3C-965F-DBE85C4414BC}.Release|x64.Build.0 = Release|x64
{4EA469D8-1A2C-4B3C-965F-DBE85C4414BC}.Release|x86.ActiveCfg = Release|x86
{4EA469D8-1A2C-4B3C-965F-DBE85C4414BC}.Release|x86.Build.0 = Release|x86
{AF8CBDF8-6713-4E88-A2CD-A5ED53AAE26F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{AF8CBDF8-6713-4E88-A2CD-A5ED53AAE26F}.Debug|Any CPU.Build.0 = Debug|Any CPU
{AF8CBDF8-6713-4E88-A2CD-A5ED53AAE26F}.Debug|x64.ActiveCfg = Debug|Any CPU
{AF8CBDF8-6713-4E88-A2CD-A5ED53AAE26F}.Debug|x64.Build.0 = Debug|Any CPU
{AF8CBDF8-6713-4E88-A2CD-A5ED53AAE26F}.Debug|x86.ActiveCfg = Debug|Any CPU
{AF8CBDF8-6713-4E88-A2CD-A5ED53AAE26F}.Debug|x86.Build.0 = Debug|Any CPU
{AF8CBDF8-6713-4E88-A2CD-A5ED53AAE26F}.Release|Any CPU.ActiveCfg = Release|Any CPU
{AF8CBDF8-6713-4E88-A2CD-A5ED53AAE26F}.Release|Any CPU.Build.0 = Release|Any CPU
{AF8CBDF8-6713-4E88-A2CD-A5ED53AAE26F}.Release|x64.ActiveCfg = Release|Any CPU
{AF8CBDF8-6713-4E88-A2CD-A5ED53AAE26F}.Release|x64.Build.0 = Release|Any CPU
{AF8CBDF8-6713-4E88-A2CD-A5ED53AAE26F}.Release|x86.ActiveCfg = Release|Any CPU
{AF8CBDF8-6713-4E88-A2CD-A5ED53AAE26F}.Release|x86.Build.0 = Release|Any CPU
{7E4C3E44-3418-43D0-915B-57F76CF4CAB4}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{7E4C3E44-3418-43D0-915B-57F76CF4CAB4}.Debug|Any CPU.Build.0 = Debug|Any CPU
{7E4C3E44-3418-43D0-915B-57F76CF4CAB4}.Debug|x64.ActiveCfg = Debug|Any CPU
{7E4C3E44-3418-43D0-915B-57F76CF4CAB4}.Debug|x64.Build.0 = Debug|Any CPU
{7E4C3E44-3418-43D0-915B-57F76CF4CAB4}.Debug|x86.ActiveCfg = Debug|Any CPU
{7E4C3E44-3418-43D0-915B-57F76CF4CAB4}.Debug|x86.Build.0 = Debug|Any CPU
{7E4C3E44-3418-43D0-915B-57F76CF4CAB4}.Release|Any CPU.ActiveCfg = Release|Any CPU
{7E4C3E44-3418-43D0-915B-57F76CF4CAB4}.Release|Any CPU.Build.0 = Release|Any CPU
{7E4C3E44-3418-43D0-915B-57F76CF4CAB4}.Release|x64.ActiveCfg = Release|Any CPU
{7E4C3E44-3418-43D0-915B-57F76CF4CAB4}.Release|x64.Build.0 = Release|Any CPU
{7E4C3E44-3418-43D0-915B-57F76CF4CAB4}.Release|x86.ActiveCfg = Release|Any CPU
{7E4C3E44-3418-43D0-915B-57F76CF4CAB4}.Release|x86.Build.0 = Release|Any CPU
{111435B9-7C04-4AE7-A9E0-FF7052D9F196}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{111435B9-7C04-4AE7-A9E0-FF7052D9F196}.Debug|Any CPU.Build.0 = Debug|Any CPU
{111435B9-7C04-4AE7-A9E0-FF7052D9F196}.Debug|x64.ActiveCfg = Debug|Any CPU
{111435B9-7C04-4AE7-A9E0-FF7052D9F196}.Debug|x64.Build.0 = Debug|Any CPU
{111435B9-7C04-4AE7-A9E0-FF7052D9F196}.Debug|x86.ActiveCfg = Debug|Any CPU
{111435B9-7C04-4AE7-A9E0-FF7052D9F196}.Debug|x86.Build.0 = Debug|Any CPU
{111435B9-7C04-4AE7-A9E0-FF7052D9F196}.Release|Any CPU.ActiveCfg = Release|Any CPU
{111435B9-7C04-4AE7-A9E0-FF7052D9F196}.Release|Any CPU.Build.0 = Release|Any CPU
{111435B9-7C04-4AE7-A9E0-FF7052D9F196}.Release|x64.ActiveCfg = Release|Any CPU
{111435B9-7C04-4AE7-A9E0-FF7052D9F196}.Release|x64.Build.0 = Release|Any CPU
{111435B9-7C04-4AE7-A9E0-FF7052D9F196}.Release|x86.ActiveCfg = Release|Any CPU
{111435B9-7C04-4AE7-A9E0-FF7052D9F196}.Release|x86.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {053BA28A-1110-4232-B195-3B6EBBE2A3CC}
VisualSVNWorkingCopyRoot = .
EndGlobalSection
EndGlobal
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" />
</startup>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="System.Windows.Interactivity" publicKeyToken="31bf3856ad364e35" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-4.5.0.0" newVersion="4.5.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="CommonServiceLocator" publicKeyToken="489b6accfaf20ef0" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-2.0.5.0" newVersion="2.0.5.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
</configuration>
<Application x:Class="JmpZbPrint.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:materialDesign="http://materialdesigninxaml.net/winfx/xaml/themes"
xmlns:avalonEdit="http://icsharpcode.net/sharpdevelop/avalonedit"
xmlns:system="clr-namespace:System;assembly=mscorlib"
xmlns:local="clr-namespace:JmpZbPrint.View" StartupUri="pack://application:,,,/View/LoginWindow.xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
d1p1:Ignorable="d" xmlns:d1p1="http://schemas.openxmlformats.org/markup-compatibility/2006"
Startup="Application_Startup" DispatcherUnhandledException="Application_DispatcherUnhandledException">
<Application.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="pack://application:,,,/MaterialDesignThemes.Wpf;component/Themes/MaterialDesignTheme.Light.xaml"/>
<ResourceDictionary Source="pack://application:,,,/Panuon.UI.Silver;component/Control.xaml" />
<ResourceDictionary Source="pack://application:,,,/MaterialDesignThemes.Wpf;component/Themes/MaterialDesignTheme.Defaults.xaml"/>
</ResourceDictionary.MergedDictionaries>
<Style TargetType="TextBlock" x:Key="FiconBase">
<Setter Property="FontFamily" Value="pack://application:,,,/font/#iconfont" />
<Setter Property="Cursor" Value="Hand" />
</Style>
<Style x:Key="TextCenterStyle" TargetType="{x:Type TextBlock}">
<Setter Property="VerticalAlignment" Value="Center" />
<Setter Property="TextAlignment" Value="Center" />
</Style>
<Style x:Key="TextLeftStyle" TargetType="{x:Type TextBlock}">
<Setter Property="VerticalAlignment" Value="Center" />
<Setter Property="TextAlignment" Value="Left" />
</Style>
</ResourceDictionary>
</Application.Resources>
</Application>
\ No newline at end of file
using System;
using System.Diagnostics;
using System.Reflection;
using System.Windows;
using JmpZbPrint.Common;
using JmpZbPrint.View;
namespace JmpZbPrint
{
/// <summary>
/// App.xaml 的交互逻辑
/// </summary>
public partial class App : Application
{
private void Application_Startup(object sender, StartupEventArgs e)
{
// 获取当前活动进程的模块名称
string moduleName = Process.GetCurrentProcess().MainModule.ModuleName;
//返回指定路径字符串的文件名
string processName = System.IO.Path.GetFileNameWithoutExtension(moduleName);
//根据文件名创建进程资源数组
Process[] processes = Process.GetProcessesByName(processName);
//如果该数组长度大于1,说明多次运行
if (processes.Length > 1)
{
MessageBox.Show("已有另一个程序在运行!", "提示", MessageBoxButton.OK, MessageBoxImage.Information);//弹出提示信息
Process.GetCurrentProcess().Kill();
}
else
{
CaChe.SysConfig = CaChe.LoadSystemStep();
if (CaChe.SysConfig == null)
{
//MessageBox.Show("配置文件加载失败,请检查", "文件错误", MessageBoxButton.OK, MessageBoxImage.Error);
//Process.GetCurrentProcess().Kill();
MessageBox.Show("配置文件加载失败,创建默认配置文件");
CaChe.SysConfig = new Config();
CaChe.SaveSystemStep(CaChe.SysConfig);
}
else
{
var _update = HttpHelper.GetUpdate(CaChe.SysConfig?.AppCode ?? "");
if (_update == null)
{
return;
}
else
{
if (Version.TryParse(_update.version2, out var version) && version > new Version(CaChe.SysConfig.AppVersion))
{
if (MessageBox.Show("检测到新版本,是否更新?", "更新提示", MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.Yes)
{
System.Diagnostics.Process.Start("explorer.exe", CaChe.SysConfig.DomainUrl.TrimEnd('/') + "/" + _update.address.TrimStart('/'));
Process.GetCurrentProcess().Kill();
}
else { }
}
}
//获取供应商
//CaChe.Suppliers = HttpHelper.GetAllSupplier();
}
}
}
private void Application_DispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
{
Log.ErrorLog(e.Exception.ToString(), MethodBase.GetCurrentMethod().Name);
}
}
}
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Data;
namespace JmpZbPrint.Common
{
public class BoolConvert : IValueConverter
{
//当值从绑定源传播给绑定目标时,调用方法Convert
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value == null)
return DependencyProperty.UnsetValue;
bool.TryParse(value.ToString(), out bool result);
return result ? "√" : "";
}
//当值从绑定目标传播给绑定源时,调用此方法ConvertBack
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value == null)
{
return DependencyProperty.UnsetValue;
}
return value.ToString() == "√";
}
}
}
using JmpZbPrint.Common;
using JmpZbPrint.Model;
using Newtonsoft.Json;
using System;
using System.IO;
using System.Reflection;
using System.Text;
namespace JmpZbPrint
{
public static class CaChe
{
//public static List<WarehouseInfo> WarehouseInfo { get; set; }
public static respone_user UserInfo { get; set; }
//public static List<Supplier> Suppliers { get; set; }
//public static List<EquInfo> EquInfos { get; set; }
public static Config SysConfig { get; set; }
//public static UserInfo UserInfo { get; set; }
//public static List<EquipmentInfo> WzList { get; set; }
public static Config LoadSystemStep()
{
var v_path = AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "config.json";
if (!File.Exists(v_path))
{
return null;
}
else
{
var v_json = File.ReadAllText(v_path, Encoding.UTF8);
var des_str = JmpDes.Decrypt(v_json);
if (string.IsNullOrEmpty(des_str))
{
return null;
}
else
{
var config = JsonConvert.DeserializeObject<Config>(des_str);
//预处理
if (config.DomainUrl == "http://41.204.7.134:18761/api/service")
{
config.DomainUrl = "http://41.190.20.132:18761/api/service";
}
if (config.UserLogin == "http://41.204.7.134:10004/auth/userLogin")
{
config.UserLogin = "http://41.190.20.132:10004/auth/userLogin";
}
return config;
}
}
}
public static bool SaveSystemStep(Config config)
{
try
{
if (config == null) { return false; }
else
{
var json = JsonConvert.SerializeObject(config, Formatting.Indented);
if (string.IsNullOrEmpty(json))
{
return false;
}
else
{
System.IO.File.WriteAllText(AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "config.json", JmpDes.Encrypt(json), Encoding.UTF8);
return true;
}
}
}
catch (Exception ex)
{
Log.ErrorLog(ex.ToString(), MethodBase.GetCurrentMethod().Name);
return false;
}
}
}
}
using GalaSoft.MvvmLight;
using Newtonsoft.Json;
using System.Windows;
namespace JmpZbPrint.Common
{
public class Config : ViewModelBase
{
public Config()
{
AppTitle = "警用装备RFID初始化 v" + Application.ResourceAssembly.GetName().Version;
AppVersion = Application.ResourceAssembly.GetName().Version.ToString();
AppCode = "10002";
DomainUrl = "http://41.190.20.132:18761/api/service";
UserLogin = "http://41.190.20.132:10004/auth/userLogin";
CardOnly = false;
ApiVersion = "1.0";
AppKey = "jg/eM+bvVcTtil9yQJ1u5g==";
SecretKey = "0827414cbc1003ab865b975b6fae3c12";
IsDirectEntryStock = false;
IsAutoUpdate = true;
AutoUpdateTime = 0;
PrintType = 0;
}
/// <summary>
/// 接口域名
/// </summary>
public string DomainUrl { get; set; }
/// <summary>
/// 登录
/// </summary>
public string UserLogin { get; set; }
[JsonIgnore]
public string AppTitle { get; set; }
[JsonIgnore]
public string AppVersion { get; set; }
public string AppCode { get; set; }
public bool CardOnly { get; set; }
public string AppKey { get; set; }
public string SecretKey { get; set; }
public string ApiVersion { get; set; }
/// <summary>
/// 初始化的标签直接自动入库
/// </summary>
public bool IsDirectEntryStock { get; set; }
/// <summary>
/// 是否自动更新
/// </summary>
public bool IsAutoUpdate { get; set; }
/// <summary>
/// 自动更新时间(小时)
/// </summary>
public int AutoUpdateTime { get; set; }
/// <summary>
/// 打印机类型
/// 0 东芝
/// 1 博思得
/// </summary>
public int PrintType { get; set; }
}
public static class UrlConfig
{
public const string GetPrintList = "/api/Print/GetPrintList";
public const string SoftUpdate = "/api/SoftUpdate/GetLastUpdate";
public const string GetAllSupplier = "/api/Print/GetAllSupplier";
public const string GenExtTagEpc = "/api/Print/GenerateExtTagEpc";
public const string CheckEpcIsInstantiation = "/api/Print/CheckEpcIsInstantiation";
public const string GenInventory = "/api/Print/GenerateInventoryWithProgram";
public const string GenRangeInventory = "/api/Print/GenerateRangeInventory";
public const string BoxingInventory = "/api/Print/BoxingInventory";
public const string BoxingInventoryNormalVersion = "/api/Print/BoxingInventoryNormalVersion";
public const string UnpackRangeInventory = "/api/Print/UnpackRangeInventory";
public const string GetInventoryListByBoxMarkEpc = "/api/EquipmentBoxMark/GetInventoryListByBoxMarkEpc";
public const string GetBoxMarkList = "/api/EquipmentBoxMark/GetBoxMarkList";
public const string GetNeedPrintBoxMarkList = "/api/EquipmentBoxMark/GetNeedPrintBoxMarkList";
public const string ImportOldBoxMark = "/api/Print/ImportOldBoxMark";
public const string GenIntTagEpc = "/api/Print/GenerateIntTagEpc";
public const string UpdateEpc = "/api/Print/UpdateEpcState";
public const string OrderList = "/api/Print/GetPrintOrder";
public const string GetEquInfo = "/api/Print/GetEquInfoById";
public const string GetAllEqu = "/api/Print/GetAllEqu";
public const string DelEpc = "/api/Print/DeleteInventory";
public const string DelEpcList = "/api/Print/DeleteInventoryByEpcList";
public const string GetWarehouse = "/api/Warehouse/GetListWarehouse";
public const string GetListShelf = "/api/Shelf/GetListShelf";
public const string GetListEquipmentShelfPosition = "/api/Shelf/GetListEquipmentShelfPosition";
public const string GetPrintBagList = "/api/Print/GetPrintBagList";
public const string UpdateBagState = "/api/Print/UpdateBagState";
}
}
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Data;
namespace JmpZbPrint.Common
{
[ValueConversion(typeof(DateTime), typeof(string))]
public class DateConverter : IValueConverter
{
//源属性传给目标属性时,调用此方法ConvertBack
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value == null)
return DateTime.Now.Date;
return value;
}
//目标属性传给源属性时,调用此方法ConvertBack
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value == null)
{
return DateTime.Now.Date;
}
else
{
DateTime.TryParse(value.ToString(), out DateTime date);
return date == default ? DateTime.Now.Date : date.Date;
}
}
}
}
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Data;
namespace JmpZbPrint.Common
{
[ValueConversion(typeof(DateTime), typeof(string))]
public class DateTimeConverter : IValueConverter
{
//源属性传给目标属性时,调用此方法ConvertBack
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
DateTime obj;
if (value == null)
{
obj = DateTime.Now;
}
else
{
obj = (DateTime)value;
}
if (parameter == null || string.IsNullOrEmpty(parameter.ToString()))
{
return obj.ToLocalTime();
}
else
{
return obj.ToString(parameter.ToString());
}
}
//目标属性传给源属性时,调用此方法ConvertBack
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value == null||string.IsNullOrEmpty(value.ToString()))
{
return DateTime.Now;
}
else
{
DateTime.TryParse(value.ToString(), out DateTime date);
return date == default ? DateTime.Now: date;
}
}
}
}
using JmpZbModel.Model;
using LiteDB;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
namespace JmpZbPrint.Common
{
public class DbFactory
{
public static bool Insert(tb_general_task entity)
{
// Open database (or create if doesn't exist)
using (var db = new LiteDatabase(@"config.db"))
{
// Get a collection (or create, if doesn't exist)
var col = db.GetCollection<tb_general_task>("tb_general_task");
// Insert new customer document (Id will be auto-incremented)
var result = col.Insert(entity);
if (result.AsInt32 > 0) { return true; }
else { return false; }
}
}
public static bool Update(tb_general_task entity)
{
// Open database (or create if doesn't exist)
using (var db = new LiteDatabase(@"config.db"))
{
// Get a collection (or create, if doesn't exist)
var col = db.GetCollection<tb_general_task>("tb_general_task");
// Insert new customer document (Id will be auto-incremented)
var result = col.Update(entity);
if (result) { return true; }
else { return false; }
}
}
public static bool Delete(int id)
{
// Open database (or create if doesn't exist)
using (var db = new LiteDatabase(@"config.db"))
{
// Get a collection (or create, if doesn't exist)
var col = db.GetCollection<tb_general_task>("tb_general_task");
// Insert new customer document (Id will be auto-incremented)
var result = col.Delete(id);
if (result) { return true; }
else { return false; }
}
}
public static List<tb_general_task> GetAllTask(Expression<Func<tb_general_task,bool>> expression)
{
// Open database (or create if doesn't exist)
using (var db = new LiteDatabase(@"config.db"))
{
// Get a collection (or create, if doesn't exist)
var col = db.GetCollection<tb_general_task>("tb_general_task");
// Insert new customer document (Id will be auto-incremented)
return col.Query().Where(expression).ToList();
}
}
public static tb_general_task GetAllTask(int id)
{
// Open database (or create if doesn't exist)
using (var db = new LiteDatabase(@"config.db"))
{
// Get a collection (or create, if doesn't exist)
var col = db.GetCollection<tb_general_task>("tb_general_task");
// Insert new customer document (Id will be auto-incremented)
return col.FindById(id);
}
}
}
}
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Data;
namespace JmpZbPrint.Common
{
[ValueConversion(typeof(decimal), typeof(string))]
public class FloatConverter : IValueConverter
{
//源属性传给目标属性时,调用此方法ConvertBack
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (decimal.TryParse((value ?? "").ToString(), out decimal val))
{
return val;
}
else
{
return 0.0;
}
}
//目标属性传给源属性时,调用此方法ConvertBack
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
string strValue = value as string;
if (string.IsNullOrEmpty(strValue))
{
return 0;
}
else
{
if (strValue.IndexOf(".") == (strValue.Length - 1) && strValue.ToArray().Where(t => t == '.').Count() <= 1)
{
return Binding.DoNothing;
}
else
{
System.Text.RegularExpressions.Regex g = new System.Text.RegularExpressions.Regex(@"^[0-9].\d*$");
if (g.IsMatch(strValue))
{
decimal.TryParse(strValue, out decimal res);
return res;
}
else
{
var tmp = System.Text.RegularExpressions.Regex.Replace(strValue, @"[^\d.]*", "");
decimal.TryParse(tmp, out decimal res);
return res;
}
}
}
}
}
}
using JmpZbPrint.Model;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Reflection;
using System.Security.Cryptography;
using System.Text;
using JmpZbPrint.Common;
namespace JmpZbPrint
{
/// <summary>
/// 接口调用类
/// </summary>
public class HttpHelper
{
public static string GetHttpRqst(string strUrl, string json = "")
{
try
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(strUrl);
request.Method = "POST";
request.ContentType = "application/json";
if (!string.IsNullOrEmpty(json))
{
byte[] data = Encoding.UTF8.GetBytes(json);
request.ContentLength = data.Length;
using (Stream reqStream = request.GetRequestStream())
{
reqStream.Write(data, 0, data.Length);
reqStream.Close();
}
}
else
{
request.ContentLength = 0;
}
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream responseStream = response.GetResponseStream();
StreamReader streamReader = new StreamReader(responseStream, Encoding.UTF8);
string retString = streamReader.ReadToEnd();
streamReader.Close();
responseStream.Close();
response.Close();
return retString;
}
catch (Exception ex)
{
Log.ErrorLog(ex.ToString() + "\r\n" + strUrl, MethodBase.GetCurrentMethod().Name);
return string.Empty;
}
}
public static string PostUrlencoded(string strUrl, List<KeyValuePair<string, string>> pushData)
{
try
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(strUrl);
request.Method = "POST";
request.ContentType = "application/x-www-form-urlencoded; charset=UTF-8";
if (pushData.Count > 0)
{
using (Stream reqStream = request.GetRequestStream())
{
new FormUrlEncodedContent(pushData).CopyToAsync(reqStream).Wait();
reqStream.Close();
}
}
else
{
request.ContentLength = 0;
}
HttpWebResponse response = (HttpWebResponse)request.GetResponse();
Stream responseStream = response.GetResponseStream();
StreamReader streamReader = new StreamReader(responseStream, Encoding.UTF8);
string retString = streamReader.ReadToEnd();
streamReader.Close();
responseStream.Close();
response.Close();
return retString;
}
catch (Exception ex)
{
Log.ErrorLog(ex.ToString() + "\r\n" + strUrl, MethodBase.GetCurrentMethod().Name);
return string.Empty;
}
}
/// <summary>
/// 用户登录
/// </summary>
/// <param name="userName"></param>
/// <param name="userPwd"></param>
/// <param name="msg"></param>
/// <returns></returns>
public static respone_user UserLogin(string userName, string userPwd, out string msg)
{
try
{
var param = JsonConvert.SerializeObject(new { username = userName, password = userPwd });
Log.ErrorLog("UserLogin:" + CaChe.SysConfig.UserLogin + " param:" + param);
var json = GetHttpRqst(CaChe.SysConfig.UserLogin, param);
if (string.IsNullOrEmpty(json))
{
msg = "登录失败";
return default;
}
else
{
var res_data = JObject.Parse(json);
var jobj = JObject.Parse(json);
if (!jobj.HasValues)
{
msg = "登录异常";
return default;
}
else
{
msg = "登录成功";
var user = JsonConvert.DeserializeObject<respone_user>(json);
return user;
}
}
}
catch (Exception ex)
{
Log.ErrorLog(ex.ToString() + "\r\n", MethodBase.GetCurrentMethod().Name);
msg = "请求异常";
return default;
}
}
/// <summary>
/// 获取更新信息
/// </summary>
/// <param name="appCode"></param>
/// <returns></returns>
public static respone_update GetUpdate(string appCode)
{
var parame = JsonConvert.SerializeObject(new
{
appCode = appCode
});
var json = GetHttpRqst(CaChe.SysConfig.DomainUrl + UrlConfig.SoftUpdate, parame);
if (string.IsNullOrEmpty(json))
{
Log.DebugLog("获取更新信息失败", "更新失败");
return default;
}
else
{
var res_data = JsonConvert.DeserializeObject<respone_head<respone_update>>(json);
if (res_data == null || res_data.code != 10000)
{
Log.DebugLog("获取更新信息失败", "更新失败");
return default;
}
else
{
Log.DebugLog("获取更新信息成功", "更新成功");
return res_data.data;
}
}
}
/// <summary>
/// 供应商获取
/// </summary>
/// <returns></returns>
public static List<Supplier> GetAllSupplier()
{
try
{
var body_par = string.Empty;
var body_result = GetBody(body_par);
if (body_result == null)
{
Log.WorkLog("签名值生成失败。");
return null;
}
else
{
var param = JsonConvert.SerializeObject(new request_sign
{
appKey = CaChe.SysConfig.AppKey,
body = body_result.Item1,
sign = body_result.Item2,
timestamp = body_result.Item3,
version = CaChe.SysConfig.ApiVersion,
orgId = CaChe.UserInfo?.baseJpOrganization?.id ?? "",
});
var json = GetHttpRqst(CaChe.SysConfig.DomainUrl + UrlConfig.GetAllSupplier, param);
if (string.IsNullOrEmpty(json))
{
Log.DebugLog("供应商列表获取失败", "请求失败");
return default;
}
else
{
var res_data = JsonConvert.DeserializeObject<respone_head<respone_supplier>>(json);
if (res_data == null || res_data.code != 10000)
{
Log.DebugLog("供应商列表获取失败", "请求失败");
return default;
}
else
{
Log.WorkLog(json, "[JSON]");
return res_data.data.record;
}
}
}
}
catch (Exception ex)
{
Log.ErrorLog(ex.ToString() + "\r\n", MethodBase.GetCurrentMethod().Name);
return default;
}
}
/// <summary>
/// 装备列表获取
/// </summary>
/// <returns></returns>
public static List<EquInfo> GetAllEqu()
{
try
{
var body_par = string.Empty;
var body_result = GetBody(body_par);
if (body_result == null)
{
Log.WorkLog("签名值生成失败。");
return null;
}
else
{
var param = JsonConvert.SerializeObject(new request_sign
{
appKey = CaChe.SysConfig.AppKey,
body = body_result.Item1,
sign = body_result.Item2,
timestamp = body_result.Item3,
version = CaChe.SysConfig.ApiVersion,
orgId = CaChe.UserInfo?.baseJpOrganization?.id ?? "",
});
var json = GetHttpRqst(CaChe.SysConfig.DomainUrl + UrlConfig.GetAllEqu, param);
if (string.IsNullOrEmpty(json))
{
Log.DebugLog("装备列表获取失败", "请求失败");
return default;
}
else
{
var res_data = JsonConvert.DeserializeObject<respone_head<List<EquInfo>>>(json);
if (res_data == null || res_data.code != 10000)
{
Log.DebugLog("装备列表获取失败", "请求失败");
return default;
}
else
{
Log.WorkLog(json, "[JSON]");
return res_data.data;
}
}
}
}
catch (Exception ex)
{
Log.ErrorLog(ex.ToString() + "\r\n", MethodBase.GetCurrentMethod().Name);
return default;
}
}
/// <summary>
/// 装备属性获取
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
public static EquAttr GetEquInfoById(string id)
{
try
{
var body_par = JsonConvert.SerializeObject(new
{
id = id
});
var body_result = GetBody(body_par);
if (body_result == null)
{
Log.WorkLog("签名值生成失败。");
return null;
}
else
{
var param = JsonConvert.SerializeObject(new request_sign
{
appKey = CaChe.SysConfig.AppKey,
body = body_result.Item1,
sign = body_result.Item2,
timestamp = body_result.Item3,
version = CaChe.SysConfig.ApiVersion,
orgId = CaChe.UserInfo?.baseJpOrganization?.id ?? "",
});
var json = GetHttpRqst(CaChe.SysConfig.DomainUrl + UrlConfig.GetEquInfo, param);
if (string.IsNullOrEmpty(json))
{
Log.DebugLog("装备属性获取失败", "请求失败");
return default;
}
else
{
var res_data = JsonConvert.DeserializeObject<respone_head<EquAttr>>(json);
if (res_data == null || res_data.code != 10000)
{
Log.DebugLog("装备属性获取失败", "请求失败");
return default;
}
else
{
Log.WorkLog(json, "[JSON]");
return res_data.data;
}
}
}
}
catch (Exception ex)
{
Log.ErrorLog(ex.ToString() + "\r\n", MethodBase.GetCurrentMethod().Name);
return default;
}
}
/// <summary>
/// 仓库列表获取
/// </summary>
/// <returns></returns>
public static List<WarehouseInfo> GetWarehouse()
{
try
{
var body_par = JsonConvert.SerializeObject(new
{
orgizationId = CaChe.UserInfo.baseJpOrganization.id
});
var body_result = GetBody(body_par);
if (body_result == null)
{
Log.WorkLog("签名值生成失败。");
return null;
}
else
{
var param = JsonConvert.SerializeObject(new request_sign
{
appKey = CaChe.SysConfig.AppKey,
body = body_result.Item1,
sign = body_result.Item2,
timestamp = body_result.Item3,
version = CaChe.SysConfig.ApiVersion,
orgId = CaChe.UserInfo?.baseJpOrganization?.id ?? "",
});
var json = GetHttpRqst(CaChe.SysConfig.DomainUrl + UrlConfig.GetWarehouse, param);
if (string.IsNullOrEmpty(json))
{
Log.DebugLog("仓库获取失败", "请求失败");
return default;
}
else
{
var res_data = JsonConvert.DeserializeObject<respone_head<List<WarehouseInfo>>>(json);
if (res_data == null || res_data.code != 10000)
{
Log.DebugLog("仓库获取失败", "请求失败");
return default;
}
else
{
Log.WorkLog(json, "[JSON]");
return res_data.data;
}
}
}
}
catch (Exception ex)
{
Log.ErrorLog(ex.ToString() + "\r\n", MethodBase.GetCurrentMethod().Name);
return default;
}
}
/// <summary>
/// 根据仓库id获取货架
/// </summary>
/// <param name="warehouseId"></param>
/// <returns></returns>
public static List<ShelfInfo> GetShelfByWarehouseId(string warehouseId)
{
try
{
var body_par = JsonConvert.SerializeObject(new
{
warehouseId = warehouseId
});
var body_result = GetBody(body_par);
if (body_result == null)
{
Log.WorkLog("签名值生成失败。");
return null;
}
else
{
var param = JsonConvert.SerializeObject(new request_sign
{
appKey = CaChe.SysConfig.AppKey,
body = body_result.Item1,
sign = body_result.Item2,
timestamp = body_result.Item3,
version = CaChe.SysConfig.ApiVersion,
orgId = CaChe.UserInfo?.baseJpOrganization?.id ?? "",
});
var json = GetHttpRqst(CaChe.SysConfig.DomainUrl + UrlConfig.GetListShelf, param);
if (string.IsNullOrEmpty(json))
{
Log.DebugLog("货架获取失败", "请求失败");
return default;
}
else
{
var res_data = JsonConvert.DeserializeObject<respone_head<List<ShelfInfo>>>(json);
if (res_data == null || res_data.code != 10000)
{
Log.DebugLog("货架获取失败", "请求失败");
return default;
}
else
{
Log.WorkLog(json, "[JSON]");
return res_data.data;
}
}
}
}
catch (Exception ex)
{
Log.ErrorLog(ex.ToString() + "\r\n", MethodBase.GetCurrentMethod().Name);
return default;
}
}
/// <summary>
/// 获取指定物资类型存放位置
/// </summary>
/// <param name="warehouseId"></param>
/// <param name="equipmentDetailId"></param>
/// <param name="sizeId"></param>
/// <returns></returns>
public static List<ShelfInfo> GetListEquipmentShelfPosition(string warehouseId, string equipmentDetailId, string sizeId)
{
try
{
var body_par = JsonConvert.SerializeObject(new
{
warehouseId = warehouseId,
equipmentDetailId = equipmentDetailId,
sizeId = sizeId,
});
var body_result = GetBody(body_par);
if (body_result == null)
{
Log.WorkLog("签名值生成失败。");
return null;
}
else
{
var param = JsonConvert.SerializeObject(new request_sign
{
appKey = CaChe.SysConfig.AppKey,
body = body_result.Item1,
sign = body_result.Item2,
timestamp = body_result.Item3,
version = CaChe.SysConfig.ApiVersion,
orgId = CaChe.UserInfo?.baseJpOrganization?.id ?? "",
});
var json = GetHttpRqst(CaChe.SysConfig.DomainUrl + UrlConfig.GetListEquipmentShelfPosition, param);
if (string.IsNullOrEmpty(json))
{
Log.DebugLog("装备存放货架位置获取失败", "请求失败");
return default;
}
else
{
var res_data = JsonConvert.DeserializeObject<respone_head<List<ShelfInfo>>>(json);
if (res_data == null || res_data.code != 10000)
{
Log.DebugLog("装备存放货架位置获取失败", "请求失败");
return default;
}
else
{
Log.WorkLog(json, "[JSON]");
return res_data.data;
}
}
}
}
catch (Exception ex)
{
Log.ErrorLog(ex.ToString() + "\r\n", MethodBase.GetCurrentMethod().Name);
return default;
}
}
/// <summary>
/// 获取打印任务
/// </summary>
/// <param name="epcType">epc类型 0:全部 1:件标 2:箱标</param>
/// <param name="labelType"></param>
/// <param name="pageIndex"></param>
/// <param name="vendorName"></param>
/// <param name="productName"></param>
/// <returns></returns>
public static respone_print GetPrintList(int epcType, LabelType labelType, int pageIndex = 1, string vendorName = "", string productName = "")
{
try
{
var body_par = JsonConvert.SerializeObject(new
{
epcType = epcType,
orgId = CaChe.UserInfo.baseJpOrganization.id,
printState = 0,
labelType = (int)labelType,
vendorName,
productName,
page = pageIndex - 1,
});
var body_result = GetBody(body_par);
if (body_result == null)
{
Log.WorkLog("签名值生成失败。");
return null;
}
else
{
var param = JsonConvert.SerializeObject(new request_sign
{
appKey = CaChe.SysConfig.AppKey,
body = body_result.Item1,
sign = body_result.Item2,
timestamp = body_result.Item3,
version = CaChe.SysConfig.ApiVersion,
orgId = CaChe.UserInfo?.baseJpOrganization?.id ?? "",
});
var json = GetHttpRqst(CaChe.SysConfig.DomainUrl + UrlConfig.GetPrintList, param);
if (string.IsNullOrEmpty(json))
{
Log.DebugLog("打印任务获取失败", "请求失败");
return default;
}
else
{
var res_data = JsonConvert.DeserializeObject<respone_head<respone_print>>(json);
if (res_data == null || res_data.code != 10000)
{
Log.DebugLog("打印任务获取失败", "请求失败");
return default;
}
else
{
Log.WorkLog(json, "[JSON]");
return res_data.data;
}
}
}
}
catch (Exception ex)
{
Log.ErrorLog(ex.ToString() + "\r\n", MethodBase.GetCurrentMethod().Name);
return default;
}
}
/// <summary>
/// 订单列表获取
/// </summary>
/// <param name="_orderCode"></param>
/// <param name="_equName"></param>
/// <returns></returns>
public static respone_order GetOrderList(string _orderCode, string _equName)
{
try
{
var body_par = JsonConvert.SerializeObject(new
{
orgId = CaChe.UserInfo.baseJpOrganization.id,
orderCode = _orderCode,
equName = _equName
});
var body_result = GetBody(body_par);
if (body_result == null)
{
Log.WorkLog("签名值生成失败。");
return null;
}
else
{
var param = JsonConvert.SerializeObject(new request_sign
{
appKey = CaChe.SysConfig.AppKey,
body = body_result.Item1,
sign = body_result.Item2,
timestamp = body_result.Item3,
version = CaChe.SysConfig.ApiVersion,
orgId = CaChe.UserInfo?.baseJpOrganization?.id ?? "",
});
var json = GetHttpRqst(CaChe.SysConfig.DomainUrl + UrlConfig.OrderList, param);
if (string.IsNullOrEmpty(json))
{
Log.DebugLog("订单列表获取失败", "请求失败");
return default;
}
else
{
var res_data = JsonConvert.DeserializeObject<respone_head<respone_order>>(json);
if (res_data == null || res_data.code != 10000)
{
Log.DebugLog("订单列表获取失败", "请求失败");
return default;
}
else
{
Log.WorkLog(json, "[JSON]");
return res_data.data;
}
}
}
}
catch (Exception ex)
{
Log.ErrorLog(ex.ToString() + "\r\n", MethodBase.GetCurrentMethod().Name);
return default;
}
}
/// <summary>
/// EPC判断是否已经被打印/绑定过
/// </summary>
/// <param name="epc"></param>
/// <param name="msg"></param>
/// <returns></returns>
public static bool CheckEpcIsInstantiation(string epc, out string msg)
{
try
{
msg = string.Empty;
var body_par = JsonConvert.SerializeObject(new
{
epc = epc
});
var body_result = GetBody(body_par);
if (body_result == null)
{
Log.WorkLog("签名值生成失败。");
return false;
}
else
{
var param = JsonConvert.SerializeObject(new request_sign
{
appKey = CaChe.SysConfig.AppKey,
body = body_result.Item1,
sign = body_result.Item2,
timestamp = body_result.Item3,
version = CaChe.SysConfig.ApiVersion,
orgId = CaChe.UserInfo?.baseJpOrganization?.id ?? "",
});
var json = GetHttpRqst(CaChe.SysConfig.DomainUrl + UrlConfig.CheckEpcIsInstantiation, param);
if (string.IsNullOrEmpty(json))
{
Log.DebugLog("网络异常", "请求失败");
msg = "网络异常";
return default;
}
else
{
var res_data = JsonConvert.DeserializeObject<respone_head<object>>(json);
if (res_data == null || res_data.code != 10000)
{
msg = res_data.msg;
Log.DebugLog($"绑定失败,{msg}", "请求失败");
return default;
}
else
{
Log.WorkLog(json, "[JSON]");
return true;
}
}
}
}
catch (Exception ex)
{
Log.ErrorLog(ex.ToString() + "\r\n", MethodBase.GetCurrentMethod().Name);
msg = ex.InnerException?.Message ?? ex.Message ?? "";
return false;
}
}
/// <summary>
/// 根据采购单信息生成EPC
/// </summary>
/// <param name="infos"></param>
/// <param name="msg"></param>
/// <returns></returns>
public static bool GenerateExtTagEpc(request_ext_info infos, out string msg)
{
try
{
msg = string.Empty;
var body_par = JsonConvert.SerializeObject(infos);
var body_result = GetBody(body_par);
if (body_result == null)
{
Log.WorkLog("签名值生成失败。");
return false;
}
else
{
var param = JsonConvert.SerializeObject(new request_sign
{
appKey = CaChe.SysConfig.AppKey,
body = body_result.Item1,
sign = body_result.Item2,
timestamp = body_result.Item3,
version = CaChe.SysConfig.ApiVersion,
orgId = CaChe.UserInfo?.baseJpOrganization?.id ?? "",
});
var json = GetHttpRqst(CaChe.SysConfig.DomainUrl + UrlConfig.GenExtTagEpc, param);
if (string.IsNullOrEmpty(json))
{
Log.DebugLog("网络异常", "请求失败");
msg = "网络异常";
return default;
}
else
{
var res_data = JsonConvert.DeserializeObject<respone_head<object>>(json);
if (res_data == null || res_data.code != 10000)
{
msg = res_data.msg;
Log.DebugLog($"EPC生成失败,{msg}", "请求失败");
return default;
}
else
{
Log.WorkLog(json, "[JSON]");
return true;
}
}
}
}
catch (Exception ex)
{
Log.ErrorLog(ex.ToString() + "\r\n", MethodBase.GetCurrentMethod().Name);
msg = ex.InnerException?.Message ?? ex.Message ?? "";
return false;
}
}
/// <summary>
/// EPC状态更新
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
public static Tuple<bool, string> UpdateEpc(string id)
{
try
{
var body_par = JsonConvert.SerializeObject(new
{
id = id,
isDirectEntryStock = CaChe.SysConfig.IsDirectEntryStock
});
var body_result = GetBody(body_par);
if (body_result == null)
{
Log.WorkLog("签名值生成失败。");
return new Tuple<bool, string>(false, "签名值生成失败");
}
else
{
var param = JsonConvert.SerializeObject(new request_sign
{
appKey = CaChe.SysConfig.AppKey,
body = body_result.Item1,
sign = body_result.Item2,
timestamp = body_result.Item3,
version = CaChe.SysConfig.ApiVersion,
orgId = CaChe.UserInfo?.baseJpOrganization?.id ?? "",
});
var json = GetHttpRqst(CaChe.SysConfig.DomainUrl + UrlConfig.UpdateEpc, param);
if (string.IsNullOrEmpty(json))
{
Log.DebugLog("EPC状态更新失败", "请求失败");
return new Tuple<bool, string>(false, "请求失败,网络异常");
}
else
{
var res_data = JsonConvert.DeserializeObject<respone_head<string>>(json);
if (res_data == null || res_data.code != 10000)
{
Log.DebugLog(res_data?.msg, "请求失败");
return new Tuple<bool, string>(false, res_data?.msg);
}
else
{
Log.DebugLog("EPC状态更新成功", "请求成功");
return new Tuple<bool, string>(true, "EPC状态更新成功");
}
}
}
}
catch (Exception ex)
{
Log.ErrorLog(ex.ToString() + "\r\n", MethodBase.GetCurrentMethod().Name);
return new Tuple<bool, string>(false, "EPC状态更新异常");
}
}
/// <summary>
/// 直接创建装备
/// </summary>
/// <param name="recode"></param>
/// <param name="msg"></param>
/// <returns></returns>
public static bool GenerateInventory(recode_info recode, out string msg)
{
try
{
msg = string.Empty;
var body_par = JsonConvert.SerializeObject(new
{
sizeId = recode.sizeId,
equId = recode.equId,
epc = recode.epc,
supplierId = recode.supplierId,
warehouseId = recode.warehouseId,
productTime = recode.productTime,
useTime = recode.useTime,
warrantyCycle = recode.warrantyCycle,
price = recode.price,
repairCycle = recode.repairCycle,
isUnboxingLabel = recode.IsUnboxingLabel,
shelfId = recode.ShelfId,
shelfRange = recode.ShelfRange,
shelfRow = recode.ShelfRow,
shelfColumn = recode.ShelfColumn,
});
var body_result = GetBody(body_par);
if (body_result == null)
{
Log.WorkLog("签名值生成失败。");
return false;
}
else
{
var param = JsonConvert.SerializeObject(new request_sign
{
appKey = CaChe.SysConfig.AppKey,
body = body_result.Item1,
sign = body_result.Item2,
timestamp = body_result.Item3,
version = CaChe.SysConfig.ApiVersion,
orgId = CaChe.UserInfo?.baseJpOrganization?.id ?? "",
});
var json = GetHttpRqst(CaChe.SysConfig.DomainUrl + UrlConfig.GenInventory, param);
if (string.IsNullOrEmpty(json))
{
Log.DebugLog("写入库存失败:网络异常", "请求失败");
msg = "网络异常";
return default;
}
else
{
var res_data = JsonConvert.DeserializeObject<respone_head<respone_order>>(json);
if (res_data == null || res_data.code != 10000)
{
msg = res_data?.msg;
Log.DebugLog($"写入库存失败,{msg}", "请求失败");
return default;
}
else
{
Log.WorkLog(json, "[JSON]");
return true;
}
}
}
}
catch (Exception ex)
{
Log.ErrorLog(ex.ToString() + "\r\n", MethodBase.GetCurrentMethod().Name);
msg = ex.InnerException?.Message ?? ex.Message ?? "";
return false;
}
}
/// <summary>
/// 直接创建装备(批量)
/// </summary>
/// <param name="recode"></param>
/// <param name="msg"></param>
/// <returns></returns>
public static bool GenerateRangeInventory(recode_info recode, out string msg)
{
try
{
msg = string.Empty;
var body_par = JsonConvert.SerializeObject(new
{
epc = recode.epc,
sizeId = recode.sizeId,
equId = recode.equId,
epcListJson = recode.epcListJson,
supplierId = recode.supplierId,
warehouseId = recode.warehouseId,
productTime = recode.productTime,
useTime = recode.useTime,
warrantyCycle = recode.warrantyCycle,
price = recode.price,
repairCycle = recode.repairCycle,
isReloadBoxing = recode.IsReloadBoxing,
shelfId = recode.ShelfId,
shelfRange = recode.ShelfRange,
shelfRow = recode.ShelfRow,
shelfColumn = recode.ShelfColumn,
});
var body_result = GetBody(body_par);
if (body_result == null)
{
Log.WorkLog("签名值生成失败。");
return false;
}
else
{
var param = JsonConvert.SerializeObject(new request_sign
{
appKey = CaChe.SysConfig.AppKey,
body = body_result.Item1,
sign = body_result.Item2,
timestamp = body_result.Item3,
version = CaChe.SysConfig.ApiVersion,
orgId = CaChe.UserInfo?.baseJpOrganization?.id ?? "",
});
var json = GetHttpRqst(CaChe.SysConfig.DomainUrl + UrlConfig.GenRangeInventory, param);
if (string.IsNullOrEmpty(json))
{
Log.DebugLog("写入库存失败", "请求失败");
msg = "网络异常";
return default;
}
else
{
var res_data = JsonConvert.DeserializeObject<respone_head<respone_order>>(json);
if (res_data == null || res_data.code != 10000)
{
msg = res_data?.msg;
Log.DebugLog($"写入库存失败,{msg}", "请求失败");
return default;
}
else
{
msg = res_data.msg;
Log.WorkLog(json, "[JSON]");
return true;
}
}
}
}
catch (Exception ex)
{
Log.ErrorLog(ex.ToString() + "\r\n", MethodBase.GetCurrentMethod().Name);
msg = ex.InnerException?.Message ?? ex.Message ?? "";
return false;
}
}
/// <summary>
/// 物资装箱(后台版)
/// </summary>
/// <param name="boxMarkEpc"></param>
/// <param name="infos"></param>
/// <param name="msg"></param>
/// <returns></returns>
public static bool BoxingInventory(string boxMarkEpc, List<recode_info> infos, out string msg)
{
try
{
msg = string.Empty;
var body_par = JsonConvert.SerializeObject(new
{
boxMarkEpc = boxMarkEpc,
invList = infos.Select(x => new
{
sizeId = x.sizeId,
equId = x.equId,
epc = x.epc,
supplierId = x.supplierId,
warehouseId = x.warehouseId,
productTime = x.productTime,
warrantyCycle = x.warrantyCycle,
price = x.price,
useTime = x.useTime,
repairCycle = x.repairCycle,
isUnboxingLabel = x.IsUnboxingLabel,
shelfId = x.ShelfId,
shelfRange = x.ShelfRange,
shelfRow = x.ShelfRow,
shelfColumn = x.ShelfColumn,
})
});
var body_result = GetBody(body_par);
if (body_result == null)
{
Log.WorkLog("签名值生成失败。");
return false;
}
else
{
var param = JsonConvert.SerializeObject(new request_sign
{
appKey = CaChe.SysConfig.AppKey,
body = body_result.Item1,
sign = body_result.Item2,
timestamp = body_result.Item3,
version = CaChe.SysConfig.ApiVersion,
orgId = CaChe.UserInfo?.baseJpOrganization?.id ?? "",
});
var json = GetHttpRqst(CaChe.SysConfig.DomainUrl + UrlConfig.BoxingInventory, param);
if (string.IsNullOrEmpty(json))
{
msg = "网络异常";
Log.DebugLog("写入库存失败", "请求失败");
return default;
}
else
{
var res_data = JsonConvert.DeserializeObject<respone_head<respone_order>>(json);
if (res_data == null || res_data.code != 10000)
{
msg = res_data.msg;
Log.DebugLog($"写入库存失败,{msg}", "请求失败");
return default;
}
else
{
Log.WorkLog(json, "[JSON]");
return true;
}
}
}
}
catch (Exception ex)
{
Log.ErrorLog(ex.ToString() + "\r\n", MethodBase.GetCurrentMethod().Name);
msg = ex.InnerException?.Message ?? ex.Message ?? "";
return false;
}
}
/// <summary>
/// 物资装箱(一般版)
/// </summary>
/// <param name="boxMarkEpc"></param>
/// <param name="infos"></param>
/// <param name="msg"></param>
/// <returns></returns>
public static bool BoxingInventoryNormalVersion(string boxMarkEpc, List<print_info> infos, out string msg)
{
try
{
msg = string.Empty;
var body_par = JsonConvert.SerializeObject(new
{
boxMarkEpc = boxMarkEpc,
policeId = CaChe.UserInfo.policeman?.id ?? "",
invList = infos.Select(x => new
{
sizeId = x.sizeId,
equId = x.productId,
epc = x.epc,
supplierId = x.supplierId,
warehouseId = x.warehouseId,
productTime = x.productTime,
warrantyCycle = x.warrantyCycle,
price = x.price,
useTime = x.useTime,
repairCycle = x.repairCycle,
isUnboxingLabel = x.isUnboxingLabel
})
});
var body_result = GetBody(body_par);
if (body_result == null)
{
Log.WorkLog("签名值生成失败。");
return false;
}
else
{
var param = JsonConvert.SerializeObject(new request_sign
{
appKey = CaChe.SysConfig.AppKey,
body = body_result.Item1,
sign = body_result.Item2,
timestamp = body_result.Item3,
version = CaChe.SysConfig.ApiVersion,
orgId = CaChe.UserInfo?.baseJpOrganization?.id ?? "",
});
var json = GetHttpRqst(CaChe.SysConfig.DomainUrl + UrlConfig.BoxingInventoryNormalVersion, param);
if (string.IsNullOrEmpty(json))
{
msg = "网络异常";
Log.DebugLog("写入库存失败", "请求失败");
return default;
}
else
{
var res_data = JsonConvert.DeserializeObject<respone_head<respone_order>>(json);
if (res_data == null || res_data.code != 10000)
{
msg = res_data.msg;
Log.DebugLog($"写入库存失败,{msg}", "请求失败");
return default;
}
else
{
Log.WorkLog(json, "[JSON]");
return true;
}
}
}
}
catch (Exception ex)
{
Log.ErrorLog(ex.ToString() + "\r\n", MethodBase.GetCurrentMethod().Name);
msg = ex.InnerException?.Message ?? ex.Message ?? "";
return false;
}
}
/// <summary>
/// 物资拆箱
/// </summary>
/// <param name="boxMarkEpc"></param>
/// <param name="msg"></param>
/// <returns></returns>
public static bool UnpackRangeInventory(string boxMarkEpc, out string msg)
{
try
{
msg = string.Empty;
var body_par = JsonConvert.SerializeObject(new
{
epc = boxMarkEpc,
});
var body_result = GetBody(body_par);
if (body_result == null)
{
Log.WorkLog("签名值生成失败。");
return false;
}
else
{
var param = JsonConvert.SerializeObject(new request_sign
{
appKey = CaChe.SysConfig.AppKey,
body = body_result.Item1,
sign = body_result.Item2,
timestamp = body_result.Item3,
version = CaChe.SysConfig.ApiVersion,
orgId = CaChe.UserInfo?.baseJpOrganization?.id ?? "",
});
var json = GetHttpRqst(CaChe.SysConfig.DomainUrl + UrlConfig.UnpackRangeInventory, param);
if (string.IsNullOrEmpty(json))
{
Log.DebugLog("写入库存失败", "请求失败");
msg = "网络异常";
return default;
}
else
{
var res_data = JsonConvert.DeserializeObject<respone_head<respone_order>>(json);
if (res_data == null || res_data.code != 10000)
{
msg = res_data.msg;
Log.DebugLog($"写入库存失败,{msg}", "请求失败");
return default;
}
else
{
Log.WorkLog(json, "[JSON]");
return true;
}
}
}
}
catch (Exception ex)
{
Log.ErrorLog(ex.ToString() + "\r\n", MethodBase.GetCurrentMethod().Name);
msg = ex.InnerException?.Message ?? ex.Message ?? "";
return false;
}
}
/// <summary>
/// 直接报废EPC(删除)
/// </summary>
/// <param name="epc"></param>
/// <param name="msg"></param>
/// <returns></returns>
public static bool DeleteEpc(string epc, out string msg)
{
try
{
msg = string.Empty;
var body_par = JsonConvert.SerializeObject(new
{
epc = epc,
});
var body_result = GetBody(body_par);
if (body_result == null)
{
msg = "签名值生成失败";
Log.WorkLog("签名值生成失败。");
return false;
}
else
{
var param = JsonConvert.SerializeObject(new request_sign
{
appKey = CaChe.SysConfig.AppKey,
body = body_result.Item1,
sign = body_result.Item2,
timestamp = body_result.Item3,
version = CaChe.SysConfig.ApiVersion,
orgId = CaChe.UserInfo?.baseJpOrganization?.id ?? "",
});
var json = GetHttpRqst(CaChe.SysConfig.DomainUrl + UrlConfig.DelEpc, param);
if (string.IsNullOrEmpty(json))
{
msg = "网络异常";
Log.DebugLog("删除库存失败", "删除失败");
return default;
}
else
{
var res_data = JsonConvert.DeserializeObject<respone_head<respone_order>>(json);
if (res_data != null && res_data.msg.Contains("无效EPC"))
{
Log.WorkLog("EPC不在库中,删除本地库的EPC");
return true;
}
else if (res_data != null && res_data.code == 10000)
{
Log.WorkLog(json, "[JSON]");
return true;
}
else
{
msg = res_data.msg;
Log.DebugLog($"删除库存失败,{msg}", "请求失败");
return default;
}
}
}
}
catch (Exception ex)
{
Log.ErrorLog(ex.ToString() + "\r\n", MethodBase.GetCurrentMethod().Name);
msg = ex.InnerException?.Message ?? ex.Message ?? "";
return false;
}
}
/// <summary>
/// 直接报废箱标EPC(包括箱内物资)
/// </summary>
/// <param name="boxMarkEpc"></param>
/// <param name="msg"></param>
/// <returns></returns>
public static bool DeleteEpcList(string boxMarkEpc, out string msg)
{
try
{
msg = string.Empty;
var body_par = JsonConvert.SerializeObject(new
{
boxMarkEpc = boxMarkEpc,
});
var body_result = GetBody(body_par);
if (body_result == null)
{
msg = "签名值生成失败";
Log.WorkLog("签名值生成失败。");
return false;
}
else
{
var param = JsonConvert.SerializeObject(new request_sign
{
appKey = CaChe.SysConfig.AppKey,
body = body_result.Item1,
sign = body_result.Item2,
timestamp = body_result.Item3,
version = CaChe.SysConfig.ApiVersion,
orgId = CaChe.UserInfo?.baseJpOrganization?.id ?? "",
});
var json = GetHttpRqst(CaChe.SysConfig.DomainUrl + UrlConfig.DelEpcList, param);
if (string.IsNullOrEmpty(json))
{
msg = "网络异常";
Log.DebugLog("删除库存失败", "删除失败");
return false;
}
else
{
var res_data = JsonConvert.DeserializeObject<respone_head<respone_order>>(json);
if (res_data != null && res_data.msg.Contains("无效EPC"))
{
Log.WorkLog("EPC不在库中,删除本地库的EPC");
return true;
}
else if (res_data != null && res_data.code == 10000)
{
Log.WorkLog(json, "[JSON]");
return true;
}
else
{
msg = res_data.msg;
Log.DebugLog($"删除库存失败,{msg}", "请求失败");
return false;
}
}
}
}
catch (Exception ex)
{
Log.ErrorLog(ex.ToString() + "\r\n", MethodBase.GetCurrentMethod().Name);
msg = ex.InnerException?.Message ?? ex.Message ?? "";
return false;
}
}
/// <summary>
/// 导入旧版箱标物资(废弃)
/// </summary>
/// <param name="infos"></param>
/// <param name="msg"></param>
/// <returns></returns>
public static Tuple<bool, respone_import_old_data> ImportOldBoxMark(List<recode_info> infos, out string msg)
{
try
{
msg = string.Empty;
var body_par = JsonConvert.SerializeObject(new
{
dataList = infos.Select(x => new
{
boxMarkEpc = x.epc,
epcListJson = x.epcListJson
})
});
var body_result = GetBody(body_par);
if (body_result == null)
{
msg = "签名值生成失败";
Log.WorkLog("签名值生成失败。");
return new Tuple<bool, respone_import_old_data>(false, null);
}
else
{
var param = JsonConvert.SerializeObject(new request_sign
{
appKey = CaChe.SysConfig.AppKey,
body = body_result.Item1,
sign = body_result.Item2,
timestamp = body_result.Item3,
version = CaChe.SysConfig.ApiVersion,
orgId = CaChe.UserInfo?.baseJpOrganization?.id ?? "",
});
var json = GetHttpRqst(CaChe.SysConfig.DomainUrl + UrlConfig.ImportOldBoxMark, param);
if (string.IsNullOrEmpty(json))
{
msg = "网络异常";
Log.DebugLog("导入旧箱标数据失败", "操作失败");
return new Tuple<bool, respone_import_old_data>(false, null);
}
else
{
var res_data = JsonConvert.DeserializeObject<respone_head<respone_import_old_data>>(json);
if (res_data != null && res_data.code == 10000)
{
msg = $"导入成功{res_data.data.successList.Count}条,失败{res_data.data.failList.Count}条";
if (res_data.data.failList.Count > 0)
{
foreach (var obj in res_data.data.failList)
{
msg += $"\nepc:{obj.epc} 失败原因:{obj.message}";
}
}
return new Tuple<bool, respone_import_old_data>(true, res_data.data);
}
else
{
msg = res_data.msg;
Log.DebugLog($"导入旧箱标数据失败,{msg} json:{json}", "请求失败");
return new Tuple<bool, respone_import_old_data>(false, null);
}
}
}
}
catch (Exception ex)
{
Log.ErrorLog(ex.ToString() + "\r\n", MethodBase.GetCurrentMethod().Name);
msg = ex.InnerException?.Message ?? ex.Message ?? "";
return new Tuple<bool, respone_import_old_data>(false, null);
}
}
/// <summary>
/// 直接生成EPC(只生成EPC)
/// </summary>
/// <param name="infos"></param>
/// <param name="msg"></param>
/// <returns></returns>
public static Tuple<bool, List<respone_epc>> GenerateIntTagEpc(request_int_info infos, out string msg)
{
try
{
msg = string.Empty;
var body_par = JsonConvert.SerializeObject(infos);
var body_result = GetBody(body_par);
if (body_result == null)
{
msg = "签名值生成失败";
Log.WorkLog("签名值生成失败。");
return new Tuple<bool, List<respone_epc>>(false, default);
}
else
{
var param = JsonConvert.SerializeObject(new request_sign
{
appKey = CaChe.SysConfig.AppKey,
body = body_result.Item1,
sign = body_result.Item2,
timestamp = body_result.Item3,
version = CaChe.SysConfig.ApiVersion,
orgId = CaChe.UserInfo?.baseJpOrganization?.id ?? "",
});
var json = GetHttpRqst(CaChe.SysConfig.DomainUrl + UrlConfig.GenIntTagEpc, param);
if (string.IsNullOrEmpty(json))
{
Log.DebugLog("EPC生成失败", "请求失败");
msg = "网络异常";
return new Tuple<bool, List<respone_epc>>(false, default);
}
else
{
var res_data = JsonConvert.DeserializeObject<respone_head<List<respone_epc>>>(json);
if (res_data == null || res_data.code != 10000)
{
msg = res_data.msg;
Log.DebugLog($"EPC生成失败,{msg}", "请求失败");
return new Tuple<bool, List<respone_epc>>(false, default);
}
else
{
Log.WorkLog(json, "[JSON]");
return new Tuple<bool, List<respone_epc>>(true, res_data.data);
}
}
}
}
catch (Exception ex)
{
Log.ErrorLog(ex.ToString() + "\r\n", MethodBase.GetCurrentMethod().Name);
msg = ex.InnerException?.Message ?? ex.Message ?? "";
return new Tuple<bool, List<respone_epc>>(false, default);
}
}
/// <summary>
/// 通过箱标epc获取件标详细信息
/// </summary>
/// <param name="boxMarkEpc"></param>
/// <param name="msg"></param>
/// <returns></returns>
public static Tuple<bool, List<respone_inventory>> GetInventoryListByBoxMarkEpc(string boxMarkEpc, out string msg)
{
try
{
msg = string.Empty;
var body_par = JsonConvert.SerializeObject(new
{
epc = boxMarkEpc
});
var body_result = GetBody(body_par);
if (body_result == null)
{
msg = "签名值生成失败";
Log.WorkLog("签名值生成失败。");
return new Tuple<bool, List<respone_inventory>>(false, default);
}
else
{
var param = JsonConvert.SerializeObject(new request_sign
{
appKey = CaChe.SysConfig.AppKey,
body = body_result.Item1,
sign = body_result.Item2,
timestamp = body_result.Item3,
version = CaChe.SysConfig.ApiVersion,
orgId = CaChe.UserInfo?.baseJpOrganization?.id ?? "",
});
var json = GetHttpRqst(CaChe.SysConfig.DomainUrl + UrlConfig.GetInventoryListByBoxMarkEpc, param);
if (string.IsNullOrEmpty(json))
{
Log.DebugLog("物资获取失败", "请求失败");
return new Tuple<bool, List<respone_inventory>>(false, default);
}
else
{
var res_data = JsonConvert.DeserializeObject<respone_head<List<respone_inventory>>>(json);
if (res_data == null || res_data.code != 10000)
{
msg = res_data.msg;
Log.DebugLog($"物资获取失败,{msg}", "请求失败");
return new Tuple<bool, List<respone_inventory>>(false, default);
}
else
{
Log.WorkLog(json, "[JSON]");
return new Tuple<bool, List<respone_inventory>>(true, res_data.data);
}
}
}
}
catch (Exception ex)
{
Log.ErrorLog(ex.ToString() + "\r\n", MethodBase.GetCurrentMethod().Name);
msg = ex.InnerException?.Message ?? ex.Message ?? "";
return new Tuple<bool, List<respone_inventory>>(false, default);
}
}
/// <summary>
/// 获取箱标列表
/// </summary>
/// <param name="orgId"></param>
/// <param name="warehouseId"></param>
/// <param name="msg"></param>
/// <returns></returns>
public static Tuple<bool, List<respone_boxMark>> GetBoxMarkList(string orgId, string warehouseId, out string msg)
{
try
{
msg = string.Empty;
var body_par = JsonConvert.SerializeObject(new
{
orgId = orgId,
warehouseId = warehouseId
});
var body_result = GetBody(body_par);
if (body_result == null)
{
msg = "签名值生成失败";
Log.WorkLog("签名值生成失败。");
return new Tuple<bool, List<respone_boxMark>>(false, default);
}
else
{
var param = JsonConvert.SerializeObject(new request_sign
{
appKey = CaChe.SysConfig.AppKey,
body = body_result.Item1,
sign = body_result.Item2,
timestamp = body_result.Item3,
version = CaChe.SysConfig.ApiVersion,
orgId = CaChe.UserInfo?.baseJpOrganization?.id ?? "",
});
var json = GetHttpRqst(CaChe.SysConfig.DomainUrl + UrlConfig.GetBoxMarkList, param);
if (string.IsNullOrEmpty(json))
{
Log.DebugLog("订单列表获取失败", "请求失败");
return new Tuple<bool, List<respone_boxMark>>(false, default);
}
else
{
var res_data = JsonConvert.DeserializeObject<respone_head<List<respone_boxMark>>>(json);
if (res_data == null || res_data.code != 10000)
{
msg = res_data.msg;
Log.DebugLog($"EPC生成失败,{msg}", "请求失败");
return new Tuple<bool, List<respone_boxMark>>(false, default);
}
else
{
Log.WorkLog(json, "[JSON]");
return new Tuple<bool, List<respone_boxMark>>(true, res_data.data);
}
}
}
}
catch (Exception ex)
{
Log.ErrorLog(ex.ToString() + "\r\n", MethodBase.GetCurrentMethod().Name);
msg = ex.InnerException?.Message ?? ex.Message ?? "";
return new Tuple<bool, List<respone_boxMark>>(false, default);
}
}
/// <summary>
/// 获取箱标打印任务
/// </summary>
/// <param name="orgId"></param>
/// <param name="msg"></param>
/// <returns></returns>
public static Tuple<bool, List<respone_boxMark>> GetNeedPrintBoxMarkList(string orgId, out string msg)
{
try
{
msg = string.Empty;
var body_par = JsonConvert.SerializeObject(new
{
orgId = orgId
});
var body_result = GetBody(body_par);
if (body_result == null)
{
msg = "签名值生成失败";
Log.WorkLog("签名值生成失败。");
return new Tuple<bool, List<respone_boxMark>>(false, default);
}
else
{
var param = JsonConvert.SerializeObject(new request_sign
{
appKey = CaChe.SysConfig.AppKey,
body = body_result.Item1,
sign = body_result.Item2,
timestamp = body_result.Item3,
version = CaChe.SysConfig.ApiVersion,
orgId = CaChe.UserInfo?.baseJpOrganization?.id ?? "",
});
var json = GetHttpRqst(CaChe.SysConfig.DomainUrl + UrlConfig.GetNeedPrintBoxMarkList, param);
if (string.IsNullOrEmpty(json))
{
Log.DebugLog("订单列表获取失败", "请求失败");
return new Tuple<bool, List<respone_boxMark>>(false, default);
}
else
{
var res_data = JsonConvert.DeserializeObject<respone_head<List<respone_boxMark>>>(json);
if (res_data == null || res_data.code != 10000)
{
msg = res_data.msg;
Log.DebugLog($"EPC生成失败,{msg}", "请求失败");
return new Tuple<bool, List<respone_boxMark>>(false, default);
}
else
{
Log.WorkLog(json, "[JSON]");
return new Tuple<bool, List<respone_boxMark>>(true, res_data.data);
}
}
}
}
catch (Exception ex)
{
Log.ErrorLog(ex.ToString() + "\r\n", MethodBase.GetCurrentMethod().Name);
msg = ex.InnerException?.Message ?? ex.Message ?? "";
return new Tuple<bool, List<respone_boxMark>>(false, default);
}
}
/// <summary>
/// 获取装备包打印任务
/// </summary>
/// <param name="orgId"></param>
/// <param name="bagName"></param>
/// <param name="msg"></param>
/// <returns></returns>
public static Tuple<bool, List<respone_bagInventory>> GetPrintBagList(string orgId, string bagName, out string msg)
{
try
{
msg = string.Empty;
var body_par = JsonConvert.SerializeObject(new
{
orgId = orgId,
bagName = bagName
});
var body_result = GetBody(body_par);
if (body_result == null)
{
msg = "签名值生成失败";
Log.WorkLog("签名值生成失败。");
return new Tuple<bool, List<respone_bagInventory>>(false, default);
}
else
{
var param = JsonConvert.SerializeObject(new request_sign
{
appKey = CaChe.SysConfig.AppKey,
body = body_result.Item1,
sign = body_result.Item2,
timestamp = body_result.Item3,
version = CaChe.SysConfig.ApiVersion,
orgId = CaChe.UserInfo?.baseJpOrganization?.id ?? "",
});
var json = GetHttpRqst(CaChe.SysConfig.DomainUrl + UrlConfig.GetPrintBagList, param);
if (string.IsNullOrEmpty(json))
{
Log.DebugLog("订单列表获取失败", "请求失败");
return new Tuple<bool, List<respone_bagInventory>>(false, default);
}
else
{
var res_data = JsonConvert.DeserializeObject<respone_head<List<respone_bagInventory>>>(json);
if (res_data == null || res_data.code != 10000)
{
msg = res_data.msg;
Log.DebugLog($"EPC生成失败,{msg}", "请求失败");
return new Tuple<bool, List<respone_bagInventory>>(false, default);
}
else
{
Log.WorkLog(json, "[JSON]");
return new Tuple<bool, List<respone_bagInventory>>(true, res_data.data);
}
}
}
}
catch (Exception ex)
{
Log.ErrorLog(ex.ToString() + "\r\n", MethodBase.GetCurrentMethod().Name);
msg = ex.InnerException?.Message ?? ex.Message ?? "";
return new Tuple<bool, List<respone_bagInventory>>(false, default);
}
}
/// <summary>
/// 装备包EPC状态更新
/// </summary>
/// <param name="id"></param>
/// <param name="msg"></param>
/// <returns></returns>
public static bool UpdateBagState(string id, out string msg)
{
try
{
msg = string.Empty;
var body_par = JsonConvert.SerializeObject(new
{
id
});
var body_result = GetBody(body_par);
if (body_result == null)
{
msg = "签名值生成失败";
Log.WorkLog("签名值生成失败。");
return false;
}
else
{
var param = JsonConvert.SerializeObject(new request_sign
{
appKey = CaChe.SysConfig.AppKey,
body = body_result.Item1,
sign = body_result.Item2,
timestamp = body_result.Item3,
version = CaChe.SysConfig.ApiVersion,
orgId = CaChe.UserInfo?.baseJpOrganization?.id ?? "",
});
var json = GetHttpRqst(CaChe.SysConfig.DomainUrl + UrlConfig.UpdateBagState, param);
if (string.IsNullOrEmpty(json))
{
Log.DebugLog("更新失败", "请求失败");
return false;
}
else
{
var res_data = JsonConvert.DeserializeObject<respone_head<List<respone_bagInventory>>>(json);
if (res_data == null || res_data.code != 10000)
{
msg = res_data.msg;
Log.DebugLog($"更新失败,{msg}", "请求失败");
return false;
}
else
{
Log.WorkLog(json, "[JSON]");
return true;
}
}
}
}
catch (Exception ex)
{
Log.ErrorLog(ex.ToString() + "\r\n", MethodBase.GetCurrentMethod().Name);
msg = ex.InnerException?.Message ?? ex.Message ?? "";
return false;
}
}
/// <summary>
/// http下载文件
/// </summary>
/// <param name="url">下载文件地址</param>
/// <param name="path">文件存放地址,包含文件名</param>
/// <returns></returns>
public static bool HttpDownload(string url, string path)
{
string tempPath = System.IO.Path.GetDirectoryName(path) + @"\temp";
System.IO.Directory.CreateDirectory(tempPath); //创建临时文件目录
string tempFile = tempPath + @"\" + System.IO.Path.GetFileName(path) + ".temp"; //临时文件
if (System.IO.File.Exists(tempFile))
{
System.IO.File.Delete(tempFile); //存在则删除
}
try
{
FileStream fs = new FileStream(tempFile, FileMode.Append, FileAccess.Write, FileShare.ReadWrite);
// 设置参数
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
//发送请求并获取相应回应数据
HttpWebResponse response = request.GetResponse() as HttpWebResponse;
//直到request.GetResponse()程序才开始向目标网页发送Post请求
Stream responseStream = response.GetResponseStream();
//创建本地文件写入流
//Stream stream = new FileStream(tempFile, FileMode.Create);
byte[] bArr = new byte[1024];
int size = responseStream.Read(bArr, 0, (int)bArr.Length);
while (size > 0)
{
//stream.Write(bArr, 0, size);
fs.Write(bArr, 0, size);
size = responseStream.Read(bArr, 0, (int)bArr.Length);
}
//stream.Close();
fs.Close();
responseStream.Close();
System.IO.File.Move(tempFile, path);
return true;
}
catch (Exception ex)
{
return false;
}
}
/// <summary>
/// 获取文件的MD5码
/// </summary>
/// <param name="fileName">传入的文件名(含路径及后缀名)</param>
/// <returns></returns>
public static string GetMD5HashFromFile(string fileName)
{
try
{
FileStream file = new FileStream(fileName, System.IO.FileMode.Open);
MD5 md5 = new MD5CryptoServiceProvider();
byte[] retVal = md5.ComputeHash(file);
file.Close();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < retVal.Length; i++)
{
sb.Append(retVal[i].ToString("x2"));
}
return sb.ToString();
}
catch (Exception ex)
{
throw new Exception("GetMD5HashFromFile() fail,error:" + ex.Message);
}
}
private static Tuple<string, string, string> GetBody(string json)
{
try
{
var timespan = GetTimeStamp();
var body = System.Web.HttpUtility.UrlEncode(json);
var content = $"{CaChe.SysConfig.SecretKey}{timespan}{CaChe.SysConfig.ApiVersion}{body}";
var sign = GetMd5(content);
return new Tuple<string, string, string>(body, sign, timespan);
}
catch (Exception ex)
{
Log.ErrorLog(ex.ToString());
return null;
}
}
private static string GetMd5(string txt)
{
//初始化MD5对象
using (MD5 md5 = MD5.Create())
{
//将源字符串转化为byte数组
byte[] soucebyte = Encoding.UTF8.GetBytes(txt);
//soucebyte转化为mf5的byte数组
byte[] md5bytes = md5.ComputeHash(soucebyte);
//将md5的byte数组再转化为MD5数组
StringBuilder sb = new StringBuilder();
foreach (byte b in md5bytes)
{
//x表示16进制,2表示2位
sb.Append(b.ToString("x2"));
}
return sb.ToString();
}
}
private static string GetTimeStamp()
{
TimeSpan ts = DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, 0);
return Convert.ToInt64(ts.TotalSeconds).ToString();
}
}
}
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Data;
namespace JmpZbPrint.Common
{
public class IsSuccessConvert : IValueConverter
{
//当值从绑定源传播给绑定目标时,调用方法Convert
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value == null)
return DependencyProperty.UnsetValue;
bool.TryParse(value.ToString(), out bool isSuccess);
if (isSuccess)
{
return "成功";
}
else
{
return "失败";
}
}
//当值从绑定目标传播给绑定源时,调用此方法ConvertBack
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
string str = value as string;
if (str== "成功")
{
return true;
}
return DependencyProperty.UnsetValue;
}
}
}
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
namespace JmpZbPrint.Common
{
public class JmpDes
{
/// <summary> 加密字符串
/// </summary>
/// <param name="strText">需被加密的字符串</param>
/// <param name="strEncrKey">密钥</param>
/// <returns></returns>
public static string Encrypt(string strText, string strKey = "jMp838668")
{
try
{
byte[] byKey = null;
byte[] IV = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };
byKey = Encoding.UTF8.GetBytes(strKey.Substring(0, 8));
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
byte[] inputByteArray = Encoding.UTF8.GetBytes(strText);
MemoryStream ms = new MemoryStream();
CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(byKey, IV), CryptoStreamMode.Write);
cs.Write(inputByteArray, 0, inputByteArray.Length);
cs.FlushFinalBlock();
return Convert.ToBase64String(ms.ToArray());
}
catch
{
return "";
}
}
/// <summary> 解密字符串
/// </summary>
/// <param name="strText">需被解密的字符串</param>
/// <param name="sDecrKey">密钥</param>
/// <returns></returns>
public static string Decrypt(string strText, string strKey = "jMp838668")
{
try
{
byte[] byKey = null;
byte[] IV = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };
byte[] inputByteArray = new Byte[strText.Length];
byKey = Encoding.UTF8.GetBytes(strKey.Substring(0, 8));
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
inputByteArray = Convert.FromBase64String(strText);
MemoryStream ms = new MemoryStream();
CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(byKey, IV), CryptoStreamMode.Write);
cs.Write(inputByteArray, 0, inputByteArray.Length);
cs.FlushFinalBlock();
Encoding encoding = new UTF8Encoding();
return encoding.GetString(ms.ToArray());
}
catch
{
return string.Empty;
}
}
}
}
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Data;
namespace JmpZbPrint.Common
{
public class LabelTypeConvert : IValueConverter
{
//当值从绑定源传播给绑定目标时,调用方法Convert
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value == null)
return DependencyProperty.UnsetValue;
bool.TryParse(value.ToString(), out bool type);
if (type == true)
{
return "箱标";
}
else
{
return "件标";
}
}
//当值从绑定目标传播给绑定源时,调用此方法ConvertBack
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
string str = value as string;
if (str== "箱标")
{
return true;
}
else
{
return false;
}
return DependencyProperty.UnsetValue;
}
}
}
using JmpZbPrint.Model;
using JmpZbPrint.Model.DbModel;
using LiteDB;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Text;
using System.Threading.Tasks;
namespace JmpZbPrint.Common
{
public class LiteDbHelper
{
public static bool AddRange(List<recode_info> recodes)
{
try
{
var path = AppDomain.CurrentDomain.SetupInformation.ApplicationBase;
using (var db = new LiteDatabase($"{path}print.db"))
{
var col = db.GetCollection<recode_info>("recode_info");
var res = col.InsertBulk(recodes);
return res > 0;
}
}
catch (Exception ex)
{
Log.ErrorLog(ex.ToString());
return default;
}
}
public static bool Update(recode_info recode)
{
try
{
var path = AppDomain.CurrentDomain.SetupInformation.ApplicationBase;
using (var db = new LiteDatabase($"{path}print.db"))
{
var col = db.GetCollection<recode_info>("recode_info");
var res = col.Update(recode);
return res;
}
}
catch (Exception ex)
{
Log.ErrorLog(ex.ToString());
return default;
}
}
public static bool Update(string epc, bool isdelete = true)
{
try
{
var path = AppDomain.CurrentDomain.SetupInformation.ApplicationBase;
using (var db = new LiteDatabase($"{path}print.db"))
{
var col = db.GetCollection<recode_info>("recode_info");
var recode = col.FindOne(t => t.epc == epc);
if (recode == null) { return false; }
else
{
recode.isdelete = isdelete;
return col.Update(recode);
}
}
}
catch (Exception ex)
{
Log.ErrorLog(ex.ToString());
return default;
}
}
public static bool Update(int id, bool isdelete = true)
{
try
{
var path = AppDomain.CurrentDomain.SetupInformation.ApplicationBase;
using (var db = new LiteDatabase($"{path}print.db"))
{
var col = db.GetCollection<recode_info>("recode_info");
var recode = col.FindOne(t => t.id == id);
if (recode == null) { return false; }
else
{
recode.PrintTime = DateTime.Now;
recode.isdelete = isdelete;
return col.Update(recode);
}
}
}
catch (Exception ex)
{
Log.ErrorLog(ex.ToString());
return default;
}
}
public static void Delete(int id)
{
try
{
var path = AppDomain.CurrentDomain.SetupInformation.ApplicationBase;
using (var db = new LiteDatabase($"{path}print.db"))
{
var col = db.GetCollection<recode_info>("recode_info");
var recode = col.FindOne(t => t.id == id);
if (recode == null) { return; }
else
{
col.Delete(recode.id);
}
}
}
catch (Exception ex)
{
Log.ErrorLog(ex.ToString());
return;
}
}
public static void DeleteByEpc(string epc)
{
try
{
var path = AppDomain.CurrentDomain.SetupInformation.ApplicationBase;
using (var db = new LiteDatabase($"{path}print.db"))
{
var col = db.GetCollection<recode_info>("recode_info");
var recode = col.FindOne(t => t.epc == epc);
if (recode == null) { return; }
else
{
col.Delete(recode.id);
}
}
}
catch (Exception ex)
{
Log.ErrorLog(ex.ToString());
return;
}
}
public static recode_info GetSingle(int id)
{
try
{
var path = AppDomain.CurrentDomain.SetupInformation.ApplicationBase;
using (var db = new LiteDatabase($"{path}print.db"))
{
var col = db.GetCollection<recode_info>("recode_info");
var res = col.FindOne(t => t.id == id);
return res;
}
}
catch (Exception ex)
{
Log.ErrorLog(ex.ToString());
return default;
}
}
public static recode_info GetSingleByEpc(string epc)
{
try
{
var path = AppDomain.CurrentDomain.SetupInformation.ApplicationBase;
using (var db = new LiteDatabase($"{path}print.db"))
{
var col = db.GetCollection<recode_info>("recode_info");
var res = col.FindOne(t => t.epc == epc);
return res;
}
}
catch (Exception ex)
{
Log.ErrorLog(ex.ToString());
return default;
}
}
public static db_page GetPage(int page, int size, Expression<Func<recode_info, bool>> @where)
{
try
{
page -= 1;
var path = AppDomain.CurrentDomain.SetupInformation.ApplicationBase;
using (var db = new LiteDatabase($"{path}print.db"))
{
var col = db.GetCollection<recode_info>("recode_info");
var count = col.Find(@where).Count();
var data = new db_page
{
total = count,
record = col.Find(@where).ToList().OrderBy(t => t.epc)
.Skip(page * size).Take(size).ToList()
};
return data;
}
}
catch (Exception ex)
{
Log.ErrorLog(ex.ToString());
return default;
}
}
}
}
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
namespace JmpZbPrint.Common
{
public static class NotifyPropertyChangedExtension
{
public static void MutateVerbose<TField>(this INotifyPropertyChanged instance, ref TField field, TField newValue, Action<PropertyChangedEventArgs> raise, [CallerMemberName] string propertyName = null)
{
if (EqualityComparer<TField>.Default.Equals(field, newValue)) return;
field = newValue;
raise?.Invoke(new PropertyChangedEventArgs(propertyName));
}
}
}
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Data;
namespace JmpZbPrint.Common
{
[ValueConversion(typeof(int), typeof(string))]
public class NumericalConverter : IValueConverter
{
//源属性传给目标属性时,调用此方法ConvertBack
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value == null)
return 0;
return value;
}
//目标属性传给源属性时,调用此方法ConvertBack
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value == null)
{
return 0;
}
else
{
int.TryParse(value.ToString(), out int index);
return index;
}
}
}
}
using System;
using System.Drawing;
using System.Drawing.Text;
using System.Windows.Media.Imaging;
namespace JmpZbPrint.Common
{
public class PreviewImageHelper
{
public static BitmapImage GetEnterpriceBoxPreview(string strBoxNo, string strProductNo
, string strSupplier, string strBoxSn, string strProductName, string strWzhx
, string strBoxNum)
{
//企业箱标
Bitmap bitmap = new Bitmap(640, 245);
Graphics G = Graphics.FromImage(bitmap);
G.FillRectangle(Brushes.White, new Rectangle(0, 0, 640, 245));
G.TextRenderingHint = TextRenderingHint.AntiAlias;
FontFamily fontFamily = new FontFamily("黑体");
Font font = new Font(fontFamily, 20f, FontStyle.Regular, GraphicsUnit.Pixel);
G.DrawString("装箱清单", font, Brushes.Black, 280, 20);
G.DrawString($"装箱序列号:{strBoxNo}", font, Brushes.Black, 40, 50);
G.DrawString($"产品代码:{strProductNo}", font, Brushes.Black, 40, 90);
G.DrawString($"供应商:{strSupplier}", font, Brushes.Black, 40, 130);
G.DrawString($"装箱码:{strBoxSn}", font, Brushes.Black, 40, 170);
G.DrawString($"产品名称:{strProductName}", font, Brushes.Black, 40, 210);
G.DrawString($"装箱号型:{strWzhx}", font, Brushes.Black, 400, 50);
G.DrawString($"装箱数量:{strBoxNum}", font, Brushes.Black, 400, 90);
return Bitmap2BitmapImage(bitmap);
}
public static BitmapImage GetPiecePreview(string strBoxNo, string strWzhx, string strSupplier, string strProductName)
{
//企业箱标
Bitmap bitmap = new Bitmap(640, 245);
Graphics G = Graphics.FromImage(bitmap);
G.FillRectangle(Brushes.White, new Rectangle(0, 0, 640, 245));
G.TextRenderingHint = TextRenderingHint.AntiAlias;
FontFamily fontFamily = new FontFamily("黑体");
Font font = new Font(fontFamily, 20f, FontStyle.Regular, GraphicsUnit.Pixel);
G.DrawString($"供应商:{strSupplier}", font, Brushes.Black, 60, 50);
G.DrawString($"品名:{strProductName}", font, Brushes.Black, 60, 90);
G.DrawString($"号型:{strWzhx}", font, Brushes.Black, 60, 130);
G.DrawString($"件序列号:{strBoxNo}", font, Brushes.Black, 60, 170);
return Bitmap2BitmapImage(bitmap);
}
public static BitmapImage GetPerBoxPreview(string strSupplier, string strName, string strPoliceNo, string strBoxNum)
{
Bitmap bitmap = new Bitmap(640, 245);
Bitmap qr = (Bitmap)Bitmap.FromFile(AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "qrcode.png");
Graphics G = Graphics.FromImage(bitmap);
G.FillRectangle(Brushes.White, new Rectangle(0, 0, 640, 245));
G.TextRenderingHint = TextRenderingHint.AntiAlias;
FontFamily fontFamily = new FontFamily("黑体");
Font font = new Font(fontFamily, 20f, FontStyle.Regular, GraphicsUnit.Pixel);
G.DrawString($"单位名称:{strSupplier}", font, Brushes.Black, 60, 50);
G.DrawString($"姓名:{strName}", font, Brushes.Black, 60, 90);
G.DrawString($"警号:{strPoliceNo}", font, Brushes.Black, 60, 130);
G.DrawString($"数量:{strBoxNum}", font, Brushes.Black, 60, 170);
G.DrawImage(qr, 460, 70, 150, 150);
return Bitmap2BitmapImage(bitmap);
}
private static BitmapImage Bitmap2BitmapImage(System.Drawing.Bitmap bitmap)
{
//BitmapImage bitmapImage = new BitmapImage();
//using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
//{
// bitmap.Save(ms, bitmap.RawFormat);
// bitmapImage.BeginInit();
// bitmapImage.StreamSource = ms;
// bitmapImage.CacheOption = BitmapCacheOption.OnLoad;
// bitmapImage.EndInit();
// bitmapImage.Freeze();
//}
//return bitmapImage;
System.Drawing.Bitmap ImageOriginalBase = new Bitmap(bitmap);
BitmapImage bitmapImage = new BitmapImage();
using (System.IO.MemoryStream ms = new System.IO.MemoryStream())
{
//ImageOriginalBase.Save(ms, ImageOriginalBase.RawFormat);
ImageOriginalBase.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
bitmapImage.BeginInit();
bitmapImage.StreamSource = ms;
bitmapImage.CacheOption = BitmapCacheOption.OnLoad;
bitmapImage.EndInit();
bitmapImage.Freeze();
}
return bitmapImage;
}
}
}
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Data;
using JmpZbModel;
using JmpZbPrint.Model;
using NetworkCommsDotNet;
using NetworkCommsDotNet.Connections;
using NetworkCommsDotNet.Connections.TCP;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
namespace JmpZbPrint.Common
{
public interface IPrintServerHelper : IDisposable
{
delegate void EnableControlDelegate(bool flag, bool startEnable, bool stopEnable, string msg = "");
abstract event EnableControlDelegate EnableControlEvent;
void Init();
bool SendPrintCmd(SingleInfo entity);
}
/// <summary>
/// 东芝打印机
/// </summary>
public class ToShiBaPrintServerHelper : IPrintServerHelper
{
public event IPrintServerHelper.EnableControlDelegate EnableControlEvent;
private CancellationTokenSource cTcpServiceToken;
private Task taskTcpService;
private Connection tcpConn;
private bool isPrintError = true;
private bool flushPrintState = false;
private AutoResetEvent resetEvent = new AutoResetEvent(false);
/// <summary>
/// 初始化
/// </summary>
public void Init()
{
if (taskTcpService == null)
{
cTcpServiceToken = new CancellationTokenSource();
taskTcpService = new Task(() =>
{
while (!cTcpServiceToken.IsCancellationRequested)
{
try
{
// 已连接的不处理
if (tcpConn?.ConnectionInfo?.ConnectionState == ConnectionState.Established
|| tcpConn?.ConnectionInfo?.ConnectionState == ConnectionState.Establishing)
{
if (isPrintError)
{
try
{
if (!tcpConn?.ConnectionAlive() ?? false
|| tcpConn?.ConnectionInfo?.ConnectionState == ConnectionState.Shutdown
|| tcpConn?.ConnectionInfo?.ConnectionState == ConnectionState.Undefined)
{
return;
}
else
{
PrintCmdInfo cmdInfo = new PrintCmdInfo()
{
CmdType = PrintCmdType.startPrint,
Message = JsonConvert.SerializeObject(new DeviceInfo() { ConnectType = ConnectType.USB, PrintType = PrintType.东芝 }),
Success = false,
};
string msg = tcpConn?.SendReceiveObject<string, string>("StartPrint", "RStartPrint", 60000, JsonConvert.SerializeObject(cmdInfo));
JObject obj = JObject.Parse(msg ?? string.Empty);
if (obj["Success"]?.ToObject<bool>() == false)
{
isPrintError = true;
EnableControlEvent?.Invoke(false, false, false, "打印机启动失败");
}
else
{
isPrintError = false;
EnableControlEvent?.Invoke(true, true, false, "打印机启动成功");
}
}
}
catch (Exception ex)
{
Log.ErrorLog(ex.ToString(), this.GetType().Name);
}
}
else
{
if (flushPrintState)
{
flushPrintState = false;
EnableControlEvent?.Invoke(true, true, false, "打印机启动成功");
}
}
}
else
{
try
{
tcpConn = TCPConnection.GetConnection(new ConnectionInfo("127.0.0.1", 8656));
tcpConn.AppendShutdownHandler(new NetworkComms.ConnectionEstablishShutdownDelegate(OnDisConnection));
EnableControlEvent?.Invoke(true, true, false, "打印服务已启动");
//StartPrint();
}
catch
{
EnableControlEvent?.Invoke(false, false, false, "打印机连接失败");
}
}
if (resetEvent.WaitOne(3000)) { continue; }
}
catch (System.Exception ex)
{
EnableControlEvent?.Invoke(false, false, false, "打印机连接失败");
Log.ErrorLog(ex.ToString(), this.GetType().Name);
}
}
});
taskTcpService.Start();
}
else
{
//刷新状态
flushPrintState = true;
resetEvent.Set();
}
}
/// <summary>
/// 打印
/// </summary>
/// <param name="entity"></param>
/// <returns></returns>
public bool SendPrintCmd(SingleInfo entity)
{
try
{
if (!tcpConn?.ConnectionAlive() ?? false
|| tcpConn?.ConnectionInfo?.ConnectionState == ConnectionState.Shutdown
|| tcpConn?.ConnectionInfo?.ConnectionState == ConnectionState.Undefined)
{
return false;
}
else
{
PrintCmdInfo cmdInfo = new PrintCmdInfo()
{
CmdType = PrintCmdType.printMsg,
Message = JsonConvert.SerializeObject(entity),
Success = false,
};
var json = JsonConvert.SerializeObject(cmdInfo);
string msg = tcpConn?.SendReceiveObject<string, string>("PrintLabel", "RPrintLabel", 60000, json);
JObject obj = JObject.Parse(msg ?? string.Empty);
if (obj["Success"]?.ToObject<bool>() == true)
{
EnableControlEvent?.Invoke(true, false, true, "数据打印成功");
return true;
}
else
{
var err_msg = obj["Message"]?.ToString() ?? "";
if (!string.IsNullOrEmpty(err_msg) && (err_msg.Contains("未连接") || err_msg.Contains("未启动")))
{
isPrintError = true;
}
EnableControlEvent?.Invoke(false, false, false, err_msg);
return false;
}
}
}
catch (Exception ex)
{
Log.ErrorLog(ex.ToString(), this.GetType().Name);
return false;
}
}
/// <summary>
/// 失去连接,重连
/// </summary>
private void OnDisConnection(Connection connection)
{
EnableControlEvent?.Invoke(false, false, false);
}
public void Dispose()
{
resetEvent.Set();
cTcpServiceToken?.Cancel();
tcpConn?.CloseConnection(false);
}
}
/// <summary>
/// 博思得打印机
/// </summary>
public class PostekPrintServerHelper : IPrintServerHelper
{
public event IPrintServerHelper.EnableControlDelegate EnableControlEvent;
private CancellationTokenSource cTcpServiceToken;
private Task taskTcpService;
private Connection tcpConn;
private bool isPrintError = true;
private bool flushPrintState = false;
private AutoResetEvent resetEvent = new AutoResetEvent(false);
/// <summary>
/// 初始化
/// </summary>
public void Init()
{
if (taskTcpService == null)
{
cTcpServiceToken = new CancellationTokenSource();
taskTcpService = new Task(() =>
{
while (!cTcpServiceToken.IsCancellationRequested)
{
try
{
if (isPrintError)
{
try
{
//重连
var json = HttpHelper.PostUrlencoded("http://127.0.0.1:888/postek/print", new List<KeyValuePair<string, string>>()
{
new KeyValuePair<string, string>("reqParam", "1"),
new KeyValuePair<string, string>("printparams", "[{\"PTK_OpenUSBPort\":\"255\"},{\"PTK_CloseUSBPort\":\"\"}]"),
});
if (string.IsNullOrEmpty(json))
{
EnableControlEvent?.Invoke(false, false, false, "打印服务连接失败,重连中");
}
else
{
var res_data = JsonConvert.DeserializeObject<respone_postek_msg>(json);
if (res_data == null || res_data.retval != "0")
{
EnableControlEvent?.Invoke(false, false, false, "打印机连接失败");
}
else
{
isPrintError = false;
EnableControlEvent?.Invoke(true, true, false, "打印机启动成功");
}
}
}
catch (Exception ex)
{
Log.ErrorLog(ex.ToString(), this.GetType().Name);
}
}
else
{
if (flushPrintState)
{
flushPrintState = false;
EnableControlEvent?.Invoke(true, true, false, "打印机启动成功");
}
}
if (resetEvent.WaitOne(3000)) { continue; }
}
catch (System.Exception ex)
{
EnableControlEvent?.Invoke(false, false, false, "打印机连接失败");
Log.ErrorLog(ex.ToString(), this.GetType().Name);
}
}
});
taskTcpService.Start();
}
else
{
//刷新状态
flushPrintState = true;
resetEvent.Set();
}
}
/// <summary>
/// 打印
/// </summary>
/// <param name="entity"></param>
/// <returns></returns>
public bool SendPrintCmd(SingleInfo entity)
{
try
{
var strTemplate = (string)(typeof(PostekPrintServerHelper).GetField(entity.ModelType + "Template")?.GetValue(this));
if (string.IsNullOrEmpty(strTemplate))
{
EnableControlEvent?.Invoke(false, false, false, "无效模板");
}
var property = typeof(SingleInfo);
foreach (var property_item in property.GetProperties())
{
var property_value = property_item.GetValue(entity)?.ToString() ?? "";
strTemplate = strTemplate.Replace("{" + property_item.Name + "}", property_value);
}
//发送指令
var pushData = @"[{""PTK_OpenUSBPort"":""255""},
{""PTK_ClearBuffer"":""""},
{""PTK_SetDirection"":""B""},
{""PTK_SetPrintSpeed"":""4""},
{""PTK_SetDarkness"":""10""},
{""PTK_SetLabelHeight"":""600,84,0,false""},
{""PTK_SetLabelWidth"":1284},
" + strTemplate + @"
{""PTK_PrintLabel"":""1,1""},
{""PTK_CloseUSBPort"":""""}]
";
var json = HttpHelper.PostUrlencoded("http://127.0.0.1:888/postek/print", new List<KeyValuePair<string, string>>()
{
new KeyValuePair<string, string>("reqParam", "1"),
new KeyValuePair<string, string>("printparams", pushData),
});
if (string.IsNullOrEmpty(json))
{
isPrintError = true;
EnableControlEvent?.Invoke(false, false, false, "打印服务连接失败,重连中");
return false;
}
else
{
var res_data = JsonConvert.DeserializeObject<respone_postek_msg>(json);
if (res_data == null || res_data.retval != "0")
{
Log.ErrorLog("数据打印失败:" + res_data?.msg, this.GetType().Name);
if (res_data?.msg.Contains("打开USB端口文件失败") == true || res_data?.msg.Contains("没有打开端口") == true)
{
isPrintError = true;
EnableControlEvent?.Invoke(false, false, false, "打印服务连接失败,重连中");
}
else
{
EnableControlEvent?.Invoke(true, false, true, "数据打印失败");
}
return false;
}
else
{
EnableControlEvent?.Invoke(true, false, true, "数据打印成功");
return true;
}
}
}
catch (Exception ex)
{
Log.ErrorLog(ex.ToString(), this.GetType().Name);
return false;
}
}
public void Dispose()
{
resetEvent.Set();
cTcpServiceToken?.Cancel();
tcpConn?.CloseConnection(false);
}
#region template
public const string pieceTemplate = @"
{""PTK_DrawText_TrueTypeEx"":""214,120,54,0,黑体,1,550,0,0,0,0,0,0,0,装备名称:{Info1}""},
{""PTK_DrawText_TrueTypeEx"":""214,190,54,0,黑体,1,550,0,0,0,0,0,0,0,装备型号:{Info2}""},
{""PTK_DrawText_TrueTypeEx"":""214,260,54,0,黑体,1,550,0,0,0,0,0,0,0,件序号:{Info4}""},
{""PTK_DrawText_TrueTypeEx"":""214,330,54,0,黑体,1,550,0,0,0,0,0,0,0,生产日期:{Info5}""},
{""PTK_DrawText_TrueTypeEx"":""214,400,54,0,黑体,1,550,0,0,0,0,0,0,0,供应商:{Info3}""},
{""PTK_RWRFIDLabel"":""1,0,2,24,1,{Info9}""},
";
public const string pieceXBTemplate = @"
{""PTK_DrawText_TrueTypeEx"":""214,120,54,0,黑体,1,550,0,0,0,0,0,0,0,装备名称:{Info1}""},
{""PTK_DrawText_TrueTypeEx"":""214,190,54,0,黑体,1,550,0,0,0,0,0,0,0,装备型号:{Info2}""},
{""PTK_DrawText_TrueTypeEx"":""214,260,54,0,黑体,1,550,0,0,0,0,0,0,0,箱序号:{Info5} 箱内数量:{Info4}""},
{""PTK_DrawText_TrueTypeEx"":""214,330,54,0,黑体,1,550,0,0,0,0,0,0,0,打印日期:{Info6}""},
{""PTK_DrawText_TrueTypeEx"":""214,400,54,0,黑体,1,550,0,0,0,0,0,0,0,供应商:{Info3}""},
{""PTK_DrawText_TrueTypeEx"":""980,84,100,0,黑体,1,550,0,0,0,0,0,0,0,箱""},
{""PTK_RWRFIDLabel"":""1,0,2,24,1,{Info9}""},
";
public const string pieceBagTemplate = @"
{""PTK_DrawText_TrueTypeEx"":""214,190,54,0,黑体,1,550,0,0,0,0,0,0,0,装备名称:{Info1}""},
{""PTK_DrawText_TrueTypeEx"":""214,260,54,0,黑体,1,550,0,0,0,0,0,0,0,编号:{Info5}""},
{""PTK_DrawText_TrueTypeEx"":""214,330,54,0,黑体,1,550,0,0,0,0,0,0,0,打印日期:{Info6}""},
{""PTK_DrawText_TrueTypeEx"":""980,84,100,0,黑体,1,550,0,0,0,0,0,0,0,包""},
{""PTK_RWRFIDLabel"":""1,0,2,24,1,{Info9}""},
";
#endregion
}
}
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Data;
namespace JmpZbPrint.Common
{
public class PrintTypeConvert : IValueConverter
{
//当值从绑定源传播给绑定目标时,调用方法Convert
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
if (value == null)
return DependencyProperty.UnsetValue;
int.TryParse(value.ToString(), out int type);
if (type == 0)
{
return "打印";
}
else
{
return "初始化";
}
}
//当值从绑定目标传播给绑定源时,调用此方法ConvertBack
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
string str = value as string;
if (int.TryParse(str, out int type))
{
return type;
}
return DependencyProperty.UnsetValue;
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace JmpZbPrint.Common
{
public class ProductTag
{
public ProductTag()
{
}
public string epc = string.Empty;
//public TAB_BZGL_WZDM wzdm = null;
public string wzmc = string.Empty;
public string wzhx = string.Empty;
public Int64 num = 0;
public string wzdm = string.Empty;
public string ulsm = string.Empty;
public int wzxh = 0;
public double wzsl = 0;
public DateTime createdate;
public string boxtype = string.Empty;
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace JmpZbPrint.Common
{
public class ProductEpc
{
ProductEpc196 pro196 = new ProductEpc196();
#region 属性
public int Index { get; set; }
public int ListIndex { get; set; }
/// <summary>
/// 有效EPC
/// </summary>
public string StrSubEpc { get; set; }
/// <summary>
/// 标签EPC长度
/// </summary>
private int iTagLength = 42;
private string strCopyright = "00";
/// <summary>
/// EPC中的版本号 2位十六进制 00-FF,FF保留
/// </summary>
public string StrCopyright
{
get { return strCopyright; }
set { strCopyright = value; }
}
/// <summary>
/// 数据库中的版本号 十进制
/// </summary>
public int ICopyright
{
get;
set;
//get { return Convert.ToInt32(StrCopyright, 16); }
//set { StrCopyright = Convert.ToString(value, 16).PadLeft(2, '0'); }
}
private String strTagType = "";
/// <summary>
/// EPC中标签类型 1位十六进制 0-F 0-单品物资标签,1-箱标签,2-托盘标签,3-货架标签,4-批物资标签
/// </summary>
public String StrTagType
{
get { return strTagType; }
set { strTagType = value; }
}
private String strSCCSNo = "";
/// <summary>
/// EPC中对应生产企业代码 6位十六进制 000000-FFFFFF
/// </summary>
public String StrSCCSNo
{
get { return strSCCSNo; }
set { strSCCSNo = value; }
}
private string strSccsCode = "";
/// <summary>
/// 数据库中生产企业代码
/// </summary>
public string StrSccsCode
{
get { return strSccsCode; }
set { strSccsCode = value; }
}
private String strSCCSName = "";
/// <summary>
/// 生产企业名称
/// </summary>
public String StrSCCSName
{
get { return strSCCSName; }
set { strSCCSName = value; }
}
private String strBzType = "1";
/// <summary>
/// EPC中包装类型 1位十六进制 0-F 1-外包装,2-中包装,3-内包装,F-零头配箱
/// </summary>
public String StrBzType
{
get { return strBzType; }
set { strBzType = value; }
}
private string strWzLsm = "0";
/// <summary>
/// EPC中物资代码,LSM 8位十六进制 00000000-FFFFFFFF
/// </summary>
public string StrWzLsm
{
get { return strWzLsm; }
set { strWzLsm = value; }
}
/// <summary>
/// 数据库中物资代码 LSM
/// </summary>
public Int64 IWzLsm
{
get { return Convert.ToInt64(StrWzLsm, 16); }
set { StrWzLsm = Convert.ToString(value, 16); }
}
private string strWzNo = "0";
/// <summary>
/// EPC中物资代码 52码 9位十六进制 000000000-FFFFFFFFF
/// </summary>
public string StrWzNo
{
get { return strWzNo; }
set { strWzNo = value; }
}
private Int64 iWzNo = 0;
/// <summary>
/// 数据库中物资代码 52码
/// </summary>
public Int64 IWzNo
{
//get;
//set;
get { return Convert.ToInt64(StrWzNo, 16); }
set { StrWzNo = Convert.ToString(value, 16); }
}
private String strWzName = "";
/// <summary>
/// 物资名称
/// </summary>
public String StrWzName
{
get { return strWzName; }
set { strWzName = value; }
}
private String strWZHXName = "";
/// <summary>
/// 号型名称
/// </summary>
public String StrWZHXName
{
get { return strWZHXName; }
set { strWZHXName = value; }
}
private String strScrq = "";
/// <summary>
/// EPC中生产日期 6位十六进制 YYMMDD
/// </summary>
public String StrScrq
{
get { return strScrq; }
set { strScrq = value; }
}
/// <summary>
/// 数据库中生产日期 DateTime
/// </summary>
public DateTime DtScrq
{
get;
set;
}
private string strXjbzsl = "";
/// <summary>
/// EPC中下级包装数量 2位十六进制 00-FF
/// </summary>
public string StrXjbzsl
{
get { return strXjbzsl; }
set { strXjbzsl = value; }
}
/// <summary>
/// 数据库中下级包装数量
/// </summary>
public int IXjbzsl
{
get { return Convert.ToInt32(StrXjbzsl, 16); }
set { StrXjbzsl = Convert.ToString(value, 16); }
}
private string strNum = "";
/// <summary>
/// EPC中产品总数量 3位十六进制 000-FFF
/// </summary>
public string StrNum
{
get { return strNum; }
set { strNum = value; }
}
/// <summary>
/// 数据库中产品总数量
/// </summary>
public int INum
{
get { return Convert.ToInt32(StrNum, 16); }
set { StrNum = Convert.ToString(value, 16); }
}
private string strScxNo = "0";
/// <summary>
/// EPC中企业生产线序号 1位十六进制 0-F 十六进制 0-E表示生产线序列号,F表示军需仓库打印的标签
/// </summary>
public string StrScxNo
{
get { return strScxNo; }
set { strScxNo = value; }
}
/// <summary>
/// 数据库中 十进制企业生产线序号
/// </summary>
public int IScxNo
{
get { return Convert.ToInt32(StrScxNo, 16) + 1; }
set { StrScxNo = Convert.ToString(value - 1, 16); }
}
private string strXiangNo = "0";
/// <summary>
/// EPC中包装箱序号 3位十六进制 000-FFF
/// </summary>
public string StrXiangNo
{
get { return strXiangNo; }
set { strXiangNo = value; }
}
/// <summary>
/// 数据库中 十进制包装箱序列号
/// </summary>
public int IXiangNo
{
get { return Convert.ToInt32(StrXiangNo, 16); }
set { StrXiangNo = Convert.ToString(value, 16); }
}
private string strXSerialNo = "0";
/// <summary>
/// EPC中 箱序列号 生产线序号+包装箱序号 0|1
/// </summary>
public string StrXSerialNo
{
get { return strXSerialNo; }// IScxNo.ToString() + '|' + IXiangNo.ToString(); }
set
{
strXSerialNo = value;
//StrScxNo = value.Substring(0, 1);
//StrXiangNo = value.Substring(1);
}
}
private string strZbhm = "0";
/// <summary>
/// EPC中的组别号码 1位十六进制 0-F
/// </summary>
public string StrZbhm
{
get { return strZbhm; }
set { strZbhm = value; }
}
/// <summary>
/// 相同EPC组别中共有几个
/// </summary>
public int IZbAll
{
get;
set;
}
/// <summary>
/// 相同epc组别中第几个
/// </summary>
public int IZbNo
{
get;
set;
}
private string strJiaoYan = "0";
/// <summary>
/// EPC中检验码 1位十六进制
/// </summary>
public string StrJiaoYan
{
get { return strJiaoYan; }
set { strJiaoYan = value; }
}
private string strXnSerialno = "00";
/// <summary>
/// EPC中箱内序号 2位 00-FF
/// </summary>
public string StrXnSerialno
{
get { return strXnSerialno; }
set { strXnSerialno = value; }
}
/// <summary>
/// 数据库中箱内序号
/// </summary>
public int IXnSerialno
{
get { return Convert.ToInt32(StrXnSerialno, 16); }
set { StrXnSerialno = Convert.ToString(value, 16); }
}
private String strEPC = "";
/// <summary>
/// 读取的EPC
/// </summary>
public String StrEPC
{
get { return strEPC; }
set
{
iTagLength = value.Length;
strEPC = value;
}
}
/// <summary>
/// 起始箱号
/// </summary>
public int iStartXNo = 0;
#endregion
#region 方法
public void getInfoFormEpc()
{
try
{
pro196.UnPackEpc(strEPC.Substring(0, 49));
this.StrSubEpc = strEPC.Substring(0, 41) + strEPC.Substring(43, 6);
this.StrCopyright = pro196.getStrHexVersion();
this.StrTagType = pro196.getStrHexTagType();
this.StrSccsCode = pro196.getStrOrgCode().TrimStart('0');
this.StrBzType = pro196.getStrHexPacktype();
this.StrWzLsm = pro196.getStrHexProductCode();
this.StrScrq = pro196.getStrHexScrq();
this.DtScrq = pro196.DtScrq;
this.StrXjbzsl = pro196.getStrHexInsidePackNum();
this.StrNum = pro196.getStrHexProductNum();
this.StrScxNo = pro196.getStrHexProductLine();
this.StrXiangNo = pro196.getStrHexPackSerialNo();
this.StrXSerialNo = this.IScxNo.ToString() + "/" + this.IXiangNo.ToString();
this.StrZbhm = pro196.getStrHexGroupNo();
this.IZbAll = pro196.IZbAll;
this.IZbNo = pro196.IZbNo;
this.StrJiaoYan = pro196.getStrHexCRCCode();
}
catch { }
}
public bool IsSameBox(string epc)
{
if (epc.Length == 52)
{
string temp = epc.Substring(0, 41) + epc.Substring(43, 6);
if (this.StrSubEpc.Equals(temp))
{
return true;
}
}
return false;
}
#endregion
}
public class ProductEpc196
{
#region 属性
/// <summary>
/// 标头信息 十六进制 //被装专业固定"05"
/// </summary>
static String CONSTHEADERINFO = "05";
/// <summary>
/// 标头信息 二进制
/// </summary>
static String CONSTHEADERINFOBIN = "00000101";
/// <summary>
/// 版本号 十六进制
/// </summary>
static String CONSTVERSION = "11";
/// <summary>
/// 版本号 二进制
/// </summary>
static String CONSTVERSIONBIN = "00010001";
/// <summary>
///静态发行机构标志 //部队发布
/// </summary>
static String CONSTMILITARYPUBLISHFLAG = "000001";
/// <summary>
///静态发行机构标志 //国家发布
/// </summary>
static String CONSTNATIONPUBLISHFLAG = "000010";
/// <summary>
///静态发行机构标志 //北约发布
/// </summary>
static String CONSTNATOPUBLISHFLAG = "000011";
//无源标签6位字段对应表
//String[] KeyWords = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z" };
/// <summary>
/// 无源标签6位字段对应表
/// </summary>
String strKeyWords = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
/// <summary>
/// 1、标头信息 十六进制 2位 被装专业专用05
/// </summary>
String strHexHeaderInfo = ProductEpc196.CONSTHEADERINFO;
/// <summary>
/// 1、标头信息 二进制 8位 被装专业专用05
/// </summary>
String strBinHeaderInfo = ProductEpc196.CONSTHEADERINFOBIN; //2进制
/// <summary>
/// 2、发行机构标识 6位 军队组织机构代码为000001
/// </summary>
String strBinPublishFlag = ProductEpc196.CONSTMILITARYPUBLISHFLAG; //2进制
//
/// <summary>
/// 3、组织机构代码 8位
/// 正常组织机构代码
/// </summary>
String strOrgCode = "";
/// <summary>
/// 3、组织机构代码 54位 每6位代表一个数字或字母,位数不够时用每一个字母使用"0"填充
/// 2进制组织机构代码
/// </summary>
String strBinOrgCode = "";
/// <summary>
/// 4、品种代码指示长度 十六进制 指示物资代码长度 N*6 = 物资代码长度,默认为6
/// </summary>
String strHexProductCodeLength = "6"; //16进制
/// <summary>
/// 4、品种代码指示长度 二进制 4位 指示物资代码长度 N*6 = 物资代码长度,默认为6
/// </summary>
String strBinProductcodeLength = "0110";//2进制
/// <summary>
/// 5、物资代码 十六进制 9位,军事物流信息系统物资代码,转换为十进制后存储。我部使用时占用36位
/// </summary>
String strHexProductCode = "000000000"; //16进制
/// <summary>
/// 5、物资代码 二进制 36位 6-48位,军事物流信息系统物资代码,转换为十进制后存储。我部使用时占用36位
/// </summary>
String strBinProductCode = "000000000000000000000000000000000000"; //2进制
/// <summary>
/// 6、序列号长度 十六进制 N*6,现固定为A
/// </summary>
String strHexSerialLength = "A";
/// <summary>
/// 6、序列号长度 二进制 ,现固定为1010
/// </summary>
String strBinSerialLength = "1010";
/// <summary>
/// 7、版本号 十六进制 2位 当前版本为"11"
/// </summary>
String strHexVersion = ProductEpc196.CONSTVERSION;
/// <summary>
/// //7、版本号 二进制 8位 当前版本为"00010001"
/// </summary>
String strBinVersion = ProductEpc196.CONSTVERSIONBIN;
/// <summary>
/// 8、标签类型 十六进制 1位 1 - 箱标签
/// </summary>
private String strHexTagType = "1";
/// <summary>
/// 8、标签类型 二进制 4位 0001 - 箱标签
/// </summary>
private String strBinTagType = "0001";
/// <summary>
/// 9、包装类型 十六进制 1位 (1-外包装,2-中包装,3-内包装,F-零头配箱)
/// </summary>
private String strHexPacktype = "1";
/// <summary>
/// 9、包装类型 二进制 4位 (1-外包装,2-中包装,3-内包装,F-零头配箱)
/// </summary>
private String strBinPacktype = "0001";
//private int iInsidePackNum = 0;
/// <summary>
/// 10、下级包装数量 十六进制 2位 最大255
/// </summary>
private String strHexInsidePackNum = "00";
/// <summary>
/// 10、下级包装数量 二进制 8位 最大255
/// </summary>
private String strBinInsidePackNum = "00000000";
//private int iProductNum = 0;
/// <summary>
/// 11、产品总数量 十六进制 3位 最大4095
/// </summary>
private String strHexProductNum = "000";
/// <summary>
/// 11、产品总数量 二进制 12位 最大4095
/// </summary>
private String strBinProductNum = "000000000000";
//private int iProductLine = 0;
/// <summary>
/// 12、生产线序列号 十六进制 1位 0-E表示生产组序列号 F表示军需仓库打印的标签
/// </summary>
private String strHexProductLine = "0";
/// <summary>
/// 12、生产线序列号 二进制 4位 0-E表示生产组序列号 F表示军需仓库打印的标签
/// </summary>
private String strBinProductLine = "0000";
//private int iPackSerialNo = 0;
/// <summary>
/// 13、产品箱序列号 十六进制 3位
/// </summary>
private String strHexPackSerialNo = "000";
/// <summary>
/// 13、产品箱序列号 二进制 12位
/// </summary>
private String strBinPackSerialNo = "000000000000";
/// <summary>
/// 组别号码 十六进制 1位
/// </summary>
private String strHexGroupNo = "0";
/// <summary>
/// 组别号码 二进制 4位
/// </summary>
private String strBinGroupNo = "0000";
/// <summary>
/// 相同EPC组别中共有几个
/// </summary>
public int IZbAll
{
get
{
int izb = 0;
switch (Convert.ToInt32(strHexGroupNo, 16))
{
case 0:
{
izb = 1;
break;
}
case 4:
{
izb = 2;
break;
}
case 5:
{
izb = 2;
break;
}
case 8:
{
izb = 4;
break;
}
case 9:
{
izb = 4;
break;
}
case 10:
{
izb = 4;
break;
}
case 11:
{
izb = 4;
break;
}
}
return izb;
}
}
/// <summary>
/// 相同epc组别中第几个
/// </summary>
public int IZbNo
{
get
{
int izb = 0;
switch (Convert.ToInt32(strHexGroupNo, 16))
{
case 0:
{
izb = 1;
break;
}
case 4:
{
izb = 1;
break;
}
case 5:
{
izb = 2;
break;
}
case 8:
{
izb = 1;
break;
}
case 9:
{
izb = 2;
break;
}
case 10:
{
izb = 3;
break;
}
case 11:
{
izb = 4;
break;
}
}
return izb;
}
}
//private int iCRCCode = 0;
/// <summary>
/// 校验码 十六进制 1位
/// </summary>
private String strHexCRCCode = "0";
/// <summary>
/// 校验码 二进制 4位
/// </summary>
private String strBinCRCCode = "0000";
//private Date dtScrq;
/// <summary>
/// 生产日期 十六进制 6位
/// </summary>
private String strHexScrq = "120101";
/// <summary>
/// 生产日期 二进制 24位
/// </summary>
private String strBinScrq = "000100100000000100000001";
/// <summary>
/// 生产日期 DateTime
/// </summary>
public DateTime DtScrq
{
get
{
string year = "20" + strHexScrq.Substring(0, 2);
string morth = strHexScrq.Substring(2, 2);
string day = strHexScrq.Substring(4, 2);
return DateTime.Parse(year + "-" + morth.ToString() + "-" + day.ToString());
}
}
/// <summary>
/// 有效期,共4位;前两位数值,后两位单位
/// </summary>
public string strBinYxq = "0000000000000000";
#endregion 属性
#region 方法
/// <summary>
/// * 1、取得16进制标头信息
/// * 位数:2位
/// * 表示方式:0-FF
/// * 说明:被装专业专用为00000101,即为05
/// * @return
/// </summary>
/// <returns></returns>
public String getStrHexHeaderInfo()
{
return strHexHeaderInfo;
}
/// <summary>
/// * 1、取得2进制标头信息
/// * 位数:8位
/// * 表示方式:0-FF
/// * 说明:被装专业专用为00000101,即为05
/// * @return
/// </summary>
/// <returns></returns>
public String getStrBinHeaderInfo()
{
return strBinHeaderInfo;
}
/// <summary>
/// * 2、取得2进制发行机构标识
/// * 位数:6位
/// * 说明:军队组织机构代码为000001
/// * @return
/// </summary>
/// <returns></returns>
public String getStrBinPublishFlag()
{
return strBinPublishFlag;
}
/// <summary>
/// * 3、取得组织机构代码
/// * 位数:54位
/// * 说明:每6位代表一个数字或字母,位数不够时前面用0填充
/// * @return
/// </summary>
/// <returns></returns>
public String getStrOrgCode()
{
return strOrgCode;
}
/// <summary>
/// * 3、设置组织机构代码
/// * 位数:54位
/// * 说明:每6位代表一个数字或字母,位数不够时前面用0填充
/// * @param strOrgCode
/// </summary>
/// <param name="strOrgCode"></param>
public void setStrOrgCode(String strOrgCode)
{
this.strOrgCode = strOrgCode;
}
/// <summary>
/// * 3、取得2进制组织机构代码
/// * 位数:54位
/// * 说明:每6位代表一个数字或字母,位数不够时前面用0填充
/// * @return
/// </summary>
/// <returns></returns>
public String getStrBinOrgCode()
{
return strBinOrgCode;
}
/// <summary>
/// * 3、设置2进制组织机构代码
/// * @param strBinOrgCode
/// </summary>
/// <param name="strBinOrgCode"></param>
public void setStrBinOrgCode(String strBinOrgCode)
{
this.strBinOrgCode = strBinOrgCode;
}
/// <summary>
/// * 4、取得16进制品种代码指示长度
/// * 位数:1位
/// * 说明:指示物资代码长度,N * 6 = 物资代码长度位数
/// * 默认值:6
/// * @return
/// </summary>
/// <returns></returns>
public String getStrHexProductCodeLength()
{
return strHexProductCodeLength;
}
/// <summary>
/// * 4、设置16进制品种代码指示长度
/// * 位数:1位
/// * 说明:指示物资代码长度,N * 6 = 物资代码长度位数
/// * 默认值:6
/// * @param strHexProductCodeLength
/// </summary>
/// <param name="strHexProductCodeLength"></param>
public void setStrHexProductCodeLength(String strHexProductCodeLength)
{
this.strHexProductCodeLength = strHexProductCodeLength;
}
/// <summary>
/// * 4、取得2进制品种代码指示长度
/// * 位数:4位
/// * 说明:指示物资代码长度,N * 6 = 物资代码长度位数
/// * 默认值:6
/// * @return
/// </summary>
/// <returns></returns>
public String getStrBinProductcodeLength()
{
return strBinProductcodeLength;
}
/// <summary>
/// * 4、设置2进制品种代码指示长度
/// * 位数:4位
/// * 说明:指示物资代码长度,N * 6 = 物资代码长度位数
/// * 默认值:6
/// * @return
/// </summary>
/// <param name="strBinProductcodeLength"></param>
public void setStrBinProductcodeLength(String strBinProductcodeLength)
{
this.strBinProductcodeLength = strBinProductcodeLength;
}
/// <summary>
/// * 5、取得16进制物资代码
/// * 位数:9位
/// * 说明:军事物流信息系统物资代码,转换为十六进制后存储。
/// * @return
/// </summary>
/// <returns></returns>
public String getStrHexProductCode()
{
return strHexProductCode;
}
/// <summary>
/// * 5、设置16进制物资代码
/// * 位数:9位
/// * 说明:6 - 48位。军事物流信息系统物资代码,转换为十六进制后存储。 我部使用时占用36位
/// * @return
/// </summary>
/// <param name="strHexProductCode"></param>
public void setStrHexProductCode(String strHexProductCode)
{
this.strHexProductCode = strHexProductCode;
}
/// <summary>
/// * 5、取得2进制物资代码
/// * 位数:36位
/// * 说明:6 - 48位。军事物流信息系统物资代码,转换为十六进制后存储。 我部使用时占用36位
/// * @return
/// </summary>
/// <returns></returns>
public String getStrBinProductCode()
{
return strBinProductCode;
}
/// <summary>
/// * 5、设置2进制物资代码
/// * 位数:36位
/// * 说明:6 - 48位。军事物流信息系统物资代码,转换为十六进制后存储。 我部使用时占用36位
/// * @return
/// </summary>
/// <param name="strBinProductCode"></param>
public void setStrBinProductCode(String strBinProductCode)
{
this.strBinProductCode = strBinProductCode;
}
/// <summary>
/// * 6、取得16进制序列号长度
/// * 位数:1位
/// * 说明:N * 6
/// * 默认:A(十进制为10)
/// * @return
/// </summary>
/// <returns></returns>
public String getStrHexSerialLength()
{
return strHexSerialLength;
}
/// <summary>
/// * 6、设置16进制序列号长度
/// * 位数:1位
/// * 说明:N * 6
/// * 默认:A(十进制为10)
/// * @return
/// </summary>
/// <param name="strHexSerialLength"></param>
public void setStrHexSerialLength(String strHexSerialLength)
{
this.strHexSerialLength = strHexSerialLength;
}
/// <summary>
/// * 6、设置2进制序列号长度
/// * 位数:4位
/// * 说明:N * 6
/// * 默认:A(十进制为10)
/// * @return
/// </summary>
/// <returns></returns>
public String getStrBinSerialLength()
{
return strBinSerialLength;
}
/// <summary>
/// * 6、取得2进制序列号长度
/// * 位数:4位
/// * 说明:N * 6
/// * 默认:A(十进制为10)
/// * @return
/// </summary>
/// <param name="strBinSerialLength"></param>
public void setStrBinSerialLength(String strBinSerialLength)
{
this.strBinSerialLength = strBinSerialLength;
}
/// <summary>
/// * 7、取得16进制版本号
/// * 位数:2位
/// * 说明:版本号
/// * 默认:当前版本号为11
/// * @return
/// </summary>
/// <returns></returns>
public String getStrHexVersion()
{
return strHexVersion;
}
/// <summary>
/// * 7、设置16进制版本号
/// * 位数:2位
/// * 说明:版本号
/// * 默认:当前版本号为11
/// * @return
/// </summary>
/// <param name="strHexVersion"></param>
public void setStrHexVersion(String strHexVersion)
{
this.strHexVersion = strHexVersion;
}
/// <summary>
/// * 7、取得2进制版本号
/// * 位数:8位
/// * 说明:版本号
/// * 默认:当前版本号为00010001
/// * @return
/// </summary>
/// <returns></returns>
public String getStrBinVersion()
{
return strBinVersion;
}
/// <summary>
/// * 7、设置2进制版本号
/// * 位数:8位
/// * 说明:版本号
/// * 默认:当前版本号为00010001
/// * @return
/// </summary>
/// <param name="strBinVersion"></param>
public void setStrBinVersion(String strBinVersion)
{
this.strBinVersion = strBinVersion;
}
/// <summary>
/// * 8、取得16进制标签类型
/// * 位数:1位
/// * 默认:1 箱标签
/// * @return
/// </summary>
/// <returns></returns>
public String getStrHexTagType()
{
return strHexTagType;
}
/// <summary>
/// * 8、设置16进制标签类型
/// * 位数:1位
/// * 默认:1 箱标签
/// * @return
/// </summary>
/// <param name="strHexTagType"></param>
public void setStrHexTagType(String strHexTagType)
{
this.strHexTagType = strHexTagType;
}
/// <summary>
/// * 8、取得2进制标签类型
/// * 位数:4位
/// * 默认:1 箱标签
/// * @return
/// </summary>
/// <returns></returns>
public String getStrBinTagType()
{
return strBinTagType;
}
/// <summary>
/// * 8、设置2进制标签类型
/// * 位数:4位
/// * 默认:1 箱标签
/// * @return
/// </summary>
/// <param name="strBinTagType"></param>
public void setStrBinTagType(String strBinTagType)
{
this.strBinTagType = strBinTagType;
}
/// <summary>
/// * 9、取得16进制包装类型
/// * 位数:1位
/// * 默认:1为外包装, F为零头配箱
/// * @return
/// </summary>
/// <returns></returns>
public String getStrHexPacktype()
{
return strHexPacktype;
}
/// <summary>
/// * 9、设置16进制包装类型
/// * 位数:1位
/// * 默认:1为外包装, F为零头配箱
/// * @return
/// </summary>
/// <param name="strHexPacktype"></param>
public void setStrHexPacktype(String strHexPacktype)
{
this.strHexPacktype = strHexPacktype;
}
/// <summary>
/// * 9、取得2进制包装类型
/// * 位数:4位
/// * 默认:1为外包装, F为零头配箱
/// * @return
/// </summary>
/// <returns></returns>
public String getStrBinPacktype()
{
return strBinPacktype;
}
/// <summary>
/// * 9、设置2进制包装类型
/// * 位数:4位
/// * 默认:1为外包装, F为零头配箱
/// * @param strBinPacktype
/// </summary>
/// <param name="strBinPacktype"></param>
public void setStrBinPacktype(String strBinPacktype)
{
this.strBinPacktype = strBinPacktype;
}
/// <summary>
/// * 10、取得16进制下级包装数
/// * 位数:2位
/// * 默认:0
/// * @return
/// </summary>
/// <returns></returns>
public String getStrHexInsidePackNum()
{
return strHexInsidePackNum;
}
/// <summary>
/// * 10、设置16进制下级包装数
/// * 位数:2位
/// * 默认:0
/// * @param strHexInsidePackNum
/// </summary>
/// <param name="strHexInsidePackNum"></param>
public void setStrHexInsidePackNum(String strHexInsidePackNum)
{
this.strHexInsidePackNum = strHexInsidePackNum;
}
/// <summary>
/// * 10、取得2进制下级包装数
/// * 位数:8位
/// * 默认:0
/// * @return
/// </summary>
/// <returns></returns>
public String getStrBinInsidePackNum()
{
return strBinInsidePackNum;
}
/// <summary>
/// * 10、设置2进制下级包装数
/// * 位数:8位
/// * 默认:0
/// * @param strBinInsidePackNum
/// </summary>
/// <param name="strBinInsidePackNum"></param>
public void setStrBinInsidePackNum(String strBinInsidePackNum)
{
this.strBinInsidePackNum = strBinInsidePackNum;
}
/// <summary>
/// * 11、取得十六进制产品总数量
/// * 位数:3位
/// * 最大:4096
/// * @return
/// </summary>
/// <returns></returns>
public String getStrHexProductNum()
{
return strHexProductNum;
}
/// <summary>
/// * 11、设置十六进制产品总数量
/// * 位数:3位
/// * 最大:4096
/// * @param strHexProductNum
/// </summary>
/// <param name="strHexProductNum"></param>
public void setStrHexProductNum(String strHexProductNum)
{
this.strHexProductNum = strHexProductNum;
}
/// <summary>
/// * 11、取得2进制产品总数量
/// * 位数:12位
/// * 最大:4096
/// * @return
/// </summary>
/// <returns></returns>
public String getStrBinProductNum()
{
return strBinProductNum;
}
/// <summary>
/// * 11、设置2进制产品总数量
/// * 位数:12位
/// * 最大:4096
/// * @param strBinProductNum
/// </summary>
/// <param name="strBinProductNum"></param>
public void setStrBinProductNum(String strBinProductNum)
{
this.strBinProductNum = strBinProductNum;
}
/// <summary>
/// * 12、取得16进制生产线序列号
/// * 位数:1位
/// * 说明:0 - E表示生产线序列号,F表示军需仓库打印的标签
/// * @return
/// </summary>
/// <returns></returns>
public String getStrHexProductLine()
{
return strHexProductLine;
}
/// <summary>
/// * 12、设置16进制生产线序列号
/// * 位数:1位
/// * 说明:0 - E表示生产线序列号,F表示军需仓库打印的标签
/// * @param strHexProductLine
/// </summary>
/// <param name="strHexProductLine"></param>
public void setStrHexProductLine(String strHexProductLine)
{
this.strHexProductLine = strHexProductLine;
}
/// <summary>
/// * 12、取得2进制生产线序列号
/// * 位数:4位
/// * 说明:0 - E表示生产线序列号,F表示军需仓库打印的标签
/// * @return
/// </summary>
/// <returns></returns>
public String getStrBinProductLine()
{
return strBinProductLine;
}
/// <summary>
/// * 12、设置2进制生产线序列号
/// * 位数:4位
/// * 说明:0 - E表示生产线序列号,F表示军需仓库打印的标签
/// * @param strBinProductLine
/// </summary>
/// <param name="strBinProductLine"></param>
public void setStrBinProductLine(String strBinProductLine)
{
this.strBinProductLine = strBinProductLine;
}
/// <summary>
/// * 取得16进制产品箱序列号
/// * 位数:3位
/// * 说明:顺序码,最大4095
/// * @return
/// </summary>
/// <returns></returns>
public String getStrHexPackSerialNo()
{
return strHexPackSerialNo;
}
/// <summary>
/// * 设置16进制产品箱序列号
/// * 位数:3位
/// * 说明:顺序码,最大4095
/// * @param strHexPackSerialNo
/// </summary>
/// <param name="strHexPackSerialNo"></param>
public void setStrHexPackSerialNo(String strHexPackSerialNo)
{
this.strHexPackSerialNo = strHexPackSerialNo;
}
/// <summary>
/// * 取得2进制产品箱序列号
/// * 位数:12位
/// * 说明:顺序码,最大4095
/// * @return
/// </summary>
/// <returns></returns>
public String getStrBinPackSerialNo()
{
return strBinPackSerialNo;
}
/// <summary>
/// * 设置2进制产品箱序列号
/// * 位数:12位
/// * 说明:顺序码,最大4095
/// * @param strBinPackSerialNo
/// </summary>
/// <param name="strBinPackSerialNo"></param>
public void setStrBinPackSerialNo(String strBinPackSerialNo)
{
this.strBinPackSerialNo = strBinPackSerialNo;
}
/// <summary>
/// * 取得16进制级别号码
/// * 位数:1位
/// * 说明: 0表示1张标签
/// * 4表示2张标签中的第一张, 5表示第二张
/// * 8表示4张标签中的第一张, 9表示第二张, 10表示第三张, 11表示第四张
/// * @return
/// </summary>
/// <returns></returns>
public String getStrHexGroupNo()
{
return strHexGroupNo;
}
/// <summary>
/// * 设置16进制级别号码
/// * 位数:1位
/// * 说明: 0表示1张标签
/// * 4表示2张标签中的第一张, 5表示第二张
/// * 8表示4张标签中的第一张, 9表示第二张, 10表示第三张, 11表示第四张
/// * @param strHexGroupNo
/// </summary>
/// <param name="strHexGroupNo"></param>
public void setStrHexGroupNo(String strHexGroupNo)
{
this.strHexGroupNo = strHexGroupNo;
}
/// <summary>
/// * 取得2进制级别号码
/// * 位数:4位
/// * 说明: 0000表示1张标签
/// * 0100表示2张标签中的第一张, 0101表示第二张
/// * 1000表示4张标签中的第一张, 1001表示第二张, 1010表示第三张, 1011表示第四张
/// * @return
/// </summary>
/// <returns></returns>
public String getStrBinGroupNo()
{
return strBinGroupNo;
}
/// <summary>
/// * 设置2进制级别号码
/// * 位数:4位
/// * 说明: 0000表示1张标签
/// * 0100表示2张标签中的第一张, 0101表示第二张
/// * 1000表示4张标签中的第一张, 1001表示第二张, 1010表示第三张, 1011表示第四张
/// * @param strBinGroupNo
/// </summary>
/// <param name="strBinGroupNo"></param>
public void setStrBinGroupNo(String strBinGroupNo)
{
this.strBinGroupNo = strBinGroupNo;
}
/// <summary>
/// * 取得16进制CRC校验码
/// * 位数:1位
/// * 说明:CRC校验
/// * @return
/// </summary>
/// <returns></returns>
public String getStrHexCRCCode()
{
return strHexCRCCode;
}
/// <summary>
/// * 设置16进制CRC校验码
/// * 位数:1位
/// * 说明:CRC校验
/// * @param strHexCRCCode
/// </summary>
/// <param name="strHexCRCCode"></param>
public void setStrHexCRCCode(String strHexCRCCode)
{
this.strHexCRCCode = strHexCRCCode;
}
/// <summary>
/// * 取得2进制CRC校验码
/// * 位数:4位
/// * 说明:CRC校验
/// * @return
/// </summary>
/// <returns></returns>
public String getStrBinCRCCode()
{
return strBinCRCCode;
}
/// <summary>
/// * 设置2进制CRC校验码
/// * 位数:4位
/// * 说明:CRC校验
/// * @param strBinCRCCode
/// </summary>
/// <param name="strBinCRCCode"></param>
public void setStrBinCRCCode(String strBinCRCCode)
{
this.strBinCRCCode = strBinCRCCode;
}
/// <summary>
/// * 取得16进制生产日期
/// * 位数:6位
/// * @return
/// </summary>
/// <returns></returns>
public String getStrHexScrq()
{
return strHexScrq;
}
/// <summary>
/// * 取得2进制生产日期
/// * 位数:24位
/// * @return
/// </summary>
/// <returns></returns>
public String getStrBinScrq()
{
return strBinScrq;
}
/// <summary>
/// * 取得2进制有效期
/// * 位数:4位
/// * @return
/// </summary>
/// <returns></returns>
public string getStrBinYxq()
{
return strBinYxq;
}
/// <summary>
/// * 设置2进制生产日期
/// * 位数:24位
/// * @param strScrq
/// </summary>
/// <param name="strBinScrq"></param>
public void setStrBinScrq(String strBinScrq)
{
this.strBinScrq = strBinScrq;
}
/// <summary>
/// * 设置16进制生产日期
/// * 位数:6位
/// * @param strHexScrq
/// </summary>
/// <param name="strHexScrq"></param>
public void setStrHexScrq(String strHexScrq)
{
this.strHexScrq = strHexScrq;
}
/// <summary>
/// * 16进制转为2进制
/// * @param hexString
/// * @return
/// </summary>
/// <param name="hexString"></param>
/// <returns></returns>
public String HexString2BinString(String hexString)
{
String binString = "";
if (hexString.Length > 0)
{
for (int i = 1; i < hexString.Length + 1; i++)
{
String tempString = "";
//取中间16进制中的一位,转为10进制后,再转为2进制,前导补足4个0
tempString = Convert.ToString(Convert.ToInt64(hexString.Substring(i - 1, 1), 16), 2).PadLeft(4, '0');
binString += tempString;// tempString.Length - 4;
}
}
return binString;
}
/// <summary>
/// * 2进制转为16进制
/// * @param binString
/// * @return
/// </summary>
/// <param name="binString"></param>
/// <returns></returns>
public String BinString2HexString(String binString)
{
String hexString = "";
int hexLength = (int)Math.Ceiling(binString.Length / 4.0);
binString = "0000" + binString;
binString = binString.Substring(binString.Length - (hexLength * 4));
if (binString.Length > 0)
{
for (int i = 0; i < hexLength; i++)
{
String tempString = "";
tempString = binString.Substring(i * 4, 4);
hexString += Convert.ToString(Convert.ToInt32(tempString, 2), 16);
}
}
return hexString;
}
/// <summary>
/// * 取得字符串
/// * 说明:每6位代表一个数字或字母,转换为字符串
/// * @param str6Bin
/// * @return
/// </summary>
/// <param name="str6Bin"></param>
/// <returns></returns>
public String Transform6Bin2Character(String str6Bin)
{
String characterString = "";
int characterLength = (int)Math.Ceiling(str6Bin.Length / 6.0);
str6Bin = "000000" + str6Bin;
str6Bin = str6Bin.Substring(str6Bin.Length - (characterLength * 6));
if (str6Bin.Length > 0)
{
for (int i = 0; i < characterLength; i++)
{
String tempString = "";
tempString = str6Bin.Substring(i * 6, 6);
characterString += strKeyWords.Substring(Convert.ToInt32(tempString, 2), 1);
}
}
return characterString;
}
public String TransformCharacter26Bin(String strCharacterString)
{
//转为大写
strCharacterString = strCharacterString.ToUpper();
String str6BinString = "";
if (strCharacterString.Length > 0)
{
for (int i = 1; i < strCharacterString.Length + 1; i++)
{
String tempString = strCharacterString.Substring(i - 1, 1);
//前面加000000,并在字符串找到字符,转为2进制
tempString = "000000" +
Convert.ToString(
strKeyWords.IndexOf(tempString), 2);
tempString = tempString.Substring(tempString.Length - 6);
str6BinString += tempString;
}
}
return str6BinString;
}
#endregion 方法
#region 生成epc 解析epc
/// <summary>
/// 根据实际EPC分解物资信息
/// </summary>
/// <param name="strHexEpc">十六进制的EPC</param>
public void UnPackEpc(String strHexEpc)
{
//将Epc转为2进制Epc编码
String strBinEpc = this.HexString2BinString(strHexEpc);
//1、取得标头信息
this.strBinHeaderInfo = strBinEpc.Substring(0, 8);
this.strHexHeaderInfo = this.BinString2HexString(this.strBinHeaderInfo);
//被装专用标头信息05
if (this.strBinHeaderInfo.Equals(ProductEpc196.CONSTHEADERINFOBIN))
{
//2、发行机构标识
this.strBinPublishFlag = strBinEpc.Substring(8, 6);
//3、组织机构代码
this.strBinOrgCode = strBinEpc.Substring(14, 54);
this.strOrgCode = this.Transform6Bin2Character(this.strBinOrgCode);
//4、品种代码指示长度
this.strBinProductcodeLength = strBinEpc.Substring(68, 4);
this.strHexProductCodeLength = this.BinString2HexString(this.strBinProductcodeLength);
//转成10进制长度
int iProductCodeLength = Convert.ToInt32(this.strHexProductCodeLength, 16);
//下一位截取操作的起始位
//5、物资代码
// 修改,根据品种代码指示长度,确定物资代码长度
this.strBinProductCode = strBinEpc.Substring(72, iProductCodeLength * 6);
this.strHexProductCode = this.BinString2HexString(this.strBinProductCode);
//6、序列号长度
int iSubStart = 72 + iProductCodeLength * 6;
this.strBinSerialLength = strBinEpc.Substring(iSubStart, 4);
this.strHexSerialLength = this.BinString2HexString(this.strBinSerialLength);
//转为10进制长度
int iSerialLength = Convert.ToInt32(this.strHexSerialLength, 16);
//具体序列号内容
String strSerial = strBinEpc.Substring(iSubStart + 4, iSerialLength * 6);
//7、版本号
this.strBinVersion = strSerial.Substring(0, 8);
this.strHexVersion = this.BinString2HexString(this.strBinVersion);
//根据版本号来判断,进行不同版本的解析
if (strHexVersion.Equals("11"))
{
//8、标签类型
this.strBinTagType = strSerial.Substring(8, 4);
this.strHexTagType = this.BinString2HexString(this.strBinTagType);
//判断当前标签是不是箱标签
if (this.strHexTagType.Equals("1"))
{
//9、包装类型
this.strBinPacktype = strSerial.Substring(12, 4);
this.strHexPacktype = this.BinString2HexString(this.strBinPacktype);
//10、下级包装数
this.strBinInsidePackNum = strSerial.Substring(16, 8);
this.strHexInsidePackNum = this.BinString2HexString(this.strBinInsidePackNum);
//11、产品总数量
this.strBinProductNum = strSerial.Substring(24, 12);
this.strHexProductNum = this.BinString2HexString(this.strBinProductNum);
//12、生产线序列号
this.strBinProductLine = strSerial.Substring(36, 4);
this.strHexProductLine = this.BinString2HexString(this.strBinProductLine);
//13、产品箱序列号
this.strBinPackSerialNo = strSerial.Substring(40, 12);
this.strHexPackSerialNo = this.BinString2HexString(this.strBinPackSerialNo);
//14、级别号码
this.strBinGroupNo = strSerial.Substring(52, 4);
this.strHexGroupNo = this.BinString2HexString(this.strBinGroupNo);
//15、校验码
this.strBinCRCCode = strSerial.Substring(56);
//16、生产日期
this.strBinScrq = strBinEpc.Substring(iSubStart + 4 + iSerialLength * 6);
this.strHexScrq = this.BinString2HexString(this.strBinScrq);
}
else //托盘标签
{
}
}
}
}
/// <summary>
/// 根据物资实际信息生成EPC
/// </summary>
/// <returns></returns>
public String PackEpc()
{
String sb = "";
//1、标头信息
sb += this.strBinHeaderInfo;
//2、发行机构标识
sb += this.strBinPublishFlag;
//3、组织机构代码
//this.setStrOrgCode("000000000" + this.getStrOrgCode());
//this.setStrOrgCode(getStrOrgCode().PadLeft(8, '0')/*/*this.getStrOrgCode().Substring(this.getStrOrgCode().Length - 9)*/*/);
this.setStrBinOrgCode(this.TransformCharacter26Bin(this.getStrOrgCode().PadLeft(9, '0')));
sb += this.getStrBinOrgCode();
//4、物资代码指示长度
sb += this.getStrBinProductcodeLength();
//5、物资代码
//this.setStrHexProductCode("000000000" + this.getStrHexProductCode());
//this.setStrHexProductCode(getStrHexProductCode().PadLeft(9, '0')/*this.getStrHexProductCode().Substring(this.getStrHexProductCode().Length - 9)*/);
this.setStrBinProductCode(this.HexString2BinString(this.getStrHexProductCode().PadLeft(9, '0')));
sb += this.getStrBinProductCode();
//6、序列号长度
sb += this.getStrBinSerialLength();
//7、版本号
sb += this.getStrBinVersion();
//8、标签类型
sb += this.getStrBinTagType();
//9、包装类型
sb += this.getStrBinPacktype();
//生产日期
////this.setStrHexScrq("000000" + this.getStrHexScrq());
//this.setStrHexScrq(this.getStrHexScrq().Substring(this.getStrHexScrq().Length - 6));
this.setStrBinScrq(this.HexString2BinString(this.getStrHexScrq().PadLeft(6, '0')));
sb += this.getStrBinScrq();
//有效期
this.setStrBinScrq(this.HexString2BinString(this.getStrBinYxq().PadLeft(4, '0')));
sb += this.getStrBinYxq();
//10、下级包装数
this.setStrHexInsidePackNum("00" + this.getStrHexInsidePackNum());
this.setStrHexInsidePackNum(this.getStrHexInsidePackNum().Substring(this.getStrHexInsidePackNum().Length - 2));
this.setStrBinInsidePackNum(this.HexString2BinString(this.getStrHexInsidePackNum()));
sb += this.getStrBinInsidePackNum();
//11、产品总数量
this.setStrHexProductNum("000" + this.getStrHexProductNum());
this.setStrHexProductNum(this.getStrHexProductNum().Substring(this.getStrHexProductNum().Length - 3));
this.setStrBinProductNum(this.HexString2BinString(this.getStrHexProductNum()));
sb += this.getStrBinProductNum();
//12、生产线序列号
this.setStrHexProductLine("0" + this.getStrHexProductLine());
this.setStrHexProductLine(this.getStrHexProductLine().Substring(this.getStrHexProductLine().Length - 1));
this.setStrBinProductLine(this.HexString2BinString(this.getStrHexProductLine()));
sb += this.getStrBinProductLine();
//13、产品箱序列号
this.setStrHexPackSerialNo("000" + this.getStrHexPackSerialNo());
this.setStrHexPackSerialNo(this.getStrHexPackSerialNo().Substring(this.getStrHexPackSerialNo().Length - 3));
this.setStrBinPackSerialNo(this.HexString2BinString(this.getStrHexPackSerialNo()));
sb += this.getStrBinPackSerialNo();
//14、组别号码
this.setStrHexGroupNo("0" + this.getStrHexGroupNo());
this.setStrHexGroupNo(this.getStrHexGroupNo().Substring(this.getStrHexGroupNo().Length - 1));
this.setStrBinGroupNo(this.HexString2BinString(this.getStrHexGroupNo()));
sb += this.getStrBinGroupNo();
//取得校验位
String rsstr = GetCRCCode(sb);
//增加校验码
sb += rsstr;
String strRet = "";
if (sb.Length == 196)
{
//System.out.print(sb.toString());
strRet = this.BinString2HexString(sb);
}
return strRet;
}
public static String GetCRCCode(String sb)
{
String tempEpc = sb.ToString();
//取得2进制长度
int sourcecodelength = tempEpc.Length;
//定义取得临时变量
String rsstr = "";
//定义数组,长度为被校验位长度
int[] b = new int[sourcecodelength];
for (int i = 1; i < sourcecodelength + 1; i++)
{
b[i - 1] = int.Parse(tempEpc.Substring(i - 1, 1));
}
MyCRC myCRC = new MyCRC();
int[] rs = myCRC.makeCRCCodes(b, myCRC.index);
for (int i = 0; i < rs.Length; i++)
{
rsstr = rsstr + rs[i];
}
return rsstr.Substring(rsstr.Length - 4);
}
#endregion
}
class MyCRC
{
public int[] index = new int[] { 4, 3, 0 };
public int[] makeCRCCodes(int[] sourceCodes, int[] multinomial)
{
int sourceLength = sourceCodes.Length;
int codesLength = sourceLength + 4;
int[] crcCodes = new int[codesLength];
System.Array.Copy(sourceCodes, 0, crcCodes, 0, sourceLength);
int temp, pos;
// Division system. 除法器。
for (int i = 0; i < sourceLength; i++)
{
// Count value of the input adding the first register.
// 用第i位原码和第一个寄存器值模二加。
temp = (crcCodes[sourceLength] + sourceCodes[i]) % 2;
// Move registers forwards from (1, length) to (0, length - 1).
// 第二个寄存器及以后的所有寄存器值前移1位。
System.Array.Copy(crcCodes, sourceLength + 1, crcCodes,
sourceLength, 3);
// Set the last register with counted value.
// 最后一个寄存器值存放计算好的输入值。
crcCodes[codesLength - 1] = temp;
// Count other registers. 按生成多项式的值算出位置,模二加出该寄存器的值。
for (int j = index.Length - 2; j > 0; j--)
{
pos = codesLength - multinomial[j] - 1;
crcCodes[pos] = (crcCodes[pos] + temp) % 2;
}
}
return crcCodes;
}
public bool checkCRC(int[] crccodes)
{
int checkindex = 0;
for (checkindex = 0; checkindex < crccodes.Length - 4; checkindex++)
{
if (crccodes[checkindex] == 0)
{
;
}
else break;
}
for (; checkindex < crccodes.Length - 4; checkindex++)
{
crccodes[checkindex] = 0;
crccodes[checkindex + 1] = (crccodes[checkindex + 1] + 1) % 2;
crccodes[checkindex + 4] = (crccodes[checkindex + 4] + 1) % 2;
for (int j = checkindex; j < crccodes.Length - 4; j++)
{
if (crccodes[j] == 0)
{
checkindex = j;
}
else break;
}
}
for (int i = 0; i < crccodes.Length; i++)
{
if (crccodes[i] == 1)
return false;
}
return true;
}
}
}
<Window x:Class="JmpZbPrint.Dialog.PrintLogWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:materialDesign="http://materialdesigninxaml.net/winfx/xaml/themes"
xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
xmlns:local="clr-namespace:JmpZbPrint.Dialog" xmlns:convert="clr-namespace:JmpZbPrint.Common" xmlns:UsControl="clr-namespace:JmpZbPrint.UsControl"
mc:Ignorable="d"
Height="768" Width="1366" AllowsTransparency="True" WindowStyle="None"
ResizeMode="NoResize" WindowState="Maximized" WindowStartupLocation="CenterScreen">
<Window.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="pack://application:,,,/MaterialDesignThemes.Wpf;component/Themes/MaterialDesignTheme.TextBox.xaml" />
<ResourceDictionary Source="pack://application:,,,/MaterialDesignThemes.Wpf;component/Themes/MaterialDesignTheme.DataGrid.xaml" />
<ResourceDictionary Source="pack://application:,,,/MaterialDesignThemes.Wpf;component/Themes/MaterialDesignTheme.TextBlock.xaml" />
</ResourceDictionary.MergedDictionaries>
<SolidColorBrush x:Key="PrimaryHueLightBrush" Color="#0093EA"/>
<SolidColorBrush x:Key="PrimaryHueLightForegroundBrush" Color="#FFFFFF"/>
<SolidColorBrush x:Key="PrimaryHueMidBrush" Color="#0093EA"/>
<SolidColorBrush x:Key="PrimaryHueMidForegroundBrush" Color="#FFFFFF"/>
<SolidColorBrush x:Key="PrimaryHueDarkBrush" Color="#0093EA"/>
<SolidColorBrush x:Key="PrimaryHueDarkForegroundBrush" Color="#FFFFFF"/>
<!-- accent -->
<SolidColorBrush x:Key="SecondaryAccentBrush" Color="#0093EA"/>
<SolidColorBrush x:Key="SecondaryAccentForegroundBrush" Color="#FFFFFF"/>
<Storyboard x:Key="Loading">
<ThicknessAnimation Duration="0:0:0.2" To="0" From="0,300,0,300"
Storyboard.TargetName="g_main" Storyboard.TargetProperty="Margin" />
</Storyboard>
<Storyboard x:Key="Closing">
<ThicknessAnimation FillBehavior="Stop" Duration="0:0:0.2" To="0,300,0,300" From="0" Storyboard.TargetName="g_main"
Storyboard.TargetProperty="Margin" Completed="Sb_Completed"/>
</Storyboard>
</ResourceDictionary>
</Window.Resources>
<Window.Effect>
<DropShadowEffect BlurRadius="20" Color="#FF858484" Direction="90" ShadowDepth="2"/>
</Window.Effect>
<Window.Triggers>
<EventTrigger RoutedEvent="FrameworkElement.Loaded" >
<BeginStoryboard Storyboard="{StaticResource Loading}"/>
</EventTrigger>
<EventTrigger RoutedEvent="UIElement.MouseLeftButtonDown" SourceName="tbclose">
<BeginStoryboard Storyboard="{StaticResource Closing}" />
</EventTrigger>
</Window.Triggers>
<i:Interaction.Triggers>
<i:EventTrigger EventName="ContentRendered">
<i:InvokeCommandAction Command="{Binding OnWindowLoadCmd}" />
</i:EventTrigger>
</i:Interaction.Triggers>
<materialDesign:DialogHost Identifier="PrintLogDialog">
<Border BorderBrush="#FF858484" x:Name="g_main" CornerRadius="3" BorderThickness="2" >
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
<RowDefinition Height="70"/>
</Grid.RowDefinitions>
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="80"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<TextBlock x:Name="txtTitle" Text="打印记录" FontSize="30" Foreground="#0092ea" VerticalAlignment="Top" Margin="20 20 0 0"/>
<TextBlock Text="返回" Style="{StaticResource FiconBase}" x:Name="tbclose"
HorizontalAlignment="Right" VerticalAlignment="Top"
Margin="0 20 20 0" FontSize="35" Foreground="#8a8a8a" />
<DataGrid EnableRowVirtualization="False" x:Name="g_vender" Margin="3 5 3 20" Grid.Row="2" BorderBrush="#dedede" FontSize="20" Foreground="#37537d" HeadersVisibility="Column"
GridLinesVisibility="None" Background="Transparent" BorderThickness="1" CanUserAddRows="False"
AutoGenerateColumns="False" SelectionMode="Single" HorizontalScrollBarVisibility="Auto" RowBackground="Transparent" CanUserSortColumns="True"
ItemsSource="{Binding UiPrintInfoList,UpdateSourceTrigger=PropertyChanged}" >
<DataGrid.ColumnHeaderStyle>
<Style TargetType="{x:Type DataGridColumnHeader}">
<Setter Property="BorderThickness" Value="0"/>
<Setter Property="VerticalAlignment" Value="Center"/>
<Setter Property="HorizontalContentAlignment" Value="Center"/>
<Setter Property="Background" Value="Transparent"/>
<Setter Property="Foreground" Value="#4682B4"/>
<Setter Property="FontSize" Value="15"/>
<Setter Property="Height" Value="25"/>
</Style>
</DataGrid.ColumnHeaderStyle>
<DataGrid.RowStyle>
<Style TargetType="{x:Type DataGridRow}">
<Setter Property="Height" Value="45" />
<Style.Triggers>
<Trigger Property="ItemsControl.AlternationIndex" Value="0">
<Setter Property="Background" Value="Transparent"/>
<Setter Property="BorderBrush" Value="Transparent"/>
</Trigger>
<Trigger Property="ItemsControl.AlternationIndex" Value="1">
<Setter Property="Background" Value="#EBEBEB"/>
<Setter Property="Opacity" Value="0.4"/>
</Trigger>
</Style.Triggers>
</Style>
</DataGrid.RowStyle>
<DataGrid.Resources>
<ResourceDictionary>
<convert:IsSuccessConvert x:Key="IsSuccessConv"/>
<convert:LabelTypeConvert x:Key="LabelTypeConv"/>
<convert:DateTimeConverter x:Key="DateTimeConv"/>
</ResourceDictionary>
</DataGrid.Resources>
<DataGrid.Columns>
<DataGridTextColumn Header="ID" IsReadOnly="True" Width="auto" FontSize="18" Visibility="Collapsed" Binding="{Binding Id}" />
<DataGridTextColumn Header="标签类型" IsReadOnly="True" MinWidth="70" Width="auto" FontSize="18" Binding="{Binding isBoxMark,Converter={StaticResource LabelTypeConv}}" ElementStyle="{StaticResource TextCenterStyle}" />
<DataGridTextColumn Header="采购单号" IsReadOnly="True" MinWidth="70" Width="auto" FontSize="18" Binding="{Binding orderCode}" ElementStyle="{StaticResource TextCenterStyle}" />
<DataGridTextColumn Header="装备名称" IsReadOnly="True" MinWidth="70" Width="auto" FontSize="18" Binding="{Binding productName}" ElementStyle="{StaticResource TextCenterStyle}" />
<DataGridTextColumn Header="装备型号" IsReadOnly="True" MinWidth="70" Width="auto" FontSize="18" Binding="{Binding sizeName}" ElementStyle="{StaticResource TextCenterStyle}"/>
<DataGridTextColumn Header="生产日期" IsReadOnly="True" MinWidth="70" Width="auto" FontSize="18" Binding="{Binding productTime}" ElementStyle="{StaticResource TextCenterStyle}"/>
<DataGridTextColumn Header="使用日期" IsReadOnly="True" MinWidth="70" Width="auto" FontSize="18" Binding="{Binding useTime}" ElementStyle="{StaticResource TextCenterStyle}"/>
<DataGridTextColumn Header="质保周期" IsReadOnly="True" MinWidth="70" Width="auto" FontSize="18" Binding="{Binding warrantyCycle}" ElementStyle="{StaticResource TextCenterStyle}"/>
<DataGridTextColumn Header="维保周期" IsReadOnly="True" MinWidth="70" Width="auto" FontSize="18" Binding="{Binding repairCycle}" ElementStyle="{StaticResource TextCenterStyle}"/>
<DataGridTextColumn Header="单价" IsReadOnly="True" MinWidth="70" Width="auto" FontSize="18" Binding="{Binding price}" ElementStyle="{StaticResource TextCenterStyle}"/>
<DataGridTextColumn Header="件序号" IsReadOnly="True" MinWidth="70" Width="auto" FontSize="18" Binding="{Binding pieceNo}" ElementStyle="{StaticResource TextCenterStyle}"/>
<DataGridTextColumn Header="箱内数量" IsReadOnly="True" MinWidth="70" Width="auto" FontSize="18" Binding="{Binding oneBoxNum}" ElementStyle="{StaticResource TextCenterStyle}"/>
<DataGridTextColumn Header="供应商" IsReadOnly="True" MinWidth="70" Width="auto" FontSize="18" Binding="{Binding supplierName}" ElementStyle="{StaticResource TextCenterStyle}" />
<DataGridTextColumn Header="入库仓库" IsReadOnly="True" MinWidth="70" Width="auto" FontSize="18" Binding="{Binding warehouseName}" ElementStyle="{StaticResource TextCenterStyle}" />
<DataGridTextColumn Header="打印结果" IsReadOnly="True" MinWidth="70" Width="auto" FontSize="18" Binding="{Binding IsSuccess,Converter={StaticResource IsSuccessConv}}" ElementStyle="{StaticResource TextCenterStyle}" />
<DataGridTextColumn Header="打印时间" IsReadOnly="True" MinWidth="70" Width="auto" FontSize="18" Binding="{Binding CreateTime,Converter={StaticResource DateTimeConv}, ConverterParameter='yyyy-MM-dd HH:mm:ss' }" ElementStyle="{StaticResource TextCenterStyle}" />
<DataGridTemplateColumn Header="操作" Width="70" >
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal" VerticalAlignment="Center" HorizontalAlignment="Center">
<Button Content="补打" Click="OnSelectItemClick" Height="30" Margin="5,0,5,0" >
</Button>
</StackPanel>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
</Grid>
<UsControl:PageControl IsEnabled="{Binding StartButton}" x:Name="d_pager" Margin="3,0,3,0" Grid.Row="1" TotalRecord="{Binding TotalRecord,Mode=TwoWay}" TotalPage="{Binding PageTotal,Mode=TwoWay}" PageSize="{Binding PageSize,Mode=TwoWay}" PageIndex="{Binding PageIndex,Mode=TwoWay}">
<i:Interaction.Triggers>
<i:EventTrigger EventName="OnPageChanged">
<i:InvokeCommandAction Command="{Binding OnPageChangeCmd}" />
</i:EventTrigger>
</i:Interaction.Triggers>
</UsControl:PageControl>
</Grid>
</Border>
</materialDesign:DialogHost>
</Window>
using JmpZbModel;
using JmpZbPrint.Model;
using JmpZbPrint.UsControl;
using JmpZbPrint.ViewModel;
using MaterialDesignThemes.Wpf;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Windows.Threading;
using JmpZbPrint.View;
namespace JmpZbPrint.Dialog
{
/// <summary>
/// PrintLogWindow.xaml 的交互逻辑
/// </summary>
public partial class PrintLogWindow : Window
{
public PrintLog PrintInfo { get; set; }
private MainWindow _window;
public PrintLogWindow(MainWindow window)
{
InitializeComponent();
_window = window;
var vm2 = new PrintLogWindowViewModel();
this.DataContext = vm2;
}
private void Sb_Completed(object sender, EventArgs e)
{
this.Close();
}
private void OnSelectItemClick(object sender, RoutedEventArgs e)
{
var tsk_item = g_vender.SelectedValue as PrintLog;
var res = _window.printServerHelper.SendPrintCmd(new SingleInfo()
{
Info1 = tsk_item.productName,
Info2 = tsk_item.sizeName,
Info3 = tsk_item.supplierName,
Info4 = tsk_item.pieceNo ?? "1",
Info5 = tsk_item.productTime,
Info9 = tsk_item.epc.Replace(" ", ""),
ModelType = "piece"
});
if (res)
{
MessageBox.Show("打印成功");
}
else
{
MessageBox.Show("打印失败");
}
}
}
}
<Window x:Class="JmpZbPrint.Dialog.SelectBoxEpc"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:materialDesign="http://materialdesigninxaml.net/winfx/xaml/themes"
xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
xmlns:local="clr-namespace:JmpZbPrint.Dialog"
mc:Ignorable="d"
Height="400" Width="920" AllowsTransparency="True" WindowStyle="None"
ResizeMode="NoResize" WindowStartupLocation="CenterScreen" Closing="Window_Closing">
<Window.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="pack://application:,,,/MaterialDesignThemes.Wpf;component/Themes/MaterialDesignTheme.TextBox.xaml" />
<ResourceDictionary Source="pack://application:,,,/MaterialDesignThemes.Wpf;component/Themes/MaterialDesignTheme.DataGrid.xaml" />
<ResourceDictionary Source="pack://application:,,,/MaterialDesignThemes.Wpf;component/Themes/MaterialDesignTheme.TextBlock.xaml" />
</ResourceDictionary.MergedDictionaries>
<SolidColorBrush x:Key="PrimaryHueLightBrush" Color="#0093EA"/>
<SolidColorBrush x:Key="PrimaryHueLightForegroundBrush" Color="#FFFFFF"/>
<SolidColorBrush x:Key="PrimaryHueMidBrush" Color="#0093EA"/>
<SolidColorBrush x:Key="PrimaryHueMidForegroundBrush" Color="#FFFFFF"/>
<SolidColorBrush x:Key="PrimaryHueDarkBrush" Color="#0093EA"/>
<SolidColorBrush x:Key="PrimaryHueDarkForegroundBrush" Color="#FFFFFF"/>
<!-- accent -->
<SolidColorBrush x:Key="SecondaryAccentBrush" Color="#0093EA"/>
<SolidColorBrush x:Key="SecondaryAccentForegroundBrush" Color="#FFFFFF"/>
<Storyboard x:Key="Loading">
<ThicknessAnimation Duration="0:0:0.2" To="0" From="0,300,0,300"
Storyboard.TargetName="g_main" Storyboard.TargetProperty="Margin" />
</Storyboard>
<Storyboard x:Key="Closing">
<ThicknessAnimation FillBehavior="Stop" Duration="0:0:0.2" To="0,300,0,300" From="0" Storyboard.TargetName="g_main"
Storyboard.TargetProperty="Margin" Completed="Sb_Completed"/>
</Storyboard>
</ResourceDictionary>
</Window.Resources>
<Window.Effect>
<DropShadowEffect BlurRadius="20" Color="#FF858484" Direction="90" ShadowDepth="2"/>
</Window.Effect>
<Window.Triggers>
<EventTrigger RoutedEvent="FrameworkElement.Loaded" >
<BeginStoryboard Storyboard="{StaticResource Loading}"/>
</EventTrigger>
<EventTrigger RoutedEvent="UIElement.MouseLeftButtonDown" SourceName="tbclose">
<BeginStoryboard Storyboard="{StaticResource Closing}" />
</EventTrigger>
</Window.Triggers>
<Border BorderBrush="#FF858484" x:Name="g_main" CornerRadius="3" BorderThickness="2" >
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="80"/>
<RowDefinition Height="50"/>
<RowDefinition Height="*"/>
<RowDefinition Height="50"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<TextBlock x:Name="txtTitle" Text="选择箱标" FontSize="30" Foreground="#0092ea" VerticalAlignment="Top" Margin="20 20 0 0"/>
<TextBlock Text="&#xE618;" Style="{StaticResource FiconBase}" x:Name="tbclose"
HorizontalAlignment="Right" VerticalAlignment="Top"
Margin="0 20 20 0" FontSize="35" Foreground="#8a8a8a" />
<Grid Grid.Row="1" Margin="0,0,0,0" >
<Grid.ColumnDefinitions>
<ColumnDefinition Width="10"/>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="20"/>
<ColumnDefinition Width="75"/>
<ColumnDefinition Width="75"/>
</Grid.ColumnDefinitions>
<StackPanel Grid.Column="1" Orientation="Horizontal">
<TextBlock Text="箱标:" FontSize="15" HorizontalAlignment="Center" VerticalAlignment="Center"/>
<TextBox x:Name="txt_vendor" Focusable="True" MinWidth="600" VerticalAlignment="Center" Width="250" FontSize="15" Background="White" />
</StackPanel>
<StackPanel Grid.Column="3" Orientation="Horizontal">
<Button FontSize="15" Content="查询" Click="OnQueryClick" VerticalAlignment="Center" Style="{StaticResource MaterialDesignRaisedButton}" Margin="0,0,0,0" Width="70" HorizontalAlignment="Left" />
</StackPanel>
<StackPanel Grid.Column="4" Orientation="Horizontal">
<Button FontSize="15" Content="重置" Click="OnClearQueryClick" VerticalAlignment="Center" Style="{StaticResource MaterialDesignRaisedButton}" Margin="0,0,0,0" Width="70" HorizontalAlignment="Left" Background="#FFFFCC00"/>
</StackPanel>
</Grid>
<DataGrid EnableRowVirtualization="False" x:Name="g_equ" Margin="3 5 3 5" Grid.Row="2" BorderBrush="#dedede" FontSize="20" Foreground="#37537d" HeadersVisibility="Column"
GridLinesVisibility="None" Background="Transparent" BorderThickness="1" CanUserAddRows="False"
AutoGenerateColumns="False" SelectionMode="Single" HorizontalScrollBarVisibility="Hidden" RowBackground="Transparent" CanUserSortColumns="True" >
<DataGrid.ColumnHeaderStyle>
<Style TargetType="{x:Type DataGridColumnHeader}">
<Setter Property="BorderThickness" Value="0"/>
<Setter Property="VerticalAlignment" Value="Center"/>
<Setter Property="HorizontalContentAlignment" Value="Center"/>
<Setter Property="Background" Value="Transparent"/>
<Setter Property="Foreground" Value="#4682B4"/>
<Setter Property="FontSize" Value="15"/>
<Setter Property="Height" Value="25"/>
</Style>
</DataGrid.ColumnHeaderStyle>
<DataGrid.RowStyle>
<Style TargetType="{x:Type DataGridRow}">
<Setter Property="Height" Value="45" />
<Style.Triggers>
<Trigger Property="ItemsControl.AlternationIndex" Value="0">
<Setter Property="Background" Value="Transparent"/>
<Setter Property="BorderBrush" Value="Transparent"/>
</Trigger>
<Trigger Property="ItemsControl.AlternationIndex" Value="1">
<Setter Property="Background" Value="#EBEBEB"/>
<Setter Property="Opacity" Value="0.4"/>
</Trigger>
</Style.Triggers>
</Style>
</DataGrid.RowStyle>
<DataGrid.Columns>
<DataGridTextColumn Header="箱标" IsReadOnly="True" Width="200" FontSize="13" Binding="{Binding epc}" ElementStyle="{StaticResource TextLeftStyle}"/>
<DataGridTextColumn Header="打印时间" IsReadOnly="True" Width="140" FontSize="13" Binding="{Binding createTime, StringFormat='yyyy-MM-dd HH:mm'}" ElementStyle="{StaticResource TextLeftStyle}"/>
<DataGridTextColumn Header="仓库" IsReadOnly="True" Width="150" FontSize="13" Binding="{Binding warehouseName}" ElementStyle="{StaticResource TextLeftStyle}"/>
<DataGridTextColumn Header="装备名称" IsReadOnly="True" Width="100" FontSize="13" Binding="{Binding equipmentDetailName}" ElementStyle="{StaticResource TextLeftStyle}"/>
<DataGridTextColumn Header="装备型号" IsReadOnly="True" Width="100" FontSize="13" Binding="{Binding sizeName}" ElementStyle="{StaticResource TextLeftStyle}"/>
<DataGridTextColumn Header="数量/件" IsReadOnly="True" Width="50" FontSize="13" Binding="{Binding oneBoxNum}" ElementStyle="{StaticResource TextLeftStyle}"/>
<DataGridTemplateColumn Header="操作" Width="170" >
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal" VerticalAlignment="Center" HorizontalAlignment="Center">
<Button Content="拆箱" Click="OnSelectItemClick" Height="30" Margin="5,0,5,0" ></Button>
<Button Visibility="{Binding DataContext.Visibility,Source={x:Reference g_main}}" Content="报废" Click="OnScrapBoxClick" Height="30" Background="Red" Margin="5,0,5,0" ></Button>
</StackPanel>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
<Grid Grid.Row="3" Margin="0,0,0,0" >
<TextBlock FontSize="24" Width="600" HorizontalAlignment="Left" Text="{Binding UiMessage}" Foreground="{Binding MsgColor}" Style="{StaticResource MaterialDesignHeadline4TextBlock}" VerticalAlignment="Center" Margin="20,0,0,0"></TextBlock>
<Button IsEnabled="{Binding BindButton}" FontSize="15" Content="读取" Click="OnReadClick" VerticalAlignment="Center" Style="{StaticResource MaterialDesignRaisedButton}" Margin="0,0,20,0" Width="70" HorizontalAlignment="Right" />
<Button Visibility="{Binding Visibility}" FontSize="12" Content="导入旧箱标" Click="ImportOldDataClick" VerticalAlignment="Center" Style="{StaticResource MaterialDesignRaisedButton}" Margin="0,0,100,0" Width="100" HorizontalAlignment="Right" Background="#FFEA2000" />
</Grid>
</Grid>
</Border>
</Window>
using JmpZbPrint.Model;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Windows.Threading;
using JmpZbModel;
using JmpZbPrint.Common;
using Newtonsoft.Json;
using WebSocketSharp;
namespace JmpZbPrint.Dialog
{
/// <summary>
/// SupplierWin.xaml 的交互逻辑
/// </summary>
public partial class SelectBoxEpc : Window
{
private class UiMessageData : INotifyPropertyChanged
{
private string _UiMessage = "状态:初始化设备连接准备中";
private string _MsgColor = "Green";
private bool _BindButton = false;
private Visibility _Visibility = Visibility.Collapsed;
public string UiMessage
{
get => _UiMessage;
set
{
_UiMessage = value;
OnPropertyChanged("UiMessage");
}
}
public string MsgColor
{
get => _MsgColor;
set
{
_MsgColor = value;
OnPropertyChanged("MsgColor");
}
}
public bool BindButton
{
get => _BindButton;
set
{
_BindButton = value;
OnPropertyChanged("BindButton");
}
}
public Visibility Visibility
{
get => _Visibility;
set
{
_Visibility = value;
OnPropertyChanged("Visibility");
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string strPropertyInfo)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(strPropertyInfo));
}
}
}
private UiMessageData uiMessageData = new UiMessageData();
private AutoResetEvent resetEvent = new AutoResetEvent(false);
public List<respone_boxMark> infoList { get; set; } = new List<respone_boxMark>();
public SelectBoxEpc(bool isInternal = false)
{
InitializeComponent();
uiMessageData.Visibility = isInternal ? Visibility.Visible : Visibility.Collapsed;
infoList = HttpHelper.GetBoxMarkList(CaChe.UserInfo.baseJpOrganization.id, "", out string msg).Item2;
g_equ.ItemsSource = infoList;
txt_vendor.Focus();
InitWs();
this.DataContext = uiMessageData;
}
public respone_boxMark RecodeInfo { get; set; }
private void Sb_Completed(object sender, EventArgs e)
{
this.Close();
}
private void OnQueryClick(object sender, RoutedEventArgs e)
{
infoList = HttpHelper.GetBoxMarkList(CaChe.UserInfo.baseJpOrganization.id, "", out string msg).Item2;
if (string.IsNullOrEmpty(txt_vendor.Text))
{
g_equ.ItemsSource = infoList;
}
else
{
g_equ.ItemsSource = infoList?.Where(t => t.epc.Contains(txt_vendor.Text) || t.oldEpc == txt_vendor.Text).ToList();
}
}
private void OnClearQueryClick(object sender, RoutedEventArgs e)
{
txt_vendor.Text = "";
OnQueryClick(null, null);
}
private void OnSelectItemClick(object sender, RoutedEventArgs e)
{
var info = g_equ.SelectedValue as respone_boxMark;
if (MessageBox.Show($"确认拆箱:{info.epc}?", "提示", MessageBoxButton.YesNo, MessageBoxImage.Question) ==
MessageBoxResult.Yes)
{
RecodeInfo = info;
this.Close();
}
}
private void OnScrapBoxClick(object sender, RoutedEventArgs e)
{
var info = g_equ.SelectedValue as respone_boxMark;
if (MessageBox.Show($"确认报废:{info.epc}?该操作无法撤销", "警告", MessageBoxButton.YesNo, MessageBoxImage.Question) ==
MessageBoxResult.Yes)
{
//报废该箱标对应物资
var res = HttpHelper.DeleteEpcList(info.epc, out string msg);
if (!res)
{
MessageBox.Show("报废失败:" + msg);
return;
}
//全部报废成功,删除箱标
LiteDbHelper.DeleteByEpc(info.epc);
MessageBox.Show("报废成功");
OnQueryClick(null, null);
}
}
private void OnReadClick(object sender, RoutedEventArgs e)
{
SendInitialMsg();
}
private void ImportOldDataClick(object sender, RoutedEventArgs e)
{
if (MessageBox.Show($"是否导入旧箱标数据?", "警告", MessageBoxButton.YesNo, MessageBoxImage.Question) ==
MessageBoxResult.Yes)
{
var list = LiteDbHelper.GetPage(1, 9999,
x => x.LabelType == "箱标" && x.epc.Length == 24 && x.IsImported != true)?.record;
if (list == null || list.Count == 0)
{
MessageBox.Show("无需导入的数据");
}
else
{
var res = HttpHelper.ImportOldBoxMark(list, out string msg);
if (res.Item1)
{
foreach (var successDetail in res.Item2.successList)
{
var data = LiteDbHelper.GetSingleByEpc(successDetail.epc);
data.IsImported = true;
LiteDbHelper.Update(data);
}
}
MessageBox.Show(msg);
}
}
}
private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
wsConn.Close();
cWsServiceToken.Cancel();
}
#region tcp method
private CancellationTokenSource cWsServiceToken;
private Task taskWsService;
private WebSocket wsConn;
private ManualResetEvent resetUhf = new ManualResetEvent(true);
private void InitWs()
{
if (taskWsService == null)
{
cWsServiceToken = new CancellationTokenSource();
taskWsService = new Task(() =>
{
wsConn = new WebSocket("ws://127.0.0.1:8081");
while (!cWsServiceToken.IsCancellationRequested)
{
try
{
// 已连接的不处理
if (wsConn.IsAlive)
{
}
else
{
// 接收数据
wsConn.OnMessage += (sender, e) =>
{
ReciveWsMsg(e.Data);
};
// 服务关闭
wsConn.OnClose += (sender, e) =>
{
uiMessageData.UiMessage = $"状态:服务已断开,重连中";
uiMessageData.MsgColor = "Red";
uiMessageData.BindButton = false;
};
wsConn.OnOpen += (sender, e) =>
{
uiMessageData.UiMessage = $"状态:正在查询设备状态";
uiMessageData.MsgColor = "Green";
uiMessageData.BindButton = true;
};
// 服务连接
wsConn.Connect();
}
}
catch (System.Exception ex)
{
uiMessageData.UiMessage = $"状态:初始化设备连接失败";
uiMessageData.MsgColor = "Red";
uiMessageData.BindButton = false;
Log.ErrorLog(ex.ToString(), this.GetType().Name);
}
if (resetEvent.WaitOne(3000)) { break; }
}
});
taskWsService.Start();
}
}
private void ReciveWsMsg(string msg)
{
var cmdInfo = JsonConvert.DeserializeObject<InitializeCmdInfo>(msg);
switch (cmdInfo.CmdType)
{
case JmpUhfService.InitializeCmdType.Busy:
uiMessageData.UiMessage = $"状态:设备正忙,请检查设备是否被占用";
uiMessageData.MsgColor = "Red";
uiMessageData.BindButton = false;
resetUhf.Set();
break;
//case JmpUhfService.InitializeCmdType.Initialize:
// if (msg.Contains("成功"))
// {
// //绑定
// }
// else
// {
// BindButton = true;
// UiMessage = $"状态:{cmdInfo.Content}";
// MsgColor = "Red";
// resetUhf.Set();
// }
// break;
case JmpUhfService.InitializeCmdType.InventoryInfo:
{
Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Normal, (Action)delegate ()
{
txt_vendor.Text = cmdInfo.Content;
OnQueryClick(null, null);
});
uiMessageData.UiMessage = $"状态:读取EPC成功";
uiMessageData.MsgColor = "Green";
resetUhf.Set();
uiMessageData.BindButton = true;
break;
}
case JmpUhfService.InitializeCmdType.Linked:
uiMessageData.UiMessage = $"状态:初始化设备已连接";
uiMessageData.MsgColor = "Green";
resetUhf.Set();
uiMessageData.BindButton = true;
break;
case JmpUhfService.InitializeCmdType.ErrorMsg:
uiMessageData.UiMessage = $"状态:{cmdInfo.Content}";
uiMessageData.MsgColor = "Red";
resetUhf.Set();
uiMessageData.BindButton = false;
break;
default:
resetUhf.Set();
break;
}
}
private void SendInitialMsg()
{
try
{
var json = JsonConvert.SerializeObject(new
{
CmdType = 0,
Content = ""
});
if (wsConn?.IsAlive ?? false)
{
uiMessageData.UiMessage = $"状态:读取EPC中";
uiMessageData.MsgColor = "DarkOrange";
resetUhf.Set();
uiMessageData.BindButton = false;
wsConn.Send(json);
Task.Run(() =>
{
Thread.Sleep(1000);
wsConn.Send(JsonConvert.SerializeObject(new
{
CmdType = 1,
Content = ""
}));
if (uiMessageData.UiMessage == "状态:读取EPC中")
{
uiMessageData.UiMessage = $"状态:未读取到EPC";
uiMessageData.MsgColor = "Red";
resetUhf.Set();
uiMessageData.BindButton = true;
}
});
}
}
catch (Exception ex)
{
Log.ErrorLog(ex.ToString(), MethodBase.GetCurrentMethod().Name);
}
}
#endregion
}
}
<Window x:Class="JmpZbPrint.Dialog.SelectEqu"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:materialDesign="http://materialdesigninxaml.net/winfx/xaml/themes"
xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
xmlns:local="clr-namespace:JmpZbPrint.Dialog"
mc:Ignorable="d"
Height="350" Width="600" AllowsTransparency="True" WindowStyle="None"
ResizeMode="NoResize" WindowStartupLocation="CenterScreen">
<Window.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="pack://application:,,,/MaterialDesignThemes.Wpf;component/Themes/MaterialDesignTheme.TextBox.xaml" />
<ResourceDictionary Source="pack://application:,,,/MaterialDesignThemes.Wpf;component/Themes/MaterialDesignTheme.DataGrid.xaml" />
<ResourceDictionary Source="pack://application:,,,/MaterialDesignThemes.Wpf;component/Themes/MaterialDesignTheme.TextBlock.xaml" />
</ResourceDictionary.MergedDictionaries>
<SolidColorBrush x:Key="PrimaryHueLightBrush" Color="#0093EA"/>
<SolidColorBrush x:Key="PrimaryHueLightForegroundBrush" Color="#FFFFFF"/>
<SolidColorBrush x:Key="PrimaryHueMidBrush" Color="#0093EA"/>
<SolidColorBrush x:Key="PrimaryHueMidForegroundBrush" Color="#FFFFFF"/>
<SolidColorBrush x:Key="PrimaryHueDarkBrush" Color="#0093EA"/>
<SolidColorBrush x:Key="PrimaryHueDarkForegroundBrush" Color="#FFFFFF"/>
<!-- accent -->
<SolidColorBrush x:Key="SecondaryAccentBrush" Color="#0093EA"/>
<SolidColorBrush x:Key="SecondaryAccentForegroundBrush" Color="#FFFFFF"/>
<Storyboard x:Key="Loading">
<ThicknessAnimation Duration="0:0:0.2" To="0" From="0,300,0,300"
Storyboard.TargetName="g_main" Storyboard.TargetProperty="Margin" />
</Storyboard>
<Storyboard x:Key="Closing">
<ThicknessAnimation FillBehavior="Stop" Duration="0:0:0.2" To="0,300,0,300" From="0" Storyboard.TargetName="g_main"
Storyboard.TargetProperty="Margin" Completed="Sb_Completed"/>
</Storyboard>
</ResourceDictionary>
</Window.Resources>
<Window.Effect>
<DropShadowEffect BlurRadius="20" Color="#FF858484" Direction="90" ShadowDepth="2"/>
</Window.Effect>
<Window.Triggers>
<EventTrigger RoutedEvent="FrameworkElement.Loaded" >
<BeginStoryboard Storyboard="{StaticResource Loading}"/>
</EventTrigger>
<EventTrigger RoutedEvent="UIElement.MouseLeftButtonDown" SourceName="tbclose">
<BeginStoryboard Storyboard="{StaticResource Closing}" />
</EventTrigger>
</Window.Triggers>
<Border BorderBrush="#FF858484" x:Name="g_main" CornerRadius="3" BorderThickness="2" >
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="80"/>
<RowDefinition Height="50"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<TextBlock x:Name="txtTitle" Text="选择装备信息" FontSize="30" Foreground="#0092ea" VerticalAlignment="Top" Margin="20 20 0 0"/>
<TextBlock Text="&#xE618;" Style="{StaticResource FiconBase}" x:Name="tbclose"
HorizontalAlignment="Right" VerticalAlignment="Top"
Margin="0 20 20 0" FontSize="35" Foreground="#8a8a8a" />
<Grid Grid.Row="1" Margin="0,0,0,0" >
<Grid.ColumnDefinitions>
<ColumnDefinition Width="10"/>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="20"/>
<ColumnDefinition Width="100"/>
</Grid.ColumnDefinitions>
<StackPanel Grid.Column="1" Orientation="Horizontal">
<TextBlock Text="装备名称:" FontSize="15" HorizontalAlignment="Center" VerticalAlignment="Center"/>
<TextBox x:Name="txt_vendor" Focusable="True" Text="{Binding VendorName,UpdateSourceTrigger=PropertyChanged}" MinWidth="400" VerticalAlignment="Center" Width="250" FontSize="15" Background="White" />
</StackPanel>
<StackPanel Grid.Column="3" Orientation="Horizontal">
<Button FontSize="15" Content="查询" Click="OnQueryClick" VerticalAlignment="Center" Style="{StaticResource MaterialDesignRaisedButton}" Margin="0,0,0,0" Width="70" HorizontalAlignment="Left" />
</StackPanel>
</Grid>
<DataGrid EnableRowVirtualization="False" x:Name="g_equ" Margin="3 5 3 20" Grid.Row="2" BorderBrush="#dedede" FontSize="20" Foreground="#37537d" HeadersVisibility="Column"
GridLinesVisibility="None" Background="Transparent" BorderThickness="1" CanUserAddRows="False"
AutoGenerateColumns="False" SelectionMode="Single" HorizontalScrollBarVisibility="Hidden" RowBackground="Transparent" CanUserSortColumns="True" >
<DataGrid.ColumnHeaderStyle>
<Style TargetType="{x:Type DataGridColumnHeader}">
<Setter Property="BorderThickness" Value="0"/>
<Setter Property="VerticalAlignment" Value="Center"/>
<Setter Property="HorizontalContentAlignment" Value="Center"/>
<Setter Property="Background" Value="Transparent"/>
<Setter Property="Foreground" Value="#4682B4"/>
<Setter Property="FontSize" Value="15"/>
<Setter Property="Height" Value="25"/>
</Style>
</DataGrid.ColumnHeaderStyle>
<DataGrid.RowStyle>
<Style TargetType="{x:Type DataGridRow}">
<Setter Property="Height" Value="45" />
<Style.Triggers>
<Trigger Property="ItemsControl.AlternationIndex" Value="0">
<Setter Property="Background" Value="Transparent"/>
<Setter Property="BorderBrush" Value="Transparent"/>
</Trigger>
<Trigger Property="ItemsControl.AlternationIndex" Value="1">
<Setter Property="Background" Value="#EBEBEB"/>
<Setter Property="Opacity" Value="0.4"/>
</Trigger>
</Style.Triggers>
</Style>
</DataGrid.RowStyle>
<DataGrid.Columns>
<DataGridTextColumn Header="装备名称" IsReadOnly="True" Width="480" FontSize="13" Binding="{Binding name}" ElementStyle="{StaticResource TextLeftStyle}"/>
<DataGridTemplateColumn Header="操作" Width="100" >
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal" VerticalAlignment="Center" HorizontalAlignment="Center">
<Button Content="选择" Click="OnSelectItemClick" Height="30" Margin="5,0,5,0" >
</Button>
</StackPanel>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
</Grid>
</Border>
</Window>
using JmpZbPrint.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
namespace JmpZbPrint.Dialog
{
/// <summary>
/// SupplierWin.xaml 的交互逻辑
/// </summary>
public partial class SelectEqu : Window
{
public List<EquInfo> EquList { get; set; } = new List<EquInfo>();
public SelectEqu()
{
InitializeComponent();
EquList = HttpHelper.GetAllEqu();
g_equ.ItemsSource = EquList?.Take(30);
txt_vendor.Focus();
}
public EquInfo EquInfo { get; set; }
private void Sb_Completed(object sender, EventArgs e)
{
this.Close();
}
private void OnQueryClick(object sender, RoutedEventArgs e)
{
if (string.IsNullOrEmpty(txt_vendor.Text))
{
g_equ.ItemsSource = EquList;
}
else
{
g_equ.ItemsSource = EquList?.Where(t => t.name.Contains(txt_vendor.Text));
}
}
private void OnSelectItemClick(object sender, RoutedEventArgs e)
{
EquInfo = g_equ.SelectedValue as EquInfo;
this.Close();
}
}
}
<Window x:Class="JmpZbPrint.Dialog.ShelfWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:materialDesign="http://materialdesigninxaml.net/winfx/xaml/themes"
xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
xmlns:local="clr-namespace:JmpZbPrint.Dialog"
mc:Ignorable="d"
Height="370" Width="550" AllowsTransparency="True" WindowStyle="None"
ResizeMode="NoResize" WindowStartupLocation="CenterScreen">
<Window.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="pack://application:,,,/MaterialDesignThemes.Wpf;component/Themes/MaterialDesignTheme.TextBox.xaml" />
<ResourceDictionary Source="pack://application:,,,/MaterialDesignThemes.Wpf;component/Themes/MaterialDesignTheme.DataGrid.xaml" />
<ResourceDictionary Source="pack://application:,,,/MaterialDesignThemes.Wpf;component/Themes/MaterialDesignTheme.TextBlock.xaml" />
</ResourceDictionary.MergedDictionaries>
<SolidColorBrush x:Key="PrimaryHueLightBrush" Color="#0093EA"/>
<SolidColorBrush x:Key="PrimaryHueLightForegroundBrush" Color="#FFFFFF"/>
<SolidColorBrush x:Key="PrimaryHueMidBrush" Color="#0093EA"/>
<SolidColorBrush x:Key="PrimaryHueMidForegroundBrush" Color="#FFFFFF"/>
<SolidColorBrush x:Key="PrimaryHueDarkBrush" Color="#0093EA"/>
<SolidColorBrush x:Key="PrimaryHueDarkForegroundBrush" Color="#FFFFFF"/>
<!-- accent -->
<SolidColorBrush x:Key="SecondaryAccentBrush" Color="#0093EA"/>
<SolidColorBrush x:Key="SecondaryAccentForegroundBrush" Color="#FFFFFF"/>
<Storyboard x:Key="Loading">
<ThicknessAnimation Duration="0:0:0.2" To="0" From="0,300,0,300"
Storyboard.TargetName="g_main" Storyboard.TargetProperty="Margin" />
</Storyboard>
<Storyboard x:Key="Closing">
<ThicknessAnimation FillBehavior="Stop" Duration="0:0:0.2" To="0,300,0,300" From="0" Storyboard.TargetName="g_main"
Storyboard.TargetProperty="Margin" Completed="Sb_Completed"/>
</Storyboard>
</ResourceDictionary>
</Window.Resources>
<Window.Effect>
<DropShadowEffect BlurRadius="20" Color="#FF858484" Direction="90" ShadowDepth="2"/>
</Window.Effect>
<Window.Triggers>
<EventTrigger RoutedEvent="FrameworkElement.Loaded" >
<BeginStoryboard Storyboard="{StaticResource Loading}"/>
</EventTrigger>
<EventTrigger RoutedEvent="UIElement.MouseLeftButtonDown" SourceName="tbclose">
<BeginStoryboard Storyboard="{StaticResource Closing}" />
</EventTrigger>
</Window.Triggers>
<Border BorderBrush="#FF858484" x:Name="g_main" CornerRadius="3" BorderThickness="2" >
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="80"/>
<RowDefinition Height="45"/>
<RowDefinition Height="45"/>
<RowDefinition Height="45"/>
<RowDefinition Height="60"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="10"/>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="10"/>
</Grid.ColumnDefinitions>
<TextBlock Grid.Row="0" Grid.Column="1" x:Name="txtTitle" Text="选择供应商信息" FontSize="30" Foreground="#0092ea" VerticalAlignment="Top" Margin="20 20 0 0"/>
<TextBlock Grid.Row="0" Grid.Column="1" Text="&#xE618;" Style="{StaticResource FiconBase}" x:Name="tbclose"
HorizontalAlignment="Right" VerticalAlignment="Top"
Margin="0 20 20 0" FontSize="35" Foreground="#8a8a8a" />
<StackPanel Grid.Row="1" Grid.Column="1" Orientation="Horizontal">
<TextBlock Text="入库仓库:" Width="120" TextAlignment="Right" FontSize="16" HorizontalAlignment="Center" VerticalAlignment="Center"/>
<TextBlock Name="tbWarehouse" Text="仓库AAAAAAA" Width="380" TextAlignment="Left" FontSize="16" HorizontalAlignment="Center" VerticalAlignment="Center"/>
</StackPanel>
<StackPanel Grid.Row="2" Grid.Column="1" Orientation="Horizontal">
<TextBlock Text="入库货架:" Width="120" TextAlignment="Right" FontSize="16" HorizontalAlignment="Center" VerticalAlignment="Center"/>
<ComboBox Name="cboShelf" VerticalAlignment="Center"
materialDesign:HintAssist.HintOpacity=".26"
IsEditable="False" Width="380" FontSize="13"
DisplayMemberPath="name" SelectedValuePath="id" HorizontalAlignment="Left" SelectionChanged="cboShelf_SelectionChanged">
</ComboBox>
</StackPanel>
<StackPanel Grid.Row="3" Grid.Column="1" Orientation="Horizontal" Name="spShelfData">
<TextBlock Text="排:" Width="120" TextAlignment="Right" FontSize="16" HorizontalAlignment="Center" VerticalAlignment="Center"/>
<ComboBox Name="cboShelfRange" VerticalAlignment="Center"
materialDesign:HintAssist.HintOpacity=".26"
IsEditable="False" Width="100" FontSize="13"
HorizontalAlignment="Left">
</ComboBox>
<TextBlock Text="列:" Width="40" TextAlignment="Right" FontSize="16" HorizontalAlignment="Center" VerticalAlignment="Center"/>
<ComboBox Name="cboShelfColumn" VerticalAlignment="Center"
materialDesign:HintAssist.HintOpacity=".26"
IsEditable="False" Width="100" FontSize="13"
HorizontalAlignment="Left">
</ComboBox>
<TextBlock Text="行:" Width="40" TextAlignment="Right" FontSize="16" HorizontalAlignment="Center" VerticalAlignment="Center"/>
<ComboBox Name="cboShelfRow" VerticalAlignment="Center"
materialDesign:HintAssist.HintOpacity=".26"
IsEditable="False" Width="100" FontSize="13"
HorizontalAlignment="Left">
</ComboBox>
</StackPanel>
<StackPanel Grid.Row="4" Grid.Column="1" Orientation="Horizontal" Name="spMessage">
<TextBlock Text="推荐存放位置:" TextAlignment="Right" FontSize="16" VerticalAlignment="Top" Foreground="Red" HorizontalAlignment="Left" Width="120"/>
<TextBlock Name="tbMessage" Text="XXXXXXXXXXXX &#x000A; XXXXXXX &#x000A; XXXXX&#x000A;XXXX" TextWrapping = "Wrap" TextAlignment="Left" FontSize="16" VerticalAlignment="Top" Foreground="Red" HorizontalAlignment="Left" Width="230"/>
</StackPanel>
<Button FontSize="20" Grid.Row="5" Click="OnSave_Click" HorizontalAlignment="Right" Content="确定" Style="{StaticResource MaterialDesignRaisedButton}" Height="40" Width="100" VerticalAlignment="Bottom" Grid.Column="1" Margin="0,5,161,20" />
<Button FontSize="20" Grid.Row="5" Click="OnCancel_Click" HorizontalAlignment="Right" Content="关闭" Background="DarkOrange" BorderBrush="Orange" Style="{StaticResource MaterialDesignRaisedButton}" Height="40" Width="100" VerticalAlignment="Bottom" Grid.Column="1" Margin="0,0,20,20"/>
</Grid>
</Border>
</Window>
using JmpZbPrint.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
namespace JmpZbPrint.Dialog
{
/// <summary>
/// ShelfWindow.xaml 的交互逻辑
/// </summary>
public partial class ShelfWindow : Window
{
public List<ShelfInfo> ShelfList { get; set; }
public List<ShelfInfo> EquipmentShelfList { get; set; }
public ShelfInfo Shelf { get; set; }
public WarehouseInfo WarehouseInfo { get; set; }
public ShelfWindow(WarehouseInfo warehouse, string equId, string sizeId)
{
InitializeComponent();
WarehouseInfo = warehouse;
ShelfList = HttpHelper.GetShelfByWarehouseId(warehouse.id) ?? new List<ShelfInfo>();
ShelfList.Insert(0, new ShelfInfo
{
id = "",
name = "(未指定)"
});
cboShelf.ItemsSource = ShelfList;
cboShelf.DisplayMemberPath = "name";
cboShelf.SelectedValuePath = "id";
cboShelf.SelectedIndex = 0;
tbWarehouse.Text = WarehouseInfo.name;
EquipmentShelfList = HttpHelper.GetListEquipmentShelfPosition(WarehouseInfo.id, equId, sizeId) ?? new List<ShelfInfo>();
InitEquipmentShelfMessage();
}
private void Sb_Completed(object sender, EventArgs e)
{
this.Close();
}
private void OnSelectItemClick(object sender, RoutedEventArgs e)
{
this.Close();
}
private void OnSave_Click(object sender, RoutedEventArgs e)
{
Shelf = new ShelfInfo()
{
id = (cboShelf.SelectionBoxItem as ShelfInfo)?.id ?? "",
name = (cboShelf.SelectionBoxItem as ShelfInfo)?.name ?? "",
};
if (!string.IsNullOrEmpty(Shelf.id))
{
Shelf.range = cboShelfRange.SelectedIndex > 0 && !string.IsNullOrEmpty(Shelf.id) ? cboShelfRange.SelectedIndex.ToString() : "0";
Shelf.column = cboShelfColumn.SelectedIndex > 0 && Convert.ToInt32(Shelf.range) > 0 ? cboShelfColumn.SelectedIndex.ToString() : "0";
Shelf.row = cboShelfRow.SelectedIndex > 0 && Convert.ToInt32(Shelf.column) > 0 ? cboShelfRow.SelectedIndex.ToString() : " 0";
}
this.Close();
}
private void OnCancel_Click(object sender, RoutedEventArgs e)
{
this.Close();
}
private void cboShelf_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
//切换货架
if (e == null || e.RemovedItems.Count > 0)
{
var shelf = cboShelf.SelectedItem as ShelfInfo;
if (!string.IsNullOrEmpty(shelf.id))
{
cboShelfRange.ItemsSource = CreateSelectList(Convert.ToInt32(shelf.range));
cboShelfRange.SelectedIndex = 0;
cboShelfRow.ItemsSource = CreateSelectList(Convert.ToInt32(shelf.row));
cboShelfRow.SelectedIndex = 0;
cboShelfColumn.ItemsSource = CreateSelectList(Convert.ToInt32(shelf.column));
cboShelfColumn.SelectedIndex = 0;
spShelfData.IsEnabled = true;
}
else
{
cboShelfRange.ItemsSource = null;
cboShelfRow.ItemsSource = null;
cboShelfColumn.ItemsSource = null;
spShelfData.IsEnabled = false;
}
}
}
private List<string> CreateSelectList(int count)
{
var list = new List<string>();
list.Add("(未指定)");
for (int i = 1; i <= count; i++)
{
list.Add(i.ToString());
}
return list;
}
private void InitEquipmentShelfMessage()
{
if (EquipmentShelfList.Count > 0)
{
spMessage.Visibility = Visibility.Visible;
tbMessage.Text = string.Join("\r\n", EquipmentShelfList.Take(3).Select(x => x.name +
(
string.IsNullOrEmpty(x.range) ? "" : "-" + x.range +
(
string.IsNullOrEmpty(x.column) ? "" : "-" + x.column +
(
string.IsNullOrEmpty(x.row) ? "" : "-" + x.row
)
)
)
));
if (EquipmentShelfList.Count > 3)
{
tbMessage.Text += " 等";
}
//装填第一条信息
var shelf = EquipmentShelfList.First();
cboShelf.SelectedIndex = cboShelf.ItemsSource.OfType<ShelfInfo>().ToList()
.FindIndex(x => x.id == shelf.id);
cboShelfRange.SelectedIndex = Convert.ToInt32(shelf.range);
cboShelfColumn.SelectedIndex = Convert.ToInt32(shelf.column);
cboShelfRow.SelectedIndex = Convert.ToInt32(shelf.row);
}
else
{
spMessage.Visibility = Visibility.Hidden;
}
}
}
}
<Window x:Class="JmpZbPrint.Dialog.SupplierWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:materialDesign="http://materialdesigninxaml.net/winfx/xaml/themes"
xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
xmlns:local="clr-namespace:JmpZbPrint.Dialog"
mc:Ignorable="d"
Height="350" Width="600" AllowsTransparency="True" WindowStyle="None"
ResizeMode="NoResize" WindowStartupLocation="CenterScreen">
<Window.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="pack://application:,,,/MaterialDesignThemes.Wpf;component/Themes/MaterialDesignTheme.TextBox.xaml" />
<ResourceDictionary Source="pack://application:,,,/MaterialDesignThemes.Wpf;component/Themes/MaterialDesignTheme.DataGrid.xaml" />
<ResourceDictionary Source="pack://application:,,,/MaterialDesignThemes.Wpf;component/Themes/MaterialDesignTheme.TextBlock.xaml" />
</ResourceDictionary.MergedDictionaries>
<SolidColorBrush x:Key="PrimaryHueLightBrush" Color="#0093EA"/>
<SolidColorBrush x:Key="PrimaryHueLightForegroundBrush" Color="#FFFFFF"/>
<SolidColorBrush x:Key="PrimaryHueMidBrush" Color="#0093EA"/>
<SolidColorBrush x:Key="PrimaryHueMidForegroundBrush" Color="#FFFFFF"/>
<SolidColorBrush x:Key="PrimaryHueDarkBrush" Color="#0093EA"/>
<SolidColorBrush x:Key="PrimaryHueDarkForegroundBrush" Color="#FFFFFF"/>
<!-- accent -->
<SolidColorBrush x:Key="SecondaryAccentBrush" Color="#0093EA"/>
<SolidColorBrush x:Key="SecondaryAccentForegroundBrush" Color="#FFFFFF"/>
<Storyboard x:Key="Loading">
<ThicknessAnimation Duration="0:0:0.2" To="0" From="0,300,0,300"
Storyboard.TargetName="g_main" Storyboard.TargetProperty="Margin" />
</Storyboard>
<Storyboard x:Key="Closing">
<ThicknessAnimation FillBehavior="Stop" Duration="0:0:0.2" To="0,300,0,300" From="0" Storyboard.TargetName="g_main"
Storyboard.TargetProperty="Margin" Completed="Sb_Completed"/>
</Storyboard>
</ResourceDictionary>
</Window.Resources>
<Window.Effect>
<DropShadowEffect BlurRadius="20" Color="#FF858484" Direction="90" ShadowDepth="2"/>
</Window.Effect>
<Window.Triggers>
<EventTrigger RoutedEvent="FrameworkElement.Loaded" >
<BeginStoryboard Storyboard="{StaticResource Loading}"/>
</EventTrigger>
<EventTrigger RoutedEvent="UIElement.MouseLeftButtonDown" SourceName="tbclose">
<BeginStoryboard Storyboard="{StaticResource Closing}" />
</EventTrigger>
</Window.Triggers>
<Border BorderBrush="#FF858484" x:Name="g_main" CornerRadius="3" BorderThickness="2" >
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="80"/>
<RowDefinition Height="50"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<TextBlock x:Name="txtTitle" Text="选择供应商信息" FontSize="30" Foreground="#0092ea" VerticalAlignment="Top" Margin="20 20 0 0"/>
<TextBlock Text="&#xE618;" Style="{StaticResource FiconBase}" x:Name="tbclose"
HorizontalAlignment="Right" VerticalAlignment="Top"
Margin="0 20 20 0" FontSize="35" Foreground="#8a8a8a" />
<Grid Grid.Row="1" Margin="0,0,0,0" >
<Grid.ColumnDefinitions>
<ColumnDefinition Width="10"/>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="20"/>
<ColumnDefinition Width="100"/>
</Grid.ColumnDefinitions>
<StackPanel Grid.Column="1" Orientation="Horizontal">
<TextBlock Text="供应商名称:" FontSize="15" HorizontalAlignment="Center" VerticalAlignment="Center"/>
<TextBox x:Name="txt_vendor" Focusable="True" Text="{Binding VendorName,UpdateSourceTrigger=PropertyChanged}" MinWidth="400" VerticalAlignment="Center" Width="250" FontSize="15" Background="White" materialDesign:HintAssist.Hint="供应商名称"/>
</StackPanel>
<StackPanel Grid.Column="3" Orientation="Horizontal">
<Button FontSize="15" Content="查询" Click="OnQueryClick" VerticalAlignment="Center" Style="{StaticResource MaterialDesignRaisedButton}" Margin="0,0,0,0" Width="70" HorizontalAlignment="Left" />
</StackPanel>
</Grid>
<DataGrid EnableRowVirtualization="False" x:Name="g_vender" Margin="3 5 3 20" Grid.Row="2" BorderBrush="#dedede" FontSize="20" Foreground="#37537d" HeadersVisibility="Column"
GridLinesVisibility="None" Background="Transparent" BorderThickness="1" CanUserAddRows="False"
AutoGenerateColumns="False" SelectionMode="Single" HorizontalScrollBarVisibility="Hidden" RowBackground="Transparent" CanUserSortColumns="True" >
<DataGrid.ColumnHeaderStyle>
<Style TargetType="{x:Type DataGridColumnHeader}">
<Setter Property="BorderThickness" Value="0"/>
<Setter Property="VerticalAlignment" Value="Center"/>
<Setter Property="HorizontalContentAlignment" Value="Center"/>
<Setter Property="Background" Value="Transparent"/>
<Setter Property="Foreground" Value="#4682B4"/>
<Setter Property="FontSize" Value="15"/>
<Setter Property="Height" Value="25"/>
</Style>
</DataGrid.ColumnHeaderStyle>
<DataGrid.RowStyle>
<Style TargetType="{x:Type DataGridRow}">
<Setter Property="Height" Value="45" />
<Style.Triggers>
<Trigger Property="ItemsControl.AlternationIndex" Value="0">
<Setter Property="Background" Value="Transparent"/>
<Setter Property="BorderBrush" Value="Transparent"/>
</Trigger>
<Trigger Property="ItemsControl.AlternationIndex" Value="1">
<Setter Property="Background" Value="#EBEBEB"/>
<Setter Property="Opacity" Value="0.4"/>
</Trigger>
</Style.Triggers>
</Style>
</DataGrid.RowStyle>
<DataGrid.Columns>
<DataGridTextColumn Header="供应商名称" IsReadOnly="True" Width="*" FontSize="13" Binding="{Binding name}" ElementStyle="{StaticResource TextLeftStyle}"/>
<DataGridTemplateColumn Header="操作" Width="100" >
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal" VerticalAlignment="Center" HorizontalAlignment="Center">
<Button Content="选择" Click="OnSelectItemClick" Height="30" Margin="5,0,5,0" >
</Button>
</StackPanel>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
</Grid>
</Border>
</Window>
using JmpZbPrint.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
namespace JmpZbPrint.Dialog
{
/// <summary>
/// SupplierWin.xaml 的交互逻辑
/// </summary>
public partial class SupplierWindow : Window
{
public Supplier Supplier { get; set; }
public List<Supplier> SupplierList { get; set; }
public SupplierWindow()
{
InitializeComponent();
SupplierList = HttpHelper.GetAllSupplier();
g_vender.ItemsSource = SupplierList?.Take(30);
txt_vendor.Focus();
}
private void Sb_Completed(object sender, EventArgs e)
{
this.Close();
}
private void OnQueryClick(object sender, RoutedEventArgs e)
{
if (string.IsNullOrEmpty(txt_vendor.Text))
{
g_vender.ItemsSource = SupplierList;
}
else
{
g_vender.ItemsSource = SupplierList?.Where(t=>t.name.Contains(txt_vendor.Text));
}
}
private void OnSelectItemClick(object sender, RoutedEventArgs e)
{
Supplier = g_vender.SelectedValue as Supplier;
this.Close();
}
}
}
<?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>{AF8CBDF8-6713-4E88-A2CD-A5ED53AAE26F}</ProjectGuid>
<OutputType>WinExe</OutputType>
<RootNamespace>JmpZbPrint</RootNamespace>
<AssemblyName>JmpZbPrint</AssemblyName>
<TargetFrameworkVersion>v4.6.1</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<ProjectTypeGuids>{60dc8134-eba5-43b8-bcc9-bb4bc16c2548};{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}</ProjectTypeGuids>
<WarningLevel>4</WarningLevel>
<AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
<Deterministic>true</Deterministic>
<NuGetPackageImportStamp>
</NuGetPackageImportStamp>
<TargetFrameworkProfile />
<PublishUrl>publish\</PublishUrl>
<Install>true</Install>
<InstallFrom>Disk</InstallFrom>
<UpdateEnabled>false</UpdateEnabled>
<UpdateMode>Foreground</UpdateMode>
<UpdateInterval>7</UpdateInterval>
<UpdateIntervalUnits>Days</UpdateIntervalUnits>
<UpdatePeriodically>false</UpdatePeriodically>
<UpdateRequired>false</UpdateRequired>
<MapFileExtensions>true</MapFileExtensions>
<ApplicationRevision>0</ApplicationRevision>
<ApplicationVersion>1.0.0.%2a</ApplicationVersion>
<IsWebBootstrapper>false</IsWebBootstrapper>
<UseApplicationTrust>false</UseApplicationTrust>
<BootstrapperEnabled>true</BootstrapperEnabled>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<PlatformTarget>x86</PlatformTarget>
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>..\Programe\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<LangVersion>8</LangVersion>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>..\Programe\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<LangVersion>8</LangVersion>
</PropertyGroup>
<PropertyGroup>
<ApplicationIcon>print.ico</ApplicationIcon>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|x86'">
<DebugSymbols>true</DebugSymbols>
<OutputPath>bin\x86\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<DebugType>full</DebugType>
<PlatformTarget>x86</PlatformTarget>
<LangVersion>8</LangVersion>
<ErrorReport>prompt</ErrorReport>
<CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet>
<Prefer32Bit>true</Prefer32Bit>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|x86'">
<OutputPath>bin\x86\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<Optimize>true</Optimize>
<DebugType>pdbonly</DebugType>
<PlatformTarget>x86</PlatformTarget>
<LangVersion>8</LangVersion>
<ErrorReport>prompt</ErrorReport>
<CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet>
<Prefer32Bit>true</Prefer32Bit>
</PropertyGroup>
<PropertyGroup>
<TargetZone>LocalIntranet</TargetZone>
</PropertyGroup>
<PropertyGroup>
<GenerateManifests>false</GenerateManifests>
</PropertyGroup>
<PropertyGroup>
<ApplicationManifest>Properties\app.manifest</ApplicationManifest>
</PropertyGroup>
<ItemGroup>
<Reference Include="CommonServiceLocator, Version=2.0.5.0, Culture=neutral, PublicKeyToken=489b6accfaf20ef0, processorArchitecture=MSIL">
<HintPath>..\packages\CommonServiceLocator.2.0.5\lib\net45\CommonServiceLocator.dll</HintPath>
</Reference>
<Reference Include="ControlzEx, Version=4.0.0.0, Culture=neutral, PublicKeyToken=69f1c32f803d307e, processorArchitecture=MSIL">
<HintPath>..\packages\ControlzEx.4.3.2\lib\net45\ControlzEx.dll</HintPath>
</Reference>
<Reference Include="GalaSoft.MvvmLight, Version=5.4.1.0, Culture=neutral, PublicKeyToken=e7570ab207bcb616, processorArchitecture=MSIL">
<HintPath>..\packages\MvvmLightLibs.5.4.1.1\lib\net45\GalaSoft.MvvmLight.dll</HintPath>
</Reference>
<Reference Include="GalaSoft.MvvmLight.Extras, Version=5.4.1.0, Culture=neutral, PublicKeyToken=669f0b5e8f868abf, processorArchitecture=MSIL">
<HintPath>..\packages\MvvmLightLibs.5.4.1.1\lib\net45\GalaSoft.MvvmLight.Extras.dll</HintPath>
</Reference>
<Reference Include="GalaSoft.MvvmLight.Platform, Version=5.4.1.0, Culture=neutral, PublicKeyToken=5f873c45e98af8a1, processorArchitecture=MSIL">
<HintPath>..\packages\MvvmLightLibs.5.4.1.1\lib\net45\GalaSoft.MvvmLight.Platform.dll</HintPath>
</Reference>
<Reference Include="LiteDB, Version=5.0.8.0, Culture=neutral, PublicKeyToken=4ee40123013c9f27, processorArchitecture=MSIL">
<HintPath>..\packages\LiteDB.5.0.8\lib\net45\LiteDB.dll</HintPath>
</Reference>
<Reference Include="MahApps.Metro, Version=2.0.0.0, Culture=neutral, PublicKeyToken=51482d6f650b2b3f, processorArchitecture=MSIL">
<HintPath>..\packages\MahApps.Metro.2.0.0\lib\net46\MahApps.Metro.dll</HintPath>
</Reference>
<Reference Include="MaterialDesignColors, Version=1.2.6.1513, Culture=neutral, processorArchitecture=MSIL">
<HintPath>..\packages\MaterialDesignColors.1.2.6\lib\net45\MaterialDesignColors.dll</HintPath>
</Reference>
<Reference Include="MaterialDesignThemes.MahApps, Version=0.1.4.1513, Culture=neutral, processorArchitecture=MSIL">
<HintPath>..\packages\MaterialDesignThemes.MahApps.0.1.4\lib\net452\MaterialDesignThemes.MahApps.dll</HintPath>
</Reference>
<Reference Include="MaterialDesignThemes.Wpf, Version=3.1.3.1513, Culture=neutral, processorArchitecture=MSIL">
<HintPath>..\packages\MaterialDesignThemes.3.1.3\lib\net45\MaterialDesignThemes.Wpf.dll</HintPath>
</Reference>
<Reference Include="Microsoft.Xaml.Behaviors, Version=1.1.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
<HintPath>..\packages\Microsoft.Xaml.Behaviors.Wpf.1.1.19\lib\net45\Microsoft.Xaml.Behaviors.dll</HintPath>
</Reference>
<Reference Include="NetworkCommsDotNet, Version=3.0.0.0, Culture=neutral, PublicKeyToken=f58108eb6480f6ec, processorArchitecture=MSIL">
<HintPath>..\packages\NetworkCommsDotNet.3.0.3\lib\NetworkCommsDotNet.dll</HintPath>
</Reference>
<Reference Include="Newtonsoft.Json, Version=12.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL">
<HintPath>..\packages\Newtonsoft.Json.12.0.3\lib\net45\Newtonsoft.Json.dll</HintPath>
</Reference>
<Reference Include="Panuon.UI.Silver, Version=1.1.3.0, Culture=neutral, processorArchitecture=MSIL">
<HintPath>..\packages\Panuon.UI.Silver.1.1.3\lib\net45\Panuon.UI.Silver.dll</HintPath>
</Reference>
<Reference Include="System" />
<Reference Include="System.ComponentModel.DataAnnotations" />
<Reference Include="System.Configuration" />
<Reference Include="System.Data" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="System.Drawing" />
<Reference Include="System.Runtime" />
<Reference Include="System.Web" />
<Reference Include="System.Web.Extensions" />
<Reference Include="System.Windows.Forms" />
<Reference Include="System.Windows.Interactivity, Version=4.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
<HintPath>..\packages\MvvmLightLibs.5.4.1.1\lib\net45\System.Windows.Interactivity.dll</HintPath>
</Reference>
<Reference Include="System.Xml" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Core" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Net.Http" />
<Reference Include="System.Xaml">
<RequiredTargetFramework>4.0</RequiredTargetFramework>
</Reference>
<Reference Include="websocket-sharp, Version=1.0.1.0, Culture=neutral, PublicKeyToken=5660b08a1845a91e, processorArchitecture=MSIL">
<HintPath>..\packages\WebSocketSharp-netstandard.1.0.1\lib\net45\websocket-sharp.dll</HintPath>
</Reference>
<Reference Include="WindowsBase" />
<Reference Include="PresentationCore" />
<Reference Include="PresentationFramework" />
</ItemGroup>
<ItemGroup>
<ApplicationDefinition Include="App.xaml">
<Generator>MSBuild:Compile</Generator>
<SubType>Designer</SubType>
</ApplicationDefinition>
<Compile Include="Common\DateTimeConverter.cs" />
<Compile Include="Common\DateConverter.cs" />
<Compile Include="Common\FloatConverter.cs" />
<Compile Include="Common\NumericalConverter.cs" />
<Compile Include="Common\JmpDes.cs" />
<Compile Include="Common\LiteDbHelper.cs" />
<Compile Include="Common\NotifyPropertyChangedExtension.cs" />
<Compile Include="Common\Config.cs" />
<Compile Include="Common\HttpHelper.cs" />
<Compile Include="Common\PreviewImageHelper.cs" />
<Compile Include="Common\IsSuccessConvert.cs" />
<Compile Include="Common\BoolConvert.cs" />
<Compile Include="Common\LabelTypeConvert.cs" />
<Compile Include="Common\PrintServerHelper.cs" />
<Compile Include="Common\PrintTypeConvert.cs" />
<Compile Include="Dialog\PrintLogWindow.xaml.cs">
<DependentUpon>PrintLogWindow.xaml</DependentUpon>
</Compile>
<Compile Include="Dialog\SelectBoxEpc.xaml.cs">
<DependentUpon>SelectBoxEpc.xaml</DependentUpon>
</Compile>
<Compile Include="Dialog\ShelfWindow.xaml.cs">
<DependentUpon>ShelfWindow.xaml</DependentUpon>
</Compile>
<Compile Include="Model\PrintLog.cs" />
<Compile Include="Model\respone_bagInventory.cs" />
<Compile Include="Model\respone_inventory.cs" />
<Compile Include="Model\respone_boxMark.cs" />
<Compile Include="Model\request_sign.cs" />
<Compile Include="Model\DbModel\db_page.cs" />
<Compile Include="Model\request_int_info.cs" />
<Compile Include="Model\respone_epc.cs" />
<Compile Include="Model\respone_import_old_data.cs" />
<Compile Include="Model\respone_postek_msg.cs" />
<Compile Include="PagePartial\IntHistoryWindow.xaml.cs">
<DependentUpon>IntHistoryWindow.xaml</DependentUpon>
</Compile>
<Compile Include="PagePartial\TagBagPrintWindow.xaml.cs">
<DependentUpon>TagBagPrintWindow.xaml</DependentUpon>
</Compile>
<Compile Include="PagePartial\TagBoxPrintWindow.xaml.cs">
<DependentUpon>TagBoxPrintWindow.xaml</DependentUpon>
</Compile>
<Compile Include="ViewModel\PrintLogWindowViewModel.cs" />
<Compile Include="ViewModel\IntHistoryViewModel.cs" />
<Compile Include="ViewModel\TagBagPrinViewModel.cs" />
<Compile Include="ViewModel\TagBoxPrinViewModel.cs" />
<Compile Include="View\AutoClosingMessageBox.xaml.cs">
<DependentUpon>AutoClosingMessageBox.xaml</DependentUpon>
</Compile>
<Compile Include="View\SetGenInfoV2.xaml.cs">
<DependentUpon>SetGenInfoV2.xaml</DependentUpon>
</Compile>
<Compile Include="View\SetGenBoxInfo.xaml.cs">
<DependentUpon>SetGenBoxInfo.xaml</DependentUpon>
</Compile>
<Compile Include="View\SetGenInfo.xaml.cs">
<DependentUpon>SetGenInfo.xaml</DependentUpon>
</Compile>
<Compile Include="Dialog\SelectEqu.xaml.cs">
<DependentUpon>SelectEqu.xaml</DependentUpon>
</Compile>
<Compile Include="Dialog\SupplierWindow.xaml.cs">
<DependentUpon>SupplierWindow.xaml</DependentUpon>
</Compile>
<Compile Include="Model\recode_info.cs" />
<Compile Include="Model\request_ext_info.cs" />
<Compile Include="Model\LabelType.cs" />
<Compile Include="Model\print_info.cs" />
<Compile Include="Model\respone_update.cs" />
<Compile Include="Model\respone_user.cs" />
<Compile Include="Model\order_info.cs" />
<Compile Include="Model\request_head.cs" />
<Compile Include="Model\request_equipment.cs" />
<Compile Include="Model\respone_head.cs" />
<Compile Include="Model\KeyName.cs" />
<Compile Include="Log.cs" />
<Compile Include="Common\CaChe.cs" />
<Compile Include="PagePartial\IntGenEpcWindow.xaml.cs">
<DependentUpon>IntGenEpcWindow.xaml</DependentUpon>
</Compile>
<Compile Include="PagePartial\SetBasicInfo.xaml.cs">
<DependentUpon>SetBasicInfo.xaml</DependentUpon>
</Compile>
<Compile Include="PagePartial\IntBindWindow.xaml.cs">
<DependentUpon>IntBindWindow.xaml</DependentUpon>
</Compile>
<Compile Include="PagePartial\TagBindWindow.xaml.cs">
<DependentUpon>TagBindWindow.xaml</DependentUpon>
</Compile>
<Compile Include="PagePartial\IntPrintWindow.xaml.cs">
<DependentUpon>IntPrintWindow.xaml</DependentUpon>
</Compile>
<Compile Include="PagePartial\TagPrintWindow.xaml.cs">
<DependentUpon>TagPrintWindow.xaml</DependentUpon>
</Compile>
<Compile Include="PagePartial\GenEpcWindow.xaml.cs">
<DependentUpon>GenEpcWindow.xaml</DependentUpon>
</Compile>
<Compile Include="ViewModel\IntBindViewModel.cs" />
<Compile Include="ViewModel\IntPrintViewModel.cs" />
<Compile Include="View\SettingsWindow.xaml.cs">
<DependentUpon>SettingsWindow.xaml</DependentUpon>
</Compile>
<Compile Include="UsControl\WaitDialog.xaml.cs">
<DependentUpon>WaitDialog.xaml</DependentUpon>
</Compile>
<Compile Include="UsControl\PageControl.xaml.cs">
<DependentUpon>PageControl.xaml</DependentUpon>
</Compile>
<Compile Include="UsControl\InputDialog.xaml.cs">
<DependentUpon>InputDialog.xaml</DependentUpon>
</Compile>
<Compile Include="ViewModel\TagBindViewModel.cs" />
<Compile Include="ViewModel\TagPrinViewModel.cs" />
<Compile Include="ViewModel\GenEpcViewModel.cs" />
<Compile Include="View\InternalWindow.xaml.cs">
<DependentUpon>InternalWindow.xaml</DependentUpon>
</Compile>
<Page Include="Dialog\PrintLogWindow.xaml">
<Generator>MSBuild:Compile</Generator>
<SubType>Designer</SubType>
</Page>
<Page Include="Dialog\SelectBoxEpc.xaml">
<Generator>MSBuild:Compile</Generator>
<SubType>Designer</SubType>
</Page>
<Page Include="Dialog\ShelfWindow.xaml">
<Generator>MSBuild:Compile</Generator>
<SubType>Designer</SubType>
</Page>
<Page Include="PagePartial\IntHistoryWindow.xaml">
<Generator>MSBuild:Compile</Generator>
<SubType>Designer</SubType>
</Page>
<Page Include="PagePartial\TagBagPrintWindow.xaml">
<Generator>MSBuild:Compile</Generator>
<SubType>Designer</SubType>
</Page>
<Page Include="PagePartial\TagBoxPrintWindow.xaml">
<Generator>MSBuild:Compile</Generator>
<SubType>Designer</SubType>
</Page>
<Page Include="View\AutoClosingMessageBox.xaml">
<Generator>MSBuild:Compile</Generator>
<SubType>Designer</SubType>
</Page>
<Page Include="View\SetGenInfoV2.xaml">
<Generator>MSBuild:Compile</Generator>
<SubType>Designer</SubType>
</Page>
<Page Include="View\SetGenBoxInfo.xaml">
<Generator>MSBuild:Compile</Generator>
<SubType>Designer</SubType>
</Page>
<Page Include="View\SetGenInfo.xaml">
<Generator>MSBuild:Compile</Generator>
<SubType>Designer</SubType>
</Page>
<Page Include="Dialog\SelectEqu.xaml">
<Generator>MSBuild:Compile</Generator>
<SubType>Designer</SubType>
</Page>
<Page Include="Dialog\SupplierWindow.xaml">
<SubType>Designer</SubType>
<Generator>MSBuild:Compile</Generator>
</Page>
<Page Include="PagePartial\IntGenEpcWindow.xaml">
<Generator>MSBuild:Compile</Generator>
<SubType>Designer</SubType>
</Page>
<Page Include="PagePartial\IntBindWindow.xaml">
<Generator>MSBuild:Compile</Generator>
<SubType>Designer</SubType>
</Page>
<Page Include="PagePartial\IntPrintWindow.xaml">
<Generator>MSBuild:Compile</Generator>
<SubType>Designer</SubType>
</Page>
<Page Include="View\LoginWindow.xaml">
<SubType>Designer</SubType>
<Generator>MSBuild:Compile</Generator>
</Page>
<Page Include="View\MainWindow.xaml">
<Generator>MSBuild:Compile</Generator>
<SubType>Designer</SubType>
</Page>
<Compile Include="App.xaml.cs">
<DependentUpon>App.xaml</DependentUpon>
<SubType>Code</SubType>
</Compile>
<Compile Include="View\LoginWindow.xaml.cs">
<DependentUpon>LoginWindow.xaml</DependentUpon>
</Compile>
<Compile Include="View\MainWindow.xaml.cs">
<DependentUpon>MainWindow.xaml</DependentUpon>
<SubType>Code</SubType>
</Compile>
<Page Include="PagePartial\SetBasicInfo.xaml">
<SubType>Designer</SubType>
<Generator>MSBuild:Compile</Generator>
</Page>
<Page Include="PagePartial\TagBindWindow.xaml">
<Generator>MSBuild:Compile</Generator>
<SubType>Designer</SubType>
</Page>
<Page Include="PagePartial\TagPrintWindow.xaml">
<Generator>MSBuild:Compile</Generator>
<SubType>Designer</SubType>
</Page>
<Page Include="PagePartial\GenEpcWindow.xaml">
<SubType>Designer</SubType>
<Generator>MSBuild:Compile</Generator>
</Page>
<Page Include="View\SettingsWindow.xaml">
<Generator>MSBuild:Compile</Generator>
<SubType>Designer</SubType>
</Page>
<Page Include="UsControl\WaitDialog.xaml">
<SubType>Designer</SubType>
<Generator>MSBuild:Compile</Generator>
</Page>
<Page Include="UsControl\PageControl.xaml">
<Generator>MSBuild:Compile</Generator>
<SubType>Designer</SubType>
</Page>
<Page Include="UsControl\InputDialog.xaml">
<SubType>Designer</SubType>
<Generator>MSBuild:Compile</Generator>
</Page>
<Page Include="View\InternalWindow.xaml">
<Generator>MSBuild:Compile</Generator>
<SubType>Designer</SubType>
</Page>
</ItemGroup>
<ItemGroup>
<Compile Include="Properties\AssemblyInfo.cs">
<SubType>Code</SubType>
</Compile>
<Compile Include="Properties\Resources.Designer.cs">
<AutoGen>True</AutoGen>
<DesignTime>True</DesignTime>
<DependentUpon>Resources.resx</DependentUpon>
</Compile>
<Compile Include="Properties\Settings.Designer.cs">
<AutoGen>True</AutoGen>
<DependentUpon>Settings.settings</DependentUpon>
<DesignTimeSharedInput>True</DesignTimeSharedInput>
</Compile>
<EmbeddedResource Include="Properties\Resources.resx">
<Generator>ResXFileCodeGenerator</Generator>
<LastGenOutput>Resources.Designer.cs</LastGenOutput>
</EmbeddedResource>
<Resource Include="font\iconfont.ttf" />
<Resource Include="font\LED.OTF" />
<None Include="config.json" />
<None Include="packages.config" />
<None Include="Properties\app.manifest" />
<None Include="Properties\Settings.settings">
<Generator>SettingsSingleFileGenerator</Generator>
<LastGenOutput>Settings.Designer.cs</LastGenOutput>
</None>
</ItemGroup>
<ItemGroup>
<None Include="App.config" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\JmpZbModel\JmpZbModel.csproj">
<Project>{7e4c3e44-3418-43d0-915b-57f76cf4cab4}</Project>
<Name>JmpZbModel</Name>
</ProjectReference>
</ItemGroup>
<ItemGroup>
<WCFMetadata Include="Connected Services\" />
</ItemGroup>
<ItemGroup>
<Resource Include="print.ico" />
</ItemGroup>
<ItemGroup>
<BootstrapperPackage Include=".NETFramework,Version=v4.6.1">
<Visible>False</Visible>
<ProductName>Microsoft .NET Framework 4.6.1 %28x86 和 x64%29</ProductName>
<Install>true</Install>
</BootstrapperPackage>
<BootstrapperPackage Include="Microsoft.Net.Framework.3.5.SP1">
<Visible>False</Visible>
<ProductName>.NET Framework 3.5 SP1</ProductName>
<Install>false</Install>
</BootstrapperPackage>
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<Import Project="..\packages\MaterialDesignThemes.3.1.3\build\MaterialDesignThemes.targets" Condition="Exists('..\packages\MaterialDesignThemes.3.1.3\build\MaterialDesignThemes.targets')" />
<Target Name="EnsureNuGetPackageBuildImports" BeforeTargets="PrepareForBuild">
<PropertyGroup>
<ErrorText>这台计算机上缺少此项目引用的 NuGet 程序包。使用“NuGet 程序包还原”可下载这些程序包。有关更多信息,请参见 http://go.microsoft.com/fwlink/?LinkID=322105。缺少的文件是 {0}。</ErrorText>
</PropertyGroup>
<Error Condition="!Exists('..\packages\MaterialDesignThemes.3.1.3\build\MaterialDesignThemes.targets')" Text="$([System.String]::Format('$(ErrorText)', '..\packages\MaterialDesignThemes.3.1.3\build\MaterialDesignThemes.targets'))" />
</Target>
<ProjectExtensions>
<VisualStudio>
<UserProperties config_1json__JsonSchema="" />
</VisualStudio>
</ProjectExtensions>
</Project>
\ No newline at end of file
[Database]
;是否保存(0不保存,1保存)
Save =0
;数据库IP地址
Source=172.18.77.25
;数据库名称
DB=RFIDReader_Data
;用户名
User=sa
;密码
Pwd=sa
;保存间隔时间(秒)
Upd=5
[RunMode]
mode=0
[ShowScoreboard]
show=True
[ShowSpeedCurve]
curveshow=False
[MacErr]
InterruptFWDPWRLEVERROR=True
using System;
using System.IO;
using System.Runtime.CompilerServices;
using System.Text;
namespace JmpZbPrint
{
public class Log
{
//private static
private static StreamWriter sr;
private static readonly object syncWorkObj = new object();
private static readonly object syncErrorObj = new object();
private static readonly object syncDebugObj = new object();
private static bool bEnableWorkLog = true;
private static bool bEnableErrorLog = true;
private static bool bEnableDebugLog = true;
public Log()
{
}
/// <summary>
/// Log 启用
/// </summary>
/// <param name="enable"></param>
public static void EnableWorkLog(bool enable)
{
bEnableWorkLog = enable;
}
/// <summary>
/// Log 启用
/// </summary>
/// <param name="enable"></param>
public static void EnableErrorLog(bool enable)
{
bEnableErrorLog = enable;
}
/// <summary>
/// Log 启用
/// </summary>
/// <param name="enable"></param>
public static void EnableDebugLog(bool enable)
{
bEnableDebugLog = enable;
}
/// <summary>
/// 工作日志
/// </summary>
/// <param name="logTxt"></param>
/// <param name="ModuleName"></param>
public static void WorkLog(string logTxt, [CallerMemberName] string ModuleName = default)
{
lock (syncWorkObj)
{
if (bEnableWorkLog)
{
WriteLine(logTxt, ModuleName, "WorkLog/");
}
}
}
/// <summary>
/// 异常日志
/// </summary>
/// <param name="logTxt"></param>
/// <param name="ModuleName"></param>
public static void ErrorLog(string logTxt, [CallerMemberName] string ModuleName = null)
{
lock (syncErrorObj)
{
if (bEnableErrorLog)
{
WriteLine(logTxt, ModuleName, "ErrorLog/");
}
}
}
/// <summary>
/// 异常日志
/// </summary>
/// <param name="logTxt"></param>
/// <param name="ModuleName"></param>
public static void DebugLog(string logTxt, string ModuleName)
{
lock (syncDebugObj)
{
if (bEnableDebugLog)
{
WriteLine(logTxt, ModuleName, "DebugLog/");
}
}
}
/// <summary>
/// 写日志
/// </summary>
/// <param name="logTxt"></param>
/// <param name="ModuleName"></param>
/// <param name="pathName"></param>
private static void WriteLine(string logTxt, string ModuleName, string pathName)
{
try
{
string logPath = AppDomain.CurrentDomain.SetupInformation.ApplicationBase + pathName
+ DateTime.Now.ToString("yyyyMMdd") + ".log";
ClearFile(AppDomain.CurrentDomain.SetupInformation.ApplicationBase + pathName);
logTxt = string.Format(" {0}|{1}|{2}",
DateTime.Now.ToString("yyyy-MM-dd HH:mm"),
ModuleName,
logTxt);
sr = new StreamWriter(logPath, true, Encoding.Default);
sr.WriteLine(logTxt);
sr.Close();
}
catch { }
}
/// <summary>
/// 日志清除文件
/// </summary>
/// <param name="FilePath"></param>
private static void ClearFile(string FilePath)
{
if (!Directory.Exists(FilePath))
{
Directory.CreateDirectory(FilePath);
}
String[] Files = Directory.GetFiles(FilePath);
if (Files.Length > 30)
{
for (int i = 0; i < 1; i++)
{
try
{
File.Delete(Files[i]);
}
catch
{
}
}
}
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace JmpZbPrint.Model.DbModel
{
public class db_page
{
public int total { get; set; }
public List<recode_info> record { get; set; }
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace JmpZbPrint.Model
{
public class KeyName
{
public int Key { get; set; }
public string Name { get; set; }
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace JmpZbPrint.Model
{
public enum LabelType
{
打印 = 0,
初始化 = 1,
}
}
using GalaSoft.MvvmLight;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace JmpZbPrint.Model
{
public class PrintLog:ViewModelBase
{
/// <summary>
/// 创建时间
/// </summary>
public DateTime CreateTime { get; set; }
/// <summary>
/// 是否打印成功
/// </summary>
public bool IsSuccess { get; set; }
public string epc { get; set; }
public string id { get; set; }
public string orderCode { get; set; }
public string warehouseName { get; set; }
public string productName { get; set; }
public string sizeName { get; set; }
public string productTime { get; set; }
public string useTime { get; set; }
public string pieceNo { get; set; }
public string warrantyCycle { get; set; }
public string repairCycle { get; set; }
public string price { get; set; }
public string supplierName { get; set; }
/// <summary>
/// 是否是箱标
/// </summary>
public bool isBoxMark { get; set; }
/// <summary>
/// 箱内数量
/// </summary>
public int oneBoxNum { get; set; }
[JsonIgnore]
public int state { get; set; }
[Newtonsoft.Json.JsonIgnore]
private bool _select = false;
[Newtonsoft.Json.JsonIgnore]
public bool IsSelected
{
get
{
return _select;
}
set
{
_select = value;
this.RaisePropertyChanged(() => IsSelected);
}
}
}
}
using GalaSoft.MvvmLight;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace JmpZbPrint.Model
{
public class PrintsInfo : ViewModelBase
{
public string Id { get; set; }
public string OrderCode { get; set; }
public string ProductNo { get; set; }
public string ProductName { get; set; }
public string SupplierName { get; set; }
public string SizeName { get; set; }
public string Epc { get; set; }
public string ProductTime { get; set; }
public string Price { get; set; }
public string UseTime { get; set; }
public string WarrantyCycle { get; set; }
public string RepairCycle { get; set; }
public int Quantity { get; set; }
public int PrintType { get; set; }
private bool _select = false;
[Newtonsoft.Json.JsonIgnore]
public bool IsSelected
{
get
{
return _select;
}
set
{
_select = value;
this.RaisePropertyChanged(() => IsSelected);
}
}
[Newtonsoft.Json.JsonIgnore]
public int State { get; set; }
public int? PieceNo { get; set; }
}
}
using GalaSoft.MvvmLight;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace JmpZbPrint.Model
{
public class order_info : ViewModelBase
{
public string orderId { get; set; }
public string detailId { get; set; }
public string createTime { get; set; }
public string equCode { get; set; }
public string equName { get; set; }
public string equId { get; set; }
public string sizeId { get; set; }
public string sizeCode { get; set; }
public string sizeName { get; set; }
public string orderCode { get; set; }
public int genedNum { get; set; }
public int totalNum { get; set; }
public ObservableCollection<Supplier> suppilers { get; set; }
public int reNum { get; set; }
[Newtonsoft.Json.JsonIgnore]
private bool _select = false;
[Newtonsoft.Json.JsonIgnore]
public bool IsSelected
{
get
{
return _select;
}
set
{
_select = value;
this.RaisePropertyChanged(() => IsSelected);
}
}
[Newtonsoft.Json.JsonIgnore]
private string _supplierId = string.Empty;
[Newtonsoft.Json.JsonIgnore]
public string supplierId
{
get { return _supplierId; }
set
{
_supplierId = value;
RaisePropertyChanged();
}
}
[Newtonsoft.Json.JsonIgnore]
public string supplierCode
{
get; set;
}
[Newtonsoft.Json.JsonIgnore]
public string supplierName
{
get; set;
}
public DateTime? productTime { get; set; } = DateTime.Now.AddDays(-7);
public DateTime? useTime { get; set; } = DateTime.Now;
public int warrantyCycle { get; set; }
public int repairCycle { get; set; }
public decimal price { get; set; }
public int needNum { get; set; }
[JsonIgnore]
public int rowNum { get; set; }
/// <summary>
/// 仓库id
/// </summary>
public string warehouseId { get; set; }
/// <summary>
/// 仓库名称
/// </summary>
public string warehouseName { get; set; }
/// <summary>
/// 货架id
/// </summary>
public string shelfId { get; set; }
/// <summary>
/// 货架名称
/// </summary>
public string shelfName { get; set; }
/// <summary>
/// 货架名称
/// </summary>
public string _shelfName { get; set; }
/// <summary>
/// 货架排
/// </summary>
public int shelfRange { get; set; }
/// <summary>
/// 货架行
/// </summary>
public int shelfRow { get; set; }
/// <summary>
/// 货架列
/// </summary>
public int shelfColumn { get; set; }
/// <summary>
/// 货架信息(拼接)
/// </summary>
[JsonIgnore]
public string shelfInfo
{
get
{
var str = shelfName;
if (shelfRange != 0)
{
str += "-" + shelfRange;
if (shelfColumn != 0)
{
str += "-" + shelfColumn;
if (shelfRow != 0)
{
str += "-" + shelfRow;
}
}
}
return str;
}
set
{
RaisePropertyChanged();
}
}
}
public class EquSupplier
{
public string id { get; set; }
public string name { get; set; }
public int num { get; set; }
}
public class EquInfo
{
public string id { get; set; }
public string name { get; set; }
public string code { get; set; }
}
public class EquAttr
{
public List<Supplier> suppliers { get; set; }
public List<EquSizeInfo> sizes { get; set; }
}
public class WarehouseInfo
{
public string id { get; set; }
public string name { get; set; }
}
public class ShelfInfo
{
public string id { get; set; }
public string name { get; set; }
public string range { get; set; }
public string row { get; set; }
public string column { get; set; }
}
public class Supplier
{
public string id { get; set; }
public string code { get; set; }
public string name { get; set; }
}
public class EquSizeInfo
{
public string id { get; set; }
public string code { get; set; }
public string name { get; set; }
/// <summary>
/// 默认价格
/// </summary>
public decimal? price { get; set; }
}
}
using GalaSoft.MvvmLight;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace JmpZbPrint.Model
{
public class print_info : ViewModelBase
{
/// <summary>
/// 标签类型
/// 箱标
/// 件标
/// 装备包
/// </summary>
public string LabelType { get; set; }
public string epc { get; set; }
public string id { get; set; }
public string orderCode { get; set; }
public string warehouseName { get; set; }
public string warehouseId { get; set; }
public string productName { get; set; }
public string productId { get; set; }
public string productNo { get; set; }
public string sizeName { get; set; }
public string sizeId { get; set; }
public string sizeCode { get; set; }
public string productTime { get; set; }
public string useTime { get; set; }
public string pieceNo { get; set; }
public string warrantyCycle { get; set; }
public string repairCycle { get; set; }
public string price { get; set; }
public string supplierName { get; set; }
public string supplierId { get; set; }
public string supplierCode { get; set; }
public bool isUnboxingLabel { get; set; }
public int oneBoxNum { get; set; }
public string epcListJson { get; set; }
/// <summary>
/// 编号
/// </summary>
public string number { get; set; }
/// <summary>
/// 装备包名称
/// </summary>
public string bagName { get; set; }
/// <summary>
/// 装备包内部装备名称概要
/// </summary>
public string invInfo { get; set; }
[JsonIgnore]
public int state { get; set; }
[Newtonsoft.Json.JsonIgnore]
private bool _select = false;
[Newtonsoft.Json.JsonIgnore]
public bool IsSelected
{
get
{
return _select;
}
set
{
_select = value;
this.RaisePropertyChanged(() => IsSelected);
}
}
}
}
using GalaSoft.MvvmLight;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
namespace JmpZbPrint.Model
{
public class recode_info : ViewModelBase
{
/// <summary>
/// 标签类型
/// 箱标
/// 件标
/// </summary>
public string LabelType { get; set; }
[JsonIgnore]
public int id { get; set; }
public string equId { get; set; }
public string equName { get; set; }
public string equCode { get; set; }
public string sizeId { get; set; }
public string sizeCode { get; set; }
public string sizeName { get; set; }
public string supplierId { get; set; }
public string suppilerCode { get; set; }
public string suppilerName { get; set; }
public DateTime? productTime { get; set; } = DateTime.Now.AddDays(-7);
public DateTime? useTime { get; set; } = DateTime.Now;
public int warrantyCycle { get; set; }
public int repairCycle { get; set; }
public float price { get; set; }
/// <summary>
/// 物品数量(件标:个数 箱标:箱数)
/// </summary>
public int needNum { get; set; }
/// <summary>
/// 单箱装箱个数
/// </summary>
public int oneBoxNum { get; set; }
public string warehouseId { get; set; }
public string warehouseName { get; set; }
/// <summary>
/// 是否是拆箱生成的标签
/// </summary>
public bool IsUnboxingLabel { get; set; }
/// <summary>
/// 是否是重装箱
/// </summary>
public bool IsReloadBoxing { get; set; }
/// <summary>
/// 货架id
/// </summary>
public string ShelfId { get; set; }
/// <summary>
/// 货架名称
/// </summary>
public string ShelfName { get; set; }
/// <summary>
/// 货架排
/// </summary>
public int ShelfRange { get; set; }
/// <summary>
/// 货架行
/// </summary>
public int ShelfRow { get; set; }
/// <summary>
/// 货架列
/// </summary>
public int ShelfColumn { get; set; }
/// <summary>
/// 货架信息(拼接)
/// </summary>
[JsonIgnore]
public string ShelfInfo
{
get
{
var str = ShelfName;
if (ShelfRange != 0)
{
str += "-" + ShelfRange;
if (ShelfColumn != 0)
{
str += "-" + ShelfColumn;
if (ShelfRow != 0)
{
str += "-" + ShelfRow;
}
}
}
return str;
}
}
[JsonIgnore]
public int num { get; set; }
[JsonIgnore]
public string epc { get; set; }
/// <summary>
/// 箱标epcList(json)
/// </summary>
[JsonIgnore]
public string epcListJson { get; set; }
[JsonIgnore]
public int type { get; set; }
[JsonIgnore]
public bool isdelete { get; set; } = false;
[JsonIgnore]
public bool _isSelected { get; set; }
[JsonIgnore]
public bool IsSelected
{
get
{
return _isSelected;
}
set
{
_isSelected = value;
RaisePropertyChanged();
}
}
[JsonIgnore]
public DateTime? createTime { get; set; }
[JsonIgnore]
public string batchNo { get; set; }
[JsonIgnore]
public string orgId { get; set; }
/// <summary>
/// 标签打印时间
/// </summary>
[JsonIgnore]
public DateTime PrintTime { get; set; }
/// <summary>
/// 是否为旧数据导入成功
/// </summary>
[JsonIgnore]
public bool IsImported { get; set; }
}
}
namespace JmpZbModel.Model
{
public class request_equipment
{
public string supplierID { get; set; }
public string equipmentID { get; set; }
public string epc { get; set; }
public string equipmentSizeID { get; set; }
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace JmpZbPrint.Model
{
public class request_ext_info
{
public string supplierName { get; set; }
public DateTime? productTime { get; set; }
public DateTime? useTime { get; set; }
public int warrantyCycle { get; set; }
public int repairCycle { get; set; }
public float price { get; set; }
public string supplierId { get; set; }
public string equCode { get; set; }
public string supplierCode { get; set; }
public string sizeCode { get; set; }
public string detailId { get; set; }
public int quantity { get; set; }
public string shelfId { get; set; }
public int shelfRange { get; set; }
public int shelfRow { get; set; }
public int shelfColumn { get; set; }
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace JmpZbPrint.Model
{
public class request_head
{
public string warehouseid { get; set; }
public string userid { get; set; }
public string orgid { get; set; }
public List<Equipment> equipments { get; set; } = new List<Equipment>();
}
public class Equipment
{
public string supplierid { get; set; }
public string equipmentid { get; set; }
public string epc { get; set; }
public string equipmentsizeid { get; set; }
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace JmpZbPrint.Model
{
public class request_int_info
{
public string labelType { get; set; }
public int warrantyCycle { get; set; }
public DateTime? productTime { get; set; }
public string equCode { get; set; }
public string supplierCode { get; set; }
public string sizeCode { get; set; }
public int oneBoxNum { get; set; }
public int quantity { get; set; }
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace JmpZbPrint.Model
{
public class request_sign
{
public string appKey { get; set; } = string.Empty;
public string orgId { get; set; } = string.Empty;
public string version { get; set; } = "1.0";
public string timestamp { get; set; }
public string body { get; set; }
public string sign { get; set; }
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using Newtonsoft.Json;
namespace JmpZbPrint.Model
{
public class respone_bagInventory
{
public string epc { get; set; }
public string id { get; set; }
public DateTime createTime { get; set; }
public int oneBoxNum { get; set; }
public string bagName { get; set; }
public string bagId { get; set; }
public int number { get; set; }
public string warehouseId { get; set; }
public string warehouseName { get; set; }
public string organizationId { get; set; }
public string invInfo { get; set; }
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using Newtonsoft.Json;
namespace JmpZbPrint.Model
{
public class respone_boxMark
{
public string epc { get; set; }
public string id { get; set; }
public DateTime createTime { get; set; }
public int oneBoxNum { get; set; }
public string warehouseId { get; set; }
public string warehouseName { get; set; }
public string orgizationId { get; set; }
public string equipmentDetailId { get; set; }
public string equipmentDetailName { get; set; }
public string equipmentDetailCode { get; set; }
public string sizeId { get; set; }
public string sizeName { get; set; }
public string sizeCode { get; set; }
public int sizeEpcType { get; set; }
public string supplierId { get; set; }
public string supplierName { get; set; }
public string oldEpc { get; set; }
public string productTime { get; set; }
public string useTime { get; set; }
public string warrantyCycle { get; set; }
public string repairCycle { get; set; }
public string price { get; set; }
public List<string> epcList { get; set; }
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace JmpZbPrint.Model
{
public class respone_epc
{
public string epc { get; set; }
public int num { get; set; }
}
}
using JmpZbModel.Model;
using JmpZbPrint.Common;
using System.Collections.Generic;
using System.ComponentModel;
namespace JmpZbPrint.Model
{
public class respone_head<T>
{
public int code { get; set; }
public string msg { get; set; }
public T data { get; set; }
}
public class respone_order
{
public int total { get; set; }
public List<order_info> record { get; set; }
}
public class respone_supplier
{
public int total { get; set; }
public List<Supplier> record { get; set; }
}
public class respone_print
{
public int total { get; set; }
public List<print_info> record { get; set; }
}
public class respone_data
{
public int total { get; set; }
public int pages { get; set; }
public int size { get; set; }
public List<order_info> record { get; set; }
public int current { get; set; }
}
//public class EquipmentInfo
//{
// public string equipmentDetailID { get; set; } = string.Empty;
// public string equipmentDetailName { get; set; } = string.Empty;
// public List<Supplier> supplierList { get; set; } = new List<Supplier>();
// public List<Size> equipmentSizeList { get; set; } = new List<Size>();
//}
//public class Supplier
//{
// public string supplierID { get; set; }
// public string supplierName { get; set; }
//}
//public class Size
//{
// public string sizeName { get; set; }
// public string sizeId { get; set; }
// public string sizeCode { get; set; }
//}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace JmpZbPrint.Model
{
public class respone_import_old_data
{
public List<respone_import_old_data_detail> successList { get; set; }
public List<respone_import_old_data_detail> failList { get; set; }
}
public class respone_import_old_data_detail
{
public string epc { get; set; }
public string message { get; set; }
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace JmpZbPrint.Model
{
public class respone_inventory
{
public string id { get; set; }
public DateTime createTime { get; set; }
public string epc { get; set; }
public string warehouseId { get; set; }
public string warehouseName { get; set; }
public string orgizationId { get; set; }
public string equipmentDetailId { get; set; }
public string equipmentDetailName { get; set; }
public string equipmentDetailCode { get; set; }
public string sizeId { get; set; }
public string sizeName { get; set; }
public string sizeCode { get; set; }
public int sizeEpcType { get; set; }
public string supplierId { get; set; }
public string supplierCode { get; set; }
public string supplierName { get; set; }
public decimal price { get; set; }
public DateTime? productTime { get; set; }
public int repairCycle { get; set; }
public DateTime? useTime { get; set; }
public int warrantyCycle { get; set; }
public string shelfId { get; set; }
public int? shelfRange { get; set; }
public int? shelfRow { get; set; }
public int? shelfColumn { get; set; }
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace JmpZbPrint.Model
{
public class respone_postek_msg
{
public string retval { get; set; }
public string msg { get; set; }
public string ReceiveData { get; set; }
}
}
namespace JmpZbPrint.Model
{
public class respone_update
{
public string version2 { get; set; }
public int version { get; set; }
public string name { get; set; }
public string appCode { get; set; }
public string note { get; set; }
public string address { get; set; }
public string updateTime { get; set; }
public string fileMd5 { get; set; }
public bool isAutoUpdate { get; set; }
public string autoUpdateAddress { get; set; }
public string autoUpdateFileMd5 { get; set; }
public string autoUpdateVersion2 { get; set; }
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace JmpZbPrint.Model
{
public class respone_user
{
public string id { get; set; }
public string username { get; set; }
public bool enabled { get; set; }
public respone_org baseJpOrganization { get; set; }
public policeman policeman { get; set; }
}
public class respone_org
{
public string id { get; set; }
public string name { get; set; }
public string code { get; set; }
public string findCode { get; set; }
}
public class policeman
{
public string id { get; set; }
public string name { get; set; }
public string policeCode { get; set; }
}
}
using GalaSoft.MvvmLight;
using System.Collections.Generic;
using System.Windows.Documents;
namespace JmpZbModel.Model
{
public class tb_general_task : ViewModelBase
{
public int Id { get; set; }
public string pmdm { get; set; }
public string pmmc { get; set; }
public string hx { get; set; }
public string hxdm { get; set; }
public string gysdm { get; set; }
public string gysmc { get; set; }
public int totalqty { get; set; }
public string type { get; set; }
public int remainqty { get; set; }
public bool issucceed { get; set; }
private bool _select = false;
public bool select
{
get
{
return _select;
}
set
{
_select = value;
this.RaisePropertyChanged(() => select);
}
}
public string epc { get; set; }
}
}
<Window x:Class="JmpZbPrint.ModifyPrint"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:materialDesign="http://materialdesigninxaml.net/winfx/xaml/themes"
xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
xmlns:local="clr-namespace:JmpZbPrint"
xmlns:System="clr-namespace:System;assembly=mscorlib"
mc:Ignorable="d"
Title="新增打印任务" Height="360" Width="450" AllowsTransparency="True" WindowStyle="None"
ResizeMode="NoResize" Loaded="OnWindowLoaded" WindowStartupLocation="CenterScreen">
<Window.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="pack://application:,,,/MaterialDesignThemes.Wpf;component/Themes/MaterialDesignTheme.TextBox.xaml" />
<ResourceDictionary Source="pack://application:,,,/MaterialDesignThemes.Wpf;component/Themes/MaterialDesignTheme.DataGrid.xaml" />
</ResourceDictionary.MergedDictionaries>
<SolidColorBrush x:Key="PrimaryHueLightBrush" Color="#0093EA"/>
<SolidColorBrush x:Key="PrimaryHueLightForegroundBrush" Color="#FFFFFF"/>
<SolidColorBrush x:Key="PrimaryHueMidBrush" Color="#0093EA"/>
<SolidColorBrush x:Key="PrimaryHueMidForegroundBrush" Color="#FFFFFF"/>
<SolidColorBrush x:Key="PrimaryHueDarkBrush" Color="#0093EA"/>
<SolidColorBrush x:Key="PrimaryHueDarkForegroundBrush" Color="#FFFFFF"/>
<!-- accent -->
<SolidColorBrush x:Key="SecondaryAccentBrush" Color="#0093EA"/>
<SolidColorBrush x:Key="SecondaryAccentForegroundBrush" Color="#FFFFFF"/>
</ResourceDictionary>
</Window.Resources>
<Border BorderBrush="#0092ea" CornerRadius="3" BorderThickness=".8" >
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="50"/>
<RowDefinition Height="50"/>
<RowDefinition Height="5"/>
<RowDefinition Height="50"/>
<RowDefinition Height="5"/>
<RowDefinition Height="50"/>
<RowDefinition Height="5"/>
<RowDefinition Height="50"/>
<RowDefinition Height="20"/>
<RowDefinition Height="auto"/>
<RowDefinition Height="50"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="50"/>
<ColumnDefinition Width="100"/>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="50"/>
</Grid.ColumnDefinitions>
<TextBlock x:Name="txtTitle" Text="新建打印任务" Grid.Row="0" Grid.ColumnSpan="3" FontSize="20" Foreground="#0092ea" VerticalAlignment="Top" Margin="170 15 0 0"/>
<TextBlock Text="&#xE618;" MouseLeftButtonDown="OnClose" Grid.Row="0" Grid.Column="3" Style="{StaticResource FiconBase}" x:Name="tbclose"
HorizontalAlignment="Right" VerticalAlignment="Top"
Margin="0 5 10 0" FontSize="35" Foreground="#8a8a8a" />
<Label VerticalAlignment="Center" Grid.Row="1" Grid.Column="1" FontSize="18" HorizontalAlignment="Right">物资品名:</Label>
<ComboBox x:Name="cboWz" Grid.Row="1" ItemsSource="{Binding}" SelectedValuePath="equipmentDetailID" DisplayMemberPath="equipmentDetailName" SelectionChanged="OnWzSelectionChanged" materialDesign:HintAssist.HintOpacity=".26" Style="{StaticResource MaterialDesignFloatingHintComboBox}" IsDropDownOpen="False" IsEditable="True" Grid.Column="2" Margin="10,0,0,0" Width="250" FontSize="18" Background="White" materialDesign:HintAssist.Hint="请选择物资"/>
<Label VerticalAlignment="Center" Grid.Row="3" Grid.Column="1" FontSize="18" HorizontalAlignment="Right">物资号型:</Label>
<ComboBox Margin="10,0,0,0" Name="cboHx" Width="250" Grid.Row="3" Grid.Column="2" SelectedValuePath="sizeId" DisplayMemberPath="sizeName" materialDesign:HintAssist.HintOpacity=".26" Style="{StaticResource MaterialDesignFloatingHintComboBox}" IsEditable="True" FontSize="18" Background="White" materialDesign:HintAssist.Hint="请选择号型"/>
<Label VerticalAlignment="Center" FontSize="18" Grid.Row="5" Grid.Column="1" HorizontalAlignment="Right">供应商:</Label>
<ComboBox Margin="10,0,0,0" Name="cboGys" Width="250" Grid.Row="5" Grid.Column="2" SelectedValuePath="supplierID" DisplayMemberPath="supplierName" materialDesign:HintAssist.HintOpacity=".26" Style="{StaticResource MaterialDesignFloatingHintComboBox}" IsEditable="True" FontSize="18" Background="White" materialDesign:HintAssist.Hint="请选择供应商"/>
<Label VerticalAlignment="Center" Grid.Row="7" Grid.Column="1" FontSize="18" HorizontalAlignment="Right">打印数量:</Label>
<TextBox Margin="10,0,0,0" Name="txtNum" Grid.Row="7" Grid.Column="2" VerticalAlignment="Bottom" Width="250" FontSize="20" Background="White" materialDesign:HintAssist.Hint="请输入数量" >
</TextBox>
<Button FontSize="20" Grid.Row="9" Click="OnSaveClick" HorizontalAlignment="Right" Content="保存" Style="{StaticResource MaterialDesignRaisedButton}" Height="40" Width="100" VerticalAlignment="Bottom" Grid.Column="1" Margin="0,5,161,0" Grid.ColumnSpan="2"/>
<Button FontSize="20" Grid.Row="9" Click="OnCancelClick" HorizontalAlignment="Right" Content="取消" Background="DarkOrange" BorderBrush="Orange" Style="{StaticResource MaterialDesignRaisedButton}" Height="40" Width="100" VerticalAlignment="Bottom" Grid.Column="2" Margin="0,5,26,0"/>
</Grid>
</Border>
</Window>
using JmpZbModel.Model;
using JmpZbPrint.Common;
using JmpZbPrint.Model;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
namespace JmpZbPrint
{
/// <summary>
/// ModifyPrint.xaml 的交互逻辑
/// </summary>
public partial class ModifyPrint : Window
{
private string type = "打印";
public ModifyPrint(string type = "打印")
{
InitializeComponent();
this.type = type;
if (type == "绑定")
{
txtTitle.Text = "新建绑定任务";
}
}
//public List<Supplier> SupplierList
//{
// get;
// set;
//} = new List<Supplier>();
//public event Action OnUpdateTask;
//public List<EquipmentInfo> EquipmentList
//{
// get;
// set;
//} = new List<EquipmentInfo>();
//protected List<JmpZbPrint.Model.Size> SizeList
//{
// get;
// set;
//} = new List<Model.Size>();
private void OnWindowLoaded(object sender, RoutedEventArgs e)
{
//EquipmentList = CaChe.WzList;
//cboWz.ItemsSource = EquipmentList;
}
private void OnWzSelectionChanged(object sender, SelectionChangedEventArgs e)
{
//var eid = cboWz.SelectedValue?.ToString() ?? "";
//if (!string.IsNullOrEmpty(eid))
//{
// var tmp_item = cboWz.SelectedItem as EquipmentInfo;
// SizeList = new List<Model.Size>(tmp_item.equipmentSizeList);
// cboHx.ItemsSource = SizeList;
// SupplierList = new List<Supplier>(tmp_item.supplierList);
// cboGys.ItemsSource = SupplierList;
//}
}
private void OnSaveClick(object sender, RoutedEventArgs e)
{
if (cboWz.SelectedValue == null)
{
MessageBox.Show("物资未选择", "提示", MessageBoxButton.OK, MessageBoxImage.Warning);
}
else if (cboHx.SelectedValue == null)
{
MessageBox.Show("号型未选择", "提示", MessageBoxButton.OK, MessageBoxImage.Warning);
}
else if (cboGys.SelectedValue == null)
{
MessageBox.Show("供应商未选择", "提示", MessageBoxButton.OK, MessageBoxImage.Warning);
}
else if (!int.TryParse(txtNum.Text, out int qty) || qty <= 0)
{
MessageBox.Show("打印数量不正确", "提示", MessageBoxButton.OK, MessageBoxImage.Warning);
}
else
{
//var supplier = cboGys.SelectedItem as Supplier;
//var size = cboHx.SelectedItem as Model.Size;
//var enqui = cboWz.SelectedItem as EquipmentInfo;
//List<string> epcList = HttpHelper.GetEpcList(qty);
//var result = false;
//for (int i = 0; i < qty; i++)
//{
// result = DbFactory.Insert(new tb_general_task()
// {
// gysdm = supplier.supplierID,
// gysmc = supplier.supplierName,
// hx = size.sizeName,
// hxdm = size.sizeId,
// issucceed = false,
// pmdm = enqui.equipmentDetailID,
// pmmc = enqui.equipmentDetailName,
// remainqty = 1,
// totalqty = 1,
// type = type,
// epc = epcList[i]
// });
//}
//if (result)
//{
// //写入到本地数据库
// OnUpdateTask?.Invoke();
// MessageBox.Show("新建成功", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
//}
//else
//{
// MessageBox.Show("数据写入失败", "提示", MessageBoxButton.OK, MessageBoxImage.Error);
//}
}
}
private void OnCancelClick(object sender, RoutedEventArgs e)
{
this.Close();
}
private void OnClose(object sender, MouseButtonEventArgs e)
{
this.Close();
}
}
}
<UserControl x:Class="JmpZbPrint.PagePartial.GenEpcWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:materialDesign="http://materialdesigninxaml.net/winfx/xaml/themes"
xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
xmlns:pu="clr-namespace:Panuon.UI.Silver;assembly=Panuon.UI.Silver"
xmlns:convert="clr-namespace:JmpZbPrint.Common"
xmlns:UsControl="clr-namespace:JmpZbPrint.UsControl"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:JmpZbPrint.PagePartial"
mc:Ignorable="d" Background="#ffffff" Margin="0,20,0,0"
>
<i:Interaction.Triggers>
<i:EventTrigger EventName="Loaded">
<i:InvokeCommandAction Command="{Binding OnWindowLoadCmd}" />
</i:EventTrigger>
</i:Interaction.Triggers>
<UserControl.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="pack://application:,,,/MaterialDesignThemes.Wpf;component/Themes/MaterialDesignTheme.TextBox.xaml" />
<ResourceDictionary Source="pack://application:,,,/MaterialDesignThemes.Wpf;component/Themes/MaterialDesignTheme.DataGrid.xaml" />
<ResourceDictionary Source="pack://application:,,,/MaterialDesignThemes.Wpf;component/Themes/MaterialDesignTheme.TextBlock.xaml" />
</ResourceDictionary.MergedDictionaries>
<SolidColorBrush x:Key="PrimaryHueLightBrush" Color="#0093EA"/>
<SolidColorBrush x:Key="PrimaryHueLightForegroundBrush" Color="#FFFFFF"/>
<SolidColorBrush x:Key="PrimaryHueMidBrush" Color="#0093EA"/>
<SolidColorBrush x:Key="PrimaryHueMidForegroundBrush" Color="#FFFFFF"/>
<SolidColorBrush x:Key="PrimaryHueDarkBrush" Color="#0093EA"/>
<SolidColorBrush x:Key="PrimaryHueDarkForegroundBrush" Color="#FFFFFF"/>
<!-- accent -->
<SolidColorBrush x:Key="SecondaryAccentBrush" Color="#0093EA"/>
<SolidColorBrush x:Key="SecondaryAccentForegroundBrush" Color="#FFFFFF"/>
</ResourceDictionary>
</UserControl.Resources>
<Grid x:Name="g_main">
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition Height="70"/>
</Grid.RowDefinitions>
<Grid x:Name="g_body" Grid.Row="0">
<Grid.RowDefinitions>
<RowDefinition Height="80"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Grid Grid.Row="0" Grid.Column="0" Margin="0,0,0,0" >
<Grid.ColumnDefinitions>
<ColumnDefinition Width="20"/>
<ColumnDefinition Width="1*"/>
<ColumnDefinition Width="20"/>
<ColumnDefinition Width="1*"/>
<ColumnDefinition Width="20"/>
<ColumnDefinition Width="1*"/>
</Grid.ColumnDefinitions>
<!--<Grid Grid.Column="1" >
<Grid.ColumnDefinitions>
<ColumnDefinition Width="110"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<TextBlock Text="申请日期:" Grid.Column="0" FontSize="20" HorizontalAlignment="Center" VerticalAlignment="Center"/>
<DatePicker Grid.Column="1" SelectedDate="{Binding CreateTime,UpdateSourceTrigger=PropertyChanged}" materialDesign:HintAssist.HintOpacity=".26" Width="200" FontSize="18" Margin="0,0,0,12" Style="{StaticResource MaterialDesignFloatingHintDatePicker}" />
</Grid>-->
<Grid Grid.Column="1">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="110"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<TextBlock Text="装备名称:" Grid.Column="0" FontSize="20" HorizontalAlignment="Center" VerticalAlignment="Center"/>
<TextBox x:Name="txt_name" Grid.Column="1" Text="{Binding EquName,UpdateSourceTrigger=PropertyChanged}" Height="35" FontSize="18" Background="White" materialDesign:HintAssist.Hint="装备名称"/>
</Grid>
<Grid Grid.Column="3" >
<Grid.ColumnDefinitions>
<ColumnDefinition Width="110"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<TextBlock Text="订单号:" Grid.Column="0" FontSize="20" HorizontalAlignment="Center" VerticalAlignment="Center"/>
<TextBox x:Name="txt_vendor" Grid.Column="1" Text="{Binding OrderCode,UpdateSourceTrigger=PropertyChanged}" Height="35" FontSize="18" Background="White" materialDesign:HintAssist.Hint="采购订单号"/>
</Grid>
<StackPanel Grid.Column="5" Orientation="Horizontal">
<Button FontSize="20" x:Name="btnQuery" Content="查询" Command="{Binding OnQueryCommand}" Style="{StaticResource MaterialDesignRaisedButton}" Margin="20,0,0,0" Height="45" Width="120" HorizontalAlignment="Center" VerticalAlignment="Center"/>
</StackPanel>
</Grid>
<DataGrid ScrollViewer.HorizontalScrollBarVisibility="Visible" ScrollViewer.VerticalScrollBarVisibility="Visible" IsEnabled="{Binding BindingEnabled,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" EnableRowVirtualization="False" x:Name="g_gen" Margin="3 5 3 0" Grid.Row="1" Grid.RowSpan="2" BorderBrush="#dedede" FontSize="20" Foreground="#37537d" HeadersVisibility="Column"
GridLinesVisibility="None" Background="Transparent" BorderThickness="1" CanUserAddRows="False"
AutoGenerateColumns="False" LoadingRow="OnDataGridLoadingRow" ItemsSource="{Binding UiGenList,UpdateSourceTrigger=PropertyChanged}" SelectionMode="Single" RowBackground="Transparent" CanUserSortColumns="True" >
<i:Interaction.Triggers>
<i:EventTrigger EventName="Loaded">
<i:InvokeCommandAction Command="{Binding OnGridLoadedCmd}" />
</i:EventTrigger>
</i:Interaction.Triggers>
<DataGrid.Resources>
<ResourceDictionary>
<convert:PrintTypeConvert x:Key="ptconv"/>
</ResourceDictionary>
</DataGrid.Resources>
<DataGrid.ColumnHeaderStyle>
<Style TargetType="{x:Type DataGridColumnHeader}">
<Setter Property="BorderThickness" Value="0"/>
<Setter Property="VerticalAlignment" Value="Center"/>
<Setter Property="HorizontalContentAlignment" Value="Center"/>
<Setter Property="Background" Value="Transparent"/>
<Setter Property="Foreground" Value="#4682B4"/>
<Setter Property="FontSize" Value="20"/>
<Setter Property="Height" Value="38"/>
</Style>
</DataGrid.ColumnHeaderStyle>
<DataGrid.RowStyle>
<Style TargetType="{x:Type DataGridRow}">
<Style.Triggers>
<Trigger Property="ItemsControl.AlternationIndex" Value="0">
<Setter Property="Background" Value="Transparent"/>
<Setter Property="BorderBrush" Value="Transparent"/>
</Trigger>
<Trigger Property="ItemsControl.AlternationIndex" Value="1">
<Setter Property="Background" Value="#EBEBEB"/>
<Setter Property="Opacity" Value="0.4"/>
</Trigger>
</Style.Triggers>
</Style>
</DataGrid.RowStyle>
<DataGrid.Columns>
<DataGridCheckBoxColumn Binding="{Binding IsSelected,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"
ElementStyle="{StaticResource MaterialDesignDataGridCheckBoxColumnStyle}"
EditingElementStyle="{StaticResource MaterialDesignDataGridCheckBoxColumnEditingStyle}">
<DataGridCheckBoxColumn.Header>
<CheckBox x:Name="chk_gen" HorizontalAlignment="Center" IsChecked="{Binding IsSelectAll,UpdateSourceTrigger=PropertyChanged,Mode=Default}" />
</DataGridCheckBoxColumn.Header>
</DataGridCheckBoxColumn>
<DataGridTemplateColumn Header="序号" Width="100" >
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBlock FontSize="18" Text="{Binding RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type DataGridRow}}, Path=Header}" HorizontalAlignment="Left" VerticalAlignment="Center" Margin="5,0,0,0"/>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
<DataGridTextColumn Header="采购订单号" IsReadOnly="True" Width="auto" FontSize="18" MinWidth="150" Binding="{Binding orderCode}" ElementStyle="{StaticResource TextCenterStyle}" />
<DataGridTextColumn Header="装备名称" IsReadOnly="True" Width="auto" FontSize="18" MinWidth="100" Binding="{Binding equName}" ElementStyle="{StaticResource TextCenterStyle}" />
<DataGridTextColumn Header="装备号型" IsReadOnly="True" Width="auto" FontSize="18" MinWidth="100" Binding="{Binding sizeName}" ElementStyle="{StaticResource TextCenterStyle}"/>
<DataGridTextColumn Header="申请数量" IsReadOnly="True" Width="auto" MinWidth="100" FontSize="18" Binding="{Binding totalNum}" ElementStyle="{StaticResource TextCenterStyle}"/>
<DataGridTextColumn Header="剩余数量" IsReadOnly="True" Width="auto" MinWidth="100" FontSize="18" Binding="{Binding reNum}" ElementStyle="{StaticResource TextCenterStyle}"/>
<DataGridTextColumn Header="申请日期" IsReadOnly="True" Width="auto" MinWidth="150" FontSize="18" Binding="{Binding createTime}" ElementStyle="{StaticResource TextCenterStyle}"/>
<DataGridTemplateColumn Header="操作" MinWidth="180" >
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal" VerticalAlignment="Center" HorizontalAlignment="Center">
<Button Content="生成" Command="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType=DataGrid}, Path=DataContext.OnGenTagCmd}" CommandParameter="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType=DataGrid}, Path=SelectedValue}" Margin="5,0,5,0" >
</Button>
</StackPanel>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
</Grid>
<UsControl:PageControl IsEnabled="{Binding StartButton}" x:Name="d_pager" Margin="3,0,3,0" Grid.Row="1" TotalRecord="{Binding TotalRecord,Mode=TwoWay}" TotalPage="{Binding PageTotal,Mode=TwoWay}" PageSize="{Binding PageSize,Mode=TwoWay}" PageIndex="{Binding PageIndex,Mode=TwoWay}">
<i:Interaction.Triggers>
<i:EventTrigger EventName="OnPageChanged">
<i:InvokeCommandAction Command="{Binding OnPageChangeCmd}" />
</i:EventTrigger>
</i:Interaction.Triggers>
</UsControl:PageControl>
</Grid>
</UserControl>
using JmpZbPrint.ViewModel;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Media.TextFormatting;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace JmpZbPrint.PagePartial
{
/// <summary>
/// GenEpcWindow.xaml 的交互逻辑
/// </summary>
public partial class GenEpcWindow : UserControl
{
public GenEpcWindow()
{
InitializeComponent();
var vm= new GenEpcViewModel();
this.DataContext = vm;
chk_gen.DataContext = vm;
}
private object syncObj = new object();
private void OnDataGridLoadingRow(object sender, DataGridRowEventArgs e)
{
lock (syncObj)
{
e.Row.Header = e.Row.GetIndex() + 1;
}
}
//private void SelectItemClick(object sender, RoutedEventArgs e)
//{
// CheckBox chk = (CheckBox)sender;
// for (int i = 0; i < g_task.Items.Count; i++)
// {
// //获取行
// DataGridRow neddrow = (DataGridRow)g_task.ItemContainerGenerator.ContainerFromIndex(i);
// //获取该行的某列
// CheckBox cb = (CheckBox)g_task.Columns[0].GetCellContent(neddrow);
// cb.IsChecked = chk.IsChecked;
// }
//}
}
}
<UserControl x:Class="JmpZbPrint.PagePartial.IntBindWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:materialDesign="http://materialdesigninxaml.net/winfx/xaml/themes"
xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
xmlns:pu="clr-namespace:Panuon.UI.Silver;assembly=Panuon.UI.Silver"
xmlns:convert="clr-namespace:JmpZbPrint.Common"
xmlns:UsControl="clr-namespace:JmpZbPrint.UsControl"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:JmpZbPrint.PagePartial"
mc:Ignorable="d" Background="#ffffff" Margin="0,20,0,0" >
<i:Interaction.Triggers>
<i:EventTrigger EventName="Loaded">
<i:InvokeCommandAction Command="{Binding OnWindowLoadCmd}" />
</i:EventTrigger>
</i:Interaction.Triggers>
<UserControl.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="pack://application:,,,/MaterialDesignThemes.Wpf;component/Themes/MaterialDesignTheme.TextBox.xaml" />
<ResourceDictionary Source="pack://application:,,,/MaterialDesignThemes.Wpf;component/Themes/MaterialDesignTheme.DataGrid.xaml" />
<ResourceDictionary Source="pack://application:,,,/MaterialDesignThemes.Wpf;component/Themes/MaterialDesignTheme.TextBlock.xaml" />
</ResourceDictionary.MergedDictionaries>
<SolidColorBrush x:Key="PrimaryHueLightBrush" Color="#0093EA"/>
<SolidColorBrush x:Key="PrimaryHueLightForegroundBrush" Color="#FFFFFF"/>
<SolidColorBrush x:Key="PrimaryHueMidBrush" Color="#0093EA"/>
<SolidColorBrush x:Key="PrimaryHueMidForegroundBrush" Color="#FFFFFF"/>
<SolidColorBrush x:Key="PrimaryHueDarkBrush" Color="#0093EA"/>
<SolidColorBrush x:Key="PrimaryHueDarkForegroundBrush" Color="#FFFFFF"/>
<!-- accent -->
<SolidColorBrush x:Key="SecondaryAccentBrush" Color="#0093EA"/>
<SolidColorBrush x:Key="SecondaryAccentForegroundBrush" Color="#FFFFFF"/>
</ResourceDictionary>
</UserControl.Resources>
<Grid x:Name="g_main">
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition Height="70"/>
<RowDefinition Height="100"/>
</Grid.RowDefinitions>
<Grid x:Name="g_body" Grid.Row="0">
<Grid.RowDefinitions>
<RowDefinition Height="80"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Grid Grid.Row="0" Grid.Column="0" Margin="0,0,0,0" >
<Grid.ColumnDefinitions>
<ColumnDefinition Width="20"/>
<ColumnDefinition Width="1*"/>
<ColumnDefinition Width="20"/>
<ColumnDefinition Width="1*"/>
<ColumnDefinition Width="20"/>
<ColumnDefinition Width="500"/>
<ColumnDefinition Width="0.1*"/>
</Grid.ColumnDefinitions>
<Grid Grid.Column="1">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="100"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<TextBlock Text="装备名称:" Grid.Column="0" Width="100" FontSize="20" HorizontalAlignment="Left" VerticalAlignment="Center"/>
<TextBox x:Name="txt_name" Grid.Column="1" Text="{Binding EquName,UpdateSourceTrigger=PropertyChanged}" MinWidth="150" Height="35" FontSize="18" Background="White" materialDesign:HintAssist.Hint="装备名称" Margin="-0.4,22,-0.2,22" />
</Grid>
<Grid Grid.Column="3" >
<Grid.ColumnDefinitions>
<ColumnDefinition Width="80"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<TextBlock Text="供应商:" Grid.Column="0" FontSize="20" HorizontalAlignment="Center" VerticalAlignment="Center"/>
<TextBox x:Name="txt_vendor" Grid.Column="1" Text="{Binding VendorName,UpdateSourceTrigger=PropertyChanged}" Height="35" FontSize="18" Background="White" materialDesign:HintAssist.Hint="供应商名称"/>
</Grid>
<UniformGrid Grid.Column="5" Columns="4">
<Button FontSize="20" x:Name="btnQuery" Content="查询" Command="{Binding OnQueryCommand}" Style="{StaticResource MaterialDesignRaisedButton}" Height="45" Width="120" HorizontalAlignment="Center" VerticalAlignment="Center"/>
<Button FontSize="20" Content="生成任务" Command="{Binding OnGenCommand}" Style="{StaticResource MaterialDesignRaisedButton}" Margin="20,0,0,0" Height="45" Width="120" HorizontalAlignment="Center" VerticalAlignment="Center"/>
<Button FontSize="20" Content="装箱" BorderBrush="#CC7033" Background="#CC7033" Command="{Binding OnBoxingCmd}" Style="{StaticResource MaterialDesignRaisedButton}" Margin="20,0,0,0" Height="45" Width="120" HorizontalAlignment="Center" VerticalAlignment="Center"/>
<Button FontSize="20" Content="删除任务" BorderBrush="OrangeRed" Background="OrangeRed" Command="{Binding OnDeleteTagCmd}" Style="{StaticResource MaterialDesignRaisedButton}" Margin="20,0,0,0" Height="45" Width="120" HorizontalAlignment="Center" VerticalAlignment="Center"/>
</UniformGrid>
</Grid>
<DataGrid ScrollViewer.HorizontalScrollBarVisibility="Visible" ScrollViewer.VerticalScrollBarVisibility="Visible" IsEnabled="{Binding BindButton}" EnableRowVirtualization="False" x:Name="g_task" Margin="3 5 3 0" Grid.Row="1" Grid.RowSpan="2" BorderBrush="#dedede" FontSize="20" Foreground="#37537d" HeadersVisibility="Column"
GridLinesVisibility="None" Background="Transparent" BorderThickness="1" CanUserAddRows="False"
AutoGenerateColumns="False" SelectionMode="Single" ItemsSource="{Binding BindTaskList,UpdateSourceTrigger=PropertyChanged}" LoadingRow="OnDataGridLoadingRow" RowBackground="Transparent" CanUserSortColumns="True" >
<i:Interaction.Triggers>
<i:EventTrigger EventName="Loaded">
<i:InvokeCommandAction Command="{Binding OnGridLoadedCmd}" />
</i:EventTrigger>
</i:Interaction.Triggers>
<DataGrid.Resources>
<ResourceDictionary>
<convert:PrintTypeConvert x:Key="ptconv"/>
<convert:BoolConvert x:Key="boolConv"/>
</ResourceDictionary>
</DataGrid.Resources>
<DataGrid.ColumnHeaderStyle>
<Style TargetType="{x:Type DataGridColumnHeader}">
<Setter Property="BorderThickness" Value="0"/>
<Setter Property="VerticalAlignment" Value="Center"/>
<Setter Property="HorizontalContentAlignment" Value="Center"/>
<Setter Property="Background" Value="Transparent"/>
<Setter Property="Foreground" Value="#4682B4"/>
<Setter Property="FontSize" Value="20"/>
<Setter Property="Height" Value="38"/>
</Style>
</DataGrid.ColumnHeaderStyle>
<DataGrid.RowStyle>
<Style TargetType="{x:Type DataGridRow}">
<Style.Triggers>
<Trigger Property="ItemsControl.AlternationIndex" Value="0">
<Setter Property="Background" Value="Transparent"/>
<Setter Property="BorderBrush" Value="Transparent"/>
</Trigger>
<Trigger Property="ItemsControl.AlternationIndex" Value="1">
<Setter Property="Background" Value="#EBEBEB"/>
<Setter Property="Opacity" Value="0.4"/>
</Trigger>
</Style.Triggers>
</Style>
</DataGrid.RowStyle>
<DataGrid.Columns>
<DataGridCheckBoxColumn Binding="{Binding IsSelected,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"
ElementStyle="{StaticResource MaterialDesignDataGridCheckBoxColumnStyle}"
EditingElementStyle="{StaticResource MaterialDesignDataGridCheckBoxColumnEditingStyle}">
<DataGridCheckBoxColumn.Header>
<CheckBox HorizontalAlignment="Center" Name="chk_pri" IsChecked="{Binding IsSelectAll,UpdateSourceTrigger=PropertyChanged,Mode=Default}"
/>
</DataGridCheckBoxColumn.Header>
</DataGridCheckBoxColumn>
<DataGridTemplateColumn Header="序号" MinWidth="80" >
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBlock FontSize="18" Text="{Binding RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type DataGridRow}}, Path=Header}" HorizontalAlignment="Left" VerticalAlignment="Center" Margin="5,0,0,0"/>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
<DataGridTextColumn Header="标签类型" IsReadOnly="True" MinWidth="100" Width="auto" FontSize="18" Binding="{Binding LabelType}" ElementStyle="{StaticResource TextCenterStyle}" />
<DataGridTextColumn Header="装备名称" IsReadOnly="True" Width="auto" MinWidth="100" FontSize="18" Binding="{Binding equName}" ElementStyle="{StaticResource TextCenterStyle}" />
<DataGridTextColumn Header="装备型号" IsReadOnly="True" Width="auto" MinWidth="100" FontSize="18" Binding="{Binding sizeName}" ElementStyle="{StaticResource TextCenterStyle}"/>
<DataGridTextColumn Header="生产日期" IsReadOnly="True" Width="auto" MinWidth="100" FontSize="18" Binding="{Binding productTime,StringFormat='yyyy-MM-dd HH:mm'}" ElementStyle="{StaticResource TextCenterStyle}"/>
<DataGridTextColumn Header="使用日期" IsReadOnly="True" Width="auto" MinWidth="100" FontSize="18" Binding="{Binding useTime,StringFormat='yyyy-MM-dd HH:mm'}" ElementStyle="{StaticResource TextCenterStyle}"/>
<DataGridTextColumn Header="质保周期" IsReadOnly="True" Width="auto" MinWidth="100" FontSize="18" Binding="{Binding warrantyCycle}" ElementStyle="{StaticResource TextCenterStyle}"/>
<DataGridTextColumn Header="维保周期" IsReadOnly="True" Width="auto" MinWidth="100" FontSize="18" Binding="{Binding repairCycle}" ElementStyle="{StaticResource TextCenterStyle}"/>
<DataGridTextColumn Header="单价" IsReadOnly="True" Width="auto" MinWidth="100" FontSize="18" Binding="{Binding price}" ElementStyle="{StaticResource TextCenterStyle}"/>
<DataGridTextColumn Header="件序号" IsReadOnly="True" Width="auto" MinWidth="100" FontSize="18" Binding="{Binding num}" ElementStyle="{StaticResource TextCenterStyle}"/>
<DataGridTextColumn Header="供应商" IsReadOnly="True" Width="auto" FontSize="18" Binding="{Binding suppilerName}" ElementStyle="{StaticResource TextCenterStyle}" />
<DataGridTextColumn Header="入库仓库" IsReadOnly="True" Width="auto" FontSize="18" Binding="{Binding warehouseName}" ElementStyle="{StaticResource TextCenterStyle}" />
<DataGridTextColumn Header="拆箱生成标记" IsReadOnly="True" MinWidth="100" Width="auto" FontSize="18" Binding="{Binding IsUnboxingLabel,Converter={StaticResource boolConv}}" ElementStyle="{StaticResource TextCenterStyle}" />
<DataGridTemplateColumn Header="操作" Width="auto" MinWidth="100" >
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal" VerticalAlignment="Center" HorizontalAlignment="Center">
<Button Content="绑定" Command="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType=DataGrid}, Path=DataContext.OnInitialTagCmd}" CommandParameter="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType=DataGrid}, Path=SelectedValue}" Margin="5,0,5,0" >
</Button>
</StackPanel>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
</Grid>
<UsControl:PageControl IsEnabled="{Binding BindButton}" x:Name="d_pager" Margin="3,0,3,0" Grid.Row="1" TotalRecord="{Binding TotalRecord,Mode=TwoWay}" TotalPage="{Binding PageTotal,Mode=TwoWay}" PageSize="{Binding PageSize,Mode=TwoWay}" PageIndex="{Binding PageIndex,Mode=TwoWay}">
<i:Interaction.Triggers>
<i:EventTrigger EventName="OnPageChanged">
<i:InvokeCommandAction Command="{Binding OnPageChangeCmd}" />
</i:EventTrigger>
</i:Interaction.Triggers>
</UsControl:PageControl>
<TextBlock Grid.Row="2" Text="{Binding UiMessage}" Foreground="{Binding MsgColor}" Style="{StaticResource MaterialDesignHeadline4TextBlock}" VerticalAlignment="Center" Margin="10,28,0,28" HorizontalAlignment="Left" Width="1078"/>
</Grid>
</UserControl>
using JmpZbPrint.ViewModel;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace JmpZbPrint.PagePartial
{
/// <summary>
/// GenEpcWindow.xaml 的交互逻辑
/// </summary>
public partial class IntBindWindow : UserControl
{
private IntBindViewModel vm;
public IntBindWindow()
{
InitializeComponent();
vm = new IntBindViewModel();
this.DataContext = vm;
chk_pri.DataContext = vm;
}
private object syncObj = new object();
private void OnDataGridLoadingRow(object sender, DataGridRowEventArgs e)
{
lock (syncObj)
{
e.Row.Header = e.Row.GetIndex() + 1;
}
}
public void Clearup()
{
vm.Cleanup();
}
}
}
<Window x:Class="JmpZbPrint.PagePartial.IntGenEpcWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:convert="clr-namespace:JmpZbPrint.Common"
xmlns:materialDesign="http://materialdesigninxaml.net/winfx/xaml/themes"
xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
xmlns:local="clr-namespace:JmpZbPrint"
xmlns:System="clr-namespace:System;assembly=mscorlib"
mc:Ignorable="d"
Height="600" Width="1366" WindowState="Maximized" AllowsTransparency="True" WindowStyle="None"
ResizeMode="NoResize" Loaded="OnWindowLoaded" Closed="Window_Closed" WindowStartupLocation="CenterScreen">
<Window.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="pack://application:,,,/MaterialDesignThemes.Wpf;component/Themes/MaterialDesignTheme.TextBox.xaml" />
<ResourceDictionary Source="pack://application:,,,/MaterialDesignThemes.Wpf;component/Themes/MaterialDesignTheme.DataGrid.xaml" />
<ResourceDictionary Source="pack://application:,,,/MaterialDesignThemes.Wpf;component/Themes/MaterialDesignTheme.TextBlock.xaml" />
</ResourceDictionary.MergedDictionaries>
<SolidColorBrush x:Key="PrimaryHueLightBrush" Color="#0093EA"/>
<SolidColorBrush x:Key="PrimaryHueLightForegroundBrush" Color="#FFFFFF"/>
<SolidColorBrush x:Key="PrimaryHueMidBrush" Color="#0093EA"/>
<SolidColorBrush x:Key="PrimaryHueMidForegroundBrush" Color="#FFFFFF"/>
<SolidColorBrush x:Key="PrimaryHueDarkBrush" Color="#0093EA"/>
<SolidColorBrush x:Key="PrimaryHueDarkForegroundBrush" Color="#FFFFFF"/>
<!-- accent -->
<SolidColorBrush x:Key="SecondaryAccentBrush" Color="#0093EA"/>
<SolidColorBrush x:Key="SecondaryAccentForegroundBrush" Color="#FFFFFF"/>
<Storyboard x:Key="Loading">
<ThicknessAnimation Duration="0:0:0.2" To="0" From="0,300,0,300"
Storyboard.TargetName="g_main" Storyboard.TargetProperty="Margin" />
</Storyboard>
<Storyboard x:Key="Closing">
<ThicknessAnimation FillBehavior="Stop" Duration="0:0:0.2" To="0,300,0,300" From="0" Storyboard.TargetName="g_main"
Storyboard.TargetProperty="Margin" Completed="Sb_Completed"/>
</Storyboard>
</ResourceDictionary>
</Window.Resources>
<Window.Effect>
<DropShadowEffect BlurRadius="10" Color="#FF858484" Direction="90" ShadowDepth="1"/>
</Window.Effect>
<Window.Triggers>
<EventTrigger RoutedEvent="FrameworkElement.Loaded" >
<BeginStoryboard Storyboard="{StaticResource Loading}"/>
</EventTrigger>
<EventTrigger RoutedEvent="UIElement.MouseLeftButtonDown" SourceName="tbclose">
<BeginStoryboard Storyboard="{StaticResource Closing}" />
</EventTrigger>
</Window.Triggers>
<Border BorderBrush="#0092ea" x:Name="g_main" CornerRadius="3" BorderThickness=".8" >
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="80"/>
<RowDefinition Height="*"/>
<RowDefinition Height="60"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<TextBlock x:Name="txtTitle" Text="生成绑定任务" FontSize="30" Foreground="#0092ea" VerticalAlignment="Top" Margin="20 20 0 0"/>
<TextBlock Text="&#xE618;" Style="{StaticResource FiconBase}" x:Name="tbclose"
HorizontalAlignment="Right" VerticalAlignment="Top"
Margin="0 20 20 0" FontSize="35" Foreground="#8a8a8a" />
<DataGrid EnableRowVirtualization="False" x:Name="g_order" Margin="3 5 3 0" Grid.Row="1" BorderBrush="#dedede" FontSize="20" Foreground="#37537d" HeadersVisibility="Column"
GridLinesVisibility="None" Background="Transparent" BorderThickness="1"
AutoGenerateColumns="False" SelectionMode="Single" RowBackground="Transparent" CanUserSortColumns="False" SelectionChanged="g_order_SelectionChanged" CanUserAddRows="False" CanUserResizeRows="False" >
<i:Interaction.Triggers>
<i:EventTrigger EventName="Loaded">
<i:InvokeCommandAction Command="{Binding OnGridLoadedCmd}" />
</i:EventTrigger>
</i:Interaction.Triggers>
<DataGrid.ColumnHeaderStyle>
<Style TargetType="{x:Type DataGridColumnHeader}">
<Setter Property="BorderThickness" Value="0"/>
<Setter Property="VerticalAlignment" Value="Center"/>
<Setter Property="HorizontalContentAlignment" Value="Center"/>
<Setter Property="Background" Value="Transparent"/>
<Setter Property="Foreground" Value="#4682B4"/>
<Setter Property="FontSize" Value="15"/>
<Setter Property="Height" Value="25"/>
</Style>
</DataGrid.ColumnHeaderStyle>
<DataGrid.RowStyle>
<Style TargetType="{x:Type DataGridRow}">
<Setter Property="Height" Value="45" />
<Style.Triggers>
<Trigger Property="ItemsControl.AlternationIndex" Value="0">
<Setter Property="Background" Value="Transparent"/>
<Setter Property="BorderBrush" Value="Transparent"/>
</Trigger>
<Trigger Property="ItemsControl.AlternationIndex" Value="1">
<Setter Property="Background" Value="#EBEBEB"/>
<Setter Property="Opacity" Value="0.4"/>
</Trigger>
</Style.Triggers>
</Style>
</DataGrid.RowStyle>
<DataGrid.Columns>
<!--<DataGridTextColumn Header="序号" Width="100" FontSize="13" IsReadOnly="True" Binding="{Binding rowNum}" ElementStyle="{Binding TextCenterStyle}"></DataGridTextColumn>-->
<DataGridTextColumn Header="标签类型" IsReadOnly="True" MinWidth="100" Width="auto" FontSize="13" Binding="{Binding LabelType}" ElementStyle="{StaticResource TextCenterStyle}" />
<DataGridTextColumn Header="装备名称" IsReadOnly="True" MinWidth="100" Width="auto" FontSize="13" Binding="{Binding equName}" ElementStyle="{StaticResource TextCenterStyle}" />
<DataGridTextColumn Header="装备型号" IsReadOnly="True" MinWidth="100" Width="auto" FontSize="13" Binding="{Binding sizeName}" ElementStyle="{StaticResource TextCenterStyle}"/>
<DataGridTextColumn Header="生产日期" IsReadOnly="True" MinWidth="100" Width="auto" FontSize="13" Binding="{Binding productTime, StringFormat='yyyy-MM-dd HH:mm'}"></DataGridTextColumn>
<DataGridTextColumn Header="使用日期" IsReadOnly="True" MinWidth="100" Width="auto" FontSize="13" Binding="{Binding useTime, StringFormat='yyyy-MM-dd HH:mm'}"></DataGridTextColumn>
<DataGridTextColumn Header="质保周期(月)" IsReadOnly="True" MinWidth="100" Width="auto" FontSize="13" Binding="{Binding warrantyCycle}"></DataGridTextColumn>
<DataGridTextColumn Header="维保周期(月)" IsReadOnly="True" MinWidth="100" Width="auto" FontSize="13" Binding="{Binding repairCycle}"></DataGridTextColumn>
<DataGridTextColumn Header="购入单价(元)" IsReadOnly="True" MinWidth="100" Width="auto" FontSize="13" Binding="{Binding price}"></DataGridTextColumn>
<DataGridTextColumn Header="货架" IsReadOnly="True" MinWidth="100" Width="auto" FontSize="13" Binding="{Binding ShelfInfo}"></DataGridTextColumn>
<DataGridTextColumn Header="数量/箱" IsReadOnly="True" MinWidth="100" Width="auto" FontSize="13" Binding="{Binding oneBoxNum}"></DataGridTextColumn>
<DataGridTextColumn Header="标签数量" IsReadOnly="True" MinWidth="100" Width="auto" FontSize="13" Binding="{Binding needNum}"></DataGridTextColumn>
<DataGridTextColumn Header="供应商" IsReadOnly="True" MinWidth="100" Width="auto" FontSize="13" Binding="{Binding suppilerName}"></DataGridTextColumn>
<DataGridTemplateColumn Header="操作" Width="100">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal" VerticalAlignment="Center" HorizontalAlignment="Center">
<Button Content="删除" Click="OnDeleteItemClick" Height="30" Margin="5,0,5,0" >
</Button>
</StackPanel>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
<Button x:Name="OnNewBoxBtn" FontSize="20" Grid.Row="2" Click="OnNewBoxClick" HorizontalAlignment="Right" Content="新增箱标" Style="{StaticResource MaterialDesignRaisedButton}" Height="40" Width="120" VerticalAlignment="Bottom" Margin="0,0,480,10"/>
<Button FontSize="20" Grid.Row="2" Click="OnNewClick" HorizontalAlignment="Right" Content="新增件标" Style="{StaticResource MaterialDesignRaisedButton}" Height="40" Width="120" VerticalAlignment="Bottom" Grid.Column="1" Margin="0,5,320,10" Grid.ColumnSpan="2"/>
<Button FontSize="20" Grid.Row="2" Click="OnSaveClick" HorizontalAlignment="Right" Content="生成任务" Style="{StaticResource MaterialDesignRaisedButton}" Height="40" Width="120" VerticalAlignment="Bottom" Grid.Column="1" Margin="0,5,160,10" Grid.ColumnSpan="2"/>
<Button FontSize="20" Grid.Row="2" Click="OnCancelClick" HorizontalAlignment="Right" Content="关闭" Background="DarkOrange" BorderBrush="Orange" Style="{StaticResource MaterialDesignRaisedButton}" Height="40" Width="100" VerticalAlignment="Bottom" Grid.Column="2" Margin="0,5,26,10"/>
</Grid>
</Border>
</Window>
using JmpZbModel.Model;
using JmpZbPrint.Common;
using JmpZbPrint.Dialog;
using JmpZbPrint.Model;
using JmpZbPrint.View;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using Newtonsoft.Json;
namespace JmpZbPrint.PagePartial
{
/// <summary>
/// IntGenEpcWindow.xaml 的交互逻辑
/// </summary>
public partial class IntGenEpcWindow : Window
{
public event Action OnRefreshGrid;
public ObservableCollection<recode_info> OrderList
{
get;
set;
}
private int type;
public IntGenEpcWindow(int type)
{
InitializeComponent();
this.type = type;
txtTitle.Text = type == 0 ? "生成打印任务" : "生成绑定任务";
//g_order.Items.Clear();
g_order.AutoGenerateColumns = false;
OrderList = new ObservableCollection<recode_info>();
g_order.ItemsSource = OrderList;
OnNewBoxBtn.Visibility = type == 0 ? Visibility.Visible : Visibility.Hidden;
}
private void Sb_Completed(object sender, EventArgs e)
{
this.Close();
}
private void OnWindowLoaded(object sender, RoutedEventArgs e)
{
}
private void OnWzSelectionChanged(object sender, SelectionChangedEventArgs e)
{
}
private void OnNewBoxClick(object sender, RoutedEventArgs e)
{
var tmp = new SetGenInfoV2("箱标");
tmp.OnRefreshGrid += RefreshGrid;
tmp.Show();
}
private void OnNewClick(object sender, RoutedEventArgs e)
{
var tmp = new SetGenInfoV2("件标");
tmp.OnRefreshGrid += RefreshGrid;
tmp.Show();
}
private void OnSaveClick(object sender, RoutedEventArgs e)
{
var tmpList = OrderList.ToList();
bool flag = false;
foreach (var s in tmpList)
{
if (s.LabelType == "箱标")
{
List<recode_info> epc_record = new List<recode_info>();
for (int i = 0; i < s.needNum; i++)
{
var _batch_no = DateTime.Now.ToString("yyyyMMddHHmmssfff");
//Thread.Sleep(1);
////5842 :'XB'的16进制
//var xbEpc = "5842" + _batch_no + "000";
//创建箱标epc
var boxRequest = new request_int_info()
{
labelType = "箱标",
equCode = s.equCode,
productTime = s.productTime,
sizeCode = s.sizeCode,
oneBoxNum = s.oneBoxNum,
quantity = s.needNum,
supplierCode = s.suppilerCode,
warrantyCycle = s.warrantyCycle
};
var boxRes = HttpHelper.GenerateIntTagEpc(boxRequest, out string boxMsg);
if (!boxRes.Item1)
{
flag = false;
MessageBox.Show($"[{s.equName}-{s.sizeName}] 箱标生成失败,原因:{boxMsg}", "提示", MessageBoxButton.OK, MessageBoxImage.Error);
return;
}
var xbEpc = boxRes.Item2.First().epc;
//箱标内件标生成epc
var request = new request_int_info()
{
labelType = "件标",
equCode = s.equCode,
productTime = s.productTime,
sizeCode = s.sizeCode,
quantity = s.oneBoxNum,
supplierCode = s.suppilerCode,
warrantyCycle = s.warrantyCycle
};
var res = HttpHelper.GenerateIntTagEpc(request, out string msg);
if (!res.Item1)
{
flag = false;
MessageBox.Show($"[{s.equName}-{s.sizeName}] 件标生成失败,原因:{msg}", "提示", MessageBoxButton.OK, MessageBoxImage.Error);
return;
}
epc_record.Add(new recode_info()
{
LabelType = "箱标",
orgId = s.orgId,
batchNo = _batch_no,
epc = xbEpc,
num = i + 1,
equCode = s.equCode,
equId = s.equId,
sizeCode = s.sizeCode,
equName = s.equName,
isdelete = false,
oneBoxNum = s.oneBoxNum,
needNum = s.needNum,
price = s.price,
productTime = s.productTime,
repairCycle = s.repairCycle,
sizeId = s.sizeId,
sizeName = s.sizeName,
suppilerCode = s.suppilerCode,
supplierId = s.supplierId,
suppilerName = s.suppilerName,
type = type,
useTime = s.useTime,
warehouseId = s.warehouseId,
warehouseName = s.warehouseName,
warrantyCycle = s.warrantyCycle,
createTime = DateTime.Now,
ShelfId = s.ShelfId,
ShelfName = s.ShelfName,
ShelfRange = s.ShelfRange,
ShelfRow = s.ShelfRow,
ShelfColumn = s.ShelfColumn,
epcListJson = JsonConvert.SerializeObject(res.Item2.Select(x => x.epc))
});
}
LiteDbHelper.AddRange(epc_record);
flag = true;
OrderList.Remove(s);
}
else
{
var request = new request_int_info()
{
equCode = s.equCode,
productTime = s.productTime,
sizeCode = s.sizeCode,
quantity = s.needNum,
supplierCode = s.suppilerCode,
warrantyCycle = s.warrantyCycle
};
var res = HttpHelper.GenerateIntTagEpc(request, out string msg);
if (res.Item1)
{
var _batch_no = DateTime.Now.ToString("yyyyMMddHHmmssfff");
//写入EPC到liteDB
List<recode_info> epc_record = new List<recode_info>();
res.Item2.ForEach(x =>
{
s.epc = x.epc;
s.num = x.num;
epc_record.Add(new recode_info()
{
LabelType = "件标",
orgId = s.orgId,
batchNo = _batch_no,
epc = x.epc,
num = x.num,
equCode = s.equCode,
equId = s.equId,
sizeCode = s.sizeCode,
equName = s.equName,
isdelete = false,
needNum = s.needNum,
price = s.price,
productTime = s.productTime,
repairCycle = s.repairCycle,
sizeId = s.sizeId,
sizeName = s.sizeName,
suppilerCode = s.suppilerCode,
supplierId = s.supplierId,
suppilerName = s.suppilerName,
type = type,
useTime = s.useTime,
warehouseId = s.warehouseId,
warehouseName = s.warehouseName,
warrantyCycle = s.warrantyCycle,
createTime = DateTime.Now,
ShelfId = s.ShelfId,
ShelfName = s.ShelfName,
ShelfRange = s.ShelfRange,
ShelfRow = s.ShelfRow,
ShelfColumn = s.ShelfColumn,
});
});
LiteDbHelper.AddRange(epc_record);
flag = true;
OrderList.Remove(s);
}
else
{
flag = false;
MessageBox.Show($"[{s.equName}-{s.sizeName}] 生成失败,原因:{msg}", "提示", MessageBoxButton.OK, MessageBoxImage.Error);
return;
}
}
}
if (flag)
{
MessageBox.Show($"任务生成成功", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
this.Close();
}
}
private void OnCancelClick(object sender, RoutedEventArgs e)
{
this.Close();
}
private void OnClose(object sender, MouseButtonEventArgs e)
{
this.Close();
}
private void g_order_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
}
private void OnDeleteItemClick(object sender, RoutedEventArgs e)
{
if (g_order.SelectedValue != null)
{
var item = g_order.SelectedValue as recode_info;
var index = g_order.SelectedIndex;
OrderList.Remove(item);
}
}
private void RefreshGrid(recode_info recode)
{
OrderList.Add(new recode_info()
{
LabelType = recode.LabelType,
orgId = CaChe.UserInfo.baseJpOrganization.id,
suppilerCode = recode.suppilerCode,
type = recode.type,
epc = recode.epc,
equCode = recode.equCode,
equId = recode.equId,
equName = recode.equName,
isdelete = false,
IsSelected = false,
needNum = recode.needNum,
oneBoxNum = recode.oneBoxNum,
num = recode.num,
price = recode.price,
productTime = recode.productTime,
repairCycle = recode.repairCycle,
sizeCode = recode.sizeCode,
sizeId = recode.sizeId,
sizeName = recode.sizeName,
supplierId = recode.supplierId,
suppilerName = recode.suppilerName,
useTime = recode.useTime,
warehouseId = recode.warehouseId,
warehouseName = recode.warehouseName,
warrantyCycle = recode.warrantyCycle,
ShelfId = recode.ShelfId,
ShelfName = recode.ShelfName,
ShelfRange = recode.ShelfRange,
ShelfRow = recode.ShelfRow,
ShelfColumn = recode.ShelfColumn,
});
}
private void Window_Closed(object sender, EventArgs e)
{
OnRefreshGrid?.Invoke();
}
}
}
<UserControl x:Class="JmpZbPrint.PagePartial.IntHistoryWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:materialDesign="http://materialdesigninxaml.net/winfx/xaml/themes"
xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
xmlns:pu="clr-namespace:Panuon.UI.Silver;assembly=Panuon.UI.Silver"
xmlns:convert="clr-namespace:JmpZbPrint.Common"
xmlns:UsControl="clr-namespace:JmpZbPrint.UsControl"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:JmpZbPrint.PagePartial"
mc:Ignorable="d" Background="#ffffff" Margin="0,20,0,0" >
<i:Interaction.Triggers>
<i:EventTrigger EventName="Loaded">
<i:InvokeCommandAction Command="{Binding OnWindowLoadCmd}" />
</i:EventTrigger>
</i:Interaction.Triggers>
<UserControl.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="pack://application:,,,/MaterialDesignThemes.Wpf;component/Themes/MaterialDesignTheme.TextBox.xaml" />
<ResourceDictionary Source="pack://application:,,,/MaterialDesignThemes.Wpf;component/Themes/MaterialDesignTheme.DataGrid.xaml" />
<ResourceDictionary Source="pack://application:,,,/MaterialDesignThemes.Wpf;component/Themes/MaterialDesignTheme.TextBlock.xaml" />
</ResourceDictionary.MergedDictionaries>
<SolidColorBrush x:Key="PrimaryHueLightBrush" Color="#0093EA"/>
<SolidColorBrush x:Key="PrimaryHueLightForegroundBrush" Color="#FFFFFF"/>
<SolidColorBrush x:Key="PrimaryHueMidBrush" Color="#0093EA"/>
<SolidColorBrush x:Key="PrimaryHueMidForegroundBrush" Color="#FFFFFF"/>
<SolidColorBrush x:Key="PrimaryHueDarkBrush" Color="#0093EA"/>
<SolidColorBrush x:Key="PrimaryHueDarkForegroundBrush" Color="#FFFFFF"/>
<!-- accent -->
<SolidColorBrush x:Key="SecondaryAccentBrush" Color="#0093EA"/>
<SolidColorBrush x:Key="SecondaryAccentForegroundBrush" Color="#FFFFFF"/>
</ResourceDictionary>
</UserControl.Resources>
<Grid x:Name="g_main">
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition Height="70"/>
</Grid.RowDefinitions>
<Grid x:Name="g_body" Grid.Row="0">
<Grid.RowDefinitions>
<RowDefinition Height="80"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Grid Grid.Row="0" Grid.Column="0" Margin="0,0,0,0" >
<Grid.ColumnDefinitions>
<ColumnDefinition Width="20"/>
<ColumnDefinition Width="1*"/>
<ColumnDefinition Width="20"/>
<ColumnDefinition Width="1*"/>
<ColumnDefinition Width="20"/>
<ColumnDefinition Width="400"/>
<ColumnDefinition Width="0.1*"/>
</Grid.ColumnDefinitions>
<Grid Grid.Column="1">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="100"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<TextBlock Text="装备名称:" Grid.Column="0" Width="100" FontSize="20" HorizontalAlignment="Left" VerticalAlignment="Center"/>
<TextBox x:Name="txt_name" Grid.Column="1" Text="{Binding EquName,UpdateSourceTrigger=PropertyChanged}" MinWidth="150" Height="35" FontSize="18" Background="White" materialDesign:HintAssist.Hint="装备名称" Margin="-0.4,22,-0.2,22" />
</Grid>
<Grid Grid.Column="3" >
<Grid.ColumnDefinitions>
<ColumnDefinition Width="80"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<TextBlock Text="供应商:" Grid.Column="0" FontSize="20" HorizontalAlignment="Center" VerticalAlignment="Center"/>
<TextBox x:Name="txt_vendor" Grid.Column="1" Text="{Binding VendorName,UpdateSourceTrigger=PropertyChanged}" Height="35" FontSize="18" Background="White" materialDesign:HintAssist.Hint="供应商名称"/>
</Grid>
<UniformGrid Grid.Column="5" Columns="3">
<Button FontSize="20" x:Name="btnQuery" Content="查询" Command="{Binding OnQueryCommand}" Style="{StaticResource MaterialDesignRaisedButton}" Margin="0,0,0,0" Height="45" Width="120" HorizontalAlignment="Center" VerticalAlignment="Center"/>
<Button FontSize="20" Content="报废选中" BorderBrush="OrangeRed" Background="OrangeRed" Command="{Binding OnScrapAllCmd}" Style="{StaticResource MaterialDesignRaisedButton}" Margin="20,0,0,0" Height="45" Width="120" HorizontalAlignment="Center" VerticalAlignment="Center"/>
</UniformGrid>
</Grid>
<DataGrid ScrollViewer.HorizontalScrollBarVisibility="Auto" ScrollViewer.VerticalScrollBarVisibility="Auto" IsEnabled="{Binding BindButton}" EnableRowVirtualization="False" x:Name="g_task" Margin="3 5 3 0" Grid.Row="1" Grid.RowSpan="2" BorderBrush="#dedede" FontSize="20" Foreground="#37537d" HeadersVisibility="Column"
GridLinesVisibility="None" Background="Transparent" BorderThickness="1" CanUserAddRows="False"
AutoGenerateColumns="False" SelectionMode="Single" ItemsSource="{Binding BindTaskList,UpdateSourceTrigger=PropertyChanged}" LoadingRow="OnDataGridLoadingRow" RowBackground="Transparent" CanUserSortColumns="True" >
<i:Interaction.Triggers>
<i:EventTrigger EventName="Loaded">
<i:InvokeCommandAction Command="{Binding OnGridLoadedCmd}" />
</i:EventTrigger>
</i:Interaction.Triggers>
<DataGrid.Resources>
<ResourceDictionary>
<convert:PrintTypeConvert x:Key="ptconv"/>
</ResourceDictionary>
</DataGrid.Resources>
<DataGrid.ColumnHeaderStyle>
<Style TargetType="{x:Type DataGridColumnHeader}">
<Setter Property="BorderThickness" Value="0"/>
<Setter Property="VerticalAlignment" Value="Center"/>
<Setter Property="HorizontalContentAlignment" Value="Center"/>
<Setter Property="Background" Value="Transparent"/>
<Setter Property="Foreground" Value="#4682B4"/>
<Setter Property="FontSize" Value="20"/>
<Setter Property="Height" Value="38"/>
</Style>
</DataGrid.ColumnHeaderStyle>
<DataGrid.RowStyle>
<Style TargetType="{x:Type DataGridRow}">
<Style.Triggers>
<Trigger Property="ItemsControl.AlternationIndex" Value="0">
<Setter Property="Background" Value="Transparent"/>
<Setter Property="BorderBrush" Value="Transparent"/>
</Trigger>
<Trigger Property="ItemsControl.AlternationIndex" Value="1">
<Setter Property="Background" Value="#EBEBEB"/>
<Setter Property="Opacity" Value="0.4"/>
</Trigger>
</Style.Triggers>
</Style>
</DataGrid.RowStyle>
<DataGrid.Columns>
<DataGridCheckBoxColumn Binding="{Binding IsSelected,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"
ElementStyle="{StaticResource MaterialDesignDataGridCheckBoxColumnStyle}"
EditingElementStyle="{StaticResource MaterialDesignDataGridCheckBoxColumnEditingStyle}">
<DataGridCheckBoxColumn.Header>
<CheckBox HorizontalAlignment="Center" Name="chk_pri" IsChecked="{Binding IsSelectAll,UpdateSourceTrigger=PropertyChanged,Mode=Default}"
/>
</DataGridCheckBoxColumn.Header>
</DataGridCheckBoxColumn>
<DataGridTemplateColumn Header="序号" MinWidth="80" >
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBlock FontSize="18" Text="{Binding RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type DataGridRow}}, Path=Header}" HorizontalAlignment="Left" VerticalAlignment="Center" Margin="5,0,0,0"/>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
<DataGridTextColumn Header="生成批号" IsReadOnly="True" Width="auto" MinWidth="100" FontSize="18" Binding="{Binding batchNo}" ElementStyle="{StaticResource TextCenterStyle}"/>
<DataGridTextColumn Header="装备名称" IsReadOnly="True" Width="*" MinWidth="100" FontSize="18" Binding="{Binding equName}" ElementStyle="{StaticResource TextCenterStyle}" />
<DataGridTextColumn Header="装备型号" IsReadOnly="True" Width="auto" MinWidth="100" FontSize="18" Binding="{Binding sizeName}" ElementStyle="{StaticResource TextCenterStyle}"/>
<DataGridTextColumn Header="件序列号" IsReadOnly="True" Width="auto" MinWidth="100" FontSize="18" Binding="{Binding num}" ElementStyle="{StaticResource TextCenterStyle}"/>
<DataGridTextColumn Header="供应商" IsReadOnly="True" Width="auto" FontSize="18" Binding="{Binding suppilerName}" ElementStyle="{StaticResource TextCenterStyle}" />
<DataGridTextColumn Header="入库仓库" IsReadOnly="True" Width="*" FontSize="18" Binding="{Binding warehouseName}" ElementStyle="{StaticResource TextCenterStyle}" />
<DataGridTextColumn Header="创建日期" IsReadOnly="True" Width="auto" MinWidth="100" FontSize="18" Binding="{Binding createTime,StringFormat='yyyy-MM-dd HH:mm'}" ElementStyle="{StaticResource TextCenterStyle}"/>
<DataGridTextColumn Header="任务类型" IsReadOnly="True" Width="auto" MinWidth="100" FontSize="18" Binding="{Binding type,Converter={StaticResource ptconv}}" ElementStyle="{StaticResource TextCenterStyle}"/>
<DataGridTemplateColumn Header="操作" Width="auto" MinWidth="100" >
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal" VerticalAlignment="Center" HorizontalAlignment="Center">
<Button Content="报废" Command="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType=DataGrid}, Path=DataContext.OnScrapCmd}" CommandParameter="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType=DataGrid}, Path=SelectedValue}" Margin="5,0,5,0" >
</Button>
</StackPanel>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
</Grid>
<UsControl:PageControl IsEnabled="{Binding BindButton}" x:Name="d_pager" Margin="3,0,3,0" Grid.Row="1" TotalRecord="{Binding TotalRecord,Mode=TwoWay}" TotalPage="{Binding PageTotal,Mode=TwoWay}" PageSize="{Binding PageSize,Mode=TwoWay}" PageIndex="{Binding PageIndex,Mode=TwoWay}">
<i:Interaction.Triggers>
<i:EventTrigger EventName="OnPageChanged">
<i:InvokeCommandAction Command="{Binding OnPageChangeCmd}" />
</i:EventTrigger>
</i:Interaction.Triggers>
</UsControl:PageControl>
</Grid>
</UserControl>
using JmpZbPrint.ViewModel;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace JmpZbPrint.PagePartial
{
/// <summary>
/// GenEpcWindow.xaml 的交互逻辑
/// </summary>
public partial class IntHistoryWindow : UserControl
{
private IntHistoryViewModel vm;
public IntHistoryWindow()
{
InitializeComponent();
vm = new IntHistoryViewModel();
this.DataContext = vm;
chk_pri.DataContext = vm;
}
private object syncObj = new object();
private void OnDataGridLoadingRow(object sender, DataGridRowEventArgs e)
{
lock (syncObj)
{
e.Row.Header = e.Row.GetIndex() + 1;
}
}
}
}
<UserControl x:Class="JmpZbPrint.PagePartial.IntPrintWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:materialDesign="http://materialdesigninxaml.net/winfx/xaml/themes"
xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
xmlns:pu="clr-namespace:Panuon.UI.Silver;assembly=Panuon.UI.Silver"
xmlns:convert="clr-namespace:JmpZbPrint.Common"
xmlns:UsControl="clr-namespace:JmpZbPrint.UsControl"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:JmpZbPrint.PagePartial" Name="pri_win"
mc:Ignorable="d" Background="#ffffff" Margin="0,20,0,0" IsVisibleChanged="pri_win_IsVisibleChanged">
<i:Interaction.Triggers>
<i:EventTrigger EventName="Loaded">
<i:InvokeCommandAction Command="{Binding OnWindowLoadCmd}" />
</i:EventTrigger>
</i:Interaction.Triggers>
<UserControl.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="pack://application:,,,/MaterialDesignThemes.Wpf;component/Themes/MaterialDesignTheme.TextBox.xaml" />
<ResourceDictionary Source="pack://application:,,,/MaterialDesignThemes.Wpf;component/Themes/MaterialDesignTheme.DataGrid.xaml" />
<ResourceDictionary Source="pack://application:,,,/MaterialDesignThemes.Wpf;component/Themes/MaterialDesignTheme.TextBlock.xaml" />
</ResourceDictionary.MergedDictionaries>
<SolidColorBrush x:Key="PrimaryHueLightBrush" Color="#0093EA"/>
<SolidColorBrush x:Key="PrimaryHueLightForegroundBrush" Color="#FFFFFF"/>
<SolidColorBrush x:Key="PrimaryHueMidBrush" Color="#0093EA"/>
<SolidColorBrush x:Key="PrimaryHueMidForegroundBrush" Color="#FFFFFF"/>
<SolidColorBrush x:Key="PrimaryHueDarkBrush" Color="#0093EA"/>
<SolidColorBrush x:Key="PrimaryHueDarkForegroundBrush" Color="#FFFFFF"/>
<!-- accent -->
<SolidColorBrush x:Key="SecondaryAccentBrush" Color="#0093EA"/>
<SolidColorBrush x:Key="SecondaryAccentForegroundBrush" Color="#FFFFFF"/>
</ResourceDictionary>
</UserControl.Resources>
<Grid x:Name="g_main">
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition Height="70"/>
<RowDefinition Height="100"/>
</Grid.RowDefinitions>
<Grid x:Name="g_body" Grid.Row="0">
<Grid.RowDefinitions>
<RowDefinition Height="80"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Grid Grid.Row="0" Grid.Column="0" Margin="0,0,0,0" >
<Grid.ColumnDefinitions>
<ColumnDefinition Width="20"/>
<ColumnDefinition Width="1*"/>
<ColumnDefinition Width="20"/>
<ColumnDefinition Width="1*"/>
<ColumnDefinition Width="20"/>
<ColumnDefinition Width="500"/>
<ColumnDefinition Width="0.1*"/>
</Grid.ColumnDefinitions>
<Grid Grid.Column="1">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="100"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<TextBlock Text="装备名称:" Grid.Column="0" Width="100" FontSize="20" HorizontalAlignment="Left" VerticalAlignment="Center"/>
<TextBox x:Name="txt_name" Grid.Column="1" Text="{Binding EquName,UpdateSourceTrigger=PropertyChanged}" MinWidth="150" Height="35" FontSize="18" Background="White" materialDesign:HintAssist.Hint="装备名称" Margin="-0.4,22,-0.2,22" />
</Grid>
<Grid Grid.Column="3" >
<Grid.ColumnDefinitions>
<ColumnDefinition Width="80"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<TextBlock Grid.Column="0" Text="供应商:" FontSize="20" HorizontalAlignment="Center" VerticalAlignment="Center"/>
<TextBox Grid.Column="1" x:Name="txt_vendor" Text="{Binding VendorName,UpdateSourceTrigger=PropertyChanged}" Height="35" FontSize="18" Background="White" materialDesign:HintAssist.Hint="供应商名称"/>
</Grid>
<UniformGrid Grid.Column="5" Columns="4">
<Button FontSize="20" x:Name="btnQuery" Content="查询" Command="{Binding OnQueryCommand}" Style="{StaticResource MaterialDesignRaisedButton}" Height="45" Width="120" HorizontalAlignment="Center" VerticalAlignment="Center"/>
<Button FontSize="20" Content="生成任务" Command="{Binding OnGenCommand}" Style="{StaticResource MaterialDesignRaisedButton}" Margin="20,0,0,0" Height="45" Width="120" HorizontalAlignment="Center" VerticalAlignment="Center"/>
<Button FontSize="20" Content="装箱" BorderBrush="#CC7033" Background="#CC7033" Command="{Binding OnBoxingCmd}" Style="{StaticResource MaterialDesignRaisedButton}" Margin="20,0,0,0" Height="45" Width="120" HorizontalAlignment="Center" VerticalAlignment="Center"/>
<Button FontSize="20" Content="删除任务" BorderBrush="OrangeRed" Background="OrangeRed" Command="{Binding OnDeleteTagCmd}" Style="{StaticResource MaterialDesignRaisedButton}" Margin="20,0,0,0" Height="45" Width="120" HorizontalAlignment="Center" VerticalAlignment="Center"/>
</UniformGrid>
</Grid>
<DataGrid ScrollViewer.HorizontalScrollBarVisibility="Visible" ScrollViewer.VerticalScrollBarVisibility="Visible" IsEnabled="{Binding StartButton,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" EnableRowVirtualization="False" x:Name="g_print" Margin="3 5 3 0" Grid.Row="1" Grid.RowSpan="2" BorderBrush="#dedede" FontSize="20" Foreground="#37537d" HeadersVisibility="Column"
GridLinesVisibility="None" Background="Transparent" BorderThickness="1" CanUserAddRows="False"
AutoGenerateColumns="False" LoadingRow="OnDataGridLoadingRow" ItemsSource="{Binding UiPrintList,UpdateSourceTrigger=PropertyChanged}" SelectionMode="Single" RowBackground="Transparent" CanUserSortColumns="True" >
<i:Interaction.Triggers>
<i:EventTrigger EventName="Loaded">
<i:InvokeCommandAction Command="{Binding OnGridLoadedCmd}" />
</i:EventTrigger>
</i:Interaction.Triggers>
<DataGrid.Resources>
<ResourceDictionary>
<convert:PrintTypeConvert x:Key="ptconv"/>
<convert:BoolConvert x:Key="boolConv"/>
</ResourceDictionary>
</DataGrid.Resources>
<DataGrid.ColumnHeaderStyle>
<Style TargetType="{x:Type DataGridColumnHeader}">
<Setter Property="BorderThickness" Value="0"/>
<Setter Property="VerticalAlignment" Value="Center"/>
<Setter Property="HorizontalContentAlignment" Value="Center"/>
<Setter Property="Background" Value="Transparent"/>
<Setter Property="Foreground" Value="#4682B4"/>
<Setter Property="FontSize" Value="20"/>
<Setter Property="Height" Value="38"/>
</Style>
</DataGrid.ColumnHeaderStyle>
<DataGrid.RowStyle>
<Style TargetType="{x:Type DataGridRow}">
<Style.Triggers>
<Trigger Property="ItemsControl.AlternationIndex" Value="0">
<Setter Property="Background" Value="Transparent"/>
<Setter Property="BorderBrush" Value="Transparent"/>
</Trigger>
<Trigger Property="ItemsControl.AlternationIndex" Value="1">
<Setter Property="Background" Value="#EBEBEB"/>
<Setter Property="Opacity" Value="0.4"/>
</Trigger>
</Style.Triggers>
</Style>
</DataGrid.RowStyle>
<DataGrid.Columns>
<DataGridCheckBoxColumn Binding="{Binding IsSelected,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"
ElementStyle="{StaticResource MaterialDesignDataGridCheckBoxColumnStyle}"
EditingElementStyle="{StaticResource MaterialDesignDataGridCheckBoxColumnEditingStyle}">
<DataGridCheckBoxColumn.Header>
<CheckBox HorizontalAlignment="Center" Name="chk_pri" IsChecked="{Binding IsSelectAll,UpdateSourceTrigger=PropertyChanged,Mode=Default}"
/>
</DataGridCheckBoxColumn.Header>
</DataGridCheckBoxColumn>
<DataGridTemplateColumn Header="序号" MinWidth="80" >
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBlock FontSize="18" Text="{Binding RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type DataGridRow}}, Path=Header}" HorizontalAlignment="Left" VerticalAlignment="Center" Margin="5,0,0,0"/>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
<DataGridTextColumn Header="ID" IsReadOnly="True" Width="*" FontSize="18" Visibility="Collapsed" Binding="{Binding Id}" />
<DataGridTextColumn Header="标签类型" IsReadOnly="True" MinWidth="100" Width="auto" FontSize="18" Binding="{Binding LabelType}" ElementStyle="{StaticResource TextCenterStyle}" />
<DataGridTextColumn Header="装备名称" IsReadOnly="True" MinWidth="100" Width="auto" FontSize="18" Binding="{Binding equName}" ElementStyle="{StaticResource TextCenterStyle}" />
<DataGridTextColumn Header="装备型号" IsReadOnly="True" MinWidth="100" Width="auto" FontSize="18" Binding="{Binding sizeName}" ElementStyle="{StaticResource TextCenterStyle}"/>
<DataGridTextColumn Header="生产日期" IsReadOnly="True" MinWidth="100" Width="auto" FontSize="18" Binding="{Binding productTime, StringFormat='yyyy-MM-dd HH:mm'}" ElementStyle="{StaticResource TextCenterStyle}"/>
<DataGridTextColumn Header="使用日期" IsReadOnly="True" MinWidth="100" Width="auto" FontSize="18" Binding="{Binding useTime,StringFormat='yyyy-MM-dd HH:mm'}" ElementStyle="{StaticResource TextCenterStyle}"/>
<DataGridTextColumn Header="质保周期" IsReadOnly="True" MinWidth="100" Width="auto" FontSize="18" Binding="{Binding warrantyCycle}" ElementStyle="{StaticResource TextCenterStyle}"/>
<DataGridTextColumn Header="维保周期" IsReadOnly="True" MinWidth="100" Width="auto" FontSize="18" Binding="{Binding repairCycle}" ElementStyle="{StaticResource TextCenterStyle}"/>
<DataGridTextColumn Header="单价" IsReadOnly="True" MinWidth="100" Width="auto" FontSize="18" Binding="{Binding price}" ElementStyle="{StaticResource TextCenterStyle}"/>
<DataGridTextColumn Header="数量/箱" IsReadOnly="True" MinWidth="100" Width="auto" FontSize="18" Binding="{Binding oneBoxNum}" ElementStyle="{StaticResource TextCenterStyle}"/>
<DataGridTextColumn Header="件序号" IsReadOnly="True" Width="auto" MinWidth="100" FontSize="18" Binding="{Binding num}" ElementStyle="{StaticResource TextCenterStyle}"/>
<DataGridTextColumn Header="供应商" IsReadOnly="True" MinWidth="100" Width="auto" FontSize="18" Binding="{Binding suppilerName}" ElementStyle="{StaticResource TextCenterStyle}" />
<DataGridTextColumn Header="入库仓库" IsReadOnly="True" MinWidth="100" Width="auto" FontSize="18" Binding="{Binding warehouseName}" ElementStyle="{StaticResource TextCenterStyle}" />
<DataGridTextColumn Header="拆箱" IsReadOnly="True" MinWidth="100" Width="auto" FontSize="18" Binding="{Binding IsUnboxingLabel,Converter={StaticResource boolConv}}" ElementStyle="{StaticResource TextCenterStyle}" />
<DataGridTextColumn Header="重装箱" IsReadOnly="True" MinWidth="100" Width="auto" FontSize="18" Binding="{Binding IsReloadBoxing,Converter={StaticResource boolConv}}" ElementStyle="{StaticResource TextCenterStyle}" />
</DataGrid.Columns>
</DataGrid>
</Grid>
<UsControl:PageControl IsEnabled="{Binding StartButton}" x:Name="d_pager" Margin="3,0,3,0" Grid.Row="1" TotalRecord="{Binding TotalRecord,Mode=TwoWay}" TotalPage="{Binding PageTotal,Mode=TwoWay}" PageSize="{Binding PageSize,Mode=TwoWay}" PageIndex="{Binding PageIndex,Mode=TwoWay}">
<i:Interaction.Triggers>
<i:EventTrigger EventName="OnPageChanged">
<i:InvokeCommandAction Command="{Binding OnPageChangeCmd}" />
</i:EventTrigger>
</i:Interaction.Triggers>
</UsControl:PageControl>
<TextBlock Grid.Row="2" Width="800" HorizontalAlignment="Left" Text="{Binding UiMessage}" Foreground="{Binding MsgColor}" Style="{StaticResource MaterialDesignHeadline4TextBlock}" VerticalAlignment="Center" Margin="10,29,0,29"></TextBlock>
<Button Grid.Row="2" FontSize="36" Command="{Binding OnUnboxingCmd}" Visibility="Visible" Content="拆箱" Style="{StaticResource MaterialDesignRaisedButton}" Background="Orange" Width="180" Height="70" HorizontalAlignment="Right" Margin="0,0,510,0" VerticalAlignment="Center" />
<Button Grid.Row="3" IsEnabled="{Binding StartEnable}" FontSize="36" Command="{Binding OnStartPrintItemsCmd}" Visibility="Visible" Content="打印" Style="{StaticResource MaterialDesignRaisedButton}" Width="180" Height="70" HorizontalAlignment="Right" Margin="0,0,280,0" VerticalAlignment="Center" />
<Button Grid.Row="3" IsEnabled="{Binding StopEnable}" FontSize="36" Command="{Binding OnStopPrintItemsCmd}" Content="停止" Style="{StaticResource MaterialDesignRaisedButton}" Width="180" Height="70" Background="OrangeRed" HorizontalAlignment="Right" Margin="0,0,50,0" VerticalAlignment="Center"/>
</Grid>
</UserControl>
using JmpZbPrint.Model;
using JmpZbPrint.ViewModel;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using JmpZbPrint.View;
namespace JmpZbPrint.PagePartial
{
/// <summary>
/// GenEpcWindow.xaml 的交互逻辑
/// </summary>
public partial class IntPrintWindow : UserControl
{
private IntPrintViewModel vm;
private InternalWindow _window;
public IntPrintWindow(InternalWindow window)
{
InitializeComponent();
_window = window;
vm = new IntPrintViewModel(window);
this.DataContext = vm;
chk_pri.DataContext = vm;
}
private object syncObj = new object();
private void OnDataGridLoadingRow(object sender, DataGridRowEventArgs e)
{
lock (syncObj)
{
e.Row.Header = e.Row.GetIndex() + 1;
}
}
public void Clearup()
{
vm.Cleanup();
}
private void pri_win_IsVisibleChanged(object sender, DependencyPropertyChangedEventArgs e)
{
if (!IsVisible)
{
_window.printServerHelper.EnableControlEvent -= vm.EnableControl;
}
}
}
}
<Window x:Class="JmpZbPrint.PagePartial.SetBasicInfo"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:cov="clr-namespace:JmpZbPrint.Common"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:convert="clr-namespace:JmpZbPrint.Common"
xmlns:materialDesign="http://materialdesigninxaml.net/winfx/xaml/themes"
xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
xmlns:local="clr-namespace:JmpZbPrint"
xmlns:System="clr-namespace:System;assembly=mscorlib"
mc:Ignorable="d"
Height="600" Width="1366" WindowState="Maximized" AllowsTransparency="True" WindowStyle="None"
ResizeMode="NoResize" Loaded="OnWindowLoaded" WindowStartupLocation="CenterScreen">
<Window.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="pack://application:,,,/MaterialDesignThemes.Wpf;component/Themes/MaterialDesignTheme.TextBox.xaml" />
<ResourceDictionary Source="pack://application:,,,/MaterialDesignThemes.Wpf;component/Themes/MaterialDesignTheme.DataGrid.xaml" />
<ResourceDictionary Source="pack://application:,,,/MaterialDesignThemes.Wpf;component/Themes/MaterialDesignTheme.TextBlock.xaml" />
</ResourceDictionary.MergedDictionaries>
<SolidColorBrush x:Key="PrimaryHueLightBrush" Color="#0093EA"/>
<SolidColorBrush x:Key="PrimaryHueLightForegroundBrush" Color="#FFFFFF"/>
<SolidColorBrush x:Key="PrimaryHueMidBrush" Color="#0093EA"/>
<SolidColorBrush x:Key="PrimaryHueMidForegroundBrush" Color="#FFFFFF"/>
<SolidColorBrush x:Key="PrimaryHueDarkBrush" Color="#0093EA"/>
<SolidColorBrush x:Key="PrimaryHueDarkForegroundBrush" Color="#FFFFFF"/>
<!-- accent -->
<SolidColorBrush x:Key="SecondaryAccentBrush" Color="#0093EA"/>
<SolidColorBrush x:Key="SecondaryAccentForegroundBrush" Color="#FFFFFF"/>
<Storyboard x:Key="Loading">
<ThicknessAnimation Duration="0:0:0.2" To="0" From="0,300,0,300"
Storyboard.TargetName="g_main" Storyboard.TargetProperty="Margin" />
</Storyboard>
<Storyboard x:Key="Closing">
<ThicknessAnimation FillBehavior="Stop" Duration="0:0:0.2" To="0,300,0,300" From="0" Storyboard.TargetName="g_main"
Storyboard.TargetProperty="Margin" Completed="Sb_Completed"/>
</Storyboard>
<cov:NumericalConverter x:Key="num_convert"></cov:NumericalConverter>
<cov:DateConverter x:Key="date_convert"></cov:DateConverter>
<cov:FloatConverter x:Key="flo_convert"></cov:FloatConverter>
</ResourceDictionary>
</Window.Resources>
<Window.Effect>
<DropShadowEffect BlurRadius="10" Color="#FF858484" Direction="90" ShadowDepth="1"/>
</Window.Effect>
<Window.Triggers>
<EventTrigger RoutedEvent="FrameworkElement.Loaded" >
<BeginStoryboard Storyboard="{StaticResource Loading}"/>
</EventTrigger>
<EventTrigger RoutedEvent="UIElement.MouseLeftButtonDown" SourceName="tbclose">
<BeginStoryboard Storyboard="{StaticResource Closing}" />
</EventTrigger>
</Window.Triggers>
<Border BorderBrush="#0092ea" x:Name="g_main" CornerRadius="3" BorderThickness=".8" >
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="80"/>
<RowDefinition Height="*"/>
<RowDefinition Height="60"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<TextBlock x:Name="txtTitle" Text="警用装备打印任务生成" FontSize="30" Foreground="#0092ea" VerticalAlignment="Top" Margin="20 20 0 0"/>
<TextBlock Text="&#xE618;" Style="{StaticResource FiconBase}" x:Name="tbclose"
HorizontalAlignment="Right" VerticalAlignment="Top"
Margin="0 20 20 0" FontSize="35" Foreground="#8a8a8a" />
<DataGrid EnableRowVirtualization="False" x:Name="g_order" Margin="3 5 3 0" Grid.Row="1" BorderBrush="#dedede" FontSize="20" Foreground="#37537d" HeadersVisibility="Column"
GridLinesVisibility="None" Background="Transparent" BorderThickness="1" CanUserAddRows="False"
AutoGenerateColumns="False" SelectionMode="Single" HorizontalScrollBarVisibility="Hidden" RowBackground="Transparent" CanUserSortColumns="True" SelectionChanged="g_order_SelectionChanged" >
<i:Interaction.Triggers>
<i:EventTrigger EventName="Loaded">
<i:InvokeCommandAction Command="{Binding OnGridLoadedCmd}" />
</i:EventTrigger>
</i:Interaction.Triggers>
<DataGrid.ColumnHeaderStyle>
<Style TargetType="{x:Type DataGridColumnHeader}">
<Setter Property="BorderThickness" Value="0"/>
<Setter Property="VerticalAlignment" Value="Center"/>
<Setter Property="HorizontalContentAlignment" Value="Center"/>
<Setter Property="Background" Value="Transparent"/>
<Setter Property="Foreground" Value="#4682B4"/>
<Setter Property="FontSize" Value="15"/>
<Setter Property="Height" Value="25"/>
</Style>
</DataGrid.ColumnHeaderStyle>
<DataGrid.RowStyle>
<Style TargetType="{x:Type DataGridRow}">
<Setter Property="Height" Value="45" />
<Style.Triggers>
<Trigger Property="ItemsControl.AlternationIndex" Value="0">
<Setter Property="Background" Value="Transparent"/>
<Setter Property="BorderBrush" Value="Transparent"/>
</Trigger>
<Trigger Property="ItemsControl.AlternationIndex" Value="1">
<Setter Property="Background" Value="#EBEBEB"/>
<Setter Property="Opacity" Value="0.4"/>
</Trigger>
</Style.Triggers>
</Style>
</DataGrid.RowStyle>
<DataGrid.Columns>
<!--<DataGridTextColumn Header="序号" Width="100" FontSize="13" IsReadOnly="True" Binding="{Binding rowNum}" ElementStyle="{Binding TextCenterStyle}"></DataGridTextColumn>-->
<DataGridTextColumn Header="装备名称" IsReadOnly="True" MinWidth="100" Width="*" FontSize="13" Binding="{Binding equName}" ElementStyle="{StaticResource TextCenterStyle}" />
<DataGridTextColumn Header="装备型号" IsReadOnly="True" MinWidth="100" Width="*" FontSize="13" Binding="{Binding sizeName}" ElementStyle="{StaticResource TextCenterStyle}"/>
<DataGridTextColumn Header="剩余数量" IsReadOnly="True" MinWidth="100" Width="*" FontSize="13" Binding="{Binding reNum}" ElementStyle="{StaticResource TextCenterStyle}"/>
<DataGridTemplateColumn Header="生产日期" Width="150">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<DatePicker VerticalContentAlignment="Top" VerticalAlignment="Bottom" SelectedDate="{Binding productTime,Converter={StaticResource date_convert},UpdateSourceTrigger=PropertyChanged,Mode=TwoWay}" materialDesign:HintAssist.HintOpacity=".26" Width="100" FontSize="13" Margin="0,0,0,0" Style="{StaticResource MaterialDesignDatePicker}" />
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
<DataGridTemplateColumn Header="使用日期" Width="150" >
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<DatePicker VerticalContentAlignment="Top" VerticalAlignment="Bottom" SelectedDate="{Binding useTime,Converter={StaticResource date_convert},UpdateSourceTrigger=PropertyChanged,Mode=TwoWay}" materialDesign:HintAssist.HintOpacity=".26" Width="100" FontSize="13" Margin="0,0,0,0" Style="{StaticResource MaterialDesignDatePicker}" />
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
<DataGridTemplateColumn Header="质保周期(月)" Width="120">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBox Width="80" VerticalAlignment="Bottom" Text="{Binding warrantyCycle,Converter={StaticResource num_convert},UpdateSourceTrigger=PropertyChanged,Mode=TwoWay}" FontSize="13" Background="White" />
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
<DataGridTemplateColumn Header="维保周期(月)" Width="120">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBox Width="80" VerticalAlignment="Bottom" Text="{Binding repairCycle ,Converter={StaticResource num_convert},UpdateSourceTrigger=PropertyChanged,Mode=TwoWay}" FontSize="13" Background="White" />
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
<DataGridTemplateColumn Header="购入单价(元)" Width="120" >
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBox Width="80" VerticalAlignment="Bottom" Text="{Binding price,Converter={StaticResource flo_convert},UpdateSourceTrigger=PropertyChanged,Mode=TwoWay}" FontSize="12" Background="White" />
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
<DataGridTemplateColumn Header="购入数量" Width="120" >
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBox Width="80" VerticalAlignment="Bottom" Text="{Binding needNum,Converter={StaticResource num_convert},UpdateSourceTrigger=PropertyChanged}" FontSize="13" Background="White" />
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
<DataGridTemplateColumn Header="供应商" Width="200" >
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal" VerticalAlignment="Bottom" HorizontalAlignment="Center">
<ComboBox VerticalAlignment="Bottom"
materialDesign:HintAssist.HintOpacity=".26"
IsEditable="False" Width="100" FontSize="13"
DisplayMemberPath="name" SelectedValuePath="id" SelectedValue="{Binding supplierId,UpdateSourceTrigger=PropertyChanged,Mode=TwoWay}" ItemsSource="{Binding suppilers,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" HorizontalAlignment="Left">
</ComboBox>
<Button Content="..." VerticalAlignment="Bottom" Height="30" Click="OnSelectSupplierClick" Margin="5,0,0,0" >
</Button>
</StackPanel>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
<DataGridTemplateColumn Header="存放货架" Width="*" >
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal" VerticalAlignment="Bottom" HorizontalAlignment="Center">
<Label VerticalAlignment="Bottom" Content="{Binding shelfInfo,UpdateSourceTrigger=PropertyChanged}" FontSize="13" />
<Button Content="..." VerticalAlignment="Bottom" Height="30" Click="OnSelectShelfClick" Margin="5,0,0,0" >
</Button>
</StackPanel>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
<DataGridTemplateColumn Header="操作" Width="180" >
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal" VerticalAlignment="Center" HorizontalAlignment="Center">
<Button Content="拆分" Click="OnSpiltItemClick" Height="30" Margin="5,0,5,0" >
</Button>
<Button Content="删除" Click="OnDeleteItemClick" Height="30" Margin="5,0,5,0" >
</Button>
</StackPanel>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
<Button FontSize="20" Grid.Row="2" Click="OnSaveClick" HorizontalAlignment="Right" Content="生成" Style="{StaticResource MaterialDesignRaisedButton}" Height="40" Width="100" VerticalAlignment="Bottom" Grid.Column="1" Margin="0,5,161,10" Grid.ColumnSpan="2"/>
<Button FontSize="20" Grid.Row="2" Click="OnCancelClick" HorizontalAlignment="Right" Content="取消" Background="DarkOrange" BorderBrush="Orange" Style="{StaticResource MaterialDesignRaisedButton}" Height="40" Width="100" VerticalAlignment="Bottom" Grid.Column="2" Margin="0,5,26,10"/>
</Grid>
</Border>
</Window>
using JmpZbModel.Model;
using JmpZbPrint.Common;
using JmpZbPrint.Dialog;
using JmpZbPrint.Model;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
namespace JmpZbPrint.PagePartial
{
/// <summary>
/// ModifyPrint.xaml 的交互逻辑
/// </summary>
public partial class SetBasicInfo : Window
{
public ObservableCollection<order_info> OrderList
{
get;
set;
}
public SetBasicInfo(List<order_info> orders)
{
InitializeComponent();
g_order.Items.Clear();
int num = 0;
orders.ForEach(s =>
{
num++;
s.rowNum = num;
if (s.suppilers != null && s.suppilers.Count == 1)
{
s.supplierId = s.suppilers.FirstOrDefault().id;
}
});
this.OrderList = new ObservableCollection<order_info>(orders);
g_order.ItemsSource = OrderList;
}
private void Sb_Completed(object sender, EventArgs e)
{
this.Close();
}
private void OnWindowLoaded(object sender, RoutedEventArgs e)
{
}
private void OnWzSelectionChanged(object sender, SelectionChangedEventArgs e)
{
}
private void OnSaveClick(object sender, RoutedEventArgs e)
{
var tmpList = OrderList.ToList();
var index = 1;
bool flag = true;
foreach (var item in tmpList)
{
if (string.IsNullOrEmpty(item.supplierId))
{
flag = false;
MessageBox.Show($"第{index}行供应商未选择!", "提示", MessageBoxButton.OK, MessageBoxImage.Warning);
break;
}
else if (item.needNum <= 0)
{
flag = false;
MessageBox.Show($"第{index}行购入数量填写不正确!", "提示", MessageBoxButton.OK, MessageBoxImage.Warning);
break;
}
else if (item.useTime == null || item.useTime == default)
{
flag = false;
MessageBox.Show($"第{index}行使用日期填写不正确!", "提示", MessageBoxButton.OK, MessageBoxImage.Warning);
break;
}
else if (item.productTime == null || item.productTime == default)
{
flag = false;
MessageBox.Show($"第{index}行生产日期填写不正确!", "提示", MessageBoxButton.OK, MessageBoxImage.Warning);
break;
}
else if (item.warrantyCycle < 0)
{
flag = false;
MessageBox.Show($"第{index}质保周期填写不正确!", "提示", MessageBoxButton.OK, MessageBoxImage.Warning);
break;
}
else if (item.repairCycle <= 0)
{
flag = false;
MessageBox.Show($"第{index}维保周期填写不正确!", "提示", MessageBoxButton.OK, MessageBoxImage.Warning);
break;
}
else if (item.price <= 0)
{
flag = false;
MessageBox.Show($"第{index}购入单价填写不正确!", "提示", MessageBoxButton.OK, MessageBoxImage.Warning);
break;
}
else
{
index++;
continue;
}
}
if (flag)
{
var grList = tmpList.GroupBy(t => new { t.detailId, t.reNum })
.Select(s => new
{
detailId = s.FirstOrDefault().detailId,
equName = s.FirstOrDefault().equName,
sizeName = s.FirstOrDefault().sizeName,
reNum = s.FirstOrDefault().reNum,
needNum = s.Sum(x => x.needNum)
}).ToList();
foreach (var item in grList)
{
if (item.needNum > item.reNum)
{
flag = false;
MessageBox.Show($"装备[{item.equName} - {item.sizeName}]购入总数量超出剩余数量{item.reNum}!", "提示", MessageBoxButton.OK, MessageBoxImage.Warning);
break;
}
else { continue; }
}
if (flag)
{
foreach (var s in tmpList)
{
var supplier = s.suppilers?.FirstOrDefault(t => t.id == s.supplierId);
s.supplierCode = supplier?.code ?? "";
s.supplierName = supplier?.name ?? "";
var request = new request_ext_info()
{
detailId = s.detailId,
equCode = s.equCode,
sizeCode = s.sizeCode,
supplierCode = s.supplierCode,
supplierId = s.supplierId,
quantity = s.needNum,
price = (float)s.price,
productTime = s.productTime,
repairCycle = s.repairCycle,
useTime = s.useTime,
warrantyCycle = s.warrantyCycle,
supplierName = s.supplierName,
shelfId = s.shelfId,
shelfRange = s.shelfRange,
shelfRow = s.shelfRow,
shelfColumn = s.shelfColumn,
};
var res = HttpHelper.GenerateExtTagEpc(request, out string msg);
if (res)
{
flag = true;
OrderList.Remove(s);
}
else
{
flag = false;
MessageBox.Show($"[{s.equName}-{s.sizeName}] 生成失败,原因:{msg}", "提示", MessageBoxButton.OK, MessageBoxImage.Error);
break;
}
}
if (flag)
{
MessageBox.Show($"任务生成成功", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
this.Close();
}
}
}
}
private void OnCancelClick(object sender, RoutedEventArgs e)
{
this.Close();
}
private void OnClose(object sender, MouseButtonEventArgs e)
{
this.Close();
}
private void g_order_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
}
private void OnSpiltItemClick(object sender, RoutedEventArgs e)
{
if (g_order.SelectedValue != null)
{
var item = g_order.SelectedValue as order_info;
var index = g_order.SelectedIndex;
OrderList.Insert(index, new order_info()
{
createTime = item.createTime,
detailId = item.detailId,
equCode = item.equCode,
equId = item.equId,
equName = item.equName,
supplierId = item.supplierId,
genedNum = item.genedNum,
IsSelected = item.IsSelected,
orderCode = item.orderCode,
orderId = item.orderId,
price = item.price,
productTime = item.productTime,
reNum = item.reNum,
repairCycle = item.repairCycle,
sizeId = item.sizeId,
sizeName = item.sizeName,
suppilers = item.suppilers,
totalNum = item.totalNum,
useTime = item.useTime,
warrantyCycle = item.warrantyCycle,
sizeCode = item.sizeCode,
supplierCode = item.supplierCode,
needNum = 0,
rowNum = 0
});
}
}
private void OnSelectSupplierClick(object sender, RoutedEventArgs e)
{
var win = new SupplierWindow();
win.ShowDialog();
if (win.Supplier != null)
{
var item = g_order.SelectedValue as order_info;
if (item.suppilers.Count(t => t.id == win.Supplier.id) == 0)
{
item.suppilers.Add(win.Supplier);
item.supplierId = win.Supplier.id;
}
}
}
private void OnSelectShelfClick(object sender, RoutedEventArgs e)
{
var item = g_order.SelectedValue as order_info;
var win = new ShelfWindow(new WarehouseInfo() { id = item.warehouseId, name = item.warehouseName }, item.equId, item.sizeId);
win.ShowDialog();
if (win.Shelf != null)
{
item.shelfName = win.Shelf.name;
item.shelfId = win.Shelf.id;
item.shelfRange = Convert.ToInt32(win.Shelf.range);
item.shelfRow = Convert.ToInt32(win.Shelf.row);
item.shelfColumn = Convert.ToInt32(win.Shelf.column);
}
//强制触发刷新
item.shelfInfo = "";
}
private void OnDeleteItemClick(object sender, RoutedEventArgs e)
{
if (g_order.SelectedValue != null)
{
var item = g_order.SelectedValue as order_info;
var index = g_order.SelectedIndex;
OrderList.Remove(item);
}
}
}
}
<UserControl x:Class="JmpZbPrint.PagePartial.TagBagPrintWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:materialDesign="http://materialdesigninxaml.net/winfx/xaml/themes"
xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
xmlns:pu="clr-namespace:Panuon.UI.Silver;assembly=Panuon.UI.Silver"
xmlns:convert="clr-namespace:JmpZbPrint.Common"
xmlns:UsControl="clr-namespace:JmpZbPrint.UsControl"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:JmpZbPrint.PagePartial" Name="pri_win"
mc:Ignorable="d" Background="#ffffff" Margin="0,20,0,0" IsVisibleChanged="pri_win_IsVisibleChanged">
<i:Interaction.Triggers>
<i:EventTrigger EventName="Loaded">
<i:InvokeCommandAction Command="{Binding OnWindowLoadCmd}" />
</i:EventTrigger>
</i:Interaction.Triggers>
<UserControl.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="pack://application:,,,/MaterialDesignThemes.Wpf;component/Themes/MaterialDesignTheme.TextBox.xaml" />
<ResourceDictionary Source="pack://application:,,,/MaterialDesignThemes.Wpf;component/Themes/MaterialDesignTheme.DataGrid.xaml" />
<ResourceDictionary Source="pack://application:,,,/MaterialDesignThemes.Wpf;component/Themes/MaterialDesignTheme.TextBlock.xaml" />
</ResourceDictionary.MergedDictionaries>
<SolidColorBrush x:Key="PrimaryHueLightBrush" Color="#0093EA"/>
<SolidColorBrush x:Key="PrimaryHueLightForegroundBrush" Color="#FFFFFF"/>
<SolidColorBrush x:Key="PrimaryHueMidBrush" Color="#0093EA"/>
<SolidColorBrush x:Key="PrimaryHueMidForegroundBrush" Color="#FFFFFF"/>
<SolidColorBrush x:Key="PrimaryHueDarkBrush" Color="#0093EA"/>
<SolidColorBrush x:Key="PrimaryHueDarkForegroundBrush" Color="#FFFFFF"/>
<!-- accent -->
<SolidColorBrush x:Key="SecondaryAccentBrush" Color="#0093EA"/>
<SolidColorBrush x:Key="SecondaryAccentForegroundBrush" Color="#FFFFFF"/>
</ResourceDictionary>
</UserControl.Resources>
<Grid x:Name="g_main">
<Grid.RowDefinitions>
<RowDefinition/>
<!--<RowDefinition Height="70"/>-->
<RowDefinition Height="100"/>
</Grid.RowDefinitions>
<Grid x:Name="g_body" Grid.Row="0">
<Grid.RowDefinitions>
<RowDefinition Height="80"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Grid Grid.Row="0" Grid.Column="0" Margin="0,0,0,0" >
<Grid.ColumnDefinitions>
<ColumnDefinition Width="20"/>
<ColumnDefinition Width="1*"/>
<ColumnDefinition Width="20"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Grid Grid.Column="1">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="130"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<TextBlock Text="装备包名称:" Grid.Column="0" FontSize="20" HorizontalAlignment="Center" VerticalAlignment="Center"/>
<TextBox x:Name="txt_name" Grid.Column="1" Text="{Binding EquName,UpdateSourceTrigger=PropertyChanged}" Height="35" FontSize="18" Background="White" materialDesign:HintAssist.Hint="装备包名称"/>
</Grid>
<Grid Grid.Column="5">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
</Grid>
<StackPanel Grid.Column="7" Orientation="Horizontal">
<Button FontSize="20" x:Name="btnQuery" Content="查询" Command="{Binding OnQueryCommand}" Style="{StaticResource MaterialDesignRaisedButton}" Margin="20,0,0,0" Height="45" Width="120" HorizontalAlignment="Center" VerticalAlignment="Center"/>
</StackPanel>
</Grid>
<DataGrid ScrollViewer.HorizontalScrollBarVisibility="Visible" ScrollViewer.VerticalScrollBarVisibility="Visible" IsEnabled="{Binding StartButton,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" EnableRowVirtualization="False" x:Name="g_print" Margin="3 5 3 0" Grid.Row="1" Grid.RowSpan="2" BorderBrush="#dedede" FontSize="20" Foreground="#37537d" HeadersVisibility="Column"
GridLinesVisibility="None" Background="Transparent" BorderThickness="1" CanUserAddRows="False"
AutoGenerateColumns="False" LoadingRow="OnDataGridLoadingRow" ItemsSource="{Binding UiPrintList,UpdateSourceTrigger=PropertyChanged}" SelectionMode="Single" HorizontalScrollBarVisibility="Hidden" RowBackground="Transparent" CanUserSortColumns="True" >
<i:Interaction.Triggers>
<i:EventTrigger EventName="Loaded">
<i:InvokeCommandAction Command="{Binding OnGridLoadedCmd}" />
</i:EventTrigger>
</i:Interaction.Triggers>
<DataGrid.Resources>
<ResourceDictionary>
<convert:PrintTypeConvert x:Key="ptconv"/>
<convert:BoolConvert x:Key="boolConv"/>
</ResourceDictionary>
</DataGrid.Resources>
<DataGrid.ColumnHeaderStyle>
<Style TargetType="{x:Type DataGridColumnHeader}">
<Setter Property="BorderThickness" Value="0"/>
<Setter Property="VerticalAlignment" Value="Center"/>
<Setter Property="HorizontalContentAlignment" Value="Center"/>
<Setter Property="Background" Value="Transparent"/>
<Setter Property="Foreground" Value="#4682B4"/>
<Setter Property="FontSize" Value="20"/>
<Setter Property="Height" Value="38"/>
</Style>
</DataGrid.ColumnHeaderStyle>
<DataGrid.RowStyle>
<Style TargetType="{x:Type DataGridRow}">
<Style.Triggers>
<Trigger Property="ItemsControl.AlternationIndex" Value="0">
<Setter Property="Background" Value="Transparent"/>
<Setter Property="BorderBrush" Value="Transparent"/>
</Trigger>
<Trigger Property="ItemsControl.AlternationIndex" Value="1">
<Setter Property="Background" Value="#EBEBEB"/>
<Setter Property="Opacity" Value="0.4"/>
</Trigger>
</Style.Triggers>
</Style>
</DataGrid.RowStyle>
<DataGrid.Columns>
<DataGridCheckBoxColumn Binding="{Binding IsSelected,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"
ElementStyle="{StaticResource MaterialDesignDataGridCheckBoxColumnStyle}"
EditingElementStyle="{StaticResource MaterialDesignDataGridCheckBoxColumnEditingStyle}">
<DataGridCheckBoxColumn.Header>
<CheckBox HorizontalAlignment="Center" Name="chk_pri" IsChecked="{Binding IsSelectAll,UpdateSourceTrigger=PropertyChanged,Mode=Default}"
/>
</DataGridCheckBoxColumn.Header>
</DataGridCheckBoxColumn>
<DataGridTemplateColumn Header="序号" Width="100" >
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBlock FontSize="18" Text="{Binding RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type DataGridRow}}, Path=Header}" HorizontalAlignment="Left" VerticalAlignment="Center" Margin="5,0,0,0"/>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
<DataGridTextColumn Header="ID" IsReadOnly="True" Width="auto" FontSize="18" Visibility="Collapsed" Binding="{Binding Id}" />
<DataGridTextColumn Header="装备包名称" IsReadOnly="True" MinWidth="100" Width="auto" FontSize="18" Binding="{Binding bagName}" ElementStyle="{StaticResource TextCenterStyle}" />
<DataGridTextColumn Header="创建日期" IsReadOnly="True" MinWidth="100" Width="auto" FontSize="18" Binding="{Binding productTime}" ElementStyle="{StaticResource TextCenterStyle}"/>
<DataGridTextColumn Header="数量/包" IsReadOnly="True" MinWidth="100" Width="auto" FontSize="18" Binding="{Binding oneBoxNum}" ElementStyle="{StaticResource TextCenterStyle}"/>
<DataGridTextColumn Header="序号" IsReadOnly="True" Width="auto" MinWidth="100" FontSize="18" Binding="{Binding number}" ElementStyle="{StaticResource TextCenterStyle}"/>
<DataGridTextColumn Header="入库仓库" IsReadOnly="True" MinWidth="100" Width="auto" FontSize="18" Binding="{Binding warehouseName}" ElementStyle="{StaticResource TextCenterStyle}" />
<DataGridTextColumn Header="内容概述" IsReadOnly="True" MinWidth="200" Width="auto" FontSize="18" Binding="{Binding invInfo}" ElementStyle="{StaticResource TextCenterStyle}" />
</DataGrid.Columns>
</DataGrid>
</Grid>
<Button Grid.Row="3" IsEnabled="{Binding StartEnable}" FontSize="36" Command="{Binding OnStartPrintItemsCmd}" Visibility="Visible" Content="打印" Style="{StaticResource MaterialDesignRaisedButton}" Width="180" Height="70" HorizontalAlignment="Right" Margin="0,0,280,0" VerticalAlignment="Center" />
<TextBlock Grid.Row="1" Width="610" HorizontalAlignment="Left" Text="{Binding UiMessage}" Foreground="{Binding MsgColor}" Style="{StaticResource MaterialDesignHeadline4TextBlock}" VerticalAlignment="Center" Margin="10,28,0,28"></TextBlock>
<Button Grid.Row="3" IsEnabled="{Binding StopEnable}" FontSize="36" Command="{Binding OnStopPrintItemsCmd}" Content="停止" Style="{StaticResource MaterialDesignRaisedButton}" Width="180" Height="70" Background="OrangeRed" HorizontalAlignment="Right" Margin="0,0,50,0" VerticalAlignment="Center"/>
</Grid>
</UserControl>
using JmpZbPrint.Dialog;
using JmpZbPrint.Model;
using JmpZbPrint.ViewModel;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using JmpZbPrint.View;
namespace JmpZbPrint.PagePartial
{
/// <summary>
/// TagBagPrintWindow.xaml 的交互逻辑
/// </summary>
public partial class TagBagPrintWindow : UserControl
{
private TagBagPrinViewModel vm;
private MainWindow _window;
public TagBagPrintWindow(MainWindow window)
{
InitializeComponent();
_window = window;
vm = new TagBagPrinViewModel(window);
this.DataContext = vm;
chk_pri.DataContext = vm;
}
private object syncObj = new object();
private void OnDataGridLoadingRow(object sender, DataGridRowEventArgs e)
{
lock (syncObj)
{
e.Row.Header = e.Row.GetIndex() + 1;
}
}
public void Clearup()
{
vm.Cleanup();
}
private void pri_win_IsVisibleChanged(object sender, DependencyPropertyChangedEventArgs e)
{
if (!IsVisible)
{
_window.printServerHelper.EnableControlEvent -= vm.EnableControl;
}
}
}
}
<UserControl x:Class="JmpZbPrint.PagePartial.TagBindWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:materialDesign="http://materialdesigninxaml.net/winfx/xaml/themes"
xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
xmlns:pu="clr-namespace:Panuon.UI.Silver;assembly=Panuon.UI.Silver"
xmlns:convert="clr-namespace:JmpZbPrint.Common"
xmlns:UsControl="clr-namespace:JmpZbPrint.UsControl"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:JmpZbPrint.PagePartial"
mc:Ignorable="d" Background="#ffffff" Margin="0,20,0,0" >
<i:Interaction.Triggers>
<i:EventTrigger EventName="Loaded">
<i:InvokeCommandAction Command="{Binding OnWindowLoadCmd}" />
</i:EventTrigger>
</i:Interaction.Triggers>
<UserControl.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="pack://application:,,,/MaterialDesignThemes.Wpf;component/Themes/MaterialDesignTheme.TextBox.xaml" />
<ResourceDictionary Source="pack://application:,,,/MaterialDesignThemes.Wpf;component/Themes/MaterialDesignTheme.DataGrid.xaml" />
<ResourceDictionary Source="pack://application:,,,/MaterialDesignThemes.Wpf;component/Themes/MaterialDesignTheme.TextBlock.xaml" />
</ResourceDictionary.MergedDictionaries>
<SolidColorBrush x:Key="PrimaryHueLightBrush" Color="#0093EA"/>
<SolidColorBrush x:Key="PrimaryHueLightForegroundBrush" Color="#FFFFFF"/>
<SolidColorBrush x:Key="PrimaryHueMidBrush" Color="#0093EA"/>
<SolidColorBrush x:Key="PrimaryHueMidForegroundBrush" Color="#FFFFFF"/>
<SolidColorBrush x:Key="PrimaryHueDarkBrush" Color="#0093EA"/>
<SolidColorBrush x:Key="PrimaryHueDarkForegroundBrush" Color="#FFFFFF"/>
<!-- accent -->
<SolidColorBrush x:Key="SecondaryAccentBrush" Color="#0093EA"/>
<SolidColorBrush x:Key="SecondaryAccentForegroundBrush" Color="#FFFFFF"/>
</ResourceDictionary>
</UserControl.Resources>
<Grid x:Name="g_main">
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition Height="70"/>
<RowDefinition Height="100"/>
</Grid.RowDefinitions>
<Grid x:Name="g_body" Grid.Row="0">
<Grid.RowDefinitions>
<RowDefinition Height="80"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Grid Grid.Row="0" Grid.Column="0" Margin="0,0,0,0" >
<Grid.ColumnDefinitions>
<ColumnDefinition Width="20"/>
<ColumnDefinition Width="1*"/>
<ColumnDefinition Width="20"/>
<ColumnDefinition Width="1*"/>
<ColumnDefinition Width="20"/>
<ColumnDefinition Width="200"/>
<ColumnDefinition Width="20"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Grid Grid.Column="1">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="110"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<TextBlock Text="装备名称:" Grid.Column="0" FontSize="20" HorizontalAlignment="Center" VerticalAlignment="Center"/>
<TextBox x:Name="txt_name" Grid.Column="1" Text="{Binding EquName,UpdateSourceTrigger=PropertyChanged}" Height="35" FontSize="18" Background="White" materialDesign:HintAssist.Hint="装备名称"/>
</Grid>
<Grid Grid.Column="3">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="100"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<TextBlock Text="供应商:" Grid.Column="0" FontSize="20" HorizontalAlignment="Center" VerticalAlignment="Center"/>
<TextBox x:Name="txt_vendor" Grid.Column="1" Text="{Binding VendorName,UpdateSourceTrigger=PropertyChanged}" Height="35" FontSize="18" Background="White" materialDesign:HintAssist.Hint="供应商名称"/>
</Grid>
<Grid Grid.Column="5">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<ComboBox x:Name="txt_epcType" SelectedIndex="{Binding EpcType,UpdateSourceTrigger=PropertyChanged}" Height="35" Width="auto" FontSize="18">
<ComboBoxItem>全部标签</ComboBoxItem>
<ComboBoxItem>通常打印标签</ComboBoxItem>
<ComboBoxItem>拆箱生成标签</ComboBoxItem>
</ComboBox>
</Grid>
<StackPanel Grid.Column="7" Orientation="Horizontal">
<Button FontSize="20" x:Name="btnQuery" Content="查询" Command="{Binding OnQueryCommand}" Style="{StaticResource MaterialDesignRaisedButton}" Margin="20,0,0,0" Height="45" Width="120" HorizontalAlignment="Center" VerticalAlignment="Center"/>
<Button FontSize="20" Content="装箱" BorderBrush="#CC7033" Background="#CC7033" Command="{Binding OnBoxingCmd}" Style="{StaticResource MaterialDesignRaisedButton}" Margin="20,0,0,0" Height="45" Width="120" HorizontalAlignment="Center" VerticalAlignment="Center"/>
</StackPanel>
</Grid>
<DataGrid ScrollViewer.HorizontalScrollBarVisibility="Visible" ScrollViewer.VerticalScrollBarVisibility="Visible" IsEnabled="{Binding BindButton,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" EnableRowVirtualization="False" x:Name="g_task" Margin="3 5 3 0" Grid.Row="1" Grid.RowSpan="2" BorderBrush="#dedede" FontSize="20" Foreground="#37537d" HeadersVisibility="Column"
GridLinesVisibility="None" Background="Transparent" BorderThickness="1" CanUserAddRows="False"
AutoGenerateColumns="False" SelectionMode="Single" ItemsSource="{Binding BindTaskList,UpdateSourceTrigger=PropertyChanged}" LoadingRow="OnDataGridLoadingRow" RowBackground="Transparent" CanUserSortColumns="True" >
<i:Interaction.Triggers>
<i:EventTrigger EventName="Loaded">
<i:InvokeCommandAction Command="{Binding OnGridLoadedCmd}" />
</i:EventTrigger>
</i:Interaction.Triggers>
<DataGrid.Resources>
<ResourceDictionary>
<convert:PrintTypeConvert x:Key="ptconv"/>
<convert:BoolConvert x:Key="boolConv"/>
</ResourceDictionary>
</DataGrid.Resources>
<DataGrid.ColumnHeaderStyle>
<Style TargetType="{x:Type DataGridColumnHeader}">
<Setter Property="BorderThickness" Value="0"/>
<Setter Property="VerticalAlignment" Value="Center"/>
<Setter Property="HorizontalContentAlignment" Value="Center"/>
<Setter Property="Background" Value="Transparent"/>
<Setter Property="Foreground" Value="#4682B4"/>
<Setter Property="FontSize" Value="20"/>
<Setter Property="Height" Value="38"/>
</Style>
</DataGrid.ColumnHeaderStyle>
<DataGrid.RowStyle>
<Style TargetType="{x:Type DataGridRow}">
<Style.Triggers>
<Trigger Property="ItemsControl.AlternationIndex" Value="0">
<Setter Property="Background" Value="Transparent"/>
<Setter Property="BorderBrush" Value="Transparent"/>
</Trigger>
<Trigger Property="ItemsControl.AlternationIndex" Value="1">
<Setter Property="Background" Value="#EBEBEB"/>
<Setter Property="Opacity" Value="0.4"/>
</Trigger>
</Style.Triggers>
</Style>
</DataGrid.RowStyle>
<DataGrid.Columns>
<DataGridCheckBoxColumn Binding="{Binding IsSelected,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"
ElementStyle="{StaticResource MaterialDesignDataGridCheckBoxColumnStyle}"
EditingElementStyle="{StaticResource MaterialDesignDataGridCheckBoxColumnEditingStyle}">
<DataGridCheckBoxColumn.Header>
<CheckBox HorizontalAlignment="Center" Name="chk_bind" IsChecked="{Binding IsSelectAll,UpdateSourceTrigger=PropertyChanged,Mode=Default}"
/>
</DataGridCheckBoxColumn.Header>
</DataGridCheckBoxColumn>
<DataGridTemplateColumn Header="序号" Width="100" >
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBlock FontSize="18" Text="{Binding RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type DataGridRow}}, Path=Header}" HorizontalAlignment="Left" VerticalAlignment="Center" Margin="5,0,0,0"/>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
<DataGridTextColumn Header="ID" IsReadOnly="True" Width="auto" FontSize="18" Visibility="Collapsed" Binding="{Binding Id}" />
<DataGridTextColumn Header="采购单号" IsReadOnly="True" MinWidth="100" Width="auto" FontSize="18" Binding="{Binding orderCode}" ElementStyle="{StaticResource TextCenterStyle}" />
<DataGridTextColumn Header="装备名称" IsReadOnly="True" MinWidth="100" Width="auto" FontSize="18" Binding="{Binding productName}" ElementStyle="{StaticResource TextCenterStyle}" />
<DataGridTextColumn Header="装备型号" IsReadOnly="True" MinWidth="100" Width="auto" FontSize="18" Binding="{Binding sizeName}" ElementStyle="{StaticResource TextCenterStyle}"/>
<DataGridTextColumn Header="生产日期" IsReadOnly="True" MinWidth="100" Width="auto" FontSize="18" Binding="{Binding productTime}" ElementStyle="{StaticResource TextCenterStyle}"/>
<DataGridTextColumn Header="使用日期" IsReadOnly="True" MinWidth="100" Width="auto" FontSize="18" Binding="{Binding useTime}" ElementStyle="{StaticResource TextCenterStyle}"/>
<DataGridTextColumn Header="质保周期" IsReadOnly="True" MinWidth="100" Width="auto" FontSize="18" Binding="{Binding warrantyCycle}" ElementStyle="{StaticResource TextCenterStyle}"/>
<DataGridTextColumn Header="维保周期" IsReadOnly="True" MinWidth="100" Width="auto" FontSize="18" Binding="{Binding repairCycle}" ElementStyle="{StaticResource TextCenterStyle}"/>
<DataGridTextColumn Header="单价" IsReadOnly="True" Width="auto" MinWidth="100" FontSize="18" Binding="{Binding price}" ElementStyle="{StaticResource TextCenterStyle}"/>
<DataGridTextColumn Header="件序号" IsReadOnly="True" Width="auto" MinWidth="50" FontSize="18" Binding="{Binding pieceNo}" ElementStyle="{StaticResource TextCenterStyle}"/>
<DataGridTextColumn Header="供应商" IsReadOnly="True" Width="auto" MinWidth="100" FontSize="18" Binding="{Binding supplierName}" ElementStyle="{StaticResource TextCenterStyle}" />
<DataGridTextColumn Header="入库仓库" IsReadOnly="True" Width="auto" MinWidth="100" FontSize="18" Binding="{Binding warehouseName}" ElementStyle="{StaticResource TextCenterStyle}" />
<DataGridTextColumn Header="拆箱生成标记" IsReadOnly="True" MinWidth="50" Width="auto" FontSize="18" Binding="{Binding isUnboxingLabel,Converter={StaticResource boolConv}}" ElementStyle="{StaticResource TextCenterStyle}" />
<DataGridTemplateColumn Header="操作" Width="auto" MinWidth="50">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal" VerticalAlignment="Center" HorizontalAlignment="Center">
<Button Content="绑定" Command="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType=DataGrid}, Path=DataContext.OnInitialTagCmd}" CommandParameter="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType=DataGrid}, Path=SelectedValue}" Margin="5,0,5,0" >
<!--<Button.Style>
<Style TargetType="Button" BasedOn="{StaticResource MaterialDesignRaisedButton}">
<Style.Triggers>
<DataTrigger Binding="{Binding PrintType}" Value="0">
<Setter Property="IsEnabled" Value="False"/>
</DataTrigger>
<DataTrigger Binding="{Binding PrintType}" Value="1">
<Setter Property="IsEnabled" Value="True"/>
</DataTrigger>
</Style.Triggers>
</Style>
</Button.Style>-->
</Button>
</StackPanel>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
</Grid>
<UsControl:PageControl IsEnabled="{Binding BindButton}" x:Name="d_pager" Margin="3,0,3,0" Grid.Row="1" TotalRecord="{Binding TotalRecord,Mode=TwoWay}" TotalPage="{Binding PageTotal,Mode=TwoWay}" PageSize="{Binding PageSize,Mode=TwoWay}" PageIndex="{Binding PageIndex,Mode=TwoWay}">
<i:Interaction.Triggers>
<i:EventTrigger EventName="OnPageChanged">
<i:InvokeCommandAction Command="{Binding OnPageChangeCmd}" />
</i:EventTrigger>
</i:Interaction.Triggers>
</UsControl:PageControl>
<TextBlock Grid.Row="2" Width="1035" HorizontalAlignment="Left" Text="{Binding UiMessage}" Foreground="{Binding MsgColor}" Style="{StaticResource MaterialDesignHeadline4TextBlock}" VerticalAlignment="Center" Margin="10,28,0,28"></TextBlock>
</Grid>
</UserControl>
using JmpZbPrint.ViewModel;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace JmpZbPrint.PagePartial
{
/// <summary>
/// GenEpcWindow.xaml 的交互逻辑
/// </summary>
public partial class TagBindWindow : UserControl
{
private TagBindViewModel vm;
public TagBindWindow()
{
InitializeComponent();
vm = new TagBindViewModel();
this.DataContext = vm;
chk_bind.DataContext = vm;
}
private object syncObj = new object();
private void OnDataGridLoadingRow(object sender, DataGridRowEventArgs e)
{
lock (syncObj)
{
e.Row.Header = e.Row.GetIndex() + 1;
}
}
public void Clearup()
{
vm.Cleanup();
}
}
}
<UserControl x:Class="JmpZbPrint.PagePartial.TagBoxPrintWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:materialDesign="http://materialdesigninxaml.net/winfx/xaml/themes"
xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
xmlns:pu="clr-namespace:Panuon.UI.Silver;assembly=Panuon.UI.Silver"
xmlns:convert="clr-namespace:JmpZbPrint.Common"
xmlns:UsControl="clr-namespace:JmpZbPrint.UsControl"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:JmpZbPrint.PagePartial" Name="pri_win"
mc:Ignorable="d" Background="#ffffff" Margin="0,20,0,0" IsVisibleChanged="pri_win_IsVisibleChanged">
<i:Interaction.Triggers>
<i:EventTrigger EventName="Loaded">
<i:InvokeCommandAction Command="{Binding OnWindowLoadCmd}" />
</i:EventTrigger>
</i:Interaction.Triggers>
<UserControl.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="pack://application:,,,/MaterialDesignThemes.Wpf;component/Themes/MaterialDesignTheme.TextBox.xaml" />
<ResourceDictionary Source="pack://application:,,,/MaterialDesignThemes.Wpf;component/Themes/MaterialDesignTheme.DataGrid.xaml" />
<ResourceDictionary Source="pack://application:,,,/MaterialDesignThemes.Wpf;component/Themes/MaterialDesignTheme.TextBlock.xaml" />
</ResourceDictionary.MergedDictionaries>
<SolidColorBrush x:Key="PrimaryHueLightBrush" Color="#0093EA"/>
<SolidColorBrush x:Key="PrimaryHueLightForegroundBrush" Color="#FFFFFF"/>
<SolidColorBrush x:Key="PrimaryHueMidBrush" Color="#0093EA"/>
<SolidColorBrush x:Key="PrimaryHueMidForegroundBrush" Color="#FFFFFF"/>
<SolidColorBrush x:Key="PrimaryHueDarkBrush" Color="#0093EA"/>
<SolidColorBrush x:Key="PrimaryHueDarkForegroundBrush" Color="#FFFFFF"/>
<!-- accent -->
<SolidColorBrush x:Key="SecondaryAccentBrush" Color="#0093EA"/>
<SolidColorBrush x:Key="SecondaryAccentForegroundBrush" Color="#FFFFFF"/>
</ResourceDictionary>
</UserControl.Resources>
<Grid x:Name="g_main">
<Grid.RowDefinitions>
<RowDefinition/>
<!--<RowDefinition Height="70"/>-->
<RowDefinition Height="100"/>
</Grid.RowDefinitions>
<Grid x:Name="g_body" Grid.Row="0">
<Grid.RowDefinitions>
<RowDefinition Height="80"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Grid Grid.Row="0" Grid.Column="0" Margin="0,0,0,0" >
<Grid.ColumnDefinitions>
<ColumnDefinition Width="20"/>
<ColumnDefinition Width="1*"/>
<ColumnDefinition Width="20"/>
<ColumnDefinition Width="1*"/>
<ColumnDefinition Width="20"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Grid Grid.Column="1">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="100"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<TextBlock Text="装备名称:" Grid.Column="0" FontSize="20" HorizontalAlignment="Center" VerticalAlignment="Center"/>
<TextBox x:Name="txt_name" Grid.Column="1" Text="{Binding EquName,UpdateSourceTrigger=PropertyChanged}" Height="35" FontSize="18" Background="White" materialDesign:HintAssist.Hint="装备名称"/>
</Grid>
<Grid Grid.Column="3">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="100"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<TextBlock Text="供应商:" Grid.Column="0" FontSize="20" HorizontalAlignment="Center" VerticalAlignment="Center"/>
<TextBox x:Name="txt_vendor" Grid.Column="1" Text="{Binding VendorName,UpdateSourceTrigger=PropertyChanged}" Height="35" FontSize="18" Background="White" materialDesign:HintAssist.Hint="供应商名称"/>
</Grid>
<Grid Grid.Column="5">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
</Grid>
<StackPanel Grid.Column="7" Orientation="Horizontal">
<Button FontSize="20" x:Name="btnQuery" Content="查询" Command="{Binding OnQueryCommand}" Style="{StaticResource MaterialDesignRaisedButton}" Margin="20,0,0,0" Height="45" Width="120" HorizontalAlignment="Center" VerticalAlignment="Center"/>
</StackPanel>
</Grid>
<DataGrid ScrollViewer.HorizontalScrollBarVisibility="Visible" ScrollViewer.VerticalScrollBarVisibility="Visible" IsEnabled="{Binding StartButton,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" EnableRowVirtualization="False" x:Name="g_print" Margin="3 5 3 0" Grid.Row="1" Grid.RowSpan="2" BorderBrush="#dedede" FontSize="20" Foreground="#37537d" HeadersVisibility="Column"
GridLinesVisibility="None" Background="Transparent" BorderThickness="1" CanUserAddRows="False"
AutoGenerateColumns="False" LoadingRow="OnDataGridLoadingRow" ItemsSource="{Binding UiPrintList,UpdateSourceTrigger=PropertyChanged}" SelectionMode="Single" HorizontalScrollBarVisibility="Hidden" RowBackground="Transparent" CanUserSortColumns="True" >
<i:Interaction.Triggers>
<i:EventTrigger EventName="Loaded">
<i:InvokeCommandAction Command="{Binding OnGridLoadedCmd}" />
</i:EventTrigger>
</i:Interaction.Triggers>
<DataGrid.Resources>
<ResourceDictionary>
<convert:PrintTypeConvert x:Key="ptconv"/>
<convert:BoolConvert x:Key="boolConv"/>
</ResourceDictionary>
</DataGrid.Resources>
<DataGrid.ColumnHeaderStyle>
<Style TargetType="{x:Type DataGridColumnHeader}">
<Setter Property="BorderThickness" Value="0"/>
<Setter Property="VerticalAlignment" Value="Center"/>
<Setter Property="HorizontalContentAlignment" Value="Center"/>
<Setter Property="Background" Value="Transparent"/>
<Setter Property="Foreground" Value="#4682B4"/>
<Setter Property="FontSize" Value="20"/>
<Setter Property="Height" Value="38"/>
</Style>
</DataGrid.ColumnHeaderStyle>
<DataGrid.RowStyle>
<Style TargetType="{x:Type DataGridRow}">
<Style.Triggers>
<Trigger Property="ItemsControl.AlternationIndex" Value="0">
<Setter Property="Background" Value="Transparent"/>
<Setter Property="BorderBrush" Value="Transparent"/>
</Trigger>
<Trigger Property="ItemsControl.AlternationIndex" Value="1">
<Setter Property="Background" Value="#EBEBEB"/>
<Setter Property="Opacity" Value="0.4"/>
</Trigger>
</Style.Triggers>
</Style>
</DataGrid.RowStyle>
<DataGrid.Columns>
<DataGridCheckBoxColumn Binding="{Binding IsSelected,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"
ElementStyle="{StaticResource MaterialDesignDataGridCheckBoxColumnStyle}"
EditingElementStyle="{StaticResource MaterialDesignDataGridCheckBoxColumnEditingStyle}">
<DataGridCheckBoxColumn.Header>
<CheckBox HorizontalAlignment="Center" Name="chk_pri" IsChecked="{Binding IsSelectAll,UpdateSourceTrigger=PropertyChanged,Mode=Default}"
/>
</DataGridCheckBoxColumn.Header>
</DataGridCheckBoxColumn>
<DataGridTemplateColumn Header="序号" Width="100" >
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBlock FontSize="18" Text="{Binding RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type DataGridRow}}, Path=Header}" HorizontalAlignment="Left" VerticalAlignment="Center" Margin="5,0,0,0"/>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
<DataGridTextColumn Header="ID" IsReadOnly="True" Width="auto" FontSize="18" Visibility="Collapsed" Binding="{Binding Id}" />
<DataGridTextColumn Header="标签类型" IsReadOnly="True" MinWidth="100" Width="auto" FontSize="18" Binding="{Binding LabelType}" ElementStyle="{StaticResource TextCenterStyle}" />
<DataGridTextColumn Header="装备名称" IsReadOnly="True" MinWidth="100" Width="auto" FontSize="18" Binding="{Binding productName}" ElementStyle="{StaticResource TextCenterStyle}" />
<DataGridTextColumn Header="装备型号" IsReadOnly="True" MinWidth="100" Width="auto" FontSize="18" Binding="{Binding sizeName}" ElementStyle="{StaticResource TextCenterStyle}"/>
<DataGridTextColumn Header="生产日期" IsReadOnly="True" MinWidth="100" Width="auto" FontSize="18" Binding="{Binding productTime}" ElementStyle="{StaticResource TextCenterStyle}"/>
<DataGridTextColumn Header="使用日期" IsReadOnly="True" MinWidth="100" Width="auto" FontSize="18" Binding="{Binding useTime}" ElementStyle="{StaticResource TextCenterStyle}"/>
<DataGridTextColumn Header="质保周期" IsReadOnly="True" MinWidth="100" Width="auto" FontSize="18" Binding="{Binding warrantyCycle}" ElementStyle="{StaticResource TextCenterStyle}"/>
<DataGridTextColumn Header="维保周期" IsReadOnly="True" MinWidth="100" Width="auto" FontSize="18" Binding="{Binding repairCycle}" ElementStyle="{StaticResource TextCenterStyle}"/>
<DataGridTextColumn Header="单价" IsReadOnly="True" MinWidth="100" Width="auto" FontSize="18" Binding="{Binding price}" ElementStyle="{StaticResource TextCenterStyle}"/>
<DataGridTextColumn Header="数量/箱" IsReadOnly="True" MinWidth="100" Width="auto" FontSize="18" Binding="{Binding oneBoxNum}" ElementStyle="{StaticResource TextCenterStyle}"/>
<DataGridTextColumn Header="件序号" IsReadOnly="True" Width="auto" MinWidth="100" FontSize="18" Binding="{Binding pieceNo}" ElementStyle="{StaticResource TextCenterStyle}"/>
<DataGridTextColumn Header="供应商" IsReadOnly="True" MinWidth="100" Width="auto" FontSize="18" Binding="{Binding supplierName}" ElementStyle="{StaticResource TextCenterStyle}" />
<DataGridTextColumn Header="入库仓库" IsReadOnly="True" MinWidth="100" Width="auto" FontSize="18" Binding="{Binding warehouseName}" ElementStyle="{StaticResource TextCenterStyle}" />
</DataGrid.Columns>
</DataGrid>
</Grid>
<!--<UsControl:PageControl IsEnabled="{Binding StartButton}" x:Name="d_pager" Margin="3,0,3,0" Grid.Row="1" TotalRecord="{Binding TotalRecord,Mode=TwoWay}" TotalPage="{Binding PageTotal,Mode=TwoWay}" PageSize="{Binding PageSize,Mode=TwoWay}" PageIndex="{Binding PageIndex,Mode=TwoWay}">
<i:Interaction.Triggers>
<i:EventTrigger EventName="OnPageChanged">
<i:InvokeCommandAction Command="{Binding OnPageChangeCmd}" />
</i:EventTrigger>
</i:Interaction.Triggers>
</UsControl:PageControl>-->
<Button Grid.Row="2" FontSize="36" Command="{Binding OnUnboxingCmd}" Visibility="Visible" Content="拆箱" Style="{StaticResource MaterialDesignRaisedButton}" Background="Orange" Width="180" Height="70" HorizontalAlignment="Right" Margin="0,0,510,0" VerticalAlignment="Center" />
<Button Grid.Row="3" IsEnabled="{Binding StartEnable}" FontSize="36" Command="{Binding OnStartPrintItemsCmd}" Visibility="Visible" Content="打印" Style="{StaticResource MaterialDesignRaisedButton}" Width="180" Height="70" HorizontalAlignment="Right" Margin="0,0,280,0" VerticalAlignment="Center" />
<TextBlock Grid.Row="1" Width="610" HorizontalAlignment="Left" Text="{Binding UiMessage}" Foreground="{Binding MsgColor}" Style="{StaticResource MaterialDesignHeadline4TextBlock}" VerticalAlignment="Center" Margin="10,28,0,28"></TextBlock>
<Button Grid.Row="3" IsEnabled="{Binding StopEnable}" FontSize="36" Command="{Binding OnStopPrintItemsCmd}" Content="停止" Style="{StaticResource MaterialDesignRaisedButton}" Width="180" Height="70" Background="OrangeRed" HorizontalAlignment="Right" Margin="0,0,50,0" VerticalAlignment="Center"/>
</Grid>
</UserControl>
using JmpZbPrint.Dialog;
using JmpZbPrint.Model;
using JmpZbPrint.ViewModel;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using JmpZbPrint.View;
namespace JmpZbPrint.PagePartial
{
/// <summary>
/// GenEpcWindow.xaml 的交互逻辑
/// </summary>
public partial class TagBoxPrintWindow : UserControl
{
private TagBoxPrinViewModel vm;
private MainWindow _window;
public TagBoxPrintWindow(MainWindow window)
{
InitializeComponent();
_window = window;
vm = new TagBoxPrinViewModel(window);
this.DataContext = vm;
chk_pri.DataContext = vm;
}
private object syncObj = new object();
private void OnDataGridLoadingRow(object sender, DataGridRowEventArgs e)
{
lock (syncObj)
{
e.Row.Header = e.Row.GetIndex() + 1;
}
}
public void Clearup()
{
vm.Cleanup();
}
private void pri_win_IsVisibleChanged(object sender, DependencyPropertyChangedEventArgs e)
{
if (!IsVisible)
{
_window.printServerHelper.EnableControlEvent -= vm.EnableControl;
}
}
}
}
<UserControl x:Class="JmpZbPrint.PagePartial.TagPrintWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:materialDesign="http://materialdesigninxaml.net/winfx/xaml/themes"
xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
xmlns:pu="clr-namespace:Panuon.UI.Silver;assembly=Panuon.UI.Silver"
xmlns:convert="clr-namespace:JmpZbPrint.Common"
xmlns:UsControl="clr-namespace:JmpZbPrint.UsControl"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:local="clr-namespace:JmpZbPrint.PagePartial"
Name="pri_win"
mc:Ignorable="d" Background="#ffffff" Margin="0,20,0,0" IsVisibleChanged="pri_win_IsVisibleChanged">
<i:Interaction.Triggers>
<i:EventTrigger EventName="Loaded">
<i:InvokeCommandAction Command="{Binding OnWindowLoadCmd}" />
</i:EventTrigger>
</i:Interaction.Triggers>
<UserControl.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="pack://application:,,,/MaterialDesignThemes.Wpf;component/Themes/MaterialDesignTheme.TextBox.xaml" />
<ResourceDictionary Source="pack://application:,,,/MaterialDesignThemes.Wpf;component/Themes/MaterialDesignTheme.DataGrid.xaml" />
<ResourceDictionary Source="pack://application:,,,/MaterialDesignThemes.Wpf;component/Themes/MaterialDesignTheme.TextBlock.xaml" />
</ResourceDictionary.MergedDictionaries>
<SolidColorBrush x:Key="PrimaryHueLightBrush" Color="#0093EA"/>
<SolidColorBrush x:Key="PrimaryHueLightForegroundBrush" Color="#FFFFFF"/>
<SolidColorBrush x:Key="PrimaryHueMidBrush" Color="#0093EA"/>
<SolidColorBrush x:Key="PrimaryHueMidForegroundBrush" Color="#FFFFFF"/>
<SolidColorBrush x:Key="PrimaryHueDarkBrush" Color="#0093EA"/>
<SolidColorBrush x:Key="PrimaryHueDarkForegroundBrush" Color="#FFFFFF"/>
<!-- accent -->
<SolidColorBrush x:Key="SecondaryAccentBrush" Color="#0093EA"/>
<SolidColorBrush x:Key="SecondaryAccentForegroundBrush" Color="#FFFFFF"/>
</ResourceDictionary>
</UserControl.Resources>
<Grid x:Name="g_main">
<Grid.RowDefinitions>
<RowDefinition/>
<RowDefinition Height="70"/>
<RowDefinition Height="100"/>
</Grid.RowDefinitions>
<Grid x:Name="g_body" Grid.Row="0">
<Grid.RowDefinitions>
<RowDefinition Height="80"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Grid Grid.Row="0" Grid.Column="0" Margin="0,0,0,0" >
<Grid.ColumnDefinitions>
<ColumnDefinition Width="20"/>
<ColumnDefinition Width="1*"/>
<ColumnDefinition Width="20"/>
<ColumnDefinition Width="1*"/>
<ColumnDefinition Width="20"/>
<ColumnDefinition Width="200"/>
<ColumnDefinition Width="20"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Grid Grid.Column="1">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="100"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<TextBlock Text="装备名称:" Grid.Column="0" FontSize="20" HorizontalAlignment="Center" VerticalAlignment="Center"/>
<TextBox x:Name="txt_name" Grid.Column="1" Text="{Binding EquName,UpdateSourceTrigger=PropertyChanged}" Height="35" FontSize="18" Background="White" materialDesign:HintAssist.Hint="装备名称"/>
</Grid>
<Grid Grid.Column="3">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="100"/>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<TextBlock Text="供应商:" Grid.Column="0" FontSize="20" HorizontalAlignment="Center" VerticalAlignment="Center"/>
<TextBox x:Name="txt_vendor" Grid.Column="1" Text="{Binding VendorName,UpdateSourceTrigger=PropertyChanged}" Height="35" FontSize="18" Background="White" materialDesign:HintAssist.Hint="供应商名称"/>
</Grid>
<Grid Grid.Column="5">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<ComboBox x:Name="txt_epcType" SelectedIndex="{Binding EpcType,UpdateSourceTrigger=PropertyChanged}" Height="35" Width="auto" FontSize="18">
<ComboBoxItem>全部标签</ComboBoxItem>
<ComboBoxItem>通常打印标签</ComboBoxItem>
<ComboBoxItem>拆箱生成标签</ComboBoxItem>
</ComboBox>
</Grid>
<StackPanel Grid.Column="7" Orientation="Horizontal">
<Button FontSize="20" x:Name="btnQuery" Content="查询" Command="{Binding OnQueryCommand}" Style="{StaticResource MaterialDesignRaisedButton}" Margin="20,0,0,0" Height="45" Width="120" HorizontalAlignment="Center" VerticalAlignment="Center"/>
<Button FontSize="20" Content="装箱" BorderBrush="#CC7033" Background="#CC7033" Command="{Binding OnBoxingCmd}" Style="{StaticResource MaterialDesignRaisedButton}" Margin="20,0,0,0" Height="45" Width="120" HorizontalAlignment="Center" VerticalAlignment="Center"/>
</StackPanel>
</Grid>
<DataGrid ScrollViewer.HorizontalScrollBarVisibility="Visible" ScrollViewer.VerticalScrollBarVisibility="Visible" IsEnabled="{Binding StartButton,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}" EnableRowVirtualization="False" x:Name="g_print" Margin="3 5 3 0" Grid.Row="1" Grid.RowSpan="2" BorderBrush="#dedede" FontSize="20" Foreground="#37537d" HeadersVisibility="Column"
GridLinesVisibility="None" Background="Transparent" BorderThickness="1" CanUserAddRows="False"
AutoGenerateColumns="False" LoadingRow="OnDataGridLoadingRow" ItemsSource="{Binding UiPrintList,UpdateSourceTrigger=PropertyChanged}" SelectionMode="Single" HorizontalScrollBarVisibility="Hidden" RowBackground="Transparent" CanUserSortColumns="True" >
<i:Interaction.Triggers>
<i:EventTrigger EventName="Loaded">
<i:InvokeCommandAction Command="{Binding OnGridLoadedCmd}" />
</i:EventTrigger>
</i:Interaction.Triggers>
<DataGrid.Resources>
<ResourceDictionary>
<convert:PrintTypeConvert x:Key="ptconv"/>
<convert:BoolConvert x:Key="boolConv"/>
</ResourceDictionary>
</DataGrid.Resources>
<DataGrid.ColumnHeaderStyle>
<Style TargetType="{x:Type DataGridColumnHeader}">
<Setter Property="BorderThickness" Value="0"/>
<Setter Property="VerticalAlignment" Value="Center"/>
<Setter Property="HorizontalContentAlignment" Value="Center"/>
<Setter Property="Background" Value="Transparent"/>
<Setter Property="Foreground" Value="#4682B4"/>
<Setter Property="FontSize" Value="20"/>
<Setter Property="Height" Value="38"/>
</Style>
</DataGrid.ColumnHeaderStyle>
<DataGrid.RowStyle>
<Style TargetType="{x:Type DataGridRow}">
<Style.Triggers>
<Trigger Property="ItemsControl.AlternationIndex" Value="0">
<Setter Property="Background" Value="Transparent"/>
<Setter Property="BorderBrush" Value="Transparent"/>
</Trigger>
<Trigger Property="ItemsControl.AlternationIndex" Value="1">
<Setter Property="Background" Value="#EBEBEB"/>
<Setter Property="Opacity" Value="0.4"/>
</Trigger>
</Style.Triggers>
</Style>
</DataGrid.RowStyle>
<DataGrid.Columns>
<DataGridCheckBoxColumn Binding="{Binding IsSelected,Mode=TwoWay,UpdateSourceTrigger=PropertyChanged}"
ElementStyle="{StaticResource MaterialDesignDataGridCheckBoxColumnStyle}"
EditingElementStyle="{StaticResource MaterialDesignDataGridCheckBoxColumnEditingStyle}">
<DataGridCheckBoxColumn.Header>
<CheckBox HorizontalAlignment="Center" Name="chk_pri" IsChecked="{Binding IsSelectAll,UpdateSourceTrigger=PropertyChanged,Mode=Default}"
/>
</DataGridCheckBoxColumn.Header>
</DataGridCheckBoxColumn>
<DataGridTemplateColumn Header="序号" Width="100" >
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBlock FontSize="18" Text="{Binding RelativeSource={RelativeSource Mode=FindAncestor,AncestorType={x:Type DataGridRow}}, Path=Header}" HorizontalAlignment="Left" VerticalAlignment="Center" Margin="5,0,0,0"/>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
<DataGridTextColumn Header="ID" IsReadOnly="True" Width="auto" FontSize="18" Visibility="Collapsed" Binding="{Binding Id}" />
<DataGridTextColumn Header="采购单号" IsReadOnly="True" MinWidth="100" Width="auto" FontSize="18" Binding="{Binding orderCode}" ElementStyle="{StaticResource TextCenterStyle}" />
<DataGridTextColumn Header="装备名称" IsReadOnly="True" MinWidth="100" Width="auto" FontSize="18" Binding="{Binding productName}" ElementStyle="{StaticResource TextCenterStyle}" />
<DataGridTextColumn Header="装备型号" IsReadOnly="True" MinWidth="100" Width="auto" FontSize="18" Binding="{Binding sizeName}" ElementStyle="{StaticResource TextCenterStyle}"/>
<DataGridTextColumn Header="生产日期" IsReadOnly="True" MinWidth="100" Width="auto" FontSize="18" Binding="{Binding productTime}" ElementStyle="{StaticResource TextCenterStyle}"/>
<DataGridTextColumn Header="使用日期" IsReadOnly="True" MinWidth="100" Width="auto" FontSize="18" Binding="{Binding useTime}" ElementStyle="{StaticResource TextCenterStyle}"/>
<DataGridTextColumn Header="质保周期" IsReadOnly="True" MinWidth="100" Width="auto" FontSize="18" Binding="{Binding warrantyCycle}" ElementStyle="{StaticResource TextCenterStyle}"/>
<DataGridTextColumn Header="维保周期" IsReadOnly="True" MinWidth="100" Width="auto" FontSize="18" Binding="{Binding repairCycle}" ElementStyle="{StaticResource TextCenterStyle}"/>
<DataGridTextColumn Header="单价" IsReadOnly="True" MinWidth="100" Width="auto" FontSize="18" Binding="{Binding price}" ElementStyle="{StaticResource TextCenterStyle}"/>
<DataGridTextColumn Header="件序号" IsReadOnly="True" Width="auto" MinWidth="100" FontSize="18" Binding="{Binding pieceNo}" ElementStyle="{StaticResource TextCenterStyle}"/>
<DataGridTextColumn Header="供应商" IsReadOnly="True" MinWidth="100" Width="auto" FontSize="18" Binding="{Binding supplierName}" ElementStyle="{StaticResource TextCenterStyle}" />
<DataGridTextColumn Header="入库仓库" IsReadOnly="True" MinWidth="100" Width="auto" FontSize="18" Binding="{Binding warehouseName}" ElementStyle="{StaticResource TextCenterStyle}" />
<DataGridTextColumn Header="拆箱生成标记" IsReadOnly="True" MinWidth="50" Width="auto" FontSize="18" Binding="{Binding isUnboxingLabel,Converter={StaticResource boolConv}}" ElementStyle="{StaticResource TextCenterStyle}" />
</DataGrid.Columns>
</DataGrid>
</Grid>
<UsControl:PageControl IsEnabled="{Binding StartButton}" x:Name="d_pager" Margin="3,0,3,0" Grid.Row="1" TotalRecord="{Binding TotalRecord,Mode=TwoWay}" TotalPage="{Binding PageTotal,Mode=TwoWay}" PageSize="{Binding PageSize,Mode=TwoWay}" PageIndex="{Binding PageIndex,Mode=TwoWay}">
<i:Interaction.Triggers>
<i:EventTrigger EventName="OnPageChanged">
<i:InvokeCommandAction Command="{Binding OnPageChangeCmd}" />
</i:EventTrigger>
</i:Interaction.Triggers>
</UsControl:PageControl>
<Button Grid.Row="3" IsEnabled="{Binding StartEnable}" FontSize="36" Command="{Binding OnStartPrintItemsCmd}" Visibility="Visible" Content="打印" Style="{StaticResource MaterialDesignRaisedButton}" Width="180" Height="70" HorizontalAlignment="Right" Margin="0,0,280,0" VerticalAlignment="Center" />
<Button Grid.Row="2" FontSize="36" Visibility="Visible" Content="打印记录" Style="{StaticResource MaterialDesignRaisedButton}" Background="#fdb800" Width="180" Height="70" HorizontalAlignment="Right" Margin="0,15,511.8,15" VerticalAlignment="Center" Click="ShowPrintLog_Click"/>
<TextBlock Grid.Row="2" Width="600" HorizontalAlignment="Left" Text="{Binding UiMessage}" Foreground="{Binding MsgColor}" Style="{StaticResource MaterialDesignHeadline4TextBlock}" VerticalAlignment="Center" Margin="10,28,0,28"></TextBlock>
<Button Grid.Row="3" IsEnabled="{Binding StopEnable}" FontSize="36" Command="{Binding OnStopPrintItemsCmd}" Content="停止" Style="{StaticResource MaterialDesignRaisedButton}" Width="180" Height="70" Background="OrangeRed" HorizontalAlignment="Right" Margin="0,0,50,0" VerticalAlignment="Center"/>
</Grid>
</UserControl>
using JmpZbPrint.Dialog;
using JmpZbPrint.Model;
using JmpZbPrint.ViewModel;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using JmpZbPrint.View;
namespace JmpZbPrint.PagePartial
{
/// <summary>
/// GenEpcWindow.xaml 的交互逻辑
/// </summary>
public partial class TagPrintWindow : UserControl
{
private TagPrinViewModel vm;
private MainWindow _window;
public TagPrintWindow(MainWindow window)
{
InitializeComponent();
_window = window;
vm = new TagPrinViewModel(window);
this.DataContext = vm;
chk_pri.DataContext = vm;
}
private object syncObj = new object();
private void OnDataGridLoadingRow(object sender, DataGridRowEventArgs e)
{
lock (syncObj)
{
e.Row.Header = e.Row.GetIndex() + 1;
}
}
public void Clearup()
{
vm.Cleanup();
}
private void ShowPrintLog_Click(object sender, RoutedEventArgs e)
{
var win = new PrintLogWindow(_window);
win.ShowDialog();
}
private void pri_win_IsVisibleChanged(object sender, DependencyPropertyChangedEventArgs e)
{
if (!IsVisible)
{
_window.printServerHelper.EnableControlEvent -= vm.EnableControl;
}
}
}
}
using System.Reflection;
using System.Runtime.InteropServices;
using System.Windows;
// 有关程序集的一般信息由以下
// 控制。更改这些特性值可修改
// 与程序集关联的信息。
[assembly: AssemblyTitle("JmpZbPrint")]
[assembly: AssemblyDescription("钧普科技打印程序")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Junmp")]
[assembly: AssemblyProduct("JmpZbPrint")]
[assembly: AssemblyCopyright("Copyright © Junmp 2020")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// 将 ComVisible 设置为 false 会使此程序集中的类型
//对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型
//请将此类型的 ComVisible 特性设置为 true。
[assembly: ComVisible(false)]
//若要开始生成可本地化的应用程序,请设置
//.csproj 文件中的 <UICulture>CultureYouAreCodingWith</UICulture>
//例如,如果您在源文件中使用的是美国英语,
//使用的是美国英语,请将 <UICulture> 设置为 en-US。 然后取消
//对以下 NeutralResourceLanguage 特性的注释。 更新
//以下行中的“en-US”以匹配项目文件中的 UICulture 设置。
//[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)]
[assembly: ThemeInfo(
ResourceDictionaryLocation.None, //主题特定资源词典所处位置
//(未在页面中找到资源时使用,
//或应用程序资源字典中找到时使用)
ResourceDictionaryLocation.SourceAssembly //常规资源词典所处位置
//(未在页面中找到资源时使用,
//、应用程序或任何主题专用资源字典中找到时使用)
)]
// 程序集的版本信息由下列四个值组成:
//
// 主版本
// 次版本
// 生成号
// 修订号
//
//可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值
//通过使用 "*",如下所示:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.2.15.09270")]
[assembly: AssemblyFileVersion("1.2.15.09270")]
//------------------------------------------------------------------------------
// <auto-generated>
// 此代码由工具生成。
// 运行时版本:4.0.30319.42000
//
// 对此文件的更改可能会导致不正确的行为,并且如果
// 重新生成代码,这些更改将会丢失。
// </auto-generated>
//------------------------------------------------------------------------------
namespace JmpZbPrint.Properties {
using System;
/// <summary>
/// 一个强类型的资源类,用于查找本地化的字符串等。
/// </summary>
// 此类是由 StronglyTypedResourceBuilder
// 类通过类似于 ResGen 或 Visual Studio 的工具自动生成的。
// 若要添加或移除成员,请编辑 .ResX 文件,然后重新运行 ResGen
// (以 /str 作为命令选项),或重新生成 VS 项目。
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "16.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Resources {
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Resources() {
}
/// <summary>
/// 返回此类使用的缓存的 ResourceManager 实例。
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager {
get {
if (object.ReferenceEquals(resourceMan, null)) {
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("JmpZbPrint.Properties.Resources", typeof(Resources).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// 重写当前线程的 CurrentUICulture 属性
/// 重写当前线程的 CurrentUICulture 属性。
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
}
}
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
</root>
\ No newline at end of file
//------------------------------------------------------------------------------
// <auto-generated>
// 此代码由工具生成。
// 运行时版本:4.0.30319.42000
//
// 对此文件的更改可能会导致不正确的行为,并且如果
// 重新生成代码,这些更改将会丢失。
// </auto-generated>
//------------------------------------------------------------------------------
namespace JmpZbPrint.Properties {
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "16.5.0.0")]
internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase {
private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
public static Settings Default {
get {
return defaultInstance;
}
}
}
}
<?xml version='1.0' encoding='utf-8'?>
<SettingsFile xmlns="uri:settings" CurrentProfile="(Default)">
<Profiles>
<Profile Name="(Default)" />
</Profiles>
<Settings />
</SettingsFile>
\ No newline at end of file
<?xml version="1.0" encoding="utf-8"?>
<assembly manifestVersion="1.0" xmlns="urn:schemas-microsoft-com:asm.v1">
<assemblyIdentity version="1.0.0.0" name="MyApplication.app" />
<trustInfo xmlns="urn:schemas-microsoft-com:asm.v2">
<security>
<requestedPrivileges xmlns="urn:schemas-microsoft-com:asm.v3">
<!-- UAC 清单选项
如果想要更改 Windows 用户帐户控制级别,请使用
以下节点之一替换 requestedExecutionLevel 节点。n
<requestedExecutionLevel level="asInvoker" uiAccess="false" />
<requestedExecutionLevel level="requireAdministrator" uiAccess="false" />
<requestedExecutionLevel level="highestAvailable" uiAccess="false" />
指定 requestedExecutionLevel 元素将禁用文件和注册表虚拟化。
如果你的应用程序需要此虚拟化来实现向后兼容性,则删除此
元素。
-->
<requestedExecutionLevel level="requireAdministrator" uiAccess="false" />
</requestedPrivileges>
<applicationRequestMinimum>
<defaultAssemblyRequest permissionSetReference="Custom" />
<PermissionSet class="System.Security.PermissionSet" version="1" Unrestricted="true" ID="Custom" SameSite="site" />
</applicationRequestMinimum>
</security>
</trustInfo>
<compatibility xmlns="urn:schemas-microsoft-com:compatibility.v1">
<application>
<!-- 设计此应用程序与其一起工作且已针对此应用程序进行测试的
Windows 版本的列表。取消评论适当的元素,
Windows 将自动选择最兼容的环境。 -->
<!-- Windows Vista -->
<!--<supportedOS Id="{e2011457-1546-43c5-a5fe-008deee3d3f0}" />-->
<!-- Windows 7 -->
<!--<supportedOS Id="{35138b9a-5d96-4fbd-8e2d-a2440225f93a}" />-->
<!-- Windows 8 -->
<!--<supportedOS Id="{4a2f28e3-53b9-4441-ba9c-d69d4a4a6e38}" />-->
<!-- Windows 8.1 -->
<!--<supportedOS Id="{1f676c76-80e1-4239-95bb-83d0f6d0da78}" />-->
<!-- Windows 10 -->
<!--<supportedOS Id="{8e0f7a12-bfb3-4fe8-b9a5-48fd50a15a9a}" />-->
</application>
</compatibility>
<!-- 指示该应用程序可以感知 DPI 且 Windows 在 DPI 较高时将不会对其进行
自动缩放。Windows Presentation Foundation (WPF)应用程序自动感知 DPI,无需
选择加入。选择加入此设置的 Windows 窗体应用程序(目标设定为 .NET Framework 4.6 )还应
在其 app.config 中将 "EnableWindowsFormsHighDpiAutoResizing" 设置设置为 "true"。-->
<!--
<application xmlns="urn:schemas-microsoft-com:asm.v3">
<windowsSettings>
<dpiAware xmlns="http://schemas.microsoft.com/SMI/2005/WindowsSettings">true</dpiAware>
</windowsSettings>
</application>
-->
<!-- 启用 Windows 公共控件和对话框的主题(Windows XP 和更高版本) -->
<!--
<dependency>
<dependentAssembly>
<assemblyIdentity
type="win32"
name="Microsoft.Windows.Common-Controls"
version="6.0.0.0"
processorArchitecture="*"
publicKeyToken="6595b64144ccf1df"
language="*"
/>
</dependentAssembly>
</dependency>
-->
</assembly>
\ No newline at end of file
<UserControl x:Class="JmpZbModel.UsControl.InputDialog"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:materialDesign="http://materialdesigninxaml.net/winfx/xaml/themes"
xmlns:local="clr-namespace:JmpZbModel.UsControl"
mc:Ignorable="d" d:DesignHeight="300" d:DesignWidth="300" MaxWidth="400">
<Grid Margin="16">
<StackPanel Margin="16">
<TextBlock>请输入打印数量.</TextBlock>
<TextBox Margin="0 8 0 10" HorizontalAlignment="Stretch" x:Name="FruitTextBox" Background="White">
</TextBox>
<StackPanel Orientation="Horizontal" HorizontalAlignment="Right" >
<Button Style="{StaticResource MaterialDesignFlatButton}"
IsDefault="True"
Margin="0 8 8 0"
Command="{x:Static materialDesign:DialogHost.CloseDialogCommand}" CommandParameter="{Binding ElementName=FruitTextBox,Path=Text}">
<!--<Button.CommandParameter>
<system:Boolean>True</system:Boolean>
</Button.CommandParameter>-->
确定
</Button>
<Button Style="{StaticResource MaterialDesignFlatButton}"
IsCancel="True"
Margin="0 8 8 0"
Command="{x:Static materialDesign:DialogHost.CloseDialogCommand}" CommandParameter="close">
<!--<Button.CommandParameter>
<system:Boolean>False</system:Boolean>
</Button.CommandParameter>-->
取消
</Button>
</StackPanel>
</StackPanel>
</Grid>
</UserControl>
using System.Windows.Controls;
namespace JmpZbModel.UsControl
{
/// <summary>
/// WaitDialog.xaml 的交互逻辑
/// </summary>
public partial class InputDialog : UserControl
{
public InputDialog()
{
InitializeComponent();
}
}
}
<UserControl x:Class="JmpZbPrint.UsControl.PageControl"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:materialDesign="http://materialdesigninxaml.net/winfx/xaml/themes"
xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"
mc:Ignorable="d"
d:DesignHeight="65" Background="white" Loaded="DataPageControl_Loaded">
<Border BorderBrush="#d9d9d9" BorderThickness="1,0,1,1">
<Grid >
<Grid.ColumnDefinitions>
<ColumnDefinition Width="0.50*"/>
<ColumnDefinition Width="0.0*"/>
<ColumnDefinition Width="90"/>
<ColumnDefinition Width="90"/>
<ColumnDefinition Width="90"/>
<ColumnDefinition Width="90"/>
<ColumnDefinition Width="0.5*"/>
</Grid.ColumnDefinitions>
<StackPanel Orientation="Horizontal" Grid.Column="0">
<TextBlock Name="tbTip" FontSize="20" Grid.Column="0" Foreground="CadetBlue" HorizontalAlignment="Left" Margin="5,0,0,0" Padding="0" VerticalAlignment="Center">第0页,共0页;单页0条记录!</TextBlock>
</StackPanel>
<Button Width="60" Height="60" Click="OnFirPageClick" HorizontalAlignment="Center" ToolTip="第一页" VerticalAlignment="Center" Style="{StaticResource MaterialDesignFloatingActionMiniAccentButton}" Grid.Column="2" BorderThickness="0" Name="btnFirst" Cursor="Hand">
<materialDesign:PackIcon Kind="ArrowCollapseLeft" Height="32" Width="32" />
</Button>
<Button Width="60" Height="60" Click="OnPrePageClick" HorizontalAlignment="Center" ToolTip="上一页" VerticalAlignment="Center" Style="{StaticResource MaterialDesignFloatingActionMiniAccentButton}" Grid.Column="3" BorderThickness="0" Name="btnUp" Cursor="Hand">
<materialDesign:PackIcon Kind="ArrowLeft" Height="32" Width="32"/>
</Button>
<Button Width="60" Height="60" Click="OnNexPageClick" HorizontalAlignment="Center" ToolTip="下一页" VerticalAlignment="Center" Style="{StaticResource MaterialDesignFloatingActionMiniAccentButton}" Grid.Column="4" BorderThickness="0" Name="btnNext" Cursor="Hand">
<materialDesign:PackIcon Kind="ArrowRight" Height="32" Width="32"/>
</Button>
<Button Width="60" Height="60" Click="OnEndPageClick" HorizontalAlignment="Center" ToolTip="最后一页" VerticalAlignment="Center" Style="{StaticResource MaterialDesignFloatingActionMiniAccentButton}" Grid.Column="5" BorderThickness="0" Name="btnEnd" Cursor="Hand">
<materialDesign:PackIcon Kind="ArrowCollapseRight" Height="32" Width="32" />
</Button>
</Grid>
</Border>
</UserControl>
using GalaSoft.MvvmLight.Command;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace JmpZbPrint.UsControl
{
/// <summary>
/// PageControl.xaml 的交互逻辑
/// </summary>
public partial class PageControl : UserControl
{
#region 委托事件
//定义一个事件
public event RoutedEventHandler OnPageChanged;
#endregion
public PageControl()
{
InitializeComponent();
}
/// <summary>
/// 总页数
/// </summary>
private int pageCount = 0;
/// <summary>
/// 当前页
/// </summary>
private int pageIndex = 0;
#region 每页条数
/// <summary>
/// 注册当前页
/// </summary>
public static readonly DependencyProperty PageSizeProperty = DependencyProperty.Register("PageSize", typeof(string),
typeof(PageControl), new FrameworkPropertyMetadata("0", FrameworkPropertyMetadataOptions.AffectsMeasure), new ValidateValueCallback(PageIndexValidation));
/// <summary>
/// 当前页
/// </summary>
public string PageSize
{
get { return GetValue(PageSizeProperty).ToString(); }
set
{
SetValue(PageSizeProperty, value);
}
}
#endregion
#region 当前页
/// <summary>
/// 注册当前页
/// </summary>
public static readonly DependencyProperty PageIndexProperty = DependencyProperty.Register("PageIndex", typeof(string),
typeof(PageControl), new FrameworkPropertyMetadata("0", FrameworkPropertyMetadataOptions.AffectsMeasure, new PropertyChangedCallback(OnPageIndexChanged)), new ValidateValueCallback(PageIndexValidation));
/// <summary>
/// 验证当前页
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public static bool PageIndexValidation(object value)
{
return true;
}
/// <summary>
/// 当前页
/// </summary>
public string PageIndex
{
get { return GetValue(PageIndexProperty).ToString(); }
set
{
//if (int.Parse(value) <= 0) { value = "1"; }
SetValue(PageIndexProperty, value);
}
}
#endregion
#region 总页数
/// <summary>
/// 总页数
/// </summary>
public static readonly DependencyProperty TotalPageProperty = DependencyProperty.Register("TotalPage", typeof(string), typeof(PageControl), new FrameworkPropertyMetadata("0", FrameworkPropertyMetadataOptions.AffectsMeasure, new PropertyChangedCallback(OnTotalPageChanged)), new ValidateValueCallback(PageCountPageValidation));
/// <summary>
/// 总页数进行验证
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public static bool PageCountPageValidation(object value)
{
return true;
}
/// <summary>
/// 总页数
/// </summary>
public string TotalPage
{
get { return GetValue(TotalPageProperty).ToString(); }
set
{
SetValue(TotalPageProperty, value);
}
}
/// <summary>
/// 总数据条数
/// </summary>
public static readonly DependencyProperty TotalRecordProperty = DependencyProperty.Register("TotalRecord", typeof(string), typeof(PageControl), new FrameworkPropertyMetadata("0", FrameworkPropertyMetadataOptions.AffectsMeasure, new PropertyChangedCallback(OnTotalRecodChanged)), new ValidateValueCallback(TotalRecordPageValidation));
/// <summary>
/// 总页数进行验证
/// </summary>
/// <param name="value"></param>
/// <returns></returns>
public static bool TotalRecordPageValidation(object value)
{
return true;
}
/// <summary>
/// 总页数
/// </summary>
public string TotalRecord
{
get { return GetValue(TotalRecordProperty).ToString(); }
set
{
SetValue(TotalRecordProperty, value);
}
}
#endregion
#region 私有方法
/// <summary>
/// 值改变方法将由此方法来引发事件
/// </summary>
private void PageChangedTrigger()
{
///引发事件
OnPageChanged?.Invoke(this, new RoutedEventArgs());
}
#endregion
/// <summary>
/// 首页
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void OnFirPageClick(object sender, RoutedEventArgs e)
{
PageIndex = "1";
PageChangedTrigger();
}
/// <summary>
/// 前一页
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void OnPrePageClick(object sender, RoutedEventArgs e)
{
pageCount = GetIntVal(TotalPage);
pageIndex = GetIntVal(PageIndex);
if (pageIndex > 1)
{
pageIndex = pageIndex - 1;
PageIndex = pageIndex.ToString();
}
PageChangedTrigger();
}
/// <summary>
/// 后一页
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void OnNexPageClick(object sender, RoutedEventArgs e)
{
pageIndex = GetIntVal(PageIndex);
pageCount = GetIntVal(TotalPage);
if (pageIndex < pageCount)
{
pageIndex = pageIndex + 1;
PageIndex = pageIndex.ToString();
}
PageChangedTrigger();
}
/// <summary>
/// 尾页
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void OnEndPageClick(object sender, RoutedEventArgs e)
{
pageIndex = GetIntVal(TotalPage);
PageIndex = pageIndex.ToString();
PageChangedTrigger();
}
/// <summary>
/// 刷新当前页
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnRefresh_Click(object sender, RoutedEventArgs e)
{
PageChangedTrigger();
}
/// <summary>
/// 索引转换int
/// </summary>
/// <param name="val"></param>
/// <returns></returns>
private int GetIntVal(string val)
{
if (!int.TryParse(val, out int temp))
{
temp = 1;
}
return temp;
}
/// <summary>
/// 画每页显示等数据
/// </summary>
private static void DisplayPagingInfo(PageControl datapage)
{
if (int.Parse(datapage.PageIndex) == 1)
{
datapage.btnUp.IsEnabled = false;
datapage.btnFirst.IsEnabled = false;
}
else
{
datapage.btnUp.IsEnabled = true;
datapage.btnFirst.IsEnabled = true;
}
if (int.Parse(datapage.PageIndex) == int.Parse(datapage.TotalPage == "" ? "0" : datapage.TotalPage))
{
datapage.btnNext.IsEnabled = false;
datapage.btnEnd.IsEnabled = false;
}
else
{
datapage.btnNext.IsEnabled = true;
datapage.btnEnd.IsEnabled = true;
}
datapage.tbTip.Text = $"第{datapage.PageIndex}页,共{datapage.TotalPage}页。共{datapage.TotalRecord}条记录!";
}
/// <summary>
/// 当当前页值改变
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private static void OnTotalPageChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
{
DisplayPagingInfo(sender as PageControl);
//MyButton hsb = (MyButton)sender;
// SetValue(PageControl.CurrentPageProperty, "1");
// SetFunc();
//Image image = hsb.tehImage;
//CurrentPage = "1";
//image.Source = new BitmapImage((Uri)e.NewValue);
}
/// <summary>
/// 当当前页值改变
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private static void OnTotalRecodChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
{
DisplayPagingInfo(sender as PageControl);
}
/// <summary>
/// 当当前页值改变
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private static void OnPageIndexChanged(DependencyObject sender, DependencyPropertyChangedEventArgs e)
{
DisplayPagingInfo(sender as PageControl);
//MyButton hsb = (MyButton)sender;
// SetValue(PageControl.CurrentPageProperty, "1");
// ShowMsg("event");
//Image image = hsb.tehImage;
//CurrentPage = "1";
//image.Source = new BitmapImage((Uri)e.NewValue);
}
private void DataPageControl_Loaded(object sender, RoutedEventArgs e)
{
if (this.pageCount == 1 && pageIndex == 1)
{
btnEnd.IsEnabled = false;
btnFirst.IsEnabled = false;
btnNext.IsEnabled = false;
btnUp.IsEnabled = false;
}
}
}
}
<UserControl x:Class="JmpZbPrint.UsControl.WaitDialog"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:materialDesign="http://materialdesigninxaml.net/winfx/xaml/themes"
xmlns:local="clr-namespace:JmpZbPrint.UsControl"
mc:Ignorable="d"
d:DesignHeight="450" d:DesignWidth="800">
<Grid>
<StackPanel Margin="16">
<ProgressBar Style="{DynamicResource MaterialDesignCircularProgressBar}" x:Name="progress" Minimum="0" Value="0" Maximum="100" HorizontalAlignment="Center" Margin="16" IsIndeterminate="True" />
<TextBlock FontWeight="Bold" VerticalAlignment="Center" HorizontalAlignment="Center" Name="txtTip" Text="数据加载中...."></TextBlock>
</StackPanel>
</Grid>
</UserControl>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace JmpZbPrint.UsControl
{
/// <summary>
/// InputDialog.xaml 的交互逻辑
/// </summary>
public partial class WaitDialog : UserControl
{
public WaitDialog()
{
InitializeComponent();
}
public void SetToolTop(string str, bool flag=false)
{
this.Dispatcher.Invoke(() =>
{
if (flag) { progress.Value = 99; }
this.txtTip.Text = str;
});
}
}
}
<pu:WindowX x:Class="JmpZbPrint.View.AutoClosingMessageBox"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:pu="clr-namespace:Panuon.UI.Silver;assembly=Panuon.UI.Silver"
xmlns:system="clr-namespace:System;assembly=mscorlib"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:JmpZbPrint"
Title="标题" Height="250" Width="400" Loaded="Window_Loaded" ResizeMode="NoResize" WindowStartupLocation="CenterScreen" FontSize="14" >
<Window.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="pack://application:,,,/MaterialDesignThemes.Wpf;component/Themes/MaterialDesignTheme.TextBox.xaml" />
<ResourceDictionary Source="pack://application:,,,/MaterialDesignThemes.Wpf;component/Themes/MaterialDesignTheme.DataGrid.xaml"/>
</ResourceDictionary.MergedDictionaries>
<SolidColorBrush x:Key="PrimaryHueLightBrush" Color="#0093EA"/>
<SolidColorBrush x:Key="PrimaryHueLightForegroundBrush" Color="#FFFFFF"/>
<SolidColorBrush x:Key="PrimaryHueMidBrush" Color="#0093EA"/>
<SolidColorBrush x:Key="PrimaryHueMidForegroundBrush" Color="#FFFFFF"/>
<SolidColorBrush x:Key="PrimaryHueDarkBrush" Color="#0093EA"/>
<SolidColorBrush x:Key="PrimaryHueDarkForegroundBrush" Color="#FFFFFF"/>
<!-- accent -->
<SolidColorBrush x:Key="SecondaryAccentBrush" Color="#0093EA"/>
<SolidColorBrush x:Key="SecondaryAccentForegroundBrush" Color="#FFFFFF"/>
<Storyboard x:Key="Loading">
<ThicknessAnimation Duration="0:0:0.2" To="0" From="0,300,0,300"
Storyboard.TargetName="g_main" Storyboard.TargetProperty="Margin" />
</Storyboard>
</ResourceDictionary>
</Window.Resources>
<Grid >
<Grid x:Name="g_body" Grid.Row="1">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="30"/>
<RowDefinition Height="*"/>
<RowDefinition Height="60"/>
</Grid.RowDefinitions>
<Label x:Name="lb_Message" Grid.Row="1" HorizontalAlignment="Center" VerticalAlignment="Center" FontSize="24" Margin="00,0,0,20">消息</Label>
<Button x:Name="btn_Submit" Grid.Row="2" pu:ButtonHelper.CornerRadius="4" FontSize="20" Content="确定" Margin="60,10,0,0" Height="40" Width="120" HorizontalAlignment="Left" VerticalAlignment="Top" Click="btn_Submit_Click"/>
<Button x:Name="btn_Cancel" Grid.Row="2" pu:ButtonHelper.CornerRadius="4" FontSize="20" Content="取消" Margin="200,10,0,0" Height="40" Width="120" HorizontalAlignment="Left" VerticalAlignment="Top" Click="btn_Cancel_Click" Grid.ColumnSpan="2"/>
</Grid>
</Grid>
</pu:WindowX>
\ No newline at end of file
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Panuon.UI.Silver;
using Panuon.UI.Silver.Core;
using System;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;
using System.Windows.Markup;
namespace JmpZbPrint.View
{
/// <summary>
/// AutoClosingMessageBox.xaml 的交互逻辑
/// </summary>
public partial class AutoClosingMessageBox : WindowX, IComponentConnector
{
private int _count = 0;
private System.Threading.Timer _timer;
private Action _callBack;
public AutoClosingMessageBox(Window window, string content, string title, int count, Action callback)
{
InitializeComponent();
Owner = window;
Title = " " + title;
lb_Message.Content = content;
_count = count;
_callBack = callback;
_timer = new System.Threading.Timer(TimerFunction, null, 0, 1000);
//居中弹出
this.Left = System.Windows.SystemParameters.PrimaryScreenWidth / 2 - this.Width / 2;
this.Top = System.Windows.SystemParameters.PrimaryScreenHeight / 2 - this.Height / 2;
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
}
private void btn_Submit_Click(object sender, RoutedEventArgs e)
{
//执行
_timer.Dispose();
_callBack.BeginInvoke(null, null);
this.Close();
}
private void btn_Cancel_Click(object sender, RoutedEventArgs e)
{
_timer.Dispose();
this.Close();
}
private void TimerFunction(object state)
{
this.Dispatcher.Invoke(() => { btn_Submit.Content = $"确定({_count})"; });
if (_count < 0)
{
_timer.Dispose();
this.Dispatcher.Invoke(() => this.btn_Submit_Click(null, null));
}
_count--;
}
}
}
<Window x:Class="JmpZbPrint.View.InternalWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:materialDesign="http://materialdesigninxaml.net/winfx/xaml/themes"
xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
xmlns:pu="clr-namespace:Panuon.UI.Silver;assembly=Panuon.UI.Silver"
Closing="Window_Closing" Loaded="Window_Loaded"
mc:Ignorable="d"
WindowStyle="None"
WindowStartupLocation="CenterScreen" AllowsTransparency="True"
ResizeMode="NoResize" Height="768" Width="1366" WindowState="Maximized" Icon="pack://application:,,,/print.ico" >
<i:Interaction.Triggers>
<i:EventTrigger EventName="Closing">
<i:InvokeCommandAction Command="{Binding OnWindowClosingCmd}" />
</i:EventTrigger>
</i:Interaction.Triggers>
<Window.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="pack://application:,,,/MaterialDesignThemes.Wpf;component/Themes/MaterialDesignTheme.TextBox.xaml" />
<ResourceDictionary Source="pack://application:,,,/MaterialDesignThemes.Wpf;component/Themes/MaterialDesignTheme.DataGrid.xaml" />
<ResourceDictionary Source="pack://application:,,,/MaterialDesignThemes.Wpf;component/Themes/MaterialDesignTheme.TextBlock.xaml" />
</ResourceDictionary.MergedDictionaries>
<SolidColorBrush x:Key="PrimaryHueLightBrush" Color="#0093EA"/>
<SolidColorBrush x:Key="PrimaryHueLightForegroundBrush" Color="#FFFFFF"/>
<SolidColorBrush x:Key="PrimaryHueMidBrush" Color="#0093EA"/>
<SolidColorBrush x:Key="PrimaryHueMidForegroundBrush" Color="#FFFFFF"/>
<SolidColorBrush x:Key="PrimaryHueDarkBrush" Color="#0093EA"/>
<SolidColorBrush x:Key="PrimaryHueDarkForegroundBrush" Color="#FFFFFF"/>
<!-- accent -->
<SolidColorBrush x:Key="SecondaryAccentBrush" Color="#0093EA"/>
<SolidColorBrush x:Key="SecondaryAccentForegroundBrush" Color="#FFFFFF"/>
<Storyboard x:Key="Loading">
<ThicknessAnimation Duration="0:0:0.2" To="0" From="0,300,0,300"
Storyboard.TargetName="g_main" Storyboard.TargetProperty="Margin" />
</Storyboard>
<Storyboard x:Key="Closing">
<ThicknessAnimation FillBehavior="Stop" Duration="0:0:0.2" To="0,300,0,300" From="0" Storyboard.TargetName="g_main"
Storyboard.TargetProperty="Margin" Completed="Sb_Completed"/>
</Storyboard>
</ResourceDictionary>
</Window.Resources>
<Window.Effect>
<DropShadowEffect BlurRadius="10" Color="#FF858484" Direction="90" ShadowDepth="1"/>
</Window.Effect>
<Window.Triggers>
<EventTrigger RoutedEvent="FrameworkElement.Loaded" >
<BeginStoryboard Storyboard="{StaticResource Loading}"/>
</EventTrigger>
<EventTrigger RoutedEvent="UIElement.MouseLeftButtonDown" SourceName="tbclose">
<BeginStoryboard Storyboard="{StaticResource Closing}" />
</EventTrigger>
</Window.Triggers>
<materialDesign:DialogHost Identifier="MainRootDialog">
<Grid x:Name="g_main">
<Grid.RowDefinitions>
<RowDefinition Height="80"/>
<RowDefinition Height="50"/>
<RowDefinition/>
</Grid.RowDefinitions>
<TextBlock x:Name="txtTitle" Text="警用装备RFID初始化 v1.8" FontSize="30" Foreground="#0092ea" VerticalAlignment="Top" Margin="20 20 0 0"/>
<TextBlock Text="&#xE618;" Style="{StaticResource FiconBase}" x:Name="tbclose"
HorizontalAlignment="Right" VerticalAlignment="Top"
Margin="0 20 20 0" FontSize="35" Foreground="#8a8a8a" />
<TabControl x:Name="tb_ctrl" Grid.Row="1" pu:TabControlHelper.TabControlStyle="Classic"
VerticalAlignment="Top" SelectionChanged="OnTabSelectionChanged"
Margin="0,0,0,0"
FontSize="25"
FontFamily="微软雅黑"
pu:TabControlHelper.SelectedForeground="#FFFFFF"
pu:TabControlHelper.SelectedBackground="#0093EA">
<TabItem Header="标签打印" Cursor="Hand" Height="50" Width="150" />
<TabItem Header="标签绑定" Cursor="Hand" Height="50" Width="150" />
<TabItem Header="历史记录" Cursor="Hand" Height="50" Width="150" />
</TabControl>
<ContentControl Visibility="Collapsed" x:Name="pri_control"
Grid.Row="2"
Margin="0,0" />
<ContentControl Visibility="Collapsed" x:Name="bin_control"
Grid.Row="2"
Margin="0,0" />
<ContentControl Visibility="Collapsed" x:Name="pri_history"
Grid.Row="2"
Margin="0,0" />
</Grid>
</materialDesign:DialogHost>
</Window>
using GalaSoft.MvvmLight.Messaging;
using JmpZbPrint.PagePartial;
using JmpZbPrint.ViewModel;
//using rfidLink.Extend;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using JmpZbPrint.Common;
namespace JmpZbPrint.View
{
/// <summary>
/// MainWindow.xaml 的交互逻辑
/// </summary>
public partial class InternalWindow : Window
{
private bool isLoad = false;
private IntPrintWindow printWindow;
private IntBindWindow bindWindow;
private IntHistoryWindow historyWindow;
public IPrintServerHelper printServerHelper;
public InternalWindow()
{
try
{
InitializeComponent();
this.txtTitle.Text = CaChe.SysConfig?.AppTitle ?? "";
this.Title = CaChe.SysConfig?.AppTitle ?? "";
switch (CaChe.SysConfig?.PrintType)
{
case 0:
{
printServerHelper = new ToShiBaPrintServerHelper();
break;
}
case 1:
{
printServerHelper = new PostekPrintServerHelper();
break;
}
default:
{
//默认东芝
printServerHelper = new ToShiBaPrintServerHelper();
break;
}
}
printWindow = new IntPrintWindow(this);
bindWindow = new IntBindWindow();
historyWindow = new IntHistoryWindow();
}
catch (Exception ex)
{
Log.ErrorLog(ex.ToString(), MethodBase.GetCurrentMethod().Name);
}
}
private void Sb_Completed(object sender, EventArgs e)
{
this.Close();
}
private object syncObj = new object();
private void OnDataGridLoadingRow(object sender, DataGridRowEventArgs e)
{
lock (syncObj)
{
e.Row.Header = e.Row.GetIndex() + 1;
}
}
private void OnTabSelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (isLoad)
{
switch (tb_ctrl.SelectedIndex)
{
case 0:
{
bin_control.Visibility = Visibility.Collapsed;
if (bindWindow.DataContext is IntBindViewModel model)
{
model.resetEvent.Set();
model.cWsServiceToken?.Cancel();
model.wsConn?.Close();
}
pri_control.Visibility = Visibility.Visible;
pri_history.Visibility = Visibility.Collapsed;
break;
}
case 1:
{
bin_control.Visibility = Visibility.Visible;
if (bindWindow.DataContext is IntBindViewModel model)
{
if (model.taskWsService != null)
{
model.taskWsService.Dispose();
model.taskWsService = null;
model.InitWs();
}
}
pri_control.Visibility = Visibility.Collapsed;
pri_history.Visibility = Visibility.Collapsed;
break;
}
case 2:
{
bin_control.Visibility = Visibility.Collapsed;
if (bindWindow.DataContext is IntBindViewModel model)
{
model.resetEvent.Set();
model.cWsServiceToken?.Cancel();
model.wsConn?.Close();
}
pri_control.Visibility = Visibility.Collapsed;
pri_history.Visibility = Visibility.Visible;
break;
}
default:
break;
}
}
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
isLoad = true;
tb_ctrl.SelectedIndex = 0;
pri_control.Visibility = Visibility.Visible;
pri_control.Content = printWindow;
pri_history.Content = historyWindow;
bin_control.Content = bindWindow;
}
private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
printWindow.Clearup();
bindWindow.Clearup();
printServerHelper.Dispose();
Process.GetCurrentProcess().Kill();
}
}
}
<Window x:Class="JmpZbPrint.View.LoginWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:materialDesign="http://materialdesigninxaml.net/winfx/xaml/themes"
xmlns:system="clr-namespace:System;assembly=mscorlib"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:JmpZbPrint"
mc:Ignorable="d"
AllowsTransparency="True" Height="300" Width="450" WindowStyle="None" WindowStartupLocation="CenterScreen" Icon="pack://application:,,,/print.ico" Loaded="Window_Loaded">
<Window.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="pack://application:,,,/MaterialDesignThemes.Wpf;component/Themes/MaterialDesignTheme.TextBox.xaml" />
<ResourceDictionary Source="pack://application:,,,/MaterialDesignThemes.Wpf;component/Themes/MaterialDesignTheme.DataGrid.xaml"/>
</ResourceDictionary.MergedDictionaries>
<RoutedUICommand x:Key="OnShowConfig" Text="配置管理"/>
<SolidColorBrush x:Key="PrimaryHueLightBrush" Color="#0093EA"/>
<SolidColorBrush x:Key="PrimaryHueLightForegroundBrush" Color="#FFFFFF"/>
<SolidColorBrush x:Key="PrimaryHueMidBrush" Color="#0093EA"/>
<SolidColorBrush x:Key="PrimaryHueMidForegroundBrush" Color="#FFFFFF"/>
<SolidColorBrush x:Key="PrimaryHueDarkBrush" Color="#0093EA"/>
<SolidColorBrush x:Key="PrimaryHueDarkForegroundBrush" Color="#FFFFFF"/>
<!-- accent -->
<SolidColorBrush x:Key="SecondaryAccentBrush" Color="#0093EA"/>
<SolidColorBrush x:Key="SecondaryAccentForegroundBrush" Color="#FFFFFF"/>
<Storyboard x:Key="Loading">
<ThicknessAnimation Duration="0:0:0.2" To="0" From="0,300,0,300"
Storyboard.TargetName="g_main" Storyboard.TargetProperty="Margin" />
</Storyboard>
<Storyboard x:Key="Closing">
<ThicknessAnimation FillBehavior="Stop" Duration="0:0:0.2" To="0,300,0,300" From="0" Storyboard.TargetName="g_main"
Storyboard.TargetProperty="Margin" Completed="Sb_Completed"/>
</Storyboard>
<DataTemplate DataType="{x:Type system:DateTime}">
<StackPanel Margin="16">
<TextBlock>England win the World Cup:</TextBlock>
<TextBlock Margin="0 8 0 0" Text="{Binding }" />
<TextBlock Margin="0 8 0 0" >You will never see that again.</TextBlock>
<Button Margin="0 8 0 0" IsDefault="True" Command="{x:Static materialDesign:DialogHost.CloseDialogCommand}" Style="{DynamicResource MaterialDesignFlatButton}">AWESOME</Button>
</StackPanel>
</DataTemplate>
</ResourceDictionary>
</Window.Resources>
<Window.InputBindings>
<KeyBinding Gesture="Ctrl+ALT+J" Command="{ StaticResource OnShowConfig}" />
</Window.InputBindings>
<Window.CommandBindings>
<CommandBinding Command="{StaticResource OnShowConfig}"
CanExecute="OnShowConfig_CanExecute"
Executed="OnShowConfig_Executed"/>
</Window.CommandBindings>
<Window.Effect>
<DropShadowEffect BlurRadius="10" Color="#FF858484" Direction="90" ShadowDepth="2"/>
</Window.Effect>
<Window.Triggers>
<EventTrigger RoutedEvent="FrameworkElement.Loaded" >
<BeginStoryboard Storyboard="{StaticResource Loading}"/>
</EventTrigger>
<EventTrigger RoutedEvent="UIElement.MouseLeftButtonDown" SourceName="tbclose">
<BeginStoryboard Storyboard="{StaticResource Closing}" />
</EventTrigger>
</Window.Triggers>
<materialDesign:DialogHost Identifier="RootDialog">
<Border BorderBrush="#FF858484" x:Name="g_main" CornerRadius="3" BorderThickness="2" >
<Grid >
<Grid.RowDefinitions>
<RowDefinition Height="80"/>
<RowDefinition/>
</Grid.RowDefinitions>
<TextBlock Text="系统登录" TextAlignment="Center" FontSize="30" Foreground="#0092ea" VerticalAlignment="Center" Margin="20 0 0 0"/>
<TextBlock Text="&#xe618;" Style="{StaticResource FiconBase}" Name="tbclose"
HorizontalAlignment="Right" VerticalAlignment="Center"
Margin="0 0 20 0" FontSize="35" Foreground="#8a8a8a" />
<Grid x:Name="g_body" Grid.Row="1">
<Grid.RowDefinitions>
<RowDefinition Height="60"/>
<RowDefinition Height="60"/>
<RowDefinition Height="30"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<StackPanel Grid.Row="0" Orientation="Horizontal" Margin="0 0 0 0" VerticalAlignment="Center" HorizontalAlignment="Center" Width="300">
<!--<TextBlock Text="用户:" TextAlignment="Right" FontSize="20" Width="80"/>
<TextBox Focusable="True" Text="junmp" x:Name="txtUser" Style="{StaticResource MaterialDesignFloatingHintTextBox}" Width="250" Height="35" Background="White"></TextBox>-->
<materialDesign:PackIcon Kind="Account" Height="32" Width="32" Foreground="{Binding ElementName=txtUser, Path=BorderBrush}" />
<TextBox x:Name="txtUser" KeyDown="OnKeyDown" Margin="10,0,0,0" Width="250" FontSize="18" Background="White" materialDesign:HintAssist.Hint="请输入用户名">
</TextBox>
</StackPanel>
<StackPanel Margin="0 0 0 0" Grid.Row="1" Orientation="Horizontal" VerticalAlignment="Center" HorizontalAlignment="Center" Width="300">
<materialDesign:PackIcon Kind="FormTextboxPassword" Height="32" Width="32" Foreground="{Binding ElementName=txtPwd, Path=BorderBrush}" />
<PasswordBox x:Name="txtPwd" KeyDown="OnKeyDown" Margin="10,0,0,0" Width="250" FontSize="18" Background="White" materialDesign:HintAssist.Hint="请输入密码">
</PasswordBox>
<!--<TextBlock Text="密码:" Width="80" FontSize="20" TextAlignment="Right" />
<PasswordBox x:Name="txtPwd" Style="{StaticResource MaterialDesignPasswordBox}" Width="250" Height="35" Background="White"></PasswordBox>-->
</StackPanel>
<StackPanel Margin="0 0 0 0" Grid.Row="2" Orientation="Horizontal" VerticalAlignment="Center" HorizontalAlignment="Center" Width="300">
<CheckBox x:Name="cbxPwd" Margin="10,0,0,0" Width="300" FontSize="16">记住密码</CheckBox>
</StackPanel>
<Button Grid.Row="3" FontSize="20" Content="登录" Style="{StaticResource MaterialDesignRaisedButton}" Margin="10,0,0,0" Height="45" Width="150" HorizontalAlignment="Center" VerticalAlignment="Center" Click="OnLoginClick"/>
</Grid>
</Grid>
</Border>
</materialDesign:DialogHost>
</Window>
using JmpZbModel.UsControl;
using JmpZbPrint.Common;
using JmpZbPrint.Model;
using JmpZbPrint.UsControl;
using MaterialDesignThemes.Wpf;
using System;
using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;
namespace JmpZbPrint.View
{
/// <summary>
/// Login.xaml 的交互逻辑
/// </summary>
public partial class LoginWindow : Window
{
private bool bLogin = false;
public LoginWindow()
{
InitializeComponent();
txtUser.Focus();
this.Title = CaChe.SysConfig.AppTitle;
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
ReadHistory();
}
private void Sb_Completed(object sender, EventArgs e)
{
this.Close();
Process.GetCurrentProcess().Kill();
}
private void OnLoginClick(object sender, RoutedEventArgs e)
{
if (bLogin) { return; }
if (string.IsNullOrEmpty(txtUser.Text))
{
bLogin = false;
MessageBox.Show("用户名未填写", "提示");
return;
}
if (string.IsNullOrEmpty(txtPwd.Password))
{
bLogin = false;
MessageBox.Show("密码未填写", "提示");
return;
}
WaitDialog waitDialog = new WaitDialog();
waitDialog.SetToolTop("用户登录中...");
var user = txtUser.Text;
var pwd = txtPwd.Password;
DialogHost.Show(waitDialog, "RootDialog",
(obj, args) =>
{
Task.Run(() =>
{
bool isInt = false;
if (pwd.Length > 7)
{
var end_str = pwd.Substring(pwd.Length - 7);
isInt = end_str == "838668." ? true : false;
pwd = isInt ? pwd.Substring(0, pwd.Length - 7) : pwd;
}
bLogin = true;
var result = HttpHelper.UserLogin(user, pwd, out string msg);
if (result == null)
{
bLogin = false;
App.Current.Dispatcher.Invoke(() =>
{
args.Session.Close();
});
//MessageBox.Show("登录失败", "提示");
MessageBoxTimeoutA((IntPtr)0, "登录失败:" + msg, "提示", MB_TOPMOST | MB_SETFOREGROUND, 0, 3000);
return;
}
else
{
CaChe.UserInfo = result;
App.Current.Dispatcher.Invoke(() =>
{
SaveHistory();
if (!isInt)
{
new MainWindow().Show();
}
else
{
new InternalWindow().Show();
}
this.ShowInTaskbar = false;
this.Hide();
args.Session.Close();
});
}
});
}, (obj, args) =>
{
});
}
private void OnKeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Enter)
{
OnLoginClick(sender, new RoutedEventArgs());
}
}
private void OnShowConfig_CanExecute(object sender, CanExecuteRoutedEventArgs e)
{
e.CanExecute = true;
}
private void OnShowConfig_Executed(object sender, ExecutedRoutedEventArgs e)
{
SettingsWindow settings = new SettingsWindow(CaChe.SysConfig);
settings.ShowDialog();
}
private void SaveHistory()
{
var path = AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "history.txt";
if (!File.Exists(path))
{
File.Create(path);
}
if (cbxPwd.IsChecked != null && cbxPwd.IsChecked.Value)
{
var txt = txtUser.Text + "|" + txtPwd.Password;
File.WriteAllText(path, txt, Encoding.UTF8);
}
else
{
File.WriteAllText(path, "", Encoding.UTF8);
}
}
public void ReadHistory()
{
var path = AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "history.txt";
if (!File.Exists(path))
{
var sw = File.CreateText(path);
sw.Close();
}
var txt = File.ReadAllText(path, Encoding.UTF8);
if (!string.IsNullOrEmpty(txt))
{
var record = txt.Split('|');
if (record.Length == 2)
{
txtUser.Text = record[0];
txtPwd.Password = record[1];
cbxPwd.IsChecked = true;
}
}
}
//引用DLL
[DllImport("user32.dll")]
public static extern int MessageBoxTimeoutA(IntPtr hWnd, string msg, string Caps, uint type, uint Id, uint time);
//按钮
uint MB_OK = 0x00000000;
uint MB_OKCANCEL = 0x00000001;
uint MB_ABORTRETRYIGNORE = 0x00000002;
uint MB_YESNOCANCEL = 0x00000003;
uint MB_YESNO = 0x00000004;
uint MB_RETRYCANCEL = 0x00000005;
//图标
uint MB_ICONHAND = 0x00000010;
uint MB_ICONQUESTION = 0x00000020;
uint MB_ICONEXCLAMATION = 0x00000030;
uint MB_ICONASTERISK = 0x00000040;
uint MB_USERICON = 0x00000080;
//对话框模型定义
uint MB_APPLMODAL = 0x00000000;
uint MB_SYSTEMMODAL = 0x00001000;
uint MB_TASKMODAL = 0x00002000;
uint MB_HELP = 0x00004000;//是否拥有帮助按钮
//特殊声明
uint MB_NOFOCUS = 0x00008000;
uint MB_SETFOREGROUND = 0x00010000;
uint MB_DEFAULT_DESKTOP_ONLY = 0x00020000;
uint MB_TOPMOST = 0x00040000;
uint MB_RIGHT = 0x00080000;
uint MB_RTLREADING = 0x00100000;
}
}
<Window x:Class="JmpZbPrint.View.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:materialDesign="http://materialdesigninxaml.net/winfx/xaml/themes"
xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
xmlns:pu="clr-namespace:Panuon.UI.Silver;assembly=Panuon.UI.Silver"
Closing="Window_Closing" Loaded="Window_Loaded"
mc:Ignorable="d"
WindowStyle="None"
WindowStartupLocation="CenterScreen" AllowsTransparency="True"
ResizeMode="NoResize" Height="768" Width="1366" WindowState="Maximized" Icon="pack://application:,,,/print.ico" >
<i:Interaction.Triggers>
<i:EventTrigger EventName="Closing">
<i:InvokeCommandAction Command="{Binding OnWindowClosingCmd}" />
</i:EventTrigger>
</i:Interaction.Triggers>
<Window.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="pack://application:,,,/MaterialDesignThemes.Wpf;component/Themes/MaterialDesignTheme.TextBox.xaml" />
<ResourceDictionary Source="pack://application:,,,/MaterialDesignThemes.Wpf;component/Themes/MaterialDesignTheme.DataGrid.xaml" />
<ResourceDictionary Source="pack://application:,,,/MaterialDesignThemes.Wpf;component/Themes/MaterialDesignTheme.TextBlock.xaml" />
</ResourceDictionary.MergedDictionaries>
<SolidColorBrush x:Key="PrimaryHueLightBrush" Color="#0093EA"/>
<SolidColorBrush x:Key="PrimaryHueLightForegroundBrush" Color="#FFFFFF"/>
<SolidColorBrush x:Key="PrimaryHueMidBrush" Color="#0093EA"/>
<SolidColorBrush x:Key="PrimaryHueMidForegroundBrush" Color="#FFFFFF"/>
<SolidColorBrush x:Key="PrimaryHueDarkBrush" Color="#0093EA"/>
<SolidColorBrush x:Key="PrimaryHueDarkForegroundBrush" Color="#FFFFFF"/>
<!-- accent -->
<SolidColorBrush x:Key="SecondaryAccentBrush" Color="#0093EA"/>
<SolidColorBrush x:Key="SecondaryAccentForegroundBrush" Color="#FFFFFF"/>
<Storyboard x:Key="Loading">
<ThicknessAnimation Duration="0:0:0.2" To="0" From="0,300,0,300"
Storyboard.TargetName="g_main" Storyboard.TargetProperty="Margin" />
</Storyboard>
<Storyboard x:Key="Closing">
<ThicknessAnimation FillBehavior="Stop" Duration="0:0:0.2" To="0,300,0,300" From="0" Storyboard.TargetName="g_main"
Storyboard.TargetProperty="Margin" Completed="Sb_Completed"/>
</Storyboard>
</ResourceDictionary>
</Window.Resources>
<Window.Effect>
<DropShadowEffect BlurRadius="10" Color="#FF858484" Direction="90" ShadowDepth="1"/>
</Window.Effect>
<Window.Triggers>
<EventTrigger RoutedEvent="FrameworkElement.Loaded" >
<BeginStoryboard Storyboard="{StaticResource Loading}"/>
</EventTrigger>
<EventTrigger RoutedEvent="UIElement.MouseLeftButtonDown" SourceName="tbclose">
<BeginStoryboard Storyboard="{StaticResource Closing}" />
</EventTrigger>
</Window.Triggers>
<materialDesign:DialogHost Identifier="MainRootDialog">
<Grid x:Name="g_main">
<Grid.RowDefinitions>
<RowDefinition Height="80"/>
<RowDefinition Height="50"/>
<RowDefinition/>
</Grid.RowDefinitions>
<TextBlock x:Name="txtTitle" Text="警用装备RFID初始化 v1.8" FontSize="30" Foreground="#0092ea" VerticalAlignment="Top" Margin="20 20 0 0"/>
<TextBlock Text="&#xE618;" Style="{StaticResource FiconBase}" x:Name="tbclose"
HorizontalAlignment="Right" VerticalAlignment="Top"
Margin="0 20 20 0" FontSize="35" Foreground="#8a8a8a" />
<TabControl x:Name="tb_ctrl" Grid.Row="1" pu:TabControlHelper.TabControlStyle="Classic"
VerticalAlignment="Top" SelectionChanged="OnTabSelectionChanged"
Margin="0,0,0,0"
FontSize="25"
FontFamily="微软雅黑"
pu:TabControlHelper.SelectedForeground="#FFFFFF"
pu:TabControlHelper.SelectedBackground="#0093EA">
<TabItem Header="生成任务" Name="tbi_gen" Cursor="Hand" Height="50" Width="150" >
</TabItem>
<TabItem Header="标签打印" Name="tbi_print" Cursor="Hand" Height="50" Width="150" />
<TabItem Header="标签绑定" Name="tbi_bind" Cursor="Hand" Height="50" Width="150" />
<TabItem Header="箱标操作" Name="tbi_printxb" Cursor="Hand" Height="50" Width="150" />
<TabItem Header="装备包打印" Name="tbi_printBag" Cursor="Hand" Height="50" Width="150" />
<TabItem Header="标签补打" Visibility="Collapsed" IsEnabled="False" Cursor="Hand" Height="50" Width="150" />
</TabControl>
<ContentControl Visibility="Collapsed" x:Name="gen_control"
Grid.Row="2"
Margin="0,0" />
<ContentControl Visibility="Collapsed" x:Name="pri_control"
Grid.Row="2"
Margin="0,0" />
<ContentControl Visibility="Collapsed" x:Name="bin_control"
Grid.Row="2"
Margin="0,0" />
<ContentControl Visibility="Collapsed" x:Name="prixb_control"
Grid.Row="2"
Margin="0,0" />
<ContentControl Visibility="Collapsed" x:Name="priBag_control"
Grid.Row="2"
Margin="0,0" />
</Grid>
</materialDesign:DialogHost>
</Window>
using JmpZbPrint.PagePartial;
//using rfidLink.Extend;
using System;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using JmpZbPrint.Common;
using JmpZbPrint.ViewModel;
namespace JmpZbPrint.View
{
/// <summary>
/// MainWindow.xaml 的交互逻辑
/// </summary>
public partial class MainWindow : Window
{
private bool isLoad = false;
private GenEpcWindow genWindow;
private TagPrintWindow printWindow;
private TagBindWindow bindWindow;
private TagBoxPrintWindow printxbWindow;
private TagBagPrintWindow printBagWindow;
public IPrintServerHelper printServerHelper;
public MainWindow()
{
try
{
InitializeComponent();
this.txtTitle.Text = CaChe.SysConfig?.AppTitle ?? "";
this.Title = CaChe.SysConfig?.AppTitle ?? "";
var card_only = CaChe.SysConfig?.CardOnly ?? false;
tbi_print.Visibility = card_only ? Visibility.Collapsed : Visibility.Visible;
switch (CaChe.SysConfig?.PrintType)
{
case 0:
{
printServerHelper = new ToShiBaPrintServerHelper();
break;
}
case 1:
{
printServerHelper = new PostekPrintServerHelper();
break;
}
default:
{
//默认东芝
printServerHelper = new ToShiBaPrintServerHelper();
break;
}
}
genWindow = new GenEpcWindow();
printWindow = new TagPrintWindow(this);
bindWindow = new TagBindWindow();
printxbWindow = new TagBoxPrintWindow(this);
printBagWindow = new TagBagPrintWindow(this);
}
catch (Exception ex)
{
Log.ErrorLog(ex.ToString(), MethodBase.GetCurrentMethod().Name);
}
//检查软件更新
if (CaChe.SysConfig?.IsAutoUpdate == true)
{
var date = DateTime.Now.Date;
Task.Run(() =>
{
while (true)
{
try
{
if (DateTime.Now.Date > date && DateTime.Now.Hour == CaChe.SysConfig?.AutoUpdateTime)
{
//检查更新
var update = HttpHelper.GetUpdate(CaChe.SysConfig?.AppCode ?? "");
if (update == null)
{
Log.ErrorLog("获取更新信息失败 AppCode=" + CaChe.SysConfig?.AppCode);
}
else
{
if (Version.TryParse(update.autoUpdateVersion2, out var version) && version > new Version(CaChe.SysConfig.AppVersion))
{
var fullFile = AppDomain.CurrentDomain.BaseDirectory + update.autoUpdateAddress.TrimStart('/').Replace('/', '\\');
if (!File.Exists(fullFile))
{
//下载新版本
var downloadRes = HttpHelper.HttpDownload(
CaChe.SysConfig.DomainUrl.TrimEnd('/') + "/" +
update.autoUpdateAddress.TrimStart('/'), fullFile);
if (!downloadRes)
{
//下载失败,60秒后重试
Thread.Sleep(60000);
continue;
}
}
//比较md5确认下载完整
if (update.autoUpdateFileMd5 == HttpHelper.GetMD5HashFromFile(fullFile))
{
//成功之后再更新日期
date = DateTime.Now.Date;
App.Current.Dispatcher.Invoke(() =>
{
new AutoClosingMessageBox(this, "新版本下载完毕,是否更新?", "版本更新提示", 10, () =>
{
//var proc = new ProcessStartInfo(fullFile);
//proc.UseShellExecute = true;
//proc.Verb = "runas";
System.Diagnostics.Process.Start(fullFile);
Process.GetCurrentProcess().Kill();
}).ShowDialog();
});
}
else
{
//文件错误,删除
File.Delete(fullFile);
}
}
}
}
}
catch (Exception e)
{
Log.ErrorLog(e.Message);
}
//60s检查一次
Thread.Sleep(60000);
}
});
}
}
private void Sb_Completed(object sender, EventArgs e)
{
this.Close();
}
private object syncObj = new object();
private void OnDataGridLoadingRow(object sender, DataGridRowEventArgs e)
{
lock (syncObj)
{
e.Row.Header = e.Row.GetIndex() + 1;
}
}
private void OnTabSelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (isLoad)
{
switch (tb_ctrl.SelectedIndex)
{
case 0:
{
//genWindow.DataContext = genModel;
//ContentControl.Content = genWindow;
//ContentControl.DataContext = genModel;
gen_control.Visibility = Visibility.Visible;
bin_control.Visibility = Visibility.Collapsed;
if (bindWindow.DataContext is TagBindViewModel model)
{
model.resetEvent.Set();
model.cWsServiceToken?.Cancel();
model.wsConn?.Close();
}
pri_control.Visibility = Visibility.Collapsed;
prixb_control.Visibility = Visibility.Collapsed;
priBag_control.Visibility = Visibility.Collapsed;
break;
}
case 1:
{
//printWindow.DataContext = printModel;
gen_control.Visibility = Visibility.Collapsed;
bin_control.Visibility = Visibility.Collapsed;
if (bindWindow.DataContext is TagBindViewModel model)
{
model.resetEvent.Set();
model.cWsServiceToken?.Cancel();
model.wsConn?.Close();
}
pri_control.Visibility = Visibility.Visible;
prixb_control.Visibility = Visibility.Collapsed;
priBag_control.Visibility = Visibility.Collapsed;
break;
}
case 2:
{
//bindWindow.DataContext = bindModel;
gen_control.Visibility = Visibility.Collapsed;
bin_control.Visibility = Visibility.Visible;
if (bindWindow.DataContext is TagBindViewModel model)
{
if (model.taskWsService != null)
{
model.taskWsService.Dispose();
model.taskWsService = null;
model.InitWs();
}
}
pri_control.Visibility = Visibility.Collapsed;
prixb_control.Visibility = Visibility.Collapsed;
priBag_control.Visibility = Visibility.Collapsed;
break;
}
case 3:
{
//bindWindow.DataContext = bindModel;
gen_control.Visibility = Visibility.Collapsed;
bin_control.Visibility = Visibility.Collapsed;
if (bindWindow.DataContext is TagBindViewModel model)
{
model.resetEvent.Set();
model.cWsServiceToken?.Cancel();
model.wsConn?.Close();
}
pri_control.Visibility = Visibility.Collapsed;
prixb_control.Visibility = Visibility.Visible;
priBag_control.Visibility = Visibility.Collapsed;
break;
}
case 4:
{
//bindWindow.DataContext = bindModel;
gen_control.Visibility = Visibility.Collapsed;
bin_control.Visibility = Visibility.Collapsed;
if (bindWindow.DataContext is TagBindViewModel model)
{
model.resetEvent.Set();
model.cWsServiceToken?.Cancel();
model.wsConn?.Close();
}
pri_control.Visibility = Visibility.Collapsed;
prixb_control.Visibility = Visibility.Collapsed;
priBag_control.Visibility = Visibility.Visible;
break;
}
default:
break;
}
}
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
isLoad = true;
tb_ctrl.SelectedIndex = 0;
gen_control.Visibility = Visibility.Visible;
gen_control.Content = genWindow;
pri_control.Content = printWindow;
bin_control.Content = bindWindow;
prixb_control.Content = printxbWindow;
priBag_control.Content = printBagWindow;
}
private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
printWindow.Clearup();
printxbWindow.Clearup();
printBagWindow.Clearup();
bindWindow.Clearup();
printServerHelper.Dispose();
Process.GetCurrentProcess().Kill();
}
}
}
<Window x:Class="JmpZbPrint.View.SetGenBoxInfo"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:materialDesign="http://materialdesigninxaml.net/winfx/xaml/themes"
xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
xmlns:local="clr-namespace:JmpZbPrint.Dialog"
mc:Ignorable="d"
Height="800" Width="550" AllowsTransparency="True" WindowStyle="None"
ResizeMode="NoResize" WindowStartupLocation="CenterScreen" Loaded="Window_Loaded">
<Window.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="pack://application:,,,/MaterialDesignThemes.Wpf;component/Themes/MaterialDesignTheme.TextBox.xaml" />
<ResourceDictionary Source="pack://application:,,,/MaterialDesignThemes.Wpf;component/Themes/MaterialDesignTheme.DataGrid.xaml" />
<ResourceDictionary Source="pack://application:,,,/MaterialDesignThemes.Wpf;component/Themes/MaterialDesignTheme.TextBlock.xaml" />
</ResourceDictionary.MergedDictionaries>
<SolidColorBrush x:Key="PrimaryHueLightBrush" Color="#0093EA"/>
<SolidColorBrush x:Key="PrimaryHueLightForegroundBrush" Color="#FFFFFF"/>
<SolidColorBrush x:Key="PrimaryHueMidBrush" Color="#0093EA"/>
<SolidColorBrush x:Key="PrimaryHueMidForegroundBrush" Color="#FFFFFF"/>
<SolidColorBrush x:Key="PrimaryHueDarkBrush" Color="#0093EA"/>
<SolidColorBrush x:Key="PrimaryHueDarkForegroundBrush" Color="#FFFFFF"/>
<!-- accent -->
<SolidColorBrush x:Key="SecondaryAccentBrush" Color="#0093EA"/>
<SolidColorBrush x:Key="SecondaryAccentForegroundBrush" Color="#FFFFFF"/>
<Storyboard x:Key="Loading">
<ThicknessAnimation Duration="0:0:0.2" To="0" From="0,300,0,300"
Storyboard.TargetName="g_main" Storyboard.TargetProperty="Margin" />
</Storyboard>
<Storyboard x:Key="Closing">
<ThicknessAnimation FillBehavior="Stop" Duration="0:0:0.2" To="0,300,0,300" From="0" Storyboard.TargetName="g_main"
Storyboard.TargetProperty="Margin" Completed="Sb_Completed"/>
</Storyboard>
</ResourceDictionary>
</Window.Resources>
<Window.Effect>
<DropShadowEffect BlurRadius="20" Color="#FF858484" Direction="90" ShadowDepth="2"/>
</Window.Effect>
<Window.Triggers>
<EventTrigger RoutedEvent="FrameworkElement.Loaded" >
<BeginStoryboard Storyboard="{StaticResource Loading}"/>
</EventTrigger>
<EventTrigger RoutedEvent="UIElement.MouseLeftButtonDown" SourceName="tbclose">
<BeginStoryboard Storyboard="{StaticResource Closing}" />
</EventTrigger>
</Window.Triggers>
<Border BorderBrush="#FF858484" x:Name="g_main" CornerRadius="3" BorderThickness="2" >
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="80"/>
<RowDefinition Height="45"/>
<RowDefinition Height="45"/>
<RowDefinition Height="45"/>
<RowDefinition Height="45"/>
<RowDefinition Height="45"/>
<RowDefinition Height="45"/>
<RowDefinition Height="45"/>
<RowDefinition Height="45"/>
<RowDefinition Height="45"/>
<RowDefinition Height="45"/>
<RowDefinition Height="45"/>
<RowDefinition Height="45"/>
<RowDefinition Height="45"/>
<RowDefinition Height="60"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="10"/>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="10"/>
</Grid.ColumnDefinitions>
<TextBlock x:Name="txtTitle" Grid.ColumnSpan="6" Text="创建箱标" FontSize="30" Foreground="#0092ea" VerticalAlignment="Top" Margin="20 20 0 0"/>
<TextBlock Text="&#xE618;" Grid.ColumnSpan="6" Style="{StaticResource FiconBase}" x:Name="tbclose"
HorizontalAlignment="Right" VerticalAlignment="Top"
Margin="0 20 20 0" FontSize="35" Foreground="#8a8a8a" />
<StackPanel Grid.Row="1" Grid.Column="1" Orientation="Horizontal">
<TextBlock Text="装备名称:" Width="120" TextAlignment="Right" FontSize="16" HorizontalAlignment="Center" VerticalAlignment="Center"/>
<TextBox x:Name="txtEquName" IsReadOnly="True" Height="35" FontSize="16" Background="White" Width="340" />
<Button Content="..." Height="30" Click="OnSelectEqu_Click" Margin="5,0,5,0" />
</StackPanel>
<StackPanel Grid.Row="2" Grid.Column="1" Orientation="Horizontal">
<TextBlock Text="装备号型:" Width="120" TextAlignment="Right" FontSize="16" HorizontalAlignment="Right" VerticalAlignment="Center"/>
<ComboBox Name="cboSize" VerticalAlignment="Center"
materialDesign:HintAssist.HintOpacity=".26"
IsEditable="False" Width="380" FontSize="13"
DisplayMemberPath="name" SelectedValuePath="id" HorizontalAlignment="Left" SelectionChanged="cboSize_SelectionChanged">
</ComboBox>
</StackPanel>
<StackPanel Grid.Row="3" Grid.Column="1" Orientation="Horizontal">
<TextBlock Text="供应商:" TextAlignment="Right" Width="120" FontSize="16" HorizontalAlignment="Center" VerticalAlignment="Center"/>
<ComboBox Name="cboSupplier" VerticalAlignment="Center"
materialDesign:HintAssist.HintOpacity=".26"
IsEditable="False" Width="340" FontSize="13"
DisplayMemberPath="name" SelectedValuePath="id" HorizontalAlignment="Left">
</ComboBox>
<Button Content="..." Height="30" Click="OnSelectVendor_Click" Margin="5,0,5,0" />
</StackPanel>
<StackPanel Grid.Row="4" Grid.Column="1" Orientation="Horizontal">
<TextBlock Text="使用日期:" TextAlignment="Right" Width="120" FontSize="16" HorizontalAlignment="Center" VerticalAlignment="Center"/>
<DatePicker SelectedDateFormat="Short" Name="dtUseDate" VerticalContentAlignment="Top" Width="380" materialDesign:HintAssist.HintOpacity=".26" FontSize="16" Height="35" HorizontalAlignment="Center" VerticalAlignment="Center" Margin="0,0,0,0" Style="{StaticResource MaterialDesignDatePicker}" />
</StackPanel>
<StackPanel Grid.Row="5" Grid.Column="1" Orientation="Horizontal">
<TextBlock Text="生产日期:" TextAlignment="Right" Width="120" FontSize="16" HorizontalAlignment="Center" VerticalAlignment="Center"/>
<DatePicker SelectedDateFormat="Short" Name="dtProductDate" VerticalContentAlignment="Top" Width="380" materialDesign:HintAssist.HintOpacity=".26" FontSize="16" Height="35" HorizontalAlignment="Center" VerticalAlignment="Center" Margin="0,0,0,0" Style="{StaticResource MaterialDesignDatePicker}" />
</StackPanel>
<StackPanel Grid.Row="6" Grid.Column="1" Orientation="Horizontal">
<TextBlock Text="维保周期(月):" TextAlignment="Right" Width="120" FontSize="16" HorizontalAlignment="Center" VerticalAlignment="Center"/>
<TextBox x:Name="txtWxzq" Height="35" FontSize="16" Background="White" Width="380" />
</StackPanel>
<StackPanel Grid.Row="7" Grid.Column="1" Orientation="Horizontal">
<TextBlock Text="质保周期(月):" TextAlignment="Right" Width="120" FontSize="16" HorizontalAlignment="Center" VerticalAlignment="Center"/>
<TextBox x:Name="txtZbq" Height="35" FontSize="16" Text="" Background="White" Width="380" />
</StackPanel>
<StackPanel Grid.Row="8" Grid.Column="1" Orientation="Horizontal">
<TextBlock Text="单价:" Width="120" TextAlignment="Right" FontSize="16" HorizontalAlignment="Center" VerticalAlignment="Center"/>
<TextBox x:Name="txtPrice" Height="35" FontSize="16" Background="White" Width="380" />
</StackPanel>
<StackPanel Grid.Row="9" Grid.Column="1" Orientation="Horizontal">
<TextBlock Text="数量/箱:" Width="120" TextAlignment="Right" FontSize="16" HorizontalAlignment="Center" VerticalAlignment="Center"/>
<TextBox x:Name="txtOneBoxNum" Height="35" FontSize="16" Background="White" Width="380" />
</StackPanel>
<StackPanel Grid.Row="10" Grid.Column="1" Orientation="Horizontal">
<TextBlock Text="箱数:" Width="120" TextAlignment="Right" FontSize="16" HorizontalAlignment="Center" VerticalAlignment="Center"/>
<TextBox x:Name="txtBoxNum" Height="35" FontSize="16" Background="White" Width="380" />
</StackPanel>
<StackPanel Grid.Row="11" Grid.Column="1" Orientation="Horizontal">
<TextBlock Text="入库仓库:" Width="120" TextAlignment="Right" FontSize="16" HorizontalAlignment="Center" VerticalAlignment="Center"/>
<ComboBox Name="cboWarehouse" VerticalAlignment="Center"
materialDesign:HintAssist.HintOpacity=".26"
IsEditable="False" Width="380" FontSize="13"
DisplayMemberPath="name" SelectedValuePath="id" HorizontalAlignment="Left" SelectionChanged="cboWarehouse_SelectionChanged">
</ComboBox>
</StackPanel>
<StackPanel Grid.Row="12" Grid.Column="1" Orientation="Horizontal">
<TextBlock Text="入库货架:" Width="120" TextAlignment="Right" FontSize="16" HorizontalAlignment="Center" VerticalAlignment="Center"/>
<ComboBox Name="cboShelf" VerticalAlignment="Center"
materialDesign:HintAssist.HintOpacity=".26"
IsEditable="False" Width="380" FontSize="13"
DisplayMemberPath="name" SelectedValuePath="id" HorizontalAlignment="Left" SelectionChanged="cboShelf_SelectionChanged">
</ComboBox>
</StackPanel>
<StackPanel Grid.Row="13" Grid.Column="1" Orientation="Horizontal" Name="spShelfData">
<TextBlock Text="排:" Width="120" TextAlignment="Right" FontSize="16" HorizontalAlignment="Center" VerticalAlignment="Center"/>
<ComboBox Name="cboShelfRange" VerticalAlignment="Center"
materialDesign:HintAssist.HintOpacity=".26"
IsEditable="False" Width="100" FontSize="13"
HorizontalAlignment="Left">
</ComboBox>
<TextBlock Text="列:" Width="40" TextAlignment="Right" FontSize="16" HorizontalAlignment="Center" VerticalAlignment="Center"/>
<ComboBox Name="cboShelfColumn" VerticalAlignment="Center"
materialDesign:HintAssist.HintOpacity=".26"
IsEditable="False" Width="100" FontSize="13"
HorizontalAlignment="Left">
</ComboBox>
<TextBlock Text="行:" Width="40" TextAlignment="Right" FontSize="16" HorizontalAlignment="Center" VerticalAlignment="Center"/>
<ComboBox Name="cboShelfRow" VerticalAlignment="Center"
materialDesign:HintAssist.HintOpacity=".26"
IsEditable="False" Width="100" FontSize="13"
HorizontalAlignment="Left">
</ComboBox>
</StackPanel>
<StackPanel Grid.Row="14" Grid.Column="1" Orientation="Horizontal" Name="spMessage">
<TextBlock Text="推荐存放位置:" TextAlignment="Right" FontSize="16" VerticalAlignment="Top" Foreground="Red" HorizontalAlignment="Left" Width="120"/>
<TextBlock Name="tbMessage" Text="XXXXXXXXXXXX &#x000A; XXXXXXX &#x000A; XXXXX&#x000A;XXXX" TextWrapping = "Wrap" TextAlignment="Left" FontSize="16" VerticalAlignment="Top" Foreground="Red" HorizontalAlignment="Left" Width="230"/>
</StackPanel>
<Button FontSize="20" Grid.Row="15" Click="OnSave_Click" HorizontalAlignment="Right" Content="确定" Style="{StaticResource MaterialDesignRaisedButton}" Height="40" Width="100" VerticalAlignment="Bottom" Grid.Column="1" Margin="0,5,161,20" />
<Button FontSize="20" Grid.Row="15" Click="OnCancel_Click" HorizontalAlignment="Right" Content="关闭" Background="DarkOrange" BorderBrush="Orange" Style="{StaticResource MaterialDesignRaisedButton}" Height="40" Width="100" VerticalAlignment="Bottom" Grid.Column="1" Margin="0,0,20,20"/>
</Grid>
</Border>
</Window>
using JmpZbPrint.Dialog;
using JmpZbPrint.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
namespace JmpZbPrint.View
{
/// <summary>
/// SupplierWin.xaml 的交互逻辑
/// </summary>
public partial class SetGenBoxInfo : Window
{
public event Action<recode_info> OnRefreshGrid;
public recode_info record { get; set; }
public List<Supplier> SupplierList { get; set; } = new List<Supplier>();
public List<WarehouseInfo> WarehouseList { get; set; } = new List<WarehouseInfo>();
public SetGenBoxInfo()
{
InitializeComponent();
record = new recode_info();
WarehouseList = HttpHelper.GetWarehouse();
}
private void Sb_Completed(object sender, EventArgs e)
{
this.Close();
}
private void OnSelectVendor_Click(object sender, RoutedEventArgs e)
{
var win = new SupplierWindow();
win.ShowDialog();
if (win.Supplier != null)
{
if (!SupplierList.Any(t => t.id == win.Supplier.id))
{
SupplierList.Insert(0, win.Supplier);
cboSupplier.ItemsSource = null;
cboSupplier.ItemsSource = SupplierList;
cboSupplier.DisplayMemberPath = "name";
cboSupplier.SelectedValuePath = "id";
cboSupplier.SelectedIndex = 0;
}
}
}
private void OnSelectEqu_Click(object sender, RoutedEventArgs e)
{
var equ = new SelectEqu();
equ.ShowDialog();
if (equ.EquInfo != null)
{
txtEquName.Text = equ.EquInfo.name;
record = new recode_info();
record.equCode = equ.EquInfo.code;
record.equId = equ.EquInfo.id;
record.equName = equ.EquInfo.name;
//查询号型
var equ_attr = HttpHelper.GetEquInfoById(equ.EquInfo.id);
if (equ_attr != null)
{
SupplierList = equ_attr.suppliers;
cboSupplier.ItemsSource = null;
cboSupplier.ItemsSource = SupplierList;
cboSupplier.DisplayMemberPath = "name";
cboSupplier.SelectedValuePath = "id";
cboSupplier.SelectedIndex = 0;
cboSize.ItemsSource = equ_attr.sizes;
cboSize.DisplayMemberPath = "name";
cboSize.SelectedValuePath = "id";
cboSize.SelectedIndex = 0;
cboSize_SelectionChanged(null, null);
}
}
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
cboWarehouse.ItemsSource = WarehouseList;
cboWarehouse.DisplayMemberPath = "name";
cboWarehouse.SelectedValuePath = "id";
cboWarehouse.SelectedIndex = 0;
if (cboWarehouse.SelectedItem != null)
{
var warehouse = cboWarehouse.SelectedItem as WarehouseInfo;
var shelfList = HttpHelper.GetShelfByWarehouseId(warehouse.id) ?? new List<ShelfInfo>();
shelfList.Insert(0, new ShelfInfo
{
id = "",
name = "(未指定)"
});
cboShelf.ItemsSource = shelfList;
cboShelf.DisplayMemberPath = "name";
cboShelf.SelectedValuePath = "id";
cboShelf.SelectedIndex = 0;
}
spShelfData.IsEnabled = false;
spMessage.Visibility = Visibility.Hidden;
dtProductDate.SelectedDate = DateTime.Now.AddDays(-7);
dtUseDate.SelectedDate = DateTime.Now;
}
private void OnSave_Click(object sender, RoutedEventArgs e)
{
if (string.IsNullOrEmpty(record.equId))
{
MessageBox.Show("装备未选择", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
}
else if (cboSize.SelectedItem == null)
{
MessageBox.Show("号型未选择", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
}
else if (cboWarehouse.SelectedItem == null)
{
MessageBox.Show("入库仓库未选择", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
}
else if (cboSupplier.SelectedItem == null)
{
MessageBox.Show("供应商未选择", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
}
else if (dtUseDate.SelectedDate == null)
{
MessageBox.Show("使用日期未选择", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
}
else if (dtProductDate.SelectedDate == null)
{
MessageBox.Show("生产日期未选择", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
}
else if (string.IsNullOrEmpty(txtPrice.Text)
|| !decimal.TryParse(txtPrice.Text, out decimal price)
|| price <= 0)
{
MessageBox.Show("单价输入不正确", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
}
else if (string.IsNullOrEmpty(txtZbq.Text)
|| !int.TryParse(txtZbq.Text, out int warrantyCycle)
|| warrantyCycle < 0)
{
MessageBox.Show("质保周期输入不正确", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
}
else if (string.IsNullOrEmpty(txtWxzq.Text)
|| !int.TryParse(txtWxzq.Text, out int repairCycle)
|| repairCycle <= 0)
{
MessageBox.Show("维保周期输入不正确", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
}
else if (string.IsNullOrEmpty(txtOneBoxNum.Text)
|| !int.TryParse(txtOneBoxNum.Text, out int oneBoxNum)
|| oneBoxNum <= 0)
{
MessageBox.Show("数量/箱输入不正确", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
}
else if (string.IsNullOrEmpty(txtBoxNum.Text)
|| !int.TryParse(txtBoxNum.Text, out int boxNum)
|| boxNum <= 0)
{
MessageBox.Show("箱数输入不正确", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
}
else
{
var size = cboSize.SelectedItem as EquSizeInfo;
var supplier = cboSupplier.SelectedItem as Supplier;
var warehouse = cboWarehouse.SelectedItem as WarehouseInfo;
var shelf = cboShelf.SelectedItem as ShelfInfo;
record.sizeCode = size.code;
record.sizeId = size.id;
record.sizeName = size.name;
record.suppilerCode = supplier.code;
record.supplierId = supplier.id;
record.suppilerName = supplier.name;
record.warehouseId = warehouse.id;
record.warehouseName = warehouse.name;
record.useTime = dtUseDate.SelectedDate;
record.productTime = dtProductDate.SelectedDate;
record.repairCycle = repairCycle;
record.warrantyCycle = warrantyCycle;
record.price = (float)price;
record.ShelfId = shelf?.id;
record.ShelfName = string.IsNullOrEmpty(record.ShelfId) ? "" : shelf?.name;
record.ShelfRange = cboShelfRange.SelectedIndex > 0 && !string.IsNullOrEmpty(record.ShelfId) ? cboShelfRange.SelectedIndex : 0;
record.ShelfColumn = cboShelfColumn.SelectedIndex > 0 && record.ShelfRange > 0 ? cboShelfColumn.SelectedIndex : 0;
record.ShelfRow = cboShelfRow.SelectedIndex > 0 && record.ShelfColumn > 0 ? cboShelfRow.SelectedIndex : 0;
record.needNum = boxNum;
record.oneBoxNum = oneBoxNum;
record.LabelType = "箱标";
OnRefreshGrid?.Invoke(record);
}
}
private void OnCancel_Click(object sender, RoutedEventArgs e)
{
this.Close();
}
private void cboWarehouse_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
//切换仓库
if (e.RemovedItems.Count > 0)
{
//事件响应
var warehouse = cboWarehouse.SelectedItem as WarehouseInfo;
var shelfList = HttpHelper.GetShelfByWarehouseId(warehouse.id) ?? new List<ShelfInfo>();
shelfList.Insert(0, new ShelfInfo
{
id = "",
name = "(未指定)"
});
cboShelf.SelectionChanged -= cboShelf_SelectionChanged;
cboShelf.ItemsSource = null;
cboShelf.ItemsSource = shelfList;
cboShelf.DisplayMemberPath = "name";
cboShelf.SelectedValuePath = "id";
cboShelf.SelectedIndex = 0;
cboShelf.SelectionChanged += cboShelf_SelectionChanged;
cboShelfRange.ItemsSource = null;
cboShelfRow.ItemsSource = null;
cboShelfColumn.ItemsSource = null;
spShelfData.IsEnabled = false;
spMessage.Visibility = Visibility.Hidden;
cboSize_SelectionChanged(null, null);
}
}
private void cboShelf_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
//切换货架
if (e.RemovedItems.Count > 0)
{
//事件响应
var shelf = cboShelf.SelectedItem as ShelfInfo;
if (!string.IsNullOrEmpty(shelf.id))
{
cboShelfRange.ItemsSource = CreateSelectList(Convert.ToInt32(shelf.range));
cboShelfRange.SelectedIndex = 0;
cboShelfRow.ItemsSource = CreateSelectList(Convert.ToInt32(shelf.row));
cboShelfRow.SelectedIndex = 0;
cboShelfColumn.ItemsSource = CreateSelectList(Convert.ToInt32(shelf.column));
cboShelfColumn.SelectedIndex = 0;
spShelfData.IsEnabled = true;
}
else
{
cboShelfRange.ItemsSource = null;
cboShelfRow.ItemsSource = null;
cboShelfColumn.ItemsSource = null;
spShelfData.IsEnabled = false;
}
}
}
private List<string> CreateSelectList(int count)
{
var list = new List<string>();
list.Add("(未指定)");
for (int i = 1; i <= count; i++)
{
list.Add(i.ToString());
}
return list;
}
private void cboSize_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
//切换号型
if (e == null || e.RemovedItems.Count > 0)
{
if (cboSize.SelectedItem is EquSizeInfo size)
{
var warehouse = cboWarehouse.SelectedItem as WarehouseInfo;
var shelfList = HttpHelper.GetListEquipmentShelfPosition(warehouse.id, record.equId, size.id) ?? new List<ShelfInfo>();
if (shelfList.Count > 0)
{
spMessage.Visibility = Visibility.Visible;
tbMessage.Text = string.Join("\r\n", shelfList.Take(3).Select(x => x.name + "-" + x.range + "-" + x.column + "-" + x.row));
if (shelfList.Count > 3)
{
tbMessage.Text += " 等";
}
//装填第一条信息
var shelf = shelfList.First();
cboShelf.SelectedIndex = cboShelf.ItemsSource.OfType<ShelfInfo>().ToList()
.FindIndex(x => x.id == shelf.id);
cboShelfRange.SelectedIndex = Convert.ToInt32(shelf.range);
cboShelfColumn.SelectedIndex = Convert.ToInt32(shelf.column);
cboShelfRow.SelectedIndex = Convert.ToInt32(shelf.row);
}
else
{
spMessage.Visibility = Visibility.Hidden;
}
}
else
{
spMessage.Visibility = Visibility.Hidden;
}
}
}
}
}
<Window x:Class="JmpZbPrint.View.SetGenInfo"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:materialDesign="http://materialdesigninxaml.net/winfx/xaml/themes"
xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
xmlns:local="clr-namespace:JmpZbPrint.Dialog"
mc:Ignorable="d"
Height="620" Width="550" AllowsTransparency="True" WindowStyle="None"
ResizeMode="NoResize" WindowStartupLocation="CenterScreen" Loaded="Window_Loaded">
<Window.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="pack://application:,,,/MaterialDesignThemes.Wpf;component/Themes/MaterialDesignTheme.TextBox.xaml" />
<ResourceDictionary Source="pack://application:,,,/MaterialDesignThemes.Wpf;component/Themes/MaterialDesignTheme.DataGrid.xaml" />
<ResourceDictionary Source="pack://application:,,,/MaterialDesignThemes.Wpf;component/Themes/MaterialDesignTheme.TextBlock.xaml" />
</ResourceDictionary.MergedDictionaries>
<SolidColorBrush x:Key="PrimaryHueLightBrush" Color="#0093EA"/>
<SolidColorBrush x:Key="PrimaryHueLightForegroundBrush" Color="#FFFFFF"/>
<SolidColorBrush x:Key="PrimaryHueMidBrush" Color="#0093EA"/>
<SolidColorBrush x:Key="PrimaryHueMidForegroundBrush" Color="#FFFFFF"/>
<SolidColorBrush x:Key="PrimaryHueDarkBrush" Color="#0093EA"/>
<SolidColorBrush x:Key="PrimaryHueDarkForegroundBrush" Color="#FFFFFF"/>
<!-- accent -->
<SolidColorBrush x:Key="SecondaryAccentBrush" Color="#0093EA"/>
<SolidColorBrush x:Key="SecondaryAccentForegroundBrush" Color="#FFFFFF"/>
<Storyboard x:Key="Loading">
<ThicknessAnimation Duration="0:0:0.2" To="0" From="0,300,0,300"
Storyboard.TargetName="g_main" Storyboard.TargetProperty="Margin" />
</Storyboard>
<Storyboard x:Key="Closing">
<ThicknessAnimation FillBehavior="Stop" Duration="0:0:0.2" To="0,300,0,300" From="0" Storyboard.TargetName="g_main"
Storyboard.TargetProperty="Margin" Completed="Sb_Completed"/>
</Storyboard>
</ResourceDictionary>
</Window.Resources>
<Window.Effect>
<DropShadowEffect BlurRadius="20" Color="#FF858484" Direction="90" ShadowDepth="2"/>
</Window.Effect>
<Window.Triggers>
<EventTrigger RoutedEvent="FrameworkElement.Loaded" >
<BeginStoryboard Storyboard="{StaticResource Loading}"/>
</EventTrigger>
<EventTrigger RoutedEvent="UIElement.MouseLeftButtonDown" SourceName="tbclose">
<BeginStoryboard Storyboard="{StaticResource Closing}" />
</EventTrigger>
</Window.Triggers>
<Border BorderBrush="#FF858484" x:Name="g_main" CornerRadius="3" BorderThickness="2" >
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="80"/>
<RowDefinition Height="45"/>
<RowDefinition Height="45"/>
<RowDefinition Height="45"/>
<RowDefinition Height="45"/>
<RowDefinition Height="45"/>
<RowDefinition Height="45"/>
<RowDefinition Height="45"/>
<RowDefinition Height="45"/>
<RowDefinition Height="45"/>
<RowDefinition Height="45"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="10"/>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="10"/>
</Grid.ColumnDefinitions>
<TextBlock x:Name="txtTitle" Grid.ColumnSpan="6" Text="选择装备信息" FontSize="30" Foreground="#0092ea" VerticalAlignment="Top" Margin="20 20 0 0"/>
<TextBlock Text="&#xE618;" Grid.ColumnSpan="6" Style="{StaticResource FiconBase}" x:Name="tbclose"
HorizontalAlignment="Right" VerticalAlignment="Top"
Margin="0 20 20 0" FontSize="35" Foreground="#8a8a8a" />
<StackPanel Grid.Row="1" Grid.Column="1" Orientation="Horizontal">
<TextBlock Text="装备名称:" Width="120" TextAlignment="Right" FontSize="16" HorizontalAlignment="Center" VerticalAlignment="Center"/>
<TextBox x:Name="txtEquName" IsReadOnly="True" Height="35" FontSize="16" Background="White" Width="340" />
<Button Content="..." Height="30" Click="OnSelectEqu_Click" Margin="5,0,5,0" />
</StackPanel>
<StackPanel Grid.Row="2" Grid.Column="1" Orientation="Horizontal">
<TextBlock Text="装备号型:" Width="120" TextAlignment="Right" FontSize="16" HorizontalAlignment="Right" VerticalAlignment="Center"/>
<ComboBox Name="cboSize" VerticalAlignment="Center"
materialDesign:HintAssist.HintOpacity=".26"
IsEditable="False" Width="380" FontSize="13"
DisplayMemberPath="name" SelectedValuePath="id" HorizontalAlignment="Left">
</ComboBox>
</StackPanel>
<StackPanel Grid.Row="3" Grid.Column="1" Orientation="Horizontal">
<TextBlock Text="供应商:" TextAlignment="Right" Width="120" FontSize="16" HorizontalAlignment="Center" VerticalAlignment="Center"/>
<ComboBox Name="cboSupplier" VerticalAlignment="Center"
materialDesign:HintAssist.HintOpacity=".26"
IsEditable="False" Width="340" FontSize="13"
DisplayMemberPath="name" SelectedValuePath="id" HorizontalAlignment="Left">
</ComboBox>
<Button Content="..." Height="30" Click="OnSelectVendor_Click" Margin="5,0,5,0" />
</StackPanel>
<StackPanel Grid.Row="4" Grid.Column="1" Orientation="Horizontal">
<TextBlock Text="使用日期:" TextAlignment="Right" Width="120" FontSize="16" HorizontalAlignment="Center" VerticalAlignment="Center"/>
<DatePicker SelectedDateFormat="Short" Name="dtUseDate" VerticalContentAlignment="Top" Width="380" materialDesign:HintAssist.HintOpacity=".26" FontSize="16" Height="35" HorizontalAlignment="Center" VerticalAlignment="Center" Margin="0,0,0,0" Style="{StaticResource MaterialDesignDatePicker}" />
</StackPanel>
<StackPanel Grid.Row="5" Grid.Column="1" Orientation="Horizontal">
<TextBlock Text="生产日期:" TextAlignment="Right" Width="120" FontSize="16" HorizontalAlignment="Center" VerticalAlignment="Center"/>
<DatePicker SelectedDateFormat="Short" Name="dtProductDate" VerticalContentAlignment="Top" Width="380" materialDesign:HintAssist.HintOpacity=".26" FontSize="16" Height="35" HorizontalAlignment="Center" VerticalAlignment="Center" Margin="0,0,0,0" Style="{StaticResource MaterialDesignDatePicker}" />
</StackPanel>
<StackPanel Grid.Row="6" Grid.Column="1" Orientation="Horizontal">
<TextBlock Text="维保周期(月):" TextAlignment="Right" Width="120" FontSize="16" HorizontalAlignment="Center" VerticalAlignment="Center"/>
<TextBox x:Name="txtWxzq" Height="35" FontSize="16" Background="White" Width="380" />
</StackPanel>
<StackPanel Grid.Row="7" Grid.Column="1" Orientation="Horizontal">
<TextBlock Text="质保周期(月):" TextAlignment="Right" Width="120" FontSize="16" HorizontalAlignment="Center" VerticalAlignment="Center"/>
<TextBox x:Name="txtZbq" Height="35" FontSize="16" Text="" Background="White" Width="380" />
</StackPanel>
<StackPanel Grid.Row="8" Grid.Column="1" Orientation="Horizontal">
<TextBlock Text="单价:" Width="120" TextAlignment="Right" FontSize="16" HorizontalAlignment="Center" VerticalAlignment="Center"/>
<TextBox x:Name="txtPrice" Height="35" FontSize="16" Background="White" Width="380" />
</StackPanel>
<StackPanel Grid.Row="9" Grid.Column="1" Orientation="Horizontal">
<TextBlock Text="数量:" Width="120" TextAlignment="Right" FontSize="16" HorizontalAlignment="Center" VerticalAlignment="Center"/>
<TextBox x:Name="txtNum" Height="35" FontSize="16" Background="White" Width="380" />
</StackPanel>
<StackPanel Grid.Row="10" Grid.Column="1" Orientation="Horizontal">
<TextBlock Text="入库仓库:" Width="120" TextAlignment="Right" FontSize="16" HorizontalAlignment="Center" VerticalAlignment="Center"/>
<ComboBox Name="cboWarehouse" VerticalAlignment="Center"
materialDesign:HintAssist.HintOpacity=".26"
IsEditable="False" Width="380" FontSize="13"
DisplayMemberPath="name" SelectedValuePath="id" HorizontalAlignment="Left">
</ComboBox>
</StackPanel>
<Button FontSize="20" Grid.Row="11" Click="OnSave_Click" HorizontalAlignment="Right" Content="确定" Style="{StaticResource MaterialDesignRaisedButton}" Height="40" Width="100" VerticalAlignment="Bottom" Grid.Column="1" Margin="0,5,161,20" />
<Button FontSize="20" Grid.Row="11" Click="OnCancel_Click" HorizontalAlignment="Right" Content="关闭" Background="DarkOrange" BorderBrush="Orange" Style="{StaticResource MaterialDesignRaisedButton}" Height="40" Width="100" VerticalAlignment="Bottom" Grid.Column="1" Margin="0,0,20,20"/>
</Grid>
</Border>
</Window>
using JmpZbPrint.Dialog;
using JmpZbPrint.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
namespace JmpZbPrint.View
{
/// <summary>
/// SupplierWin.xaml 的交互逻辑
/// </summary>
public partial class SetGenInfo : Window
{
public event Action<recode_info> OnRefreshGrid;
public recode_info record { get; set; }
public List<Supplier> SupplierList { get; set; } = new List<Supplier>();
public List<WarehouseInfo> WarehouseList { get; set; } = new List<WarehouseInfo>();
public SetGenInfo()
{
InitializeComponent();
record = new recode_info();
WarehouseList = HttpHelper.GetWarehouse();
}
private void Sb_Completed(object sender, EventArgs e)
{
this.Close();
}
private void OnSelectVendor_Click(object sender, RoutedEventArgs e)
{
var win = new SupplierWindow();
win.ShowDialog();
if (win.Supplier != null)
{
if (!SupplierList.Any(t => t.id == win.Supplier.id))
{
SupplierList.Insert(0, win.Supplier);
cboSupplier.ItemsSource = null;
cboSupplier.ItemsSource = SupplierList;
cboSupplier.DisplayMemberPath = "name";
cboSupplier.SelectedValuePath = "id";
cboSupplier.SelectedIndex = 0;
}
}
}
private void OnSelectEqu_Click(object sender, RoutedEventArgs e)
{
var equ = new SelectEqu();
equ.ShowDialog();
if (equ.EquInfo != null)
{
txtEquName.Text = equ.EquInfo.name;
record = new recode_info();
record.equCode = equ.EquInfo.code;
record.equId = equ.EquInfo.id;
record.equName = equ.EquInfo.name;
//查询号型
var equ_attr = HttpHelper.GetEquInfoById(equ.EquInfo.id);
if (equ_attr != null)
{
SupplierList = equ_attr.suppliers;
cboSupplier.ItemsSource = null;
cboSupplier.ItemsSource = SupplierList;
cboSupplier.DisplayMemberPath = "name";
cboSupplier.SelectedValuePath = "id";
cboSupplier.SelectedIndex = 0;
cboSize.ItemsSource = equ_attr.sizes;
cboSize.DisplayMemberPath = "name";
cboSize.SelectedValuePath = "id";
cboSize.SelectedIndex = 0;
}
}
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
cboWarehouse.ItemsSource = WarehouseList;
cboWarehouse.DisplayMemberPath = "name";
cboWarehouse.SelectedValuePath = "id";
cboWarehouse.SelectedIndex = 0;
dtProductDate.SelectedDate = DateTime.Now.AddDays(-7);
dtUseDate.SelectedDate = DateTime.Now;
}
private void OnSave_Click(object sender, RoutedEventArgs e)
{
if (string.IsNullOrEmpty(record.equId))
{
MessageBox.Show("装备未选择", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
}
else if (cboSize.SelectedItem == null)
{
MessageBox.Show("号型未选择", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
}
else if (cboWarehouse.SelectedItem == null)
{
MessageBox.Show("入库仓库未选择", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
}
else if (cboSupplier.SelectedItem == null)
{
MessageBox.Show("供应商未选择", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
}
else if (dtUseDate.SelectedDate == null)
{
MessageBox.Show("使用日期未选择", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
}
else if (dtProductDate.SelectedDate == null)
{
MessageBox.Show("生产日期未选择", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
}
else if (string.IsNullOrEmpty(txtPrice.Text)
|| !decimal.TryParse(txtPrice.Text, out decimal price)
|| price <= 0)
{
MessageBox.Show("单价输入不正确", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
}
else if (string.IsNullOrEmpty(txtZbq.Text)
|| !int.TryParse(txtZbq.Text, out int warrantyCycle)
|| warrantyCycle < 0)
{
MessageBox.Show("质保周期输入不正确", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
}
else if (string.IsNullOrEmpty(txtWxzq.Text)
|| !int.TryParse(txtWxzq.Text, out int repairCycle)
|| repairCycle <= 0)
{
MessageBox.Show("维保周期输入不正确", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
}
else if (string.IsNullOrEmpty(txtNum.Text)
|| !int.TryParse(txtNum.Text, out int genNum)
|| genNum <= 0)
{
MessageBox.Show("数量输入不正确", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
}
else
{
var size = cboSize.SelectedItem as EquSizeInfo;
var supplier = cboSupplier.SelectedItem as Supplier;
var warehouse = cboWarehouse.SelectedItem as WarehouseInfo;
record.sizeCode = size.code;
record.sizeId = size.id;
record.sizeName = size.name;
record.suppilerCode = supplier.code;
record.supplierId = supplier.id;
record.suppilerName = supplier.name;
record.warehouseId = warehouse.id;
record.warehouseName = warehouse.name;
record.useTime = dtUseDate.SelectedDate;
record.productTime = dtProductDate.SelectedDate;
record.repairCycle = repairCycle;
record.warrantyCycle = warrantyCycle;
record.price = (float)price;
record.needNum = genNum;
record.LabelType = "件标";
OnRefreshGrid?.Invoke(record);
}
}
private void OnCancel_Click(object sender, RoutedEventArgs e)
{
this.Close();
}
}
}
<Window x:Class="JmpZbPrint.View.SetGenInfoV2"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:materialDesign="http://materialdesigninxaml.net/winfx/xaml/themes"
xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
xmlns:local="clr-namespace:JmpZbPrint.Dialog"
mc:Ignorable="d"
Height="800" Width="550" AllowsTransparency="True" WindowStyle="None"
ResizeMode="NoResize" WindowStartupLocation="CenterScreen" Loaded="Window_Loaded">
<Window.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="pack://application:,,,/MaterialDesignThemes.Wpf;component/Themes/MaterialDesignTheme.TextBox.xaml" />
<ResourceDictionary Source="pack://application:,,,/MaterialDesignThemes.Wpf;component/Themes/MaterialDesignTheme.DataGrid.xaml" />
<ResourceDictionary Source="pack://application:,,,/MaterialDesignThemes.Wpf;component/Themes/MaterialDesignTheme.TextBlock.xaml" />
</ResourceDictionary.MergedDictionaries>
<SolidColorBrush x:Key="PrimaryHueLightBrush" Color="#0093EA"/>
<SolidColorBrush x:Key="PrimaryHueLightForegroundBrush" Color="#FFFFFF"/>
<SolidColorBrush x:Key="PrimaryHueMidBrush" Color="#0093EA"/>
<SolidColorBrush x:Key="PrimaryHueMidForegroundBrush" Color="#FFFFFF"/>
<SolidColorBrush x:Key="PrimaryHueDarkBrush" Color="#0093EA"/>
<SolidColorBrush x:Key="PrimaryHueDarkForegroundBrush" Color="#FFFFFF"/>
<!-- accent -->
<SolidColorBrush x:Key="SecondaryAccentBrush" Color="#0093EA"/>
<SolidColorBrush x:Key="SecondaryAccentForegroundBrush" Color="#FFFFFF"/>
<Storyboard x:Key="Loading">
<ThicknessAnimation Duration="0:0:0.2" To="0" From="0,300,0,300"
Storyboard.TargetName="g_main" Storyboard.TargetProperty="Margin" />
</Storyboard>
<Storyboard x:Key="Closing">
<ThicknessAnimation FillBehavior="Stop" Duration="0:0:0.2" To="0,300,0,300" From="0" Storyboard.TargetName="g_main"
Storyboard.TargetProperty="Margin" Completed="Sb_Completed"/>
</Storyboard>
</ResourceDictionary>
</Window.Resources>
<Window.Effect>
<DropShadowEffect BlurRadius="20" Color="#FF858484" Direction="90" ShadowDepth="2"/>
</Window.Effect>
<Window.Triggers>
<EventTrigger RoutedEvent="FrameworkElement.Loaded" >
<BeginStoryboard Storyboard="{StaticResource Loading}"/>
</EventTrigger>
<EventTrigger RoutedEvent="UIElement.MouseLeftButtonDown" SourceName="tbclose">
<BeginStoryboard Storyboard="{StaticResource Closing}" />
</EventTrigger>
</Window.Triggers>
<Border BorderBrush="#FF858484" x:Name="g_main" CornerRadius="3" BorderThickness="2" >
<Grid Name="Grid">
<Grid.RowDefinitions >
<RowDefinition Height="80"/>
<RowDefinition Height="45"/>
<RowDefinition Height="45"/>
<RowDefinition Height="45"/>
<RowDefinition Height="45"/>
<RowDefinition Height="45"/>
<RowDefinition Height="45"/>
<RowDefinition Height="45"/>
<RowDefinition Height="45"/>
<RowDefinition Height="45"/>
<RowDefinition Height="45"/>
<RowDefinition Height="45"/>
<RowDefinition Height="45"/>
<RowDefinition Height="45"/>
<RowDefinition Height="60"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="10"/>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="10"/>
</Grid.ColumnDefinitions>
<TextBlock x:Name="txtTitle" Grid.ColumnSpan="6" Text="创建箱标" FontSize="30" Foreground="#0092ea" VerticalAlignment="Top" Margin="20 20 0 0"/>
<TextBlock Text="&#xE618;" Grid.ColumnSpan="6" Style="{StaticResource FiconBase}" x:Name="tbclose"
HorizontalAlignment="Right" VerticalAlignment="Top"
Margin="0 20 20 0" FontSize="35" Foreground="#8a8a8a" />
<StackPanel Grid.Row="1" Grid.Column="1" Orientation="Horizontal">
<TextBlock Text="装备名称:" Width="120" TextAlignment="Right" FontSize="16" HorizontalAlignment="Center" VerticalAlignment="Center"/>
<TextBox x:Name="txtEquName" IsReadOnly="True" Height="35" FontSize="16" Background="White" Width="340" />
<Button Content="..." Height="30" Click="OnSelectEqu_Click" Margin="5,0,5,0" />
</StackPanel>
<StackPanel Grid.Row="2" Grid.Column="1" Orientation="Horizontal">
<TextBlock Text="装备号型:" Width="120" TextAlignment="Right" FontSize="16" HorizontalAlignment="Right" VerticalAlignment="Center"/>
<ComboBox Name="cboSize" VerticalAlignment="Center"
materialDesign:HintAssist.HintOpacity=".26"
IsEditable="False" Width="380" FontSize="13"
DisplayMemberPath="name" SelectedValuePath="id" HorizontalAlignment="Left" SelectionChanged="cboSize_SelectionChanged">
</ComboBox>
</StackPanel>
<StackPanel Grid.Row="3" Grid.Column="1" Orientation="Horizontal">
<TextBlock Text="供应商:" TextAlignment="Right" Width="120" FontSize="16" HorizontalAlignment="Center" VerticalAlignment="Center"/>
<ComboBox Name="cboSupplier" VerticalAlignment="Center"
materialDesign:HintAssist.HintOpacity=".26"
IsEditable="False" Width="340" FontSize="13"
DisplayMemberPath="name" SelectedValuePath="id" HorizontalAlignment="Left">
</ComboBox>
<Button Content="..." Height="30" Click="OnSelectVendor_Click" Margin="5,0,5,0" />
</StackPanel>
<StackPanel Grid.Row="4" Grid.Column="1" Orientation="Horizontal">
<TextBlock Text="使用日期:" TextAlignment="Right" Width="120" FontSize="16" HorizontalAlignment="Center" VerticalAlignment="Center"/>
<DatePicker SelectedDateFormat="Short" Name="dtUseDate" VerticalContentAlignment="Top" Width="380" materialDesign:HintAssist.HintOpacity=".26" FontSize="16" Height="35" HorizontalAlignment="Center" VerticalAlignment="Center" Margin="0,0,0,0" Style="{StaticResource MaterialDesignDatePicker}" />
</StackPanel>
<StackPanel Grid.Row="5" Grid.Column="1" Orientation="Horizontal">
<TextBlock Text="生产日期:" TextAlignment="Right" Width="120" FontSize="16" HorizontalAlignment="Center" VerticalAlignment="Center"/>
<DatePicker SelectedDateFormat="Short" Name="dtProductDate" VerticalContentAlignment="Top" Width="380" materialDesign:HintAssist.HintOpacity=".26" FontSize="16" Height="35" HorizontalAlignment="Center" VerticalAlignment="Center" Margin="0,0,0,0" Style="{StaticResource MaterialDesignDatePicker}" />
</StackPanel>
<StackPanel Grid.Row="6" Grid.Column="1" Orientation="Horizontal">
<TextBlock Text="维保周期(月):" TextAlignment="Right" Width="120" FontSize="16" HorizontalAlignment="Center" VerticalAlignment="Center"/>
<TextBox x:Name="txtWxzq" Height="35" FontSize="16" Background="White" Width="380" />
</StackPanel>
<StackPanel Grid.Row="7" Grid.Column="1" Orientation="Horizontal">
<TextBlock Text="质保周期(月):" TextAlignment="Right" Width="120" FontSize="16" HorizontalAlignment="Center" VerticalAlignment="Center"/>
<TextBox x:Name="txtZbq" Height="35" FontSize="16" Text="" Background="White" Width="380" />
</StackPanel>
<StackPanel Grid.Row="8" Grid.Column="1" Orientation="Horizontal">
<TextBlock Text="单价:" Width="120" TextAlignment="Right" FontSize="16" HorizontalAlignment="Center" VerticalAlignment="Center"/>
<TextBox x:Name="txtPrice" Height="35" FontSize="16" Background="White" Width="380" />
</StackPanel>
<StackPanel Grid.Row="9" Grid.Column="1" Orientation="Horizontal" Name="spOneBoxNum">
<TextBlock Text="数量/箱:" Width="120" TextAlignment="Right" FontSize="16" HorizontalAlignment="Center" VerticalAlignment="Center"/>
<TextBox x:Name="txtOneBoxNum" Height="35" FontSize="16" Background="White" Width="380" />
</StackPanel>
<StackPanel Grid.Row="9" Grid.Column="1" Orientation="Horizontal" Name="spNum" Visibility="Collapsed">
<TextBlock Text="数量:" Width="120" TextAlignment="Right" FontSize="16" HorizontalAlignment="Center" VerticalAlignment="Center"/>
<TextBox x:Name="txtNum" Height="35" FontSize="16" Background="White" Width="380" />
</StackPanel>
<StackPanel Grid.Row="10" Grid.Column="1" Orientation="Horizontal" Name="spBoxNum">
<TextBlock Text="箱数:" Width="120" TextAlignment="Right" FontSize="16" HorizontalAlignment="Center" VerticalAlignment="Center"/>
<TextBox x:Name="txtBoxNum" Height="35" FontSize="16" Background="White" Width="380" />
</StackPanel>
<StackPanel Grid.Row="11" Grid.Column="1" Orientation="Horizontal">
<TextBlock Text="入库仓库:" Width="120" TextAlignment="Right" FontSize="16" HorizontalAlignment="Center" VerticalAlignment="Center"/>
<ComboBox Name="cboWarehouse" VerticalAlignment="Center"
materialDesign:HintAssist.HintOpacity=".26"
IsEditable="False" Width="380" FontSize="13"
DisplayMemberPath="name" SelectedValuePath="id" HorizontalAlignment="Left" SelectionChanged="cboWarehouse_SelectionChanged">
</ComboBox>
</StackPanel>
<StackPanel Grid.Row="12" Grid.Column="1" Orientation="Horizontal">
<TextBlock Text="入库货架:" Width="120" TextAlignment="Right" FontSize="16" HorizontalAlignment="Center" VerticalAlignment="Center"/>
<ComboBox Name="cboShelf" VerticalAlignment="Center"
materialDesign:HintAssist.HintOpacity=".26"
IsEditable="False" Width="380" FontSize="13"
DisplayMemberPath="name" SelectedValuePath="id" HorizontalAlignment="Left" SelectionChanged="cboShelf_SelectionChanged">
</ComboBox>
</StackPanel>
<StackPanel Grid.Row="13" Grid.Column="1" Orientation="Horizontal" Name="spShelfData">
<TextBlock Text="排:" Width="120" TextAlignment="Right" FontSize="16" HorizontalAlignment="Center" VerticalAlignment="Center"/>
<ComboBox Name="cboShelfRange" VerticalAlignment="Center"
materialDesign:HintAssist.HintOpacity=".26"
IsEditable="False" Width="100" FontSize="13"
HorizontalAlignment="Left">
</ComboBox>
<TextBlock Text="列:" Width="40" TextAlignment="Right" FontSize="16" HorizontalAlignment="Center" VerticalAlignment="Center"/>
<ComboBox Name="cboShelfColumn" VerticalAlignment="Center"
materialDesign:HintAssist.HintOpacity=".26"
IsEditable="False" Width="100" FontSize="13"
HorizontalAlignment="Left">
</ComboBox>
<TextBlock Text="行:" Width="40" TextAlignment="Right" FontSize="16" HorizontalAlignment="Center" VerticalAlignment="Center"/>
<ComboBox Name="cboShelfRow" VerticalAlignment="Center"
materialDesign:HintAssist.HintOpacity=".26"
IsEditable="False" Width="100" FontSize="13"
HorizontalAlignment="Left">
</ComboBox>
</StackPanel>
<StackPanel Grid.Row="14" Grid.Column="1" Orientation="Horizontal" Name="spMessage">
<TextBlock Text="推荐存放位置:" TextAlignment="Right" FontSize="16" VerticalAlignment="Top" Foreground="Red" HorizontalAlignment="Left" Width="120"/>
<TextBlock Name="tbMessage" Text="XXXXXXXXXXXX &#x000A; XXXXXXX &#x000A; XXXXX&#x000A;XXXX" TextWrapping = "Wrap" TextAlignment="Left" FontSize="16" VerticalAlignment="Top" Foreground="Red" HorizontalAlignment="Left" Width="230"/>
</StackPanel>
<Button FontSize="20" Grid.Row="15" Click="OnSave_Click" HorizontalAlignment="Right" Content="确定" Style="{StaticResource MaterialDesignRaisedButton}" Height="40" Width="100" VerticalAlignment="Bottom" Grid.Column="1" Margin="0,5,161,20" />
<Button FontSize="20" Grid.Row="15" Click="OnCancel_Click" HorizontalAlignment="Right" Content="关闭" Background="DarkOrange" BorderBrush="Orange" Style="{StaticResource MaterialDesignRaisedButton}" Height="40" Width="100" VerticalAlignment="Bottom" Grid.Column="1" Margin="0,0,20,20"/>
</Grid>
</Border>
</Window>
using JmpZbPrint.Dialog;
using JmpZbPrint.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
namespace JmpZbPrint.View
{
/// <summary>
/// SupplierWin.xaml 的交互逻辑
/// </summary>
public partial class SetGenInfoV2 : Window
{
private readonly string _type;
public event Action<recode_info> OnRefreshGrid;
public recode_info record { get; set; }
public List<Supplier> SupplierList { get; set; } = new List<Supplier>();
public List<WarehouseInfo> WarehouseList { get; set; } = new List<WarehouseInfo>();
public SetGenInfoV2(string type)
{
InitializeComponent();
_type = type;
record = new recode_info();
WarehouseList = HttpHelper.GetWarehouse();
//修正界面
if (_type == "件标")
{
this.Height = 755;
txtTitle.Text = "创建件标";
spOneBoxNum.Visibility = Visibility.Collapsed;
spNum.Visibility = Visibility.Visible;
spBoxNum.Visibility = Visibility.Collapsed;
Grid.RowDefinitions[10].Height = new GridLength(0);
}
}
private void Sb_Completed(object sender, EventArgs e)
{
this.Close();
}
private void OnSelectVendor_Click(object sender, RoutedEventArgs e)
{
var win = new SupplierWindow();
win.ShowDialog();
if (win.Supplier != null)
{
if (!SupplierList.Any(t => t.id == win.Supplier.id))
{
SupplierList.Insert(0, win.Supplier);
cboSupplier.ItemsSource = null;
cboSupplier.ItemsSource = SupplierList;
cboSupplier.DisplayMemberPath = "name";
cboSupplier.SelectedValuePath = "id";
cboSupplier.SelectedIndex = 0;
}
}
}
private void OnSelectEqu_Click(object sender, RoutedEventArgs e)
{
var equ = new SelectEqu();
equ.ShowDialog();
if (equ.EquInfo != null)
{
txtEquName.Text = equ.EquInfo.name;
record = new recode_info();
record.equCode = equ.EquInfo.code;
record.equId = equ.EquInfo.id;
record.equName = equ.EquInfo.name;
//查询号型
var equ_attr = HttpHelper.GetEquInfoById(equ.EquInfo.id);
if (equ_attr != null)
{
SupplierList = equ_attr.suppliers;
cboSupplier.ItemsSource = null;
cboSupplier.ItemsSource = SupplierList;
cboSupplier.DisplayMemberPath = "name";
cboSupplier.SelectedValuePath = "id";
cboSupplier.SelectedIndex = 0;
cboSize.ItemsSource = equ_attr.sizes;
cboSize.DisplayMemberPath = "name";
cboSize.SelectedValuePath = "id";
cboSize.SelectedIndex = 0;
cboSize_SelectionChanged(null, null);
}
}
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
cboWarehouse.ItemsSource = WarehouseList;
cboWarehouse.DisplayMemberPath = "name";
cboWarehouse.SelectedValuePath = "id";
cboWarehouse.SelectedIndex = 0;
if (cboWarehouse.SelectedItem != null)
{
var warehouse = cboWarehouse.SelectedItem as WarehouseInfo;
var shelfList = HttpHelper.GetShelfByWarehouseId(warehouse.id) ?? new List<ShelfInfo>();
shelfList.Insert(0, new ShelfInfo
{
id = "",
name = "(未指定)"
});
cboShelf.ItemsSource = shelfList;
cboShelf.DisplayMemberPath = "name";
cboShelf.SelectedValuePath = "id";
cboShelf.SelectedIndex = 0;
}
spShelfData.IsEnabled = false;
spMessage.Visibility = Visibility.Hidden;
dtProductDate.SelectedDate = DateTime.Now.AddDays(-7);
dtUseDate.SelectedDate = DateTime.Now;
}
private void OnSave_Click(object sender, RoutedEventArgs e)
{
int oneBoxNum = 0;
int boxNum = 0;
int genNum = 0;
if (string.IsNullOrEmpty(record.equId))
{
MessageBox.Show("装备未选择", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
}
else if (cboSize.SelectedItem == null)
{
MessageBox.Show("号型未选择", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
}
else if (cboWarehouse.SelectedItem == null)
{
MessageBox.Show("入库仓库未选择", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
}
else if (cboSupplier.SelectedItem == null)
{
MessageBox.Show("供应商未选择", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
}
else if (dtUseDate.SelectedDate == null)
{
MessageBox.Show("使用日期未选择", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
}
else if (dtProductDate.SelectedDate == null)
{
MessageBox.Show("生产日期未选择", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
}
else if (string.IsNullOrEmpty(txtPrice.Text)
|| !decimal.TryParse(txtPrice.Text, out decimal price)
|| price <= 0)
{
MessageBox.Show("单价输入不正确", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
}
else if (string.IsNullOrEmpty(txtZbq.Text)
|| !int.TryParse(txtZbq.Text, out int warrantyCycle)
|| warrantyCycle < 0)
{
MessageBox.Show("质保周期输入不正确", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
}
else if (string.IsNullOrEmpty(txtWxzq.Text)
|| !int.TryParse(txtWxzq.Text, out int repairCycle)
|| repairCycle <= 0)
{
MessageBox.Show("维保周期输入不正确", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
}
else if (_type == "件标" && (string.IsNullOrEmpty(txtNum.Text)
|| !int.TryParse(txtNum.Text, out genNum)
|| genNum <= 0))
{
MessageBox.Show("数量输入不正确", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
}
else if (_type == "箱标" && (string.IsNullOrEmpty(txtOneBoxNum.Text)
|| !int.TryParse(txtOneBoxNum.Text, out oneBoxNum)
|| oneBoxNum <= 0))
{
MessageBox.Show("数量/箱输入不正确", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
}
else if (_type == "箱标" && (string.IsNullOrEmpty(txtBoxNum.Text)
|| !int.TryParse(txtBoxNum.Text, out boxNum)
|| boxNum <= 0))
{
MessageBox.Show("箱数输入不正确", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
}
else
{
var size = cboSize.SelectedItem as EquSizeInfo;
var supplier = cboSupplier.SelectedItem as Supplier;
var warehouse = cboWarehouse.SelectedItem as WarehouseInfo;
var shelf = cboShelf.SelectedItem as ShelfInfo;
record.sizeCode = size.code;
record.sizeId = size.id;
record.sizeName = size.name;
record.suppilerCode = supplier.code;
record.supplierId = supplier.id;
record.suppilerName = supplier.name;
record.warehouseId = warehouse.id;
record.warehouseName = warehouse.name;
record.useTime = dtUseDate.SelectedDate;
record.productTime = dtProductDate.SelectedDate;
record.repairCycle = repairCycle;
record.warrantyCycle = warrantyCycle;
record.price = (float)price;
record.ShelfId = shelf?.id;
record.ShelfName = string.IsNullOrEmpty(record.ShelfId) ? "" : shelf?.name;
record.ShelfRange = cboShelfRange.SelectedIndex > 0 && !string.IsNullOrEmpty(record.ShelfId) ? cboShelfRange.SelectedIndex : 0;
record.ShelfColumn = cboShelfColumn.SelectedIndex > 0 && record.ShelfRange > 0 ? cboShelfColumn.SelectedIndex : 0;
record.ShelfRow = cboShelfRow.SelectedIndex > 0 && record.ShelfColumn > 0 ? cboShelfRow.SelectedIndex : 0;
if (_type == "箱标")
{
record.needNum = boxNum;
record.oneBoxNum = oneBoxNum;
}
else
{
record.needNum = genNum;
}
record.LabelType = _type;
OnRefreshGrid?.Invoke(record);
}
}
private void OnCancel_Click(object sender, RoutedEventArgs e)
{
this.Close();
}
private void cboWarehouse_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
//切换仓库
if (e.RemovedItems.Count > 0)
{
//事件响应
var warehouse = cboWarehouse.SelectedItem as WarehouseInfo;
if (warehouse == null)
{
return;
}
var shelfList = HttpHelper.GetShelfByWarehouseId(warehouse.id) ?? new List<ShelfInfo>();
shelfList.Insert(0, new ShelfInfo
{
id = "",
name = "(未指定)"
});
cboShelf.SelectionChanged -= cboShelf_SelectionChanged;
cboShelf.ItemsSource = null;
cboShelf.ItemsSource = shelfList;
cboShelf.DisplayMemberPath = "name";
cboShelf.SelectedValuePath = "id";
cboShelf.SelectedIndex = 0;
cboShelf.SelectionChanged += cboShelf_SelectionChanged;
cboShelfRange.ItemsSource = null;
cboShelfRow.ItemsSource = null;
cboShelfColumn.ItemsSource = null;
spShelfData.IsEnabled = false;
spMessage.Visibility = Visibility.Hidden;
cboSize_SelectionChanged(null, null);
}
}
private void cboShelf_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
//切换货架
if (e.RemovedItems.Count > 0)
{
//事件响应
var shelf = cboShelf.SelectedItem as ShelfInfo;
if (!string.IsNullOrEmpty(shelf?.id))
{
cboShelfRange.ItemsSource = CreateSelectList(Convert.ToInt32(shelf.range));
cboShelfRange.SelectedIndex = 0;
cboShelfRow.ItemsSource = CreateSelectList(Convert.ToInt32(shelf.row));
cboShelfRow.SelectedIndex = 0;
cboShelfColumn.ItemsSource = CreateSelectList(Convert.ToInt32(shelf.column));
cboShelfColumn.SelectedIndex = 0;
spShelfData.IsEnabled = true;
}
else
{
cboShelfRange.ItemsSource = null;
cboShelfRow.ItemsSource = null;
cboShelfColumn.ItemsSource = null;
spShelfData.IsEnabled = false;
}
}
}
private List<string> CreateSelectList(int count)
{
var list = new List<string>();
list.Add("(未指定)");
for (int i = 1; i <= count; i++)
{
list.Add(i.ToString());
}
return list;
}
private void cboSize_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
//切换号型
if (e == null || e.RemovedItems.Count > 0)
{
if (cboSize.SelectedItem is EquSizeInfo size)
{
txtPrice.Text = size.price?.ToString() ?? "";
var warehouse = cboWarehouse.SelectedItem as WarehouseInfo;
if (warehouse == null)
{
return;
}
var shelfList = HttpHelper.GetListEquipmentShelfPosition(warehouse.id, record.equId, size.id) ?? new List<ShelfInfo>();
if (shelfList.Count > 0)
{
spMessage.Visibility = Visibility.Visible;
tbMessage.Text = string.Join("\r\n", shelfList.Take(3).Select(x => x.name +
(
string.IsNullOrEmpty(x.range) ? "" : "-" + x.range +
(
string.IsNullOrEmpty(x.column) ? "" : "-" + x.column +
(
string.IsNullOrEmpty(x.row) ? "" : "-" + x.row
)
)
)
));
if (shelfList.Count > 3)
{
tbMessage.Text += " 等";
}
//装填第一条信息
var shelf = shelfList.First();
cboShelf.SelectedIndex = cboShelf.ItemsSource.OfType<ShelfInfo>().ToList()
.FindIndex(x => x.id == shelf.id);
cboShelfRange.SelectedIndex = Convert.ToInt32(shelf.range);
cboShelfColumn.SelectedIndex = Convert.ToInt32(shelf.column);
cboShelfRow.SelectedIndex = Convert.ToInt32(shelf.row);
}
else
{
spMessage.Visibility = Visibility.Hidden;
}
}
else
{
spMessage.Visibility = Visibility.Hidden;
}
}
}
}
}
<Window x:Class="JmpZbPrint.View.SettingsWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:materialDesign="http://materialdesigninxaml.net/winfx/xaml/themes"
xmlns:system="clr-namespace:System;assembly=mscorlib"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:JmpZbPrint"
xmlns:silver="clr-namespace:Panuon.UI.Silver;assembly=Panuon.UI.Silver"
mc:Ignorable="d"
Title="系统设置" Height="500" Width="1100" WindowStyle="None"
WindowStartupLocation="CenterScreen" AllowsTransparency="True"
ResizeMode="NoResize" Background="Transparent" >
<Window.Effect>
<DropShadowEffect BlurRadius="10" Color="#FF858484" Direction="90" ShadowDepth="1"/>
</Window.Effect>
<Window.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="pack://application:,,,/MaterialDesignThemes.Wpf;component/Themes/MaterialDesignTheme.TextBox.xaml" />
<ResourceDictionary Source="pack://application:,,,/MaterialDesignThemes.Wpf;component/Themes/MaterialDesignTheme.DataGrid.xaml"/>
</ResourceDictionary.MergedDictionaries>
<SolidColorBrush x:Key="PrimaryHueLightBrush" Color="#0093EA"/>
<SolidColorBrush x:Key="PrimaryHueLightForegroundBrush" Color="#FFFFFF"/>
<SolidColorBrush x:Key="PrimaryHueMidBrush" Color="#0093EA"/>
<SolidColorBrush x:Key="PrimaryHueMidForegroundBrush" Color="#FFFFFF"/>
<SolidColorBrush x:Key="PrimaryHueDarkBrush" Color="#0093EA"/>
<SolidColorBrush x:Key="PrimaryHueDarkForegroundBrush" Color="#FFFFFF"/>
<!-- accent -->
<SolidColorBrush x:Key="SecondaryAccentBrush" Color="#0093EA"/>
<SolidColorBrush x:Key="SecondaryAccentForegroundBrush" Color="#FFFFFF"/>
<Storyboard x:Key="Loading">
<ThicknessAnimation Duration="0:0:0.2" To="0" From="0,300,0,300"
Storyboard.TargetName="g_main" Storyboard.TargetProperty="Margin" />
</Storyboard>
<Storyboard x:Key="Closing">
<ThicknessAnimation FillBehavior="Stop" Duration="0:0:0.2" To="0,300,0,300" From="0" Storyboard.TargetName="g_main"
Storyboard.TargetProperty="Margin" Completed="Sb_Completed"/>
</Storyboard>
<DataTemplate DataType="{x:Type system:DateTime}">
<StackPanel Margin="16">
<TextBlock>England win the World Cup:</TextBlock>
<TextBlock Margin="0 8 0 0" Text="{Binding }" />
<TextBlock Margin="0 8 0 0" >You will never see that again.</TextBlock>
<Button Margin="0 8 0 0" IsDefault="True" Command="{x:Static materialDesign:DialogHost.CloseDialogCommand}" Style="{DynamicResource MaterialDesignFlatButton}">AWESOME</Button>
</StackPanel>
</DataTemplate>
</ResourceDictionary>
</Window.Resources>
<Window.Triggers>
<EventTrigger RoutedEvent="Loaded" >
<BeginStoryboard Storyboard="{StaticResource Loading}"/>
</EventTrigger>
<EventTrigger RoutedEvent="TextBlock.MouseLeftButtonDown" SourceName="tbclose">
<BeginStoryboard Storyboard="{StaticResource Closing}" />
</EventTrigger>
</Window.Triggers>
<Border BorderBrush="#FF858484" CornerRadius="3" BorderThickness="2" >
<Grid x:Name="g_main" Background="White">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="60"/>
<RowDefinition/>
<RowDefinition Height="100"/>
</Grid.RowDefinitions>
<TextBlock Text="&#xe618;" Style="{StaticResource FiconBase}" Name="tbclose"
HorizontalAlignment="Right" VerticalAlignment="Center"
Margin="0 0 20 0" FontSize="35" Foreground="#8a8a8a" />
<Grid Grid.Row="1">
<Grid.RowDefinitions>
<RowDefinition />
</Grid.RowDefinitions>
<Border Grid.Row="0" Margin="20,0,0,0" Grid.Column="1" BorderBrush="#dedede" VerticalAlignment="Center">
<Grid>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="90"/>
<ColumnDefinition/>
<ColumnDefinition Width="90"/>
<ColumnDefinition/>
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="50"/>
<RowDefinition Height="50"/>
<RowDefinition Height="50"/>
<RowDefinition Height="50"/>
<RowDefinition Height="50"/>
<RowDefinition Height="50"/>
</Grid.RowDefinitions>
<TextBlock Text="域名地址:" FontSize="18" Foreground="#37537d" VerticalAlignment="Bottom" HorizontalAlignment="Left" />
<TextBox Grid.Column="1" Width="400" FontSize="18" Text="{Binding DomainUrl}"
Style="{StaticResource MaterialDesignFloatingHintTextBox}" VerticalContentAlignment="Center" VerticalAlignment="Bottom" HorizontalAlignment="Left" Margin="0,0,0,0" />
<TextBlock Grid.Row="0" Grid.Column="2" Text="登录接口:" FontSize="18" Foreground="#37537d" VerticalAlignment="Bottom" HorizontalAlignment="Left" />
<TextBox Grid.Row="0" Grid.Column="3" Width="400" FontSize="18" Text="{Binding UserLogin}"
Style="{StaticResource MaterialDesignFloatingHintTextBox}" VerticalContentAlignment="Center" VerticalAlignment="Bottom" HorizontalAlignment="Left" Margin="0,0,0,0" />
<TextBlock Grid.Row="1" Grid.Column="0" Text="程序标识:" FontSize="18" Foreground="#37537d" VerticalAlignment="Bottom" HorizontalAlignment="Left" />
<TextBox Grid.Row="1" Grid.Column="1" Width="400" FontSize="18" Text="{Binding AppCode}"
Style="{StaticResource MaterialDesignFloatingHintTextBox}" VerticalContentAlignment="Center" VerticalAlignment="Bottom" HorizontalAlignment="Left" Margin="0,0,0,0" />
<TextBlock Grid.Row="1" Grid.Column="2" Text="程序版本:" FontSize="18" Foreground="#37537d" VerticalAlignment="Bottom" HorizontalAlignment="Left" />
<TextBox Grid.Row="1" Grid.Column="3" Width="400" FontSize="18" Text="{Binding AppVersion}"
Style="{StaticResource MaterialDesignFloatingHintTextBox}" VerticalContentAlignment="Center" VerticalAlignment="Bottom" HorizontalAlignment="Left" Margin="0,0,0,0" IsEnabled="False" />
<TextBlock Grid.Row="2" Grid.Column="0" Text=" AppKey:" FontSize="18" Foreground="#37537d" VerticalAlignment="Bottom" HorizontalAlignment="Left" />
<TextBox Grid.Row="2" Grid.Column="1" Width="400" FontSize="18" Text="{Binding AppKey}"
Style="{StaticResource MaterialDesignFloatingHintTextBox}" VerticalContentAlignment="Center" VerticalAlignment="Bottom" HorizontalAlignment="Left" />
<TextBlock Grid.Row="2" Grid.Column="2" Text="Secret:" FontSize="18" Foreground="#37537d" VerticalAlignment="Bottom" HorizontalAlignment="Left" Margin="18,0,0,0" />
<TextBox Grid.Row="2" Width="400" Grid.Column="3" FontSize="18" Text="{Binding SecretKey}"
Style="{StaticResource MaterialDesignFloatingHintTextBox}" VerticalContentAlignment="Center" VerticalAlignment="Bottom" HorizontalAlignment="Left" Margin="0,0,0,0" />
<TextBlock Grid.Row="3" Grid.Column="0" Text="接口版本:" FontSize="18" Foreground="#37537d" VerticalAlignment="Bottom" HorizontalAlignment="Left" />
<TextBox Grid.Row="3" Grid.Column="1" Width="400" FontSize="18" Text="{Binding ApiVersion}"
Style="{StaticResource MaterialDesignFloatingHintTextBox}" VerticalContentAlignment="Center" VerticalAlignment="Bottom" HorizontalAlignment="Left" />
<TextBlock Grid.Row="4" Grid.Column="0" Text="仅发卡器:" FontSize="18" Foreground="#37537d" VerticalAlignment="Bottom" HorizontalAlignment="Left" />
<CheckBox Grid.Row="4" Grid.Column="1" HorizontalAlignment="Left" IsChecked="{Binding CardOnly}" VerticalAlignment="Bottom" FontSize="18" Foreground="#37537d" Margin="15,0,0,0" >仅使用桌面发卡器</CheckBox>
<TextBlock Grid.Row="4" Grid.Column="2" Text="采购入库:" FontSize="18" Foreground="#37537d" VerticalAlignment="Bottom" HorizontalAlignment="Left" />
<CheckBox Grid.Row="4" Grid.Column="3" HorizontalAlignment="Left" IsChecked="{Binding IsDirectEntryStock}" VerticalAlignment="Bottom" FontSize="18" Foreground="#37537d" Margin="15,0,0,0" >初始化的标签直接自动入库</CheckBox>
<TextBlock Grid.Row="5" Grid.Column="0" Text=" 自动更新:" FontSize="18" Foreground="#37537d" VerticalAlignment="Bottom" HorizontalAlignment="Left" />
<CheckBox Grid.Row="5" Grid.Column="1" x:Name="cb_autoUpdate" IsChecked="{Binding IsAutoUpdate}" FontSize="18" Foreground="#37537d" Width="auto" HorizontalAlignment="Left" VerticalAlignment="Bottom" Margin="8,8,0,0" Click="cb_autoUpdate_Click">启用自动更新,检查时间:</CheckBox>
<ComboBox Grid.Row="5" Grid.Column="1" x:Name="cbb_autoUpdate" SelectedIndex="{Binding AutoUpdateTime}" FontSize="18" Foreground="#37537d" Width="auto" HorizontalAlignment="Stretch" VerticalAlignment="Bottom" Margin="230,0,120,0" >
<ComboBoxItem>0:00</ComboBoxItem>
<ComboBoxItem>1:00</ComboBoxItem>
<ComboBoxItem>2:00</ComboBoxItem>
<ComboBoxItem>3:00</ComboBoxItem>
<ComboBoxItem>4:00</ComboBoxItem>
<ComboBoxItem>5:00</ComboBoxItem>
<ComboBoxItem>6:00</ComboBoxItem>
<ComboBoxItem>7:00</ComboBoxItem>
<ComboBoxItem>8:00</ComboBoxItem>
<ComboBoxItem>9:00</ComboBoxItem>
<ComboBoxItem>10:00</ComboBoxItem>
<ComboBoxItem>11:00</ComboBoxItem>
<ComboBoxItem>12:00</ComboBoxItem>
<ComboBoxItem>13:00</ComboBoxItem>
<ComboBoxItem>14:00</ComboBoxItem>
<ComboBoxItem>15:00</ComboBoxItem>
<ComboBoxItem>16:00</ComboBoxItem>
<ComboBoxItem>17:00</ComboBoxItem>
<ComboBoxItem>18:00</ComboBoxItem>
<ComboBoxItem>19:00</ComboBoxItem>
<ComboBoxItem>20:00</ComboBoxItem>
<ComboBoxItem>21:00</ComboBoxItem>
<ComboBoxItem>22:00</ComboBoxItem>
<ComboBoxItem>23:00</ComboBoxItem>
</ComboBox>
<TextBlock Grid.Row="5" Grid.Column="2" Text="选打印机:" FontSize="18" Foreground="#37537d" VerticalAlignment="Bottom" HorizontalAlignment="Left" />
<ComboBox Grid.Row="5" Grid.Column="3" x:Name="cbb_printType" SelectedIndex="{Binding PrintType}" FontSize="18" Foreground="#37537d" Width="auto" HorizontalAlignment="Stretch" VerticalAlignment="Bottom" Margin="15,0,50,0" >
<ComboBoxItem>东芝</ComboBoxItem>
<ComboBoxItem>博思得</ComboBoxItem>
</ComboBox>
</Grid>
</Border>
</Grid>
<Button Grid.Row="2" Height="40" FontSize="20" Content="保存" Style="{StaticResource MaterialDesignRaisedButton}" Width="100" Margin="0,0,180,0" HorizontalAlignment="Right" VerticalAlignment="Center" Click="SaveClick" />
<Button Grid.Row="2" Height="40" FontSize="20" Content="关闭" Background="OrangeRed" BorderBrush="OrangeRed" Style="{StaticResource MaterialDesignRaisedButton}" Width="100" Margin="0,0,40,0" HorizontalAlignment="Right" Click="CloseClick" VerticalAlignment="Center" />
</Grid>
</Grid>
</Border>
</Window>
using JmpZbPrint.Common;
using System;
using System.Windows;
namespace JmpZbPrint.View
{
/// <summary>
/// SettingsWindow.xaml 的交互逻辑
/// </summary>
public partial class SettingsWindow : Window
{
private Config vm;
public SettingsWindow(Config config)
{
InitializeComponent();
this.vm = config;
this.DataContext = vm;
cbb_autoUpdate.IsEnabled = vm.IsAutoUpdate;
}
private void Sb_Completed(object sender, EventArgs e)
{
this.Close();
}
private void SaveClick(object sender, RoutedEventArgs e)
{
if (CaChe.SaveSystemStep(vm))
{
MessageBox.Show("配置保存成功!", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
CaChe.LoadSystemStep();
DialogResult = true;
}
}
private void CloseClick(object sender, RoutedEventArgs e)
{
DialogResult = false;
}
private void cb_autoUpdate_Click(object sender, RoutedEventArgs e)
{
cbb_autoUpdate.IsEnabled = cb_autoUpdate.IsChecked == true;
}
}
}
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using JmpZbPrint.Model;
using JmpZbPrint.PagePartial;
using JmpZbPrint.UsControl;
using MaterialDesignThemes.Wpf;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Threading;
namespace JmpZbPrint.ViewModel
{
public class GenEpcViewModel : ViewModelBase
{
public GenEpcViewModel()
{
OnQueryCommand = new RelayCommand(OnQuery);
OnPageChangeCmd = new RelayCommand(OnPageChange);
OnGenTagCmd = new RelayCommand<order_info>(OnGenTag);
OnWindowLoadCmd = new RelayCommand(OnWindowLoad);
}
#region filed
private ObservableCollection<order_info> _printList = new ObservableCollection<order_info>();
public ObservableCollection<order_info> UiGenList
{
get { return _printList; }
set
{
//PageTotal = GetPageTotal(value.Where(t => t.Status == "未打印").Count());
//TotalRecord = value.Count;
_printList = value;
RaisePropertyChanged();
}
}
private string _orderCode;
public string OrderCode
{
get { return _orderCode; }
set
{
_orderCode = value;
RaisePropertyChanged();
}
}
private string _equName;
public string EquName
{
get { return _equName; }
set
{
_equName = value;
RaisePropertyChanged();
}
}
//private DateTime _createTime=DateTime.Now;
//public DateTime CreateTime
//{
// get { return _createTime; }
// set
// {
// _createTime = value;
// RaisePropertyChanged();
// }
//}
private bool _isSelectAll = false;
private WaitDialog waitDialog = default;
public bool IsSelectAll
{
get { return _isSelectAll; }
set
{
_isSelectAll = value;
RaisePropertyChanged(() => IsSelectAll);
SelectAll();
}
}
private int _total = 0;
public int TotalRecord
{
get { return _total; }
set
{
_total = value;
RaisePropertyChanged();
}
}
private int _page = 0;
public int PageIndex
{
get { return _page; }
set
{
_page = value;
RaisePropertyChanged();
}
}
private int _pageTotal = 0;
public int PageTotal
{
get { return _pageTotal; }
set
{
_pageTotal = value;
RaisePropertyChanged();
}
}
private int _pageSize = 50;
public int PageSize
{
get { return _pageSize; }
set
{
_pageSize = value;
RaisePropertyChanged();
}
}
#endregion
#region cmd attr
public RelayCommand OnWindowLoadCmd { get; set; }
public RelayCommand OnQueryCommand { get; set; }
public RelayCommand OnPageChangeCmd { get; set; }
public RelayCommand<order_info> OnGenTagCmd { get; set; }
#endregion
#region method
public void OnWindowLoad()
{
OnQuery();
}
public void OnWindowClosing()
{
}
private void OnQuery()
{
PageIndex = 1;
IsSelectAll = false;
UiGenList.Clear();
waitDialog = new WaitDialog();
waitDialog.SetToolTop("数据加载中...");
DialogHost.Show(waitDialog, "MainRootDialog",
(obj, args) =>
{
Task.Run(() =>
{
var tmp = HttpHelper.GetOrderList(OrderCode, EquName);
TotalRecord = tmp?.total ?? 0;
PageTotal = TotalRecord == 0 ? 0 : (TotalRecord + PageSize - 1) / PageSize;
App.Current.Dispatcher.BeginInvoke(DispatcherPriority.Normal, (Action)delegate ()
{
UiGenList?.Clear();
if (tmp?.record != null && tmp?.record.Count > 0)
{
UiGenList = new ObservableCollection<order_info>(tmp.record);
}
args.Session.Close();
});
});
},
(obj, args) =>
{
});
}
private void OnPageChange()
{
waitDialog = new WaitDialog();
waitDialog.SetToolTop("数据加载中...");
DialogHost.Show(waitDialog, "MainRootDialog",
(obj, args) =>
{
Task.Run(() =>
{
var tmp = HttpHelper.GetOrderList(OrderCode, EquName);
TotalRecord = tmp?.total ?? 0;
PageTotal = TotalRecord == 0 ? 0 : (TotalRecord + PageSize - 1) / PageSize;
App.Current.Dispatcher.BeginInvoke(DispatcherPriority.Normal, (Action)delegate ()
{
UiGenList?.Clear();
if (tmp?.record != null && tmp?.record.Count > 0)
{
UiGenList = new ObservableCollection<order_info>(tmp.record);
}
args.Session.Close();
});
});
},
(obj, args) =>
{
});
}
private void OnGenTag(order_info order)
{
var orders = UiGenList.Where(s => s.IsSelected == true).ToList();
if (orders == null || orders.Count() == 0)
{
new SetBasicInfo(new List<order_info>() { order }).ShowDialog();
}
else
{
new SetBasicInfo(orders).ShowDialog();
}
OnQuery();
}
public void SelectAll()
{
App.Current.Dispatcher.Invoke(() =>
{
foreach (var item in UiGenList)
{
item.IsSelected = _isSelectAll;
}
this.RaisePropertyChanged(() => UiGenList);
});
}
#endregion
}
}
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using JmpZbModel;
using JmpZbPrint.Common;
using JmpZbPrint.Model;
using JmpZbPrint.PagePartial;
using JmpZbPrint.UsControl;
using MaterialDesignThemes.Wpf;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Threading;
using WebSocketSharp;
namespace JmpZbPrint.ViewModel
{
public class IntBindViewModel : ViewModelBase
{
public IntBindViewModel()
{
OnGenCommand = new RelayCommand(OnGenBind);
OnQueryCommand = new RelayCommand(OnQuery);
OnPageChangeCmd = new RelayCommand(OnPageChange);
OnWindowLoadCmd = new RelayCommand(OnWindowLoad);
OnInitialTagCmd = new RelayCommand<recode_info>(OnInitialTag);
OnDeleteTagCmd = new RelayCommand(OnDeleteTag);
OnBoxingCmd = new RelayCommand(OnBoxing);
}
#region command
public RelayCommand OnWindowLoadCmd { get; set; }
public RelayCommand OnGenCommand { get; set; }
public RelayCommand OnQueryCommand { get; set; }
public RelayCommand OnGridLoadedCmd { get; set; }
public RelayCommand<recode_info> OnInitialTagCmd { get; set; }
public RelayCommand OnDeleteTagCmd { get; set; }
public RelayCommand OnPageChangeCmd { get; set; }
public RelayCommand OnBoxingCmd { get; set; }
#endregion
#region filed
private ObservableCollection<recode_info> _printList = new ObservableCollection<recode_info>();
public ObservableCollection<recode_info> BindTaskList
{
get { return _printList; }
set
{
_printList = value;
RaisePropertyChanged();
}
}
public AutoResetEvent resetEvent = new AutoResetEvent(false);
private string _equName;
public string EquName
{
get { return _equName; }
set
{
_equName = value;
RaisePropertyChanged();
}
}
private string _vendorName;
public string VendorName
{
get { return _vendorName; }
set
{
_vendorName = value;
RaisePropertyChanged();
}
}
private string _message = "状态:初始化设备连接准备中";
public string UiMessage
{
get { return _message; }
set
{
_message = value;
RaisePropertyChanged();
}
}
private string _msgccolor = "Green";
public string MsgColor
{
get { return _msgccolor; }
set
{
_msgccolor = value;
RaisePropertyChanged();
}
}
private bool _bindButton = false;
public bool BindButton
{
get { return _bindButton; }
set
{
_bindButton = value;
RaisePropertyChanged();
}
}
private int _total = 0;
public int TotalRecord
{
get { return _total; }
set
{
_total = value;
RaisePropertyChanged();
}
}
private int _page = 0;
public int PageIndex
{
get { return _page; }
set
{
_page = value;
RaisePropertyChanged();
}
}
private int _pageTotal = 0;
public int PageTotal
{
get { return _pageTotal; }
set
{
_pageTotal = value;
RaisePropertyChanged();
}
}
private int _pageSize = 50;
public int PageSize
{
get { return _pageSize; }
set
{
_pageSize = value;
RaisePropertyChanged();
}
}
private bool _isSelectAll = false;
public bool IsSelectAll
{
get { return _isSelectAll; }
set
{
_isSelectAll = value;
RaisePropertyChanged();
SelectAll();
}
}
#endregion
#region attr
#endregion
#region method
/// <summary>
/// 装箱
/// </summary>
private void OnBoxing()
{
var seled = BindTaskList.Where(t => t.IsSelected == true).ToList();
if (seled.Count > 0)
{
if (MessageBox.Show("确认装箱选中的记录?", "确认装箱", MessageBoxButton.OKCancel, MessageBoxImage.Question) ==
MessageBoxResult.OK)
{
//判断物资一致性
var info = seled.First();
if (seled.Any(x => x.equId != info.equId))
{
MessageBox.Show("物资类型不一致,无法装箱");
return;
}
if (seled.Any(x => x.sizeId != info.sizeId))
{
MessageBox.Show("物资型号不一致,无法装箱");
return;
}
if (seled.Any(x => x.supplierId != info.supplierId))
{
MessageBox.Show("供应商不一致,无法装箱");
return;
}
if (seled.Any(x => x.warehouseId != info.warehouseId))
{
MessageBox.Show("入库仓库不一致,无法装箱");
return;
}
//创建箱标epc
var boxRequest = new request_int_info()
{
labelType = "箱标",
equCode = info.equCode,
productTime = info.productTime,
sizeCode = info.sizeCode,
oneBoxNum = seled.Count,
quantity = 1,
supplierCode = info.suppilerCode,
warrantyCycle = info.warrantyCycle
};
var boxRes = HttpHelper.GenerateIntTagEpc(boxRequest, out string boxMsg);
if (!boxRes.Item1)
{
MessageBox.Show($"[{info.equName}-{info.sizeName}] 箱标生成失败,原因:{boxMsg}", "提示", MessageBoxButton.OK, MessageBoxImage.Error);
return;
}
var xbEpc = boxRes.Item2.First().epc;
var res = HttpHelper.BoxingInventory(xbEpc, seled, out string msg);
if (res)
{
var _batch_no = DateTime.Now.ToString("yyyyMMddHHmmssfff");
foreach (var obj in seled)
{
LiteDbHelper.Delete(obj.id);
}
LiteDbHelper.AddRange(new List<recode_info>()
{
new recode_info()
{
LabelType = "箱标",
orgId = info.orgId,
batchNo = _batch_no,
epc = xbEpc,
num = 1,
equCode = info.equCode,
equId = info.equId,
sizeCode = info.sizeCode,
equName = info.equName,
isdelete = false,
oneBoxNum = seled.Count,
needNum = 1,
price = info.price,
productTime = info.productTime,
repairCycle = info.repairCycle,
sizeId = info.sizeId,
sizeName = info.sizeName,
suppilerCode = info.suppilerCode,
supplierId = info.supplierId,
suppilerName = info.suppilerName,
type = 0, //打印
useTime = info.useTime,
warehouseId = info.warehouseId,
warehouseName = info.warehouseName,
warrantyCycle = info.warrantyCycle,
createTime = DateTime.Now,
IsReloadBoxing = true,
epcListJson = JsonConvert.SerializeObject(seled.Select(x => x.epc))
}
});
}
else
{
MessageBox.Show(msg);
}
OnQuery();
}
}
}
private void OnRefreshGridSrc()
{
OnQuery();
}
private WaitDialog waitDialog = default;
public void OnGenBind()
{
var gen = new IntGenEpcWindow(1);
gen.OnRefreshGrid += OnRefreshGridSrc;
gen.ShowDialog();
}
public void OnWindowLoad()
{
InitWs();
OnQuery();
}
public void OnWindowClosing()
{
}
private void OnQuery()
{
IsSelectAll = false;
BindTaskList.Clear();
PageIndex = 1;
waitDialog = new WaitDialog();
waitDialog.SetToolTop("数据加载中...");
DialogHost.Show(waitDialog, "MainRootDialog",
(obj, args) =>
{
Task.Run(() =>
{
var tmp = LiteDbHelper.GetPage(PageIndex, PageSize, t => t.isdelete == false
&& t.type == 1
&& (string.IsNullOrEmpty(EquName) || t.equName.Contains(EquName))
&& (string.IsNullOrEmpty(VendorName) || t.suppilerName.Contains(VendorName))
&& t.orgId == CaChe.UserInfo.baseJpOrganization.id);
TotalRecord = tmp?.total ?? 0;
PageTotal = TotalRecord == 0 ? 0 : (TotalRecord + PageSize - 1) / PageSize;
App.Current.Dispatcher.BeginInvoke(DispatcherPriority.Normal, (Action)delegate ()
{
BindTaskList?.Clear();
if (tmp?.record != null && tmp?.record.Count > 0)
{
BindTaskList = new ObservableCollection<recode_info>(tmp.record);
}
args.Session.Close();
});
});
},
(obj, args) =>
{
});
}
private void OnPageChange()
{
IsSelectAll = false;
waitDialog = new WaitDialog();
waitDialog.SetToolTop("数据加载中...");
DialogHost.Show(waitDialog, "MainRootDialog",
(obj, args) =>
{
Task.Run(() =>
{
var tmp = LiteDbHelper.GetPage(PageIndex, PageSize, t => t.isdelete == false
&& t.type == 1
&& (string.IsNullOrEmpty(EquName) || t.equName.Contains(EquName))
&& (string.IsNullOrEmpty(VendorName) || t.suppilerName.Contains(VendorName))
&& t.orgId == CaChe.UserInfo.baseJpOrganization.id);
TotalRecord = tmp?.total ?? 0;
PageTotal = TotalRecord == 0 ? 0 : (TotalRecord + PageSize - 1) / PageSize;
App.Current.Dispatcher.BeginInvoke(DispatcherPriority.Normal, (Action)delegate ()
{
BindTaskList?.Clear();
if (tmp?.record != null && tmp?.record.Count > 0)
{
BindTaskList = new ObservableCollection<recode_info>(tmp.record);
}
args.Session.Close();
});
});
},
(obj, args) =>
{
});
}
public override void Cleanup()
{
base.Cleanup();
resetEvent.Set();
cWsServiceToken?.Cancel();
wsConn?.Close();
}
public void SelectAll()
{
App.Current.Dispatcher.Invoke(() =>
{
foreach (var item in BindTaskList)
{
item.IsSelected = _isSelectAll;
}
this.RaisePropertyChanged(() => BindTaskList);
});
}
private void OnDeleteTag()
{
var seled = BindTaskList.Where(t => t.IsSelected == true).ToList();
if (seled.Count() > 0)
{
if (MessageBox.Show("确认删除选中的条记录?", "确认删除", MessageBoxButton.OKCancel, MessageBoxImage.Question) == MessageBoxResult.OK)
{
seled.ForEach(s =>
{
if (s.IsUnboxingLabel)
{
//拆箱生成标签直接报废记录
if (!HttpHelper.DeleteEpc(s.epc, out string msg))
{
MessageBox.Show(msg);
}
}
LiteDbHelper.Delete(s.id);
BindTaskList.Remove(s);
});
if (BindTaskList.Count == 0)
{
OnQuery();
}
IsSelectAll = false;
}
}
}
#endregion
#region ws server
public CancellationTokenSource cWsServiceToken;
public Task taskWsService;
public WebSocket wsConn;
private ManualResetEvent resetUhf = new ManualResetEvent(true);
private string tmpEpc = "";
public void InitWs()
{
if (taskWsService == null)
{
cWsServiceToken = new CancellationTokenSource();
taskWsService = new Task(() =>
{
wsConn = new WebSocket("ws://127.0.0.1:8081");
while (!cWsServiceToken.IsCancellationRequested)
{
try
{
// 已连接的不处理
if (wsConn.IsAlive)
{
}
else
{
// 接收数据
wsConn.OnMessage += (sender, e) =>
{
ReciveWsMsg(e.Data);
};
// 服务关闭
wsConn.OnClose += (sender, e) =>
{
UiMessage = $"状态:服务已断开,重连中";
MsgColor = "Red";
BindButton = false;
};
wsConn.OnOpen += (sender, e) =>
{
UiMessage = $"状态:正在查询设备状态";
MsgColor = "Green";
BindButton = true;
};
// 服务连接
wsConn.Connect();
}
}
catch (System.Exception ex)
{
UiMessage = $"状态:初始化设备连接失败";
MsgColor = "Red";
BindButton = false;
Log.ErrorLog(ex.ToString(), this.GetType().Name);
}
if (resetEvent.WaitOne(3000)) { break; }
}
});
taskWsService.Start();
}
}
private void ReciveWsMsg(string msg)
{
var cmdInfo = JsonConvert.DeserializeObject<InitializeCmdInfo>(msg);
switch (cmdInfo.CmdType)
{
case JmpUhfService.InitializeCmdType.Busy:
UiMessage = $"状态:设备正忙,请检查设备是否被占用";
MsgColor = "Red";
BindButton = false;
resetUhf.Set();
break;
case JmpUhfService.InitializeCmdType.Initialize:
if (msg.Contains("成功"))
{
UiMessage = $"状态:数据绑定成功";
MsgColor = "Green";
resetUhf.Set();
BindButton = true;
//更新状态
UpdateEpcStateByEpc(cmdInfo.Content.Replace("成功", "").Replace(" ", ""), true);
}
else
{
BindButton = true;
UiMessage = $"状态:{cmdInfo.Content}";
MsgColor = "Red";
resetUhf.Set();
}
break;
case JmpUhfService.InitializeCmdType.Linked:
UiMessage = $"状态:初始化设备已连接";
MsgColor = "Green";
resetUhf.Set();
BindButton = true;
break;
case JmpUhfService.InitializeCmdType.ErrorMsg:
UiMessage = $"状态:{cmdInfo.Content}";
MsgColor = "Red";
resetUhf.Set();
BindButton = false;
break;
case JmpUhfService.InitializeCmdType.ReadInventorySingle:
tmpEpc = cmdInfo.Content;
resetUhf.Set();
BindButton = false;
break;
case JmpUhfService.InitializeCmdType.ReadInventorySingleError:
UiMessage = $"状态:{cmdInfo.Content}";
MsgColor = "Red";
resetUhf.Set();
BindButton = true;
break;
default:
resetUhf.Set();
break;
}
}
private void UpdateEpcStateByEpc(string epc, bool apply = false)
{
App.Current.Dispatcher.Invoke(() =>
{
var item = BindTaskList.FirstOrDefault(t => t.epc.Contains(epc));
if (item != null)
{
item.isdelete = true;
var flag = true;
if (apply)
{
var res = HttpHelper.GenerateInventory(item, out string msg);
if (!res)
{
MsgColor = "Red";
UiMessage = "状态:写入入库记录失败:" + msg;
flag = false;
}
else
{
flag = LiteDbHelper.Update(epc);
}
}
if (flag)
{
BindTaskList.Remove(item);
RaisePropertyChanged(() => BindTaskList);
TotalRecord -= 1;
if (BindTaskList.Count == 0)
{
PageIndex = 1;
OnPageChange();
}
}
}
});
}
public async void OnInitialTag(recode_info entity)
{
try
{
BindButton = false;
UiMessage = "状态:绑定中";
MsgColor = "Green";
await Dispatcher.Yield();
if (ReadInventorySingle())
{
resetUhf.Reset();
resetUhf.WaitOne(3000);
//判断epc是否已被绑过装备
if (!string.IsNullOrEmpty(tmpEpc))
{
if (HttpHelper.CheckEpcIsInstantiation(tmpEpc, out string msg))
{
if (SendInitialMsg(entity.epc))
{
resetUhf.Reset();
resetUhf.WaitOne(3000);
}
}
else
{
BindButton = true;
UiMessage = "状态:绑定失败," + msg;
MsgColor = "Red";
}
tmpEpc = "";
}
}
else
{
BindButton = true;
UiMessage = "状态:绑定失败,设备异常";
MsgColor = "Red";
}
}
catch (Exception ex)
{
BindButton = true;
tmpEpc = "";
Log.ErrorLog(ex.ToString());
}
}
private bool ReadInventorySingle()
{
try
{
var json = JsonConvert.SerializeObject(new
{
CmdType = 7,
Content = ""
});
if (wsConn?.IsAlive ?? false)
{
wsConn.Send(json);
return true;
}
else
{
return false;
}
}
catch (Exception ex)
{
Log.ErrorLog(ex.ToString(), MethodBase.GetCurrentMethod().Name);
return false;
}
}
private bool SendInitialMsg(string epc, ushort len = 17, ushort offset = 1, string password = "00000000")
{
try
{
var epc_data = JsonConvert.SerializeObject(new
{
Epc = epc,
Len = len,
Offset = offset,
Password = password
});
var json = JsonConvert.SerializeObject(new
{
CmdType = 8,
Content = epc_data
});
if (wsConn?.IsAlive ?? false)
{
wsConn.Send(json);
return true;
}
else
{
return false;
}
}
catch (Exception ex)
{
Log.ErrorLog(ex.ToString());
return false;
}
}
#endregion
}
}
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using JmpZbPrint.Common;
using JmpZbPrint.Model;
using JmpZbPrint.UsControl;
using MaterialDesignThemes.Wpf;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Threading;
namespace JmpZbPrint.ViewModel
{
public class IntHistoryViewModel : ViewModelBase
{
public IntHistoryViewModel()
{
OnQueryCommand = new RelayCommand(OnQuery);
OnPageChangeCmd = new RelayCommand(OnPageChange);
OnWindowLoadCmd = new RelayCommand(OnWindowLoad);
OnScrapCmd = new RelayCommand<recode_info>(OnScrap);
OnScrapAllCmd = new RelayCommand(OnScrapAll);
}
#region command
public RelayCommand OnWindowLoadCmd { get; set; }
public RelayCommand OnQueryCommand { get; set; }
public RelayCommand OnGridLoadedCmd { get; set; }
public RelayCommand<recode_info> OnScrapCmd { get; set; }
public RelayCommand OnPageChangeCmd { get; set; }
public RelayCommand OnScrapAllCmd { get; set; }
#endregion
#region filed
private ObservableCollection<recode_info> _printList = new ObservableCollection<recode_info>();
public ObservableCollection<recode_info> BindTaskList
{
get { return _printList; }
set
{
_printList = value;
RaisePropertyChanged();
}
}
private AutoResetEvent resetEvent = new AutoResetEvent(false);
private string _equName;
public string EquName
{
get { return _equName; }
set
{
_equName = value;
RaisePropertyChanged();
}
}
private string _vendorName;
public string VendorName
{
get { return _vendorName; }
set
{
_vendorName = value;
RaisePropertyChanged();
}
}
private int _total = 0;
public int TotalRecord
{
get { return _total; }
set
{
_total = value;
RaisePropertyChanged();
}
}
private int _page = 0;
public int PageIndex
{
get { return _page; }
set
{
_page = value;
RaisePropertyChanged();
}
}
private int _pageTotal = 0;
public int PageTotal
{
get { return _pageTotal; }
set
{
_pageTotal = value;
RaisePropertyChanged();
}
}
private int _pageSize = 50;
public int PageSize
{
get { return _pageSize; }
set
{
_pageSize = value;
RaisePropertyChanged();
}
}
private bool _isSelectAll = false;
public bool IsSelectAll
{
get { return _isSelectAll; }
set
{
_isSelectAll = value;
RaisePropertyChanged();
SelectAll();
}
}
#endregion
#region attr
#endregion
#region method
private WaitDialog waitDialog = default;
public void OnWindowLoad()
{
OnQuery();
}
public void OnWindowClosing()
{
}
private void OnQuery()
{
IsSelectAll = false;
BindTaskList.Clear();
PageIndex = 1;
waitDialog = new WaitDialog();
waitDialog.SetToolTop("数据加载中...");
DialogHost.Show(waitDialog, "MainRootDialog",
(obj, args) =>
{
Task.Run(() =>
{
var tmp = LiteDbHelper.GetPage(PageIndex, PageSize, t => t.isdelete == true
&& t.LabelType == "件标"
&& (string.IsNullOrEmpty(EquName) || t.equName.Contains(EquName))
&& (string.IsNullOrEmpty(VendorName) || t.suppilerName.Contains(VendorName))
&& t.orgId == CaChe.UserInfo.baseJpOrganization.id);
TotalRecord = tmp?.total ?? 0;
PageTotal = TotalRecord == 0 ? 0 : (TotalRecord + PageSize - 1) / PageSize;
App.Current.Dispatcher.BeginInvoke(DispatcherPriority.Normal, (Action)delegate ()
{
BindTaskList?.Clear();
if (tmp?.record != null && tmp?.record.Count > 0)
{
BindTaskList = new ObservableCollection<recode_info>(tmp.record);
}
args.Session.Close();
});
});
},
(obj, args) =>
{
});
}
private void OnPageChange()
{
IsSelectAll = false;
waitDialog = new WaitDialog();
waitDialog.SetToolTop("数据加载中...");
DialogHost.Show(waitDialog, "MainRootDialog",
(obj, args) =>
{
Task.Run(() =>
{
var tmp = LiteDbHelper.GetPage(PageIndex, PageSize, t => t.isdelete == true
&& t.LabelType == "件标"
&& (string.IsNullOrEmpty(EquName) || t.equName.Contains(EquName))
&& (string.IsNullOrEmpty(VendorName) || t.suppilerName.Contains(VendorName))
&& t.orgId == CaChe.UserInfo.baseJpOrganization.id);
TotalRecord = tmp?.total ?? 0;
PageTotal = TotalRecord == 0 ? 0 : (TotalRecord + PageSize - 1) / PageSize;
App.Current.Dispatcher.BeginInvoke(DispatcherPriority.Normal, (Action)delegate ()
{
BindTaskList?.Clear();
if (tmp?.record != null && tmp?.record.Count > 0)
{
BindTaskList = new ObservableCollection<recode_info>(tmp.record);
}
args.Session.Close();
});
});
},
(obj, args) =>
{
});
}
public override void Cleanup()
{
base.Cleanup();
resetEvent.Set();
}
public void SelectAll()
{
App.Current.Dispatcher.Invoke(() =>
{
foreach (var item in BindTaskList)
{
item.IsSelected = _isSelectAll;
}
this.RaisePropertyChanged(() => BindTaskList);
});
}
private void OnScrapAll()
{
var seled = BindTaskList.Where(t => t.IsSelected == true).ToList();
if (seled.Count() > 0)
{
if (MessageBox.Show("确认删除选中的库存记录?", "确认删除", MessageBoxButton.OKCancel, MessageBoxImage.Question) == MessageBoxResult.OK)
{
foreach (var item in seled)
{
//请求http报废接口
var res = HttpHelper.DeleteEpc(item.epc, out string msg);
if (res)
{
LiteDbHelper.Delete(item.id);
BindTaskList.Remove(item);
}
else
{
MessageBox.Show($"删除失败,原因:{msg}", "提示", MessageBoxButton.OK, MessageBoxImage.Error);
break;
}
}
if (BindTaskList.Count == 0)
{
OnQuery();
}
IsSelectAll = false;
}
}
}
private void OnScrap(recode_info entity)
{
if (entity != null)
{
if (MessageBox.Show("确认删除此条库存记录?", "确认删除", MessageBoxButton.OKCancel, MessageBoxImage.Question) == MessageBoxResult.OK)
{
//请求http报废接口
var res = HttpHelper.DeleteEpc(entity.epc, out string msg);
if (res)
{
//请求成功,删除记录
LiteDbHelper.Delete(entity.id);
BindTaskList.Remove(entity);
if (BindTaskList.Count == 0)
{
OnQuery();
}
IsSelectAll = false;
}
else
{
MessageBox.Show($"删除失败,原因:{msg}", "提示", MessageBoxButton.OK, MessageBoxImage.Error);
}
}
}
}
#endregion
}
}
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using JmpZbModel;
using JmpZbPrint.Common;
using JmpZbPrint.Model;
using JmpZbPrint.PagePartial;
using JmpZbPrint.UsControl;
using MaterialDesignThemes.Wpf;
using NetworkCommsDotNet;
using NetworkCommsDotNet.Connections;
using NetworkCommsDotNet.Connections.TCP;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Threading;
using JmpZbPrint.Dialog;
using JmpZbPrint.View;
namespace JmpZbPrint.ViewModel
{
public class IntPrintViewModel : ViewModelBase
{
private InternalWindow _window;
public IntPrintViewModel(InternalWindow window)
{
_window = window;
OnStartPrintItemsCmd = new RelayCommand(OnPrintStart);
OnStopPrintItemsCmd = new RelayCommand(OnPrintStop);
OnQueryCommand = new RelayCommand(OnQuery);
OnPageChangeCmd = new RelayCommand(OnPageChange);
OnWindowLoadCmd = new RelayCommand(OnWindowLoad);
OnGenCommand = new RelayCommand(OnGenPrint);
OnDeleteTagCmd = new RelayCommand(OnDeleteTag);
OnBoxingCmd = new RelayCommand(OnBoxing);
OnUnboxingCmd = new RelayCommand(OnUnboxing);
}
#region filed
private WaitDialog waitDialog = default;
private bool isStop = false;
private ObservableCollection<recode_info> _printList = new ObservableCollection<recode_info>();
public ObservableCollection<recode_info> UiPrintList
{
get { return _printList; }
set
{
_printList = value;
RaisePropertyChanged();
}
}
private string _equName = string.Empty;
public string EquName
{
get { return _equName; }
set
{
_equName = value;
RaisePropertyChanged();
}
}
private string _vendorName = string.Empty;
public string VendorName
{
get { return _vendorName; }
set
{
_vendorName = value;
RaisePropertyChanged();
}
}
private string _message = "状态:初始化设备连接准备中";
public string UiMessage
{
get { return _message; }
set
{
_message = value;
RaisePropertyChanged();
}
}
private string _msgccolor = "Green";
public string MsgColor
{
get { return _msgccolor; }
set
{
_msgccolor = value;
RaisePropertyChanged();
}
}
private bool _bindButton = false;
public bool BindButton
{
get { return _bindButton; }
set
{
_bindButton = value;
RaisePropertyChanged();
}
}
private int _total = 0;
public int TotalRecord
{
get { return _total; }
set
{
_total = value;
RaisePropertyChanged();
}
}
private int _page = 0;
public int PageIndex
{
get { return _page; }
set
{
_page = value;
RaisePropertyChanged();
}
}
private int _pageTotal = 0;
public int PageTotal
{
get { return _pageTotal; }
set
{
_pageTotal = value;
RaisePropertyChanged();
}
}
private int _pageSize = 50;
public int PageSize
{
get { return _pageSize; }
set
{
_pageSize = value;
RaisePropertyChanged();
}
}
private bool _startEnable = false;
public bool StartEnable
{
get { return _startEnable; }
set
{
_startEnable = value;
RaisePropertyChanged();
}
}
private bool _stopEnable = false;
public bool StopEnable
{
get { return _stopEnable; }
set
{
_stopEnable = value;
RaisePropertyChanged();
}
}
private bool _isSelectAll = false;
public bool IsSelectAll
{
get { return _isSelectAll; }
set
{
_isSelectAll = value;
RaisePropertyChanged();
SelectAll();
}
}
#endregion
#region command
public RelayCommand OnGenCommand { get; set; }
public RelayCommand OnStartPrintItemsCmd { get; set; }
public RelayCommand OnStopPrintItemsCmd { get; set; }
public RelayCommand OnWindowLoadCmd { get; set; }
public RelayCommand OnQueryCommand { get; set; }
public RelayCommand OnPageChangeCmd { get; set; }
public RelayCommand OnDeleteTagCmd { get; set; }
public RelayCommand OnBoxingCmd { get; set; }
public RelayCommand OnUnboxingCmd { get; set; }
#endregion
#region method
/// <summary>
/// 装箱
/// </summary>
private void OnBoxing()
{
var seled = UiPrintList.Where(t => t.IsSelected == true).ToList();
if (seled.Count > 0)
{
if (seled.Any(x => x.LabelType == "箱标"))
{
MessageBox.Show("禁止箱标装箱");
return;
}
if (MessageBox.Show("确认装箱选中的记录?", "确认装箱", MessageBoxButton.OKCancel, MessageBoxImage.Question) ==
MessageBoxResult.OK)
{
//判断物资一致性
var info = seled.First();
if (seled.Any(x => x.equId != info.equId))
{
MessageBox.Show("物资类型不一致,无法装箱");
return;
}
if (seled.Any(x => x.sizeId != info.sizeId))
{
MessageBox.Show("物资型号不一致,无法装箱");
return;
}
if (seled.Any(x => x.supplierId != info.supplierId))
{
MessageBox.Show("供应商不一致,无法装箱");
return;
}
if (seled.Any(x => x.warehouseId != info.warehouseId))
{
MessageBox.Show("入库仓库不一致,无法装箱");
return;
}
//创建箱标epc
var boxRequest = new request_int_info()
{
labelType = "箱标",
equCode = info.equCode,
productTime = info.productTime,
sizeCode = info.sizeCode,
oneBoxNum = seled.Count,
quantity = 1,
supplierCode = info.suppilerCode,
warrantyCycle = info.warrantyCycle
};
var boxRes = HttpHelper.GenerateIntTagEpc(boxRequest, out string boxMsg);
if (!boxRes.Item1)
{
MessageBox.Show($"[{info.equName}-{info.sizeName}] 箱标生成失败,原因:{boxMsg}", "提示", MessageBoxButton.OK, MessageBoxImage.Error);
return;
}
var xbEpc = boxRes.Item2.First().epc;
var res = HttpHelper.BoxingInventory(xbEpc, seled, out string msg);
if (res)
{
var _batch_no = DateTime.Now.ToString("yyyyMMddHHmmssfff");
foreach (var obj in seled)
{
LiteDbHelper.Delete(obj.id);
}
LiteDbHelper.AddRange(new List<recode_info>()
{
new recode_info()
{
LabelType = "箱标",
orgId = info.orgId,
batchNo = _batch_no,
epc = xbEpc,
num = 1,
equCode = info.equCode,
equId = info.equId,
sizeCode = info.sizeCode,
equName = info.equName,
isdelete = false,
oneBoxNum = seled.Count,
needNum = 1,
price = info.price,
productTime = info.productTime,
repairCycle = info.repairCycle,
sizeId = info.sizeId,
sizeName = info.sizeName,
suppilerCode = info.suppilerCode,
supplierId = info.supplierId,
suppilerName = info.suppilerName,
type = 0, //打印
useTime = info.useTime,
warehouseId = info.warehouseId,
warehouseName = info.warehouseName,
warrantyCycle = info.warrantyCycle,
createTime = DateTime.Now,
IsReloadBoxing = true,
epcListJson = JsonConvert.SerializeObject(seled.Select(x => x.epc))
}
});
}
else
{
MessageBox.Show(msg);
}
OnQuery();
}
}
}
/// <summary>
/// 拆箱
/// </summary>
private void OnUnboxing()
{
var selectBox = new SelectBoxEpc(true);
selectBox.ShowDialog();
var info = selectBox.RecodeInfo;
if (info != null)
{
//拆箱
List<recode_info> epc_record = new List<recode_info>();
var epcListRes = HttpHelper.GetInventoryListByBoxMarkEpc(info.epc, out var msg);
if (!epcListRes.Item1)
{
MessageBox.Show("获取件标失败:" + msg);
}
var invList = epcListRes.Item2;
var _batch_no = DateTime.Now.ToString("yyyyMMddHHmmssfff");
for (var i = 0; i < invList.Count; i++)
{
epc_record.Add(new recode_info()
{
LabelType = "件标",
orgId = invList[i].orgizationId,
batchNo = _batch_no,
epc = invList[i].epc,
num = i + 1,
equCode = invList[i].equipmentDetailCode,
equId = invList[i].equipmentDetailId,
sizeCode = invList[i].sizeCode,
equName = invList[i].equipmentDetailName,
isdelete = false,
needNum = 1,
price = Convert.ToSingle(invList[i].price),
productTime = invList[i].productTime,
repairCycle = invList[i].repairCycle,
sizeId = invList[i].sizeId,
sizeName = invList[i].sizeName,
suppilerCode = invList[i].supplierCode,
supplierId = invList[i].supplierId,
suppilerName = invList[i].supplierName,
type = invList[i].sizeEpcType,
useTime = invList[i].useTime,
warehouseId = invList[i].warehouseId,
warehouseName = invList[i].warehouseName,
warrantyCycle = invList[i].warrantyCycle,
createTime = DateTime.Now,
IsUnboxingLabel = true,
ShelfId = invList[i].shelfId,
ShelfRange = invList[i].shelfRange ?? 0,
ShelfRow = invList[i].shelfRow ?? 0,
ShelfColumn = invList[i].shelfColumn ?? 0,
});
}
//更新inbox状态
var res = HttpHelper.UnpackRangeInventory(info.epc, out msg);
if (res)
{
LiteDbHelper.AddRange(epc_record);
LiteDbHelper.DeleteByEpc(info.epc);
OnQuery();
}
else
{
MessageBox.Show("更新状态失败:" + msg);
}
}
}
private void OnGenPrint()
{
var gen = new IntGenEpcWindow(0);
gen.OnRefreshGrid += OnRefreshGridSrc;
gen.ShowDialog();
}
private void OnDeleteTag()
{
var seled = UiPrintList.Where(t => t.IsSelected == true).ToList();
if (seled.Count() > 0)
{
if (seled.Any(x => x.IsReloadBoxing))
{
MessageBox.Show("存在再装箱标签,禁止删除");
return;
}
if (MessageBox.Show("确认删除选中的条记录?", "确认删除", MessageBoxButton.OKCancel, MessageBoxImage.Question) == MessageBoxResult.OK)
{
seled.ForEach(s =>
{
if (s.IsUnboxingLabel)
{
//拆箱生成标签直接报废记录
if (!HttpHelper.DeleteEpc(s.epc, out string msg))
{
MessageBox.Show(msg);
return;
}
}
LiteDbHelper.Delete(s.id);
UiPrintList.Remove(s);
});
if (UiPrintList.Count == 0)
{
OnQuery();
}
IsSelectAll = false;
}
}
}
private void OnRefreshGridSrc()
{
OnQuery();
}
public void OnWindowLoad()
{
OnQuery();
_window.printServerHelper.EnableControlEvent += EnableControl;
_window.printServerHelper.Init();
}
public void OnWindowClosing()
{
}
private void OnQuery()
{
PageIndex = 1;
IsSelectAll = false;
UiPrintList.Clear();
waitDialog = new WaitDialog();
waitDialog.SetToolTop("数据加载中...");
DialogHost.Show(waitDialog, "MainRootDialog",
(obj, args) =>
{
Task.Run(() =>
{
var tmp = LiteDbHelper.GetPage(PageIndex, PageSize, t => t.isdelete == false
&& t.type == 0
&& (string.IsNullOrEmpty(EquName) || t.equName.Contains(EquName))
&& (string.IsNullOrEmpty(VendorName) || t.suppilerName.Contains(VendorName))
&& t.orgId == CaChe.UserInfo.baseJpOrganization.id);
TotalRecord = tmp?.total ?? 0;
PageTotal = TotalRecord == 0 ? 0 : (TotalRecord + PageSize - 1) / PageSize;
App.Current.Dispatcher.BeginInvoke(DispatcherPriority.Normal, (Action)delegate ()
{
UiPrintList?.Clear();
if (tmp?.record != null && tmp?.record.Count > 0)
{
UiPrintList = new ObservableCollection<recode_info>(tmp.record);
}
args.Session.Close();
});
});
},
(obj, args) =>
{
});
}
private void OnPageChange()
{
waitDialog = new WaitDialog();
waitDialog.SetToolTop("数据加载中...");
DialogHost.Show(waitDialog, "MainRootDialog",
(obj, args) =>
{
Task.Run(() =>
{
var tmp = LiteDbHelper.GetPage(PageIndex, PageSize, t => t.isdelete == false
&& t.type == 0
&& (string.IsNullOrEmpty(EquName) || t.equName.Contains(EquName))
&& (string.IsNullOrEmpty(VendorName) || t.suppilerName.Contains(VendorName))
&& t.orgId == CaChe.UserInfo.baseJpOrganization.id);
TotalRecord = tmp?.total ?? 0;
PageTotal = TotalRecord == 0 ? 0 : (TotalRecord + PageSize - 1) / PageSize;
App.Current.Dispatcher.BeginInvoke(DispatcherPriority.Normal, (Action)delegate ()
{
UiPrintList?.Clear();
if (tmp?.record != null && tmp?.record.Count > 0)
{
UiPrintList = new ObservableCollection<recode_info>(tmp.record);
}
args.Session.Close();
});
});
},
(obj, args) =>
{
});
}
private void OnPrintStart()
{
isStop = false;
StopEnable = true;
StartEnable = false;
var print = UiPrintList.Where(t => t.IsSelected == true).ToList();
Task.Run(() =>
{
foreach (var tsk_item in print)
{
if (isStop)
{
break;
}
else
{
var res = false;
if (tsk_item.LabelType == "箱标")
{
//箱标
res = _window.printServerHelper.SendPrintCmd(new SingleInfo()
{
Info1 = tsk_item.equName,
Info2 = tsk_item.sizeName,
Info3 = tsk_item.suppilerName,
Info4 = tsk_item.oneBoxNum.ToString(),
Info5 = tsk_item.num.ToString(),
Info6 = DateTime.Now.ToString("yyyy-MM-dd"),
Info9 = tsk_item.epc.Replace(" ", ""),
ModelType = "pieceXB"
});
}
else
{
//件标
res = _window.printServerHelper.SendPrintCmd(new SingleInfo()
{
Info1 = tsk_item.equName,
Info2 = tsk_item.sizeName,
Info3 = tsk_item.suppilerName,
Info4 = tsk_item.num.ToString(),
Info5 = tsk_item.productTime?.ToString("yyyy-MM-dd"),
Info9 = tsk_item.epc.Replace(" ", ""),
ModelType = "piece"
});
}
if (res)
{
UpdateEpcStateById(tsk_item.id, true);
}
//打印机异常,不继续发指令
else if (!res) { break; }
else { }
}
}
OnPrintStop();
});
}
public void OnPrintStop()
{
StopEnable = false;
StartEnable = true;
isStop = true;
IsSelectAll = false;
if (MsgColor == "Green")
{
//未出现异常
UiMessage = "状态:打印结束";
}
}
/// <summary>
/// 打印成功创建物品进入数据库
/// </summary>
/// <param name="id"></param>
/// <param name="apply"></param>
private void UpdateEpcStateById(int id, bool apply = false)
{
App.Current.Dispatcher.Invoke(() =>
{
var item = UiPrintList.FirstOrDefault(t => t.id == id);
if (item != null)
{
item.isdelete = true;
var flag = true;
if (apply)
{
if (item.LabelType == "箱标")
{
//箱标创建多个物品
var res = HttpHelper.GenerateRangeInventory(item, out string msg);
if (!res)
{
MsgColor = "Red";
UiMessage = msg;
flag = false;
}
else
{
if (msg != "操作成功")
{
MsgColor = "Green";
UiMessage = msg;
}
flag = LiteDbHelper.Update(item.id);
}
}
else
{
//件标
var res = HttpHelper.GenerateInventory(item, out string msg);
if (!res)
{
MsgColor = "Red";
UiMessage = "写入入库记录失败:" + msg;
flag = false;
}
else
{
flag = LiteDbHelper.Update(item.id);
}
}
}
if (flag)
{
UiPrintList.Remove(item);
TotalRecord -= 1;
if (UiPrintList.Count == 0)
{
PageIndex = 1;
OnPageChange();
}
}
}
});
}
public void EnableControl(bool flag, bool startEnable, bool stopEnable, string msg = "")
{
StartEnable = startEnable;
StopEnable = stopEnable;
if (!string.IsNullOrEmpty(msg))
{
UiMessage = "状态:" + msg;
MsgColor = flag ? "Green" : "Red";
}
}
public void SelectAll()
{
App.Current.Dispatcher.Invoke(() =>
{
foreach (var item in UiPrintList)
{
item.IsSelected = _isSelectAll;
}
this.RaisePropertyChanged(() => UiPrintList);
});
}
public override void Cleanup()
{
base.Cleanup();
isStop = true;
_window.printServerHelper.EnableControlEvent -= EnableControl;
NetworkComms.Shutdown();
}
#endregion
}
}
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using GalaSoft.MvvmLight.Messaging;
using JmpZbModel;
using JmpZbModel.Model;
using JmpZbModel.UsControl;
using JmpZbPrint.Common;
using JmpZbPrint.Model;
using JmpZbPrint.UsControl;
using LiteDB;
using MaterialDesignThemes.Wpf;
using NetworkCommsDotNet;
using NetworkCommsDotNet.Connections;
using NetworkCommsDotNet.Connections.TCP;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
//using rfidLink.Extend;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Diagnostics.Eventing.Reader;
using System.Globalization;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Runtime.Remoting.Metadata.W3cXsd2001;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;
using System.Windows.Media.Animation;
using System.Windows.Threading;
using WebSocketSharp;
namespace JmpZbPrint.ViewModel
{
public class MainViewModel : ViewModelBase
{
public MainViewModel()
{
}
}
}
\ No newline at end of file
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using JmpZbPrint.Model;
using JmpZbPrint.PagePartial;
using JmpZbPrint.UsControl;
using MaterialDesignThemes.Wpf;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Threading;
namespace JmpZbPrint.ViewModel
{
public class PrintLogWindowViewModel : ViewModelBase
{
public PrintLogWindowViewModel()
{
OnQueryCommand = new RelayCommand(OnQuery);
OnPageChangeCmd = new RelayCommand(OnPageChange);
OnWindowLoadCmd = new RelayCommand(OnWindowLoad);
}
#region filed
private List<PrintLog> PrintInfoDataList = new List<PrintLog>();
private ObservableCollection<PrintLog> _printInfoList = new ObservableCollection<PrintLog>();
public ObservableCollection<PrintLog> UiPrintInfoList
{
get { return _printInfoList; }
set
{
//PageTotal = GetPageTotal(value.Where(t => t.Status == "未打印").Count());
//TotalRecord = value.Count;
_printInfoList = value;
RaisePropertyChanged();
}
}
private WaitDialog waitDialog = default;
private int _total = 0;
public int TotalRecord
{
get { return _total; }
set
{
_total = value;
RaisePropertyChanged();
}
}
private int _page = 0;
public int PageIndex
{
get { return _page; }
set
{
_page = value;
RaisePropertyChanged();
}
}
private int _pageTotal = 0;
public int PageTotal
{
get { return _pageTotal; }
set
{
_pageTotal = value;
RaisePropertyChanged();
}
}
private int _pageSize = 20;
public int PageSize
{
get { return _pageSize; }
set
{
_pageSize = value;
RaisePropertyChanged();
}
}
private int _saveLogCount = 1000;
#endregion
#region cmd attr
public RelayCommand OnWindowLoadCmd { get; set; }
public RelayCommand OnQueryCommand { get; set; }
public RelayCommand OnPageChangeCmd { get; set; }
#endregion
#region method
public void OnWindowLoad()
{
PrintInfoDataList = new List<PrintLog>();
if (System.IO.File.Exists(AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "PrintLog.json"))
{
var arr = System.IO.File.ReadAllLines(AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "PrintLog.json", Encoding.UTF8);
var count = 0;
for (int i = arr.Length - 1; i >= 0; i--)
{
string str = arr[i];
if (string.IsNullOrEmpty(str))
{
continue;
}
count++;
if (count > _saveLogCount)
{
//处理日志文件
System.IO.File.WriteAllLines(AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "PrintLog.json", arr.Skip(arr.Length - _saveLogCount), Encoding.UTF8);
break;
}
try
{
PrintInfoDataList.Add(JsonConvert.DeserializeObject<PrintLog>(str));
}
catch (Exception)
{
//转换错误,过滤
continue;
}
}
}
OnQuery();
}
public void OnWindowClosing()
{
}
private void OnQuery()
{
PageIndex = 1;
UiPrintInfoList.Clear();
waitDialog = new WaitDialog();
waitDialog.SetToolTop("数据加载中...");
DialogHost.Show(waitDialog, "PrintLogDialog",
(obj, args) =>
{
Task.Run(() =>
{
var tmp = PrintInfoDataList;
TotalRecord = tmp?.Count ?? 0;
PageTotal = TotalRecord == 0 ? 0 : (TotalRecord + PageSize - 1) / PageSize;
App.Current.Dispatcher.BeginInvoke(DispatcherPriority.Normal, (Action)delegate ()
{
UiPrintInfoList?.Clear();
if (tmp != null && tmp.Count > 0)
{
UiPrintInfoList = new ObservableCollection<PrintLog>(PrintInfoDataList.Skip((PageIndex - 1) * PageSize).Take(PageSize));
}
args.Session.Close();
});
});
},
(obj, args) =>
{
});
}
private void OnPageChange()
{
waitDialog = new WaitDialog();
waitDialog.SetToolTop("数据加载中...");
DialogHost.Show(waitDialog, "PrintLogDialog",
(obj, args) =>
{
Task.Run(() =>
{
var tmp = PrintInfoDataList;
TotalRecord = tmp?.Count ?? 0;
PageTotal = TotalRecord == 0 ? 0 : (TotalRecord + PageSize - 1) / PageSize;
App.Current.Dispatcher.BeginInvoke(DispatcherPriority.Normal, (Action)delegate ()
{
UiPrintInfoList?.Clear();
if (tmp != null && tmp.Count > 0)
{
UiPrintInfoList = new ObservableCollection<PrintLog>(PrintInfoDataList.Skip((PageIndex - 1) * PageSize).Take(PageSize));
}
args.Session.Close();
});
});
},
(obj, args) =>
{
});
}
#endregion
}
}
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using JmpZbModel;
using JmpZbPrint.Model;
using JmpZbPrint.UsControl;
using MaterialDesignThemes.Wpf;
using NetworkCommsDotNet;
using NetworkCommsDotNet.Connections;
using NetworkCommsDotNet.Connections.TCP;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Threading;
using JmpZbPrint.Common;
using JmpZbPrint.Dialog;
using JmpZbPrint.View;
namespace JmpZbPrint.ViewModel
{
public class TagBagPrinViewModel : ViewModelBase
{
private MainWindow _window;
public TagBagPrinViewModel(MainWindow window)
{
_window = window;
OnStartPrintItemsCmd = new RelayCommand(OnPrintStart);
OnStopPrintItemsCmd = new RelayCommand(OnPrintStop);
OnQueryCommand = new RelayCommand(OnQuery);
OnPageChangeCmd = new RelayCommand(OnPageChange);
OnGenTagCmd = new RelayCommand(OnGenTag);
OnWindowLoadCmd = new RelayCommand(OnWindowLoad);
}
#region filed
private WaitDialog waitDialog = default;
private bool isStop = false;
private ObservableCollection<print_info> _printList = new ObservableCollection<print_info>();
public ObservableCollection<print_info> UiPrintList
{
get { return _printList; }
set
{
_printList = value;
RaisePropertyChanged();
}
}
private string _equName;
public string EquName
{
get { return _equName; }
set
{
_equName = value;
RaisePropertyChanged();
}
}
private string _vendorName;
public string VendorName
{
get { return _vendorName; }
set
{
_vendorName = value;
RaisePropertyChanged();
}
}
private int _epcType;
public int EpcType
{
get { return _epcType; }
set
{
_epcType = value;
RaisePropertyChanged();
}
}
private string _message = "状态:打印机初始化中";
public string UiMessage
{
get { return _message; }
set
{
_message = value;
RaisePropertyChanged();
}
}
private string _msgccolor = "Green";
public string MsgColor
{
get { return _msgccolor; }
set
{
_msgccolor = value;
RaisePropertyChanged();
}
}
private bool _bindButton = false;
public bool BindButton
{
get { return _bindButton; }
set
{
_bindButton = value;
RaisePropertyChanged();
}
}
private int _total = 0;
public int TotalRecord
{
get { return _total; }
set
{
_total = value;
RaisePropertyChanged();
}
}
private int _page = 0;
public int PageIndex
{
get { return _page; }
set
{
_page = value;
RaisePropertyChanged();
}
}
private int _pageTotal = 0;
public int PageTotal
{
get { return _pageTotal; }
set
{
_pageTotal = value;
RaisePropertyChanged();
}
}
private int _pageSize = 50;
public int PageSize
{
get { return _pageSize; }
set
{
_pageSize = value;
RaisePropertyChanged();
}
}
private bool _startEnable = false;
public bool StartEnable
{
get { return _startEnable; }
set
{
_startEnable = value;
RaisePropertyChanged();
}
}
private bool _stopEnable = false;
public bool StopEnable
{
get { return _stopEnable; }
set
{
_stopEnable = value;
RaisePropertyChanged();
}
}
private bool _isSelectAll = false;
public bool IsSelectAll
{
get { return _isSelectAll; }
set
{
_isSelectAll = value;
RaisePropertyChanged();
SelectAll();
}
}
#endregion
#region cmd attr
public RelayCommand OnStartPrintItemsCmd { get; set; }
public RelayCommand OnStopPrintItemsCmd { get; set; }
public RelayCommand OnWindowLoadCmd { get; set; }
public RelayCommand OnQueryCommand { get; set; }
public RelayCommand OnPageChangeCmd { get; set; }
public RelayCommand OnGenTagCmd { get; set; }
public RelayCommand OnWindowClosingCmd { get; set; }
#endregion
#region method
public void OnWindowLoad()
{
OnQuery();
_window.printServerHelper.EnableControlEvent += EnableControl;
_window.printServerHelper.Init();
}
private void OnQuery()
{
PageIndex = 1;
IsSelectAll = false;
UiPrintList.Clear();
waitDialog = new WaitDialog();
waitDialog.SetToolTop("数据加载中...");
DialogHost.Show(waitDialog, "MainRootDialog",
(obj, args) =>
{
Task.Run(() =>
{
var tmp = HttpHelper.GetPrintBagList(CaChe.UserInfo.baseJpOrganization.id, EquName, out string msg);
//TotalRecord = tmp?.total ?? 0;
//PageTotal = TotalRecord == 0 ? 0 : (TotalRecord + PageSize - 1) / PageSize;
App.Current.Dispatcher.BeginInvoke(DispatcherPriority.Normal, (Action)delegate ()
{
UiPrintList?.Clear();
//if (tmp?.record != null && tmp?.record.Count > 0)
if (tmp.Item1 && tmp.Item2.Count > 0)
{
var list = tmp.Item2;
UiPrintList = new ObservableCollection<print_info>(new List<print_info>(
list.Select(x => new print_info()
{
LabelType = "装备包",
epc = x.epc,
id = x.id,
warehouseName = x.warehouseName,
warehouseId = x.warehouseId,
productTime = x.createTime.ToString("yyyy-MM-dd"),
bagName = x.bagName,
number = x.number.ToString(),
oneBoxNum = x.oneBoxNum,
invInfo = x.invInfo
})));
}
args.Session.Close();
});
});
},
(obj, args) =>
{
});
}
private void OnPageChange()
{
return;
waitDialog = new WaitDialog();
waitDialog.SetToolTop("数据加载中...");
DialogHost.Show(waitDialog, "MainRootDialog",
(obj, args) =>
{
Task.Run(() =>
{
var tmp = HttpHelper.GetPrintList(EpcType, LabelType.打印, PageIndex, VendorName, EquName);
TotalRecord = tmp?.total ?? 0;
PageTotal = TotalRecord == 0 ? 0 : (TotalRecord + PageSize - 1) / PageSize;
App.Current.Dispatcher.BeginInvoke(DispatcherPriority.Normal, (Action)delegate ()
{
UiPrintList?.Clear();
if (tmp?.record != null && tmp?.record.Count > 0)
{
UiPrintList = new ObservableCollection<print_info>(tmp.record);
}
args.Session.Close();
});
});
},
(obj, args) =>
{
});
}
private void OnGenTag()
{
}
private void OnPrintStart()
{
isStop = false;
StopEnable = true;
StartEnable = false;
var print = UiPrintList.Where(t => t.IsSelected == true).ToList();
Task.Run(() =>
{
foreach (var tsk_item in print)
{
if (isStop)
{
break;
}
else
{
//tmp_id = tsk_item.Id;
var res = _window.printServerHelper.SendPrintCmd(new SingleInfo()
{
Info1 = tsk_item.bagName,
//Info2 = tsk_item.sizeName,
//Info3 = tsk_item.supplierName,
Info4 = tsk_item.oneBoxNum.ToString(),
Info5 = tsk_item.number.ToString(),
Info6 = tsk_item.productTime,
Info9 = tsk_item.epc.Replace(" ", ""),
ModelType = "pieceBag"
});
if (res)
{
UpdateEpcStateById(tsk_item.id.Replace(" ", ""), true);
}
//打印机异常,不继续发指令
else if (!res) { break; }
else { }
}
}
OnPrintStop();
});
}
public void OnPrintStop()
{
StopEnable = false;
StartEnable = true;
isStop = true;
}
private void UpdateEpcStateById(string id, bool apply = false)
{
App.Current.Dispatcher.Invoke(() =>
{
var item = UiPrintList.FirstOrDefault(t => t.id.Contains(id));
if (item != null)
{
item.state = 1;
Tuple<bool, string> flagData = new Tuple<bool, string>(true, "");
if (apply)
{
//装备包打印成功
var res = HttpHelper.UpdateBagState(id, out string msg);
flagData = new Tuple<bool, string>(res, msg);
}
if (flagData.Item1)
{
UiPrintList.Remove(item);
LiteDbHelper.DeleteByEpc(item.epc);
TotalRecord -= 1;
if (UiPrintList.Count == 0)
{
PageIndex = 1;
OnPageChange();
}
}
else
{
//EPC状态更新失败
UiMessage = flagData.Item2;
MsgColor = "Red";
}
}
});
}
public void EnableControl(bool flag, bool startEnable, bool stopEnable, string msg = "")
{
StartEnable = startEnable;
StopEnable = stopEnable;
if (!string.IsNullOrEmpty(msg))
{
UiMessage = "状态:" + msg;
MsgColor = flag ? "Green" : "Red";
}
}
public void SelectAll()
{
App.Current.Dispatcher.Invoke(() =>
{
foreach (var item in UiPrintList)
{
item.IsSelected = _isSelectAll;
}
this.RaisePropertyChanged(() => UiPrintList);
});
}
public override void Cleanup()
{
base.Cleanup();
isStop = true;
_window.printServerHelper.EnableControlEvent -= EnableControl;
NetworkComms.Shutdown();
}
#endregion
}
}
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using JmpZbModel;
using JmpZbPrint.Model;
using JmpZbPrint.UsControl;
using MaterialDesignThemes.Wpf;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Threading;
using JmpZbPrint.Common;
using WebSocketSharp;
namespace JmpZbPrint.ViewModel
{
public class TagBindViewModel : ViewModelBase
{
public TagBindViewModel()
{
OnQueryCommand = new RelayCommand(OnQuery);
OnPageChangeCmd = new RelayCommand(OnPageChange);
OnWindowLoadCmd = new RelayCommand(OnWindowLoad);
OnInitialTagCmd = new RelayCommand<print_info>(OnInitialTag);
OnBoxingCmd = new RelayCommand(OnBoxing);
}
#region filed
private ObservableCollection<print_info> _printList = new ObservableCollection<print_info>();
public ObservableCollection<print_info> BindTaskList
{
get { return _printList; }
set
{
_printList = value;
RaisePropertyChanged();
}
}
public AutoResetEvent resetEvent = new AutoResetEvent(false);
private string _equName;
public string EquName
{
get { return _equName; }
set
{
_equName = value;
RaisePropertyChanged();
}
}
private string _vendorName;
public string VendorName
{
get { return _vendorName; }
set
{
_vendorName = value;
RaisePropertyChanged();
}
}
private int _epcType;
public int EpcType
{
get { return _epcType; }
set
{
_epcType = value;
RaisePropertyChanged();
}
}
private string _message = "状态:初始化设备连接准备中";
public string UiMessage
{
get { return _message; }
set
{
_message = value;
RaisePropertyChanged();
}
}
private string _msgccolor = "Green";
public string MsgColor
{
get { return _msgccolor; }
set
{
_msgccolor = value;
RaisePropertyChanged();
}
}
private bool _bindButton = false;
public bool BindButton
{
get { return _bindButton; }
set
{
_bindButton = value;
RaisePropertyChanged();
}
}
private int _total = 0;
public int TotalRecord
{
get { return _total; }
set
{
_total = value;
RaisePropertyChanged();
}
}
private int _page = 0;
public int PageIndex
{
get { return _page; }
set
{
_page = value;
RaisePropertyChanged();
}
}
private int _pageTotal = 0;
public int PageTotal
{
get { return _pageTotal; }
set
{
_pageTotal = value;
RaisePropertyChanged();
}
}
private int _pageSize = 50;
public int PageSize
{
get { return _pageSize; }
set
{
_pageSize = value;
RaisePropertyChanged();
}
}
private bool _isSelectAll = false;
public bool IsSelectAll
{
get { return _isSelectAll; }
set
{
_isSelectAll = value;
RaisePropertyChanged();
SelectAll();
}
}
#endregion
#region cmd attr
public RelayCommand OnWindowLoadCmd { get; set; }
public RelayCommand OnQueryCommand { get; set; }
public RelayCommand OnPageChangeCmd { get; set; }
public RelayCommand OnGenTagCmd { get; set; }
public RelayCommand<print_info> OnInitialTagCmd { get; set; }
public RelayCommand OnBoxingCmd { get; set; }
#endregion
#region method
private void OnBoxing()
{
var seled = BindTaskList.Where(t => t.IsSelected == true).ToList();
if (seled.Count > 0)
{
if (seled.Any(x => x.LabelType == "箱标"))
{
MessageBox.Show("禁止箱标装箱");
return;
}
var havePurchaseLabel = seled.Any(x => x.isUnboxingLabel == false);
if (MessageBox.Show("确认装箱选中的记录?" + (havePurchaseLabel ? "存在采购件标,将直接录入主平台。" : ""), "确认装箱", MessageBoxButton.OKCancel, MessageBoxImage.Question) ==
MessageBoxResult.OK)
{
//判断物资一致性
var info = seled.First();
if (seled.Any(x => x.productId != info.productId))
{
MessageBox.Show("物资类型不一致,无法装箱");
return;
}
if (seled.Any(x => x.sizeId != info.sizeId))
{
MessageBox.Show("物资型号不一致,无法装箱");
return;
}
if (seled.Any(x => x.supplierId != info.supplierId))
{
MessageBox.Show("供应商不一致,无法装箱");
return;
}
if (seled.Any(x => x.warehouseId != info.warehouseId))
{
MessageBox.Show("入库仓库不一致,无法装箱");
return;
}
//创建箱标epc
var boxRequest = new request_int_info()
{
labelType = "箱标",
equCode = info.productNo,
productTime = Convert.ToDateTime(info.productTime),
sizeCode = info.sizeCode,
oneBoxNum = seled.Count,
quantity = 1,
supplierCode = info.supplierCode,
warrantyCycle = Convert.ToInt32(info.warrantyCycle)
};
var boxRes = HttpHelper.GenerateIntTagEpc(boxRequest, out string boxMsg);
if (!boxRes.Item1)
{
MessageBox.Show($"[{info.productName}-{info.sizeName}] 箱标生成失败,原因:{boxMsg}", "提示", MessageBoxButton.OK, MessageBoxImage.Error);
return;
}
var xbEpc = boxRes.Item2.First().epc;
var res = HttpHelper.BoxingInventoryNormalVersion(xbEpc, seled, out string msg);
if (res)
{
var _batch_no = DateTime.Now.ToString("yyyyMMddHHmmssfff");
foreach (var obj in seled)
{
LiteDbHelper.DeleteByEpc(obj.epc);
}
//不添加箱标记录进litedb
}
else
{
MessageBox.Show(msg);
}
OnQuery();
}
}
}
private WaitDialog waitDialog = default;
public void OnWindowLoad()
{
InitWs();
OnQuery();
}
public void OnWindowClosing()
{
}
private void OnQuery()
{
BindTaskList.Clear();
PageIndex = 1;
waitDialog = new WaitDialog();
waitDialog.SetToolTop("数据加载中...");
DialogHost.Show(waitDialog, "MainRootDialog",
(obj, args) =>
{
Task.Run(() =>
{
var tmp = HttpHelper.GetPrintList(EpcType, LabelType.初始化, PageIndex, VendorName, EquName);
TotalRecord = tmp?.total ?? 0;
PageTotal = TotalRecord == 0 ? 0 : (TotalRecord + PageSize - 1) / PageSize;
App.Current.Dispatcher.BeginInvoke(DispatcherPriority.Normal, (Action)delegate ()
{
BindTaskList?.Clear();
if (tmp?.record != null && tmp?.record.Count > 0)
{
BindTaskList = new ObservableCollection<print_info>(tmp.record);
}
args.Session.Close();
});
});
},
(obj, args) =>
{
});
}
private void OnPageChange()
{
waitDialog = new WaitDialog();
waitDialog.SetToolTop("数据加载中...");
DialogHost.Show(waitDialog, "MainRootDialog",
(obj, args) =>
{
Task.Run(() =>
{
var tmp = HttpHelper.GetPrintList(EpcType, LabelType.初始化, PageIndex, VendorName, EquName);
TotalRecord = tmp?.total ?? 0;
PageTotal = TotalRecord == 0 ? 0 : (TotalRecord + PageSize - 1) / PageSize;
App.Current.Dispatcher.BeginInvoke(DispatcherPriority.Normal, (Action)delegate ()
{
BindTaskList?.Clear();
if (tmp?.record != null && tmp?.record.Count > 0)
{
BindTaskList = new ObservableCollection<print_info>(tmp.record);
}
args.Session.Close();
});
});
},
(obj, args) =>
{
});
}
public void SelectAll()
{
App.Current.Dispatcher.Invoke(() =>
{
foreach (var item in BindTaskList)
{
item.IsSelected = _isSelectAll;
}
this.RaisePropertyChanged(() => BindTaskList);
});
}
public override void Cleanup()
{
base.Cleanup();
resetEvent.Set();
cWsServiceToken?.Cancel();
wsConn?.Close();
}
#endregion
#region tcp method
public CancellationTokenSource cWsServiceToken;
public Task taskWsService;
public WebSocket wsConn;
private ManualResetEvent resetUhf = new ManualResetEvent(true);
private string tmpEpc = "";
public void InitWs()
{
if (taskWsService == null)
{
cWsServiceToken = new CancellationTokenSource();
taskWsService = new Task(() =>
{
wsConn = new WebSocket("ws://127.0.0.1:8081");
while (!cWsServiceToken.IsCancellationRequested)
{
try
{
// 已连接的不处理
if (wsConn.IsAlive)
{
}
else
{
// 接收数据
wsConn.OnMessage += (sender, e) =>
{
ReciveWsMsg(e.Data);
};
// 服务关闭
wsConn.OnClose += (sender, e) =>
{
UiMessage = $"状态:服务已断开,重连中";
MsgColor = "Red";
BindButton = false;
};
wsConn.OnOpen += (sender, e) =>
{
UiMessage = $"状态:正在查询设备状态";
MsgColor = "Green";
BindButton = true;
};
// 服务连接
wsConn.Connect();
}
}
catch (System.Exception ex)
{
UiMessage = $"状态:初始化设备连接失败";
MsgColor = "Red";
BindButton = false;
Log.ErrorLog(ex.ToString(), this.GetType().Name);
}
if (resetEvent.WaitOne(3000)) { break; }
}
});
taskWsService.Start();
}
}
private void ReciveWsMsg(string msg)
{
var cmdInfo = JsonConvert.DeserializeObject<InitializeCmdInfo>(msg);
switch (cmdInfo.CmdType)
{
case JmpUhfService.InitializeCmdType.Busy:
UiMessage = $"状态:设备正忙,请检查设备是否被占用";
MsgColor = "Red";
BindButton = false;
resetUhf.Set();
break;
case JmpUhfService.InitializeCmdType.Initialize:
if (msg.Contains("成功"))
{
UiMessage = $"状态:数据绑定成功";
MsgColor = "Green";
resetUhf.Set();
BindButton = true;
//更新状态
UpdateEpcStateByEpc(cmdInfo.Content.Replace("成功", "").Replace(" ", ""), true);
}
else
{
BindButton = true;
UiMessage = $"状态:{cmdInfo.Content}";
MsgColor = "Red";
resetUhf.Set();
}
break;
case JmpUhfService.InitializeCmdType.Linked:
UiMessage = $"状态:初始化设备已连接";
MsgColor = "Green";
resetUhf.Set();
BindButton = true;
break;
case JmpUhfService.InitializeCmdType.ErrorMsg:
UiMessage = $"状态:{cmdInfo.Content}";
MsgColor = "Red";
resetUhf.Set();
BindButton = false;
break;
case JmpUhfService.InitializeCmdType.ReadInventorySingle:
tmpEpc = cmdInfo.Content;
resetUhf.Set();
BindButton = false;
break;
case JmpUhfService.InitializeCmdType.ReadInventorySingleError:
UiMessage = $"状态:{cmdInfo.Content}";
MsgColor = "Red";
resetUhf.Set();
BindButton = true;
break;
default:
resetUhf.Set();
break;
}
}
private void UpdateEpcStateByEpc(string epc, bool apply = false)
{
App.Current.Dispatcher.Invoke(() =>
{
var item = BindTaskList.FirstOrDefault(t => t.epc.Contains(epc));
if (item != null)
{
item.state = 1;
Tuple<bool, string> flagData = new Tuple<bool, string>(true, "");
if (apply)
{
if (item.isUnboxingLabel)
{
var res = HttpHelper.GenerateInventory(new recode_info
{
sizeId = item.sizeId,
equId = item.productId,
epc = item.epc,
supplierId = item.supplierId,
warehouseId = item.warehouseId,
productTime = Convert.ToDateTime(item.productTime),
useTime = Convert.ToDateTime(item.useTime),
warrantyCycle = Convert.ToInt32(item.warrantyCycle),
price = Convert.ToSingle(item.price),
repairCycle = Convert.ToInt32(item.repairCycle),
IsUnboxingLabel = item.isUnboxingLabel
}, out string msg);
flagData = new Tuple<bool, string>(res, msg);
}
else
{
flagData = HttpHelper.UpdateEpc(item.id);
}
}
if (flagData.Item1)
{
BindTaskList.Remove(item);
LiteDbHelper.DeleteByEpc(item.epc);
RaisePropertyChanged(() => BindTaskList);
TotalRecord -= 1;
if (BindTaskList.Count == 0)
{
PageIndex = 1;
OnPageChange();
}
}
else
{
//EPC状态更新失败
UiMessage = flagData.Item2;
MsgColor = "Red";
}
}
});
}
public async void OnInitialTag(print_info entity)
{
try
{
BindButton = false;
UiMessage = "状态:绑定中";
MsgColor = "Green";
await Dispatcher.Yield();
if (ReadInventorySingle())
{
resetUhf.Reset();
resetUhf.WaitOne(3000);
//判断epc是否已被绑过装备
if (!string.IsNullOrEmpty(tmpEpc))
{
if (HttpHelper.CheckEpcIsInstantiation(tmpEpc, out string msg))
{
if (SendInitialMsg(entity.epc))
{
resetUhf.Reset();
resetUhf.WaitOne(3000);
}
}
else
{
BindButton = true;
UiMessage = "状态:绑定失败," + msg;
MsgColor = "Red";
}
tmpEpc = "";
}
}
else
{
BindButton = true;
UiMessage = "状态:绑定失败,设备异常";
MsgColor = "Red";
}
}
catch (Exception ex)
{
BindButton = true;
tmpEpc = "";
Log.ErrorLog(ex.ToString(), MethodBase.GetCurrentMethod().Name);
}
}
private bool ReadInventorySingle()
{
try
{
var json = JsonConvert.SerializeObject(new
{
CmdType = 7,
Content = ""
});
if (wsConn?.IsAlive ?? false)
{
wsConn.Send(json);
return true;
}
else
{
return false;
}
}
catch (Exception ex)
{
Log.ErrorLog(ex.ToString(), MethodBase.GetCurrentMethod().Name);
return false;
}
}
private bool SendInitialMsg(string epc, ushort len = 17, ushort offset = 1, string password = "00000000")
{
try
{
var epc_data = JsonConvert.SerializeObject(new
{
Epc = epc,
Len = len,
Offset = offset,
Password = password
});
var json = JsonConvert.SerializeObject(new
{
CmdType = 8,
Content = epc_data
});
if (wsConn?.IsAlive ?? false)
{
wsConn.Send(json);
return true;
}
else
{
return false;
}
}
catch (Exception ex)
{
Log.ErrorLog(ex.ToString(), MethodBase.GetCurrentMethod().Name);
return false;
}
}
#endregion
}
}
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using JmpZbModel;
using JmpZbPrint.Model;
using JmpZbPrint.UsControl;
using MaterialDesignThemes.Wpf;
using NetworkCommsDotNet;
using NetworkCommsDotNet.Connections;
using NetworkCommsDotNet.Connections.TCP;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Threading;
using JmpZbPrint.Common;
using JmpZbPrint.Dialog;
using JmpZbPrint.View;
namespace JmpZbPrint.ViewModel
{
public class TagBoxPrinViewModel : ViewModelBase
{
private MainWindow _window;
public TagBoxPrinViewModel(MainWindow window)
{
_window = window;
OnStartPrintItemsCmd = new RelayCommand(OnPrintStart);
OnStopPrintItemsCmd = new RelayCommand(OnPrintStop);
OnQueryCommand = new RelayCommand(OnQuery);
OnPageChangeCmd = new RelayCommand(OnPageChange);
OnGenTagCmd = new RelayCommand(OnGenTag);
OnWindowLoadCmd = new RelayCommand(OnWindowLoad);
OnUnboxingCmd = new RelayCommand(OnUnboxing);
}
#region filed
private WaitDialog waitDialog = default;
private bool isStop = false;
private ObservableCollection<print_info> _printList = new ObservableCollection<print_info>();
public ObservableCollection<print_info> UiPrintList
{
get { return _printList; }
set
{
_printList = value;
RaisePropertyChanged();
}
}
private string _equName;
public string EquName
{
get { return _equName; }
set
{
_equName = value;
RaisePropertyChanged();
}
}
private string _vendorName;
public string VendorName
{
get { return _vendorName; }
set
{
_vendorName = value;
RaisePropertyChanged();
}
}
private int _epcType;
public int EpcType
{
get { return _epcType; }
set
{
_epcType = value;
RaisePropertyChanged();
}
}
private string _message = "状态:打印机初始化中";
public string UiMessage
{
get { return _message; }
set
{
_message = value;
RaisePropertyChanged();
}
}
private string _msgccolor = "Green";
public string MsgColor
{
get { return _msgccolor; }
set
{
_msgccolor = value;
RaisePropertyChanged();
}
}
private bool _bindButton = false;
public bool BindButton
{
get { return _bindButton; }
set
{
_bindButton = value;
RaisePropertyChanged();
}
}
private int _total = 0;
public int TotalRecord
{
get { return _total; }
set
{
_total = value;
RaisePropertyChanged();
}
}
private int _page = 0;
public int PageIndex
{
get { return _page; }
set
{
_page = value;
RaisePropertyChanged();
}
}
private int _pageTotal = 0;
public int PageTotal
{
get { return _pageTotal; }
set
{
_pageTotal = value;
RaisePropertyChanged();
}
}
private int _pageSize = 50;
public int PageSize
{
get { return _pageSize; }
set
{
_pageSize = value;
RaisePropertyChanged();
}
}
private bool _startEnable = false;
public bool StartEnable
{
get { return _startEnable; }
set
{
_startEnable = value;
RaisePropertyChanged();
}
}
private bool _stopEnable = false;
public bool StopEnable
{
get { return _stopEnable; }
set
{
_stopEnable = value;
RaisePropertyChanged();
}
}
private bool _isSelectAll = false;
public bool IsSelectAll
{
get { return _isSelectAll; }
set
{
_isSelectAll = value;
RaisePropertyChanged();
SelectAll();
}
}
#endregion
#region cmd attr
public RelayCommand OnStartPrintItemsCmd { get; set; }
public RelayCommand OnStopPrintItemsCmd { get; set; }
public RelayCommand OnWindowLoadCmd { get; set; }
public RelayCommand OnQueryCommand { get; set; }
public RelayCommand OnPageChangeCmd { get; set; }
public RelayCommand OnGenTagCmd { get; set; }
public RelayCommand OnWindowClosingCmd { get; set; }
public RelayCommand OnUnboxingCmd { get; set; }
#endregion
#region method
/// <summary>
/// 拆箱
/// </summary>
private void OnUnboxing()
{
var selectBox = new SelectBoxEpc();
selectBox.ShowDialog();
var info = selectBox.RecodeInfo;
if (info != null)
{
//拆箱
List<recode_info> epc_record = new List<recode_info>();
var epcListRes = HttpHelper.GetInventoryListByBoxMarkEpc(info.epc, out var msg);
if (!epcListRes.Item1)
{
MessageBox.Show("获取件标失败:" + msg);
return;
}
var invList = epcListRes.Item2;
var _batch_no = DateTime.Now.ToString("yyyyMMddHHmmssfff");
for (var i = 0; i < invList.Count; i++)
{
epc_record.Add(new recode_info()
{
LabelType = "件标",
orgId = invList[i].orgizationId,
batchNo = _batch_no,
epc = invList[i].epc,
num = i + 1,
equCode = invList[i].equipmentDetailCode,
equId = invList[i].equipmentDetailId,
sizeCode = invList[i].sizeCode,
equName = invList[i].equipmentDetailName,
isdelete = false,
needNum = 1,
price = Convert.ToSingle(invList[i].price),
productTime = invList[i].productTime,
repairCycle = invList[i].repairCycle,
sizeId = invList[i].sizeId,
sizeName = invList[i].sizeName,
suppilerCode = invList[i].supplierCode,
supplierId = invList[i].supplierId,
suppilerName = invList[i].supplierName,
type = invList[i].sizeEpcType,
useTime = invList[i].useTime,
warehouseId = invList[i].warehouseId,
warehouseName = invList[i].warehouseName,
warrantyCycle = invList[i].warrantyCycle,
createTime = DateTime.Now,
IsUnboxingLabel = true
});
}
//更新inbox状态
var res = HttpHelper.UnpackRangeInventory(info.epc, out msg);
if (res)
{
//不录入本地数据库
//LiteDbHelper.AddRange(epc_record);
LiteDbHelper.DeleteByEpc(info.epc);
OnQuery();
}
else
{
MessageBox.Show("更新状态失败:" + msg);
}
}
}
public void OnWindowLoad()
{
OnQuery();
_window.printServerHelper.EnableControlEvent += EnableControl;
_window.printServerHelper.Init();
}
private void OnQuery()
{
PageIndex = 1;
IsSelectAll = false;
UiPrintList.Clear();
waitDialog = new WaitDialog();
waitDialog.SetToolTop("数据加载中...");
DialogHost.Show(waitDialog, "MainRootDialog",
(obj, args) =>
{
Task.Run(() =>
{
var tmp = HttpHelper.GetNeedPrintBoxMarkList(CaChe.UserInfo.baseJpOrganization.id, out string msg);
//TotalRecord = tmp?.total ?? 0;
//PageTotal = TotalRecord == 0 ? 0 : (TotalRecord + PageSize - 1) / PageSize;
App.Current.Dispatcher.BeginInvoke(DispatcherPriority.Normal, (Action)delegate ()
{
UiPrintList?.Clear();
//if (tmp?.record != null && tmp?.record.Count > 0)
if (tmp.Item1 && tmp.Item2.Count > 0)
{
var list = tmp.Item2;
if (!string.IsNullOrEmpty(EquName))
{
list = list.Where(x => x.equipmentDetailName.Contains(EquName)).ToList();
}
if (!string.IsNullOrEmpty(VendorName))
{
list = list.Where(x => x.supplierName.Contains(VendorName)).ToList();
}
UiPrintList = new ObservableCollection<print_info>(new List<print_info>(
list.Select(x => new print_info()
{
LabelType = "箱标",
epc = x.epc,
id = x.id,
warehouseName = x.warehouseName,
warehouseId = x.warehouseId,
productName = x.equipmentDetailName,
productId = x.equipmentDetailId,
sizeName = x.sizeName,
sizeId = x.sizeId,
productTime = x.productTime,
useTime = x.useTime,
pieceNo = "1",
warrantyCycle = x.warrantyCycle,
repairCycle = x.repairCycle,
price = x.price,
supplierName = x.supplierName,
supplierId = x.supplierId,
oneBoxNum = x.oneBoxNum,
epcListJson = JsonConvert.SerializeObject(x.epcList)
})));
}
args.Session.Close();
});
});
},
(obj, args) =>
{
});
}
private void OnPageChange()
{
return;
waitDialog = new WaitDialog();
waitDialog.SetToolTop("数据加载中...");
DialogHost.Show(waitDialog, "MainRootDialog",
(obj, args) =>
{
Task.Run(() =>
{
var tmp = HttpHelper.GetPrintList(EpcType, LabelType.打印, PageIndex, VendorName, EquName);
TotalRecord = tmp?.total ?? 0;
PageTotal = TotalRecord == 0 ? 0 : (TotalRecord + PageSize - 1) / PageSize;
App.Current.Dispatcher.BeginInvoke(DispatcherPriority.Normal, (Action)delegate ()
{
UiPrintList?.Clear();
if (tmp?.record != null && tmp?.record.Count > 0)
{
UiPrintList = new ObservableCollection<print_info>(tmp.record);
}
args.Session.Close();
});
});
},
(obj, args) =>
{
});
}
private void OnGenTag()
{
}
private void OnPrintStart()
{
isStop = false;
StopEnable = true;
StartEnable = false;
var print = UiPrintList.Where(t => t.IsSelected == true).ToList();
Task.Run(() =>
{
foreach (var tsk_item in print)
{
if (isStop)
{
break;
}
else
{
//tmp_id = tsk_item.Id;
var res = _window.printServerHelper.SendPrintCmd(new SingleInfo()
{
Info1 = tsk_item.productName,
Info2 = tsk_item.sizeName,
Info3 = tsk_item.supplierName,
Info4 = tsk_item.oneBoxNum.ToString(),
Info5 = tsk_item.pieceNo.ToString(),
Info6 = DateTime.Now.ToString("yyyy-MM-dd"),
Info9 = tsk_item.epc.Replace(" ", ""),
ModelType = "pieceXB"
});
//保存打印记录进文件
var json = JsonConvert.SerializeObject(new PrintLog
{
CreateTime = DateTime.Now,
IsSuccess = res,
epc = tsk_item.epc,
id = tsk_item.id,
orderCode = tsk_item.orderCode,
warehouseName = tsk_item.warehouseName,
productName = tsk_item.productName,
sizeName = tsk_item.sizeName,
productTime = tsk_item.productTime,
useTime = tsk_item.useTime,
pieceNo = tsk_item.pieceNo,
warrantyCycle = tsk_item.warrantyCycle,
repairCycle = tsk_item.repairCycle,
price = tsk_item.price,
supplierName = tsk_item.supplierName,
isBoxMark = true,
oneBoxNum = tsk_item.oneBoxNum
});
System.IO.File.AppendAllText(AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "PrintLog.json", json + "\r\n", Encoding.UTF8);
if (res)
{
UpdateEpcStateById(tsk_item.id.Replace(" ", ""), true);
}
//打印机异常,不继续发指令
else if (!res) { break; }
else { }
}
}
OnPrintStop();
});
}
public void OnPrintStop()
{
StopEnable = false;
StartEnable = true;
isStop = true;
}
private void UpdateEpcStateById(string id, bool apply = false)
{
App.Current.Dispatcher.Invoke(() =>
{
var item = UiPrintList.FirstOrDefault(t => t.id.Contains(id));
if (item != null)
{
item.state = 1;
Tuple<bool, string> flagData = new Tuple<bool, string>(true, "");
if (apply)
{
//箱标创建多个物品
var res = HttpHelper.GenerateRangeInventory(new recode_info
{
epc = item.epc,
sizeId = item.sizeId,
equId = item.productId,
epcListJson = item.epcListJson,
supplierId = item.supplierId,
warehouseId = item.warehouseId,
productTime = Convert.ToDateTime(item.productTime),
useTime = Convert.ToDateTime(item.useTime),
warrantyCycle = Convert.ToInt32(item.warrantyCycle),
price = Convert.ToSingle(item.price),
repairCycle = Convert.ToInt32(item.repairCycle),
IsReloadBoxing = true
}, out string msg);
flagData = new Tuple<bool, string>(res, msg);
}
if (flagData.Item1)
{
UiPrintList.Remove(item);
LiteDbHelper.DeleteByEpc(item.epc);
TotalRecord -= 1;
if (UiPrintList.Count == 0)
{
PageIndex = 1;
OnPageChange();
}
}
else
{
//EPC状态更新失败
UiMessage = flagData.Item2;
MsgColor = "Red";
}
}
});
}
public void EnableControl(bool flag, bool startEnable, bool stopEnable, string msg = "")
{
StartEnable = startEnable;
StopEnable = stopEnable;
if (!string.IsNullOrEmpty(msg))
{
UiMessage = "状态:" + msg;
MsgColor = flag ? "Green" : "Red";
}
}
public void SelectAll()
{
App.Current.Dispatcher.Invoke(() =>
{
foreach (var item in UiPrintList)
{
item.IsSelected = _isSelectAll;
}
this.RaisePropertyChanged(() => UiPrintList);
});
}
public override void Cleanup()
{
base.Cleanup();
isStop = true;
_window.printServerHelper.EnableControlEvent -= EnableControl;
NetworkComms.Shutdown();
}
#endregion
}
}
using GalaSoft.MvvmLight;
using JmpZbModel;
using JmpZbPrint.Model;
using JmpZbPrint.UsControl;
using MaterialDesignThemes.Wpf;
using NetworkCommsDotNet;
using NetworkCommsDotNet.Connections;
using NetworkCommsDotNet.Connections.TCP;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Input;
using System.Windows.Threading;
using GalaSoft.MvvmLight.CommandWpf;
using JmpZbPrint.Common;
using JmpZbPrint.View;
using RelayCommand = GalaSoft.MvvmLight.Command.RelayCommand;
namespace JmpZbPrint.ViewModel
{
public class TagPrinViewModel : ViewModelBase
{
private MainWindow _window;
public TagPrinViewModel(MainWindow window)
{
_window = window;
OnStartPrintItemsCmd = new RelayCommand(OnPrintStart);
OnStopPrintItemsCmd = new RelayCommand(OnPrintStop);
OnQueryCommand = new RelayCommand(OnQuery);
OnPageChangeCmd = new RelayCommand(OnPageChange);
OnGenTagCmd = new RelayCommand(OnGenTag);
OnWindowLoadCmd = new RelayCommand(OnWindowLoad);
OnBoxingCmd = new RelayCommand(OnBoxing);
}
#region filed
private WaitDialog waitDialog = default;
private bool isStop = false;
private ObservableCollection<print_info> _printList = new ObservableCollection<print_info>();
public ObservableCollection<print_info> UiPrintList
{
get { return _printList; }
set
{
_printList = value;
RaisePropertyChanged();
}
}
private string _equName;
public string EquName
{
get { return _equName; }
set
{
_equName = value;
RaisePropertyChanged();
}
}
private string _vendorName;
public string VendorName
{
get { return _vendorName; }
set
{
_vendorName = value;
RaisePropertyChanged();
}
}
private int _epcType;
public int EpcType
{
get { return _epcType; }
set
{
_epcType = value;
RaisePropertyChanged();
}
}
private string _message = "状态:打印机初始化中";
public string UiMessage
{
get { return _message; }
set
{
_message = value;
RaisePropertyChanged();
}
}
private string _msgccolor = "Green";
public string MsgColor
{
get { return _msgccolor; }
set
{
_msgccolor = value;
RaisePropertyChanged();
}
}
private bool _bindButton = false;
public bool BindButton
{
get { return _bindButton; }
set
{
_bindButton = value;
RaisePropertyChanged();
}
}
private int _total = 0;
public int TotalRecord
{
get { return _total; }
set
{
_total = value;
RaisePropertyChanged();
}
}
private int _page = 0;
public int PageIndex
{
get { return _page; }
set
{
_page = value;
RaisePropertyChanged();
}
}
private int _pageTotal = 0;
public int PageTotal
{
get { return _pageTotal; }
set
{
_pageTotal = value;
RaisePropertyChanged();
}
}
private int _pageSize = 50;
public int PageSize
{
get { return _pageSize; }
set
{
_pageSize = value;
RaisePropertyChanged();
}
}
private bool _startEnable = false;
public bool StartEnable
{
get { return _startEnable; }
set
{
_startEnable = value;
RaisePropertyChanged();
}
}
private bool _stopEnable = false;
public bool StopEnable
{
get { return _stopEnable; }
set
{
_stopEnable = value;
RaisePropertyChanged();
}
}
private bool _isSelectAll = false;
public bool IsSelectAll
{
get { return _isSelectAll; }
set
{
_isSelectAll = value;
RaisePropertyChanged();
SelectAll();
}
}
#endregion
#region cmd attr
public RelayCommand OnStartPrintItemsCmd { get; set; }
public RelayCommand OnStopPrintItemsCmd { get; set; }
public RelayCommand OnWindowLoadCmd { get; set; }
public RelayCommand OnQueryCommand { get; set; }
public RelayCommand OnPageChangeCmd { get; set; }
public RelayCommand OnGenTagCmd { get; set; }
public RelayCommand OnWindowClosingCmd { get; set; }
public RelayCommand OnBoxingCmd { get; set; }
#endregion
#region method
/// <summary>
/// 装箱
/// </summary>
private void OnBoxing()
{
var seled = UiPrintList.Where(t => t.IsSelected == true).ToList();
if (seled.Count > 0)
{
if (seled.Any(x => x.LabelType == "箱标"))
{
MessageBox.Show("禁止箱标装箱");
return;
}
var havePurchaseLabel = seled.Any(x => x.isUnboxingLabel == false);
if (MessageBox.Show("确认装箱选中的记录?" + (havePurchaseLabel ? "存在采购件标,将直接录入主平台。" : ""), "确认装箱", MessageBoxButton.OKCancel, MessageBoxImage.Question) ==
MessageBoxResult.OK)
{
//判断物资一致性
var info = seled.First();
if (seled.Any(x => x.productId != info.productId))
{
MessageBox.Show("物资类型不一致,无法装箱");
return;
}
if (seled.Any(x => x.sizeId != info.sizeId))
{
MessageBox.Show("物资型号不一致,无法装箱");
return;
}
if (seled.Any(x => x.supplierId != info.supplierId))
{
MessageBox.Show("供应商不一致,无法装箱");
return;
}
if (seled.Any(x => x.warehouseId != info.warehouseId))
{
MessageBox.Show("入库仓库不一致,无法装箱");
return;
}
//创建箱标epc
var boxRequest = new request_int_info()
{
labelType = "箱标",
equCode = info.productNo,
productTime = Convert.ToDateTime(info.productTime),
sizeCode = info.sizeCode,
oneBoxNum = seled.Count,
quantity = 1,
supplierCode = info.supplierCode,
warrantyCycle = Convert.ToInt32(info.warrantyCycle)
};
var boxRes = HttpHelper.GenerateIntTagEpc(boxRequest, out string boxMsg);
if (!boxRes.Item1)
{
MessageBox.Show($"[{info.productName}-{info.sizeName}] 箱标生成失败,原因:{boxMsg}", "提示", MessageBoxButton.OK, MessageBoxImage.Error);
return;
}
var xbEpc = boxRes.Item2.First().epc;
var res = HttpHelper.BoxingInventoryNormalVersion(xbEpc, seled, out string msg);
if (res)
{
var _batch_no = DateTime.Now.ToString("yyyyMMddHHmmssfff");
foreach (var obj in seled)
{
LiteDbHelper.DeleteByEpc(obj.epc);
}
//不添加箱标记录进litedb
}
else
{
MessageBox.Show(msg);
}
OnQuery();
}
}
}
public void OnWindowLoad()
{
OnQuery();
_window.printServerHelper.EnableControlEvent += EnableControl;
_window.printServerHelper.Init();
}
private void OnQuery()
{
PageIndex = 1;
IsSelectAll = false;
UiPrintList.Clear();
waitDialog = new WaitDialog();
waitDialog.SetToolTop("数据加载中...");
DialogHost.Show(waitDialog, "MainRootDialog",
(obj, args) =>
{
Task.Run(() =>
{
var tmp = HttpHelper.GetPrintList(EpcType, LabelType.打印, PageIndex, VendorName, EquName);
TotalRecord = tmp?.total ?? 0;
PageTotal = TotalRecord == 0 ? 0 : (TotalRecord + PageSize - 1) / PageSize;
App.Current.Dispatcher.BeginInvoke(DispatcherPriority.Normal, (Action)delegate ()
{
UiPrintList?.Clear();
if (tmp?.record != null && tmp?.record.Count > 0)
{
UiPrintList = new ObservableCollection<print_info>(tmp.record);
}
args.Session.Close();
});
});
},
(obj, args) =>
{
});
}
private void OnPageChange()
{
waitDialog = new WaitDialog();
waitDialog.SetToolTop("数据加载中...");
DialogHost.Show(waitDialog, "MainRootDialog",
(obj, args) =>
{
Task.Run(() =>
{
var tmp = HttpHelper.GetPrintList(EpcType, LabelType.打印, PageIndex, VendorName, EquName);
TotalRecord = tmp?.total ?? 0;
PageTotal = TotalRecord == 0 ? 0 : (TotalRecord + PageSize - 1) / PageSize;
App.Current.Dispatcher.BeginInvoke(DispatcherPriority.Normal, (Action)delegate ()
{
UiPrintList?.Clear();
if (tmp?.record != null && tmp?.record.Count > 0)
{
UiPrintList = new ObservableCollection<print_info>(tmp.record);
}
args.Session.Close();
});
});
},
(obj, args) =>
{
});
}
private void OnGenTag()
{
}
private void OnPrintStart()
{
isStop = false;
StopEnable = true;
StartEnable = false;
var print = UiPrintList.Where(t => t.IsSelected == true).ToList();
Task.Run(() =>
{
foreach (var tsk_item in print)
{
if (isStop)
{
break;
}
else
{
//tmp_id = tsk_item.Id;
var res = _window.printServerHelper.SendPrintCmd(new SingleInfo()
{
Info1 = tsk_item.productName,
Info2 = tsk_item.sizeName,
Info3 = tsk_item.supplierName,
Info4 = tsk_item.pieceNo ?? "1",
Info5 = tsk_item.productTime,
Info9 = tsk_item.epc.Replace(" ", ""),
ModelType = "piece"
});
//保存打印记录进文件
var json = JsonConvert.SerializeObject(new PrintLog
{
CreateTime = DateTime.Now,
IsSuccess = res,
epc = tsk_item.epc,
id = tsk_item.id,
orderCode = tsk_item.orderCode,
warehouseName = tsk_item.warehouseName,
productName = tsk_item.productName,
sizeName = tsk_item.sizeName,
productTime = tsk_item.productTime,
useTime = tsk_item.useTime,
pieceNo = tsk_item.pieceNo,
warrantyCycle = tsk_item.warrantyCycle,
repairCycle = tsk_item.repairCycle,
price = tsk_item.price,
supplierName = tsk_item.supplierName,
isBoxMark = false
});
System.IO.File.AppendAllText(AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "PrintLog.json", json + "\r\n", Encoding.UTF8);
if (res)
{
UpdateEpcStateById(tsk_item.id.Replace(" ", ""), true);
}
//打印机异常,不继续发指令
else if (!res) { break; }
else { }
}
}
OnPrintStop();
});
}
public void OnPrintStop()
{
StopEnable = false;
StartEnable = true;
isStop = true;
}
private void UpdateEpcStateById(string id, bool apply = false)
{
App.Current.Dispatcher.Invoke(() =>
{
var item = UiPrintList.FirstOrDefault(t => t.id.Contains(id));
if (item != null)
{
item.state = 1;
Tuple<bool, string> flagData = new Tuple<bool, string>(true, "");
if (apply)
{
if (item.isUnboxingLabel)
{
var res = HttpHelper.GenerateInventory(new recode_info
{
sizeId = item.sizeId,
equId = item.productId,
epc = item.epc,
supplierId = item.supplierId,
warehouseId = item.warehouseId,
productTime = Convert.ToDateTime(item.productTime),
useTime = Convert.ToDateTime(item.useTime),
warrantyCycle = Convert.ToInt32(item.warrantyCycle),
price = Convert.ToSingle(item.price),
repairCycle = Convert.ToInt32(item.repairCycle),
IsUnboxingLabel = item.isUnboxingLabel
}, out string msg);
flagData = new Tuple<bool, string>(res, msg);
}
else
{
flagData = HttpHelper.UpdateEpc(item.id);
}
}
if (flagData.Item1)
{
UiPrintList.Remove(item);
LiteDbHelper.DeleteByEpc(item.epc);
TotalRecord -= 1;
if (UiPrintList.Count == 0)
{
PageIndex = 1;
OnPageChange();
}
}
else
{
//EPC状态更新失败
UiMessage = flagData.Item2;
MsgColor = "Red";
}
}
});
}
public void EnableControl(bool flag, bool startEnable, bool stopEnable, string msg = "")
{
StartEnable = startEnable;
StopEnable = stopEnable;
if (!string.IsNullOrEmpty(msg))
{
UiMessage = "状态:" + msg;
MsgColor = flag ? "Green" : "Red";
}
}
public void SelectAll()
{
App.Current.Dispatcher.Invoke(() =>
{
foreach (var item in UiPrintList)
{
item.IsSelected = _isSelectAll;
}
this.RaisePropertyChanged(() => UiPrintList);
});
}
public override void Cleanup()
{
base.Cleanup();
isStop = true;
_window.printServerHelper.EnableControlEvent -= EnableControl;
NetworkComms.Shutdown();
}
#endregion
}
}
/*
In App.xaml:
<Application.Resources>
<vm:ViewModelLocator xmlns:vm="clr-namespace:JmpZbPrint"
x:Key="Locator" />
</Application.Resources>
In the View:
DataContext="{Binding Source={StaticResource Locator}, Path=ViewModelName}"
You can also use Blend to do all this with the tool's support.
See http://www.galasoft.ch/mvvm
*/
using CommonServiceLocator;
using GalaSoft.MvvmLight.Ioc;
namespace JmpZbPrint.ViewModel
{
/// <summary>
/// This class contains static references to all the view models in the
/// application and provides an entry point for the bindings.
/// </summary>
public class ViewModelLocator
{
/// <summary>
/// Initializes a new instance of the ViewModelLocator class.
/// </summary>
public ViewModelLocator()
{
ServiceLocator.SetLocatorProvider(() => SimpleIoc.Default);
////if (ViewModelBase.IsInDesignModeStatic)
////{
//// // Create design time view services and models
//// SimpleIoc.Default.Register<IDataService, DesignDataService>();
////}
////else
////{
//// // Create run time view services and models
//// SimpleIoc.Default.Register<IDataService, DataService>();
////}
SimpleIoc.Default.Register<MainViewModel>();
}
public MainViewModel Main
{
get
{
return ServiceLocator.Current.GetInstance<MainViewModel>();
}
}
public static void Cleanup()
{
// TODO Clear the ViewModels
}
}
}
\ No newline at end of file
qlY+cqBpLohGwnUHjysa+Xmllzuo+epWE1WatyIJg58QRCqFDWJnTpKftJAuzZk29ZfTyhRP2+vOqH0dfo7riorAXQpkerJ19cFrUTZy6zAjnF5qycCEvuz1YcQZ7B/3LuZZh6So0VrYLtNWTIce8gWn+rPraQwXrfLA0ULqsaDLnmVZjXQ2hX+MNikBML79ureg6wnjY9iTmkBsCGgL4cfOKUvW9Fdbda/EcEjGn0x4sGRevIPePa/eJ9tiX3jZk6yzyLOvyAohjuVCm6xvl7d2U+SoFFiGSLjxfZy07rTUcUiHl3RjUoiCgvCypSitfiF4VCXH+19AWDzXbFcOIyUEp3rSKxXliO/QcwVf6MK6Wy/s5g+LJOSldlmMizE4fLeg8JilOxIRlVJdhSxcY2sqBBsbrdl/XM+g2Ixj07cumu7P1qg8ELRMSxzFWBPU/501wZl/5+OWs5Cp5Dky6FxTNuxGhthx+Shv5GUBFf8nw/fotq8tIBqCVbaQbnLvXkG140GpxrzNX18P3eSVxBURCYfRnP/Ru8x+jee+6WW2BhSZdE7dqVnUXtForC/A43GzTYtJN6UwNw/vJvR9yiKupWDpJoTA+eDssBf/O6Z3H+LIFXDUdiu3/vh05dJodCvbuVLffVECyDkTimDtGLuM16tWR7G9XpUF8zTy3GVl086eG7dz9LPBtJZfrei+D+hOILaR9Upgwn+f5VIw+gzIQwMVIMxZGu2zunECzb1DjSdlBCSEnSTmCdhXHElmJSZJhoeAvaVEkm5tBWV/RwOW15DcA9lKvMZ1WjfmrauyN8dDjfaJAuY3cNYb/lViu44/TPa4pVvnRZxTdProiO9Vk8lvnEqL1fNtBfS2drnyPm/QSzZZCoeSLiaggNq8IctykfXGjwS6xt/qay1g3/Gy3gcaJa9rTvLkmjLNAUqbXwaVJyANqiJj+l+/Uowx29ycLyp/iC+T3Df9AzW0LF7ucUVLDjOLE7mc//p8Y2O5ccmrkvRE+A3nwP82TQ3HjVK2pAWxy1D5JFSecAl6/n8klbnV6Swxaw/huGkCSOQkak6J0/F3dF1AaTteNrJ73dKxuJNRuOxMI5OQIBHvbY8wO3iZsHEOWdaA96SOnqKmVewIEuX2lwtZ5uelGpXqeEe3srl66ok9AC2ifunPDnsSE1JThCp4rVmAgxteV8KAxUoulzyrsB5HnRE0/DLjPUpFwRYOxbJH0xRpikY0iw==
\ No newline at end of file
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="CommonServiceLocator" version="2.0.5" targetFramework="net45" />
<package id="ControlzEx" version="4.3.2" targetFramework="net461" />
<package id="LiteDB" version="5.0.8" targetFramework="net45" />
<package id="MahApps.Metro" version="2.0.0" targetFramework="net461" />
<package id="MaterialDesignColors" version="1.2.6" targetFramework="net461" />
<package id="MaterialDesignThemes" version="3.1.3" targetFramework="net461" />
<package id="MaterialDesignThemes.MahApps" version="0.1.4" targetFramework="net461" />
<package id="MaterialDesignThemes.Wpf" version="1.0.1" targetFramework="net461" />
<package id="Microsoft.CSharp" version="4.7.0" targetFramework="net45" />
<package id="Microsoft.Xaml.Behaviors.Wpf" version="1.1.19" targetFramework="net461" />
<package id="MvvmLight" version="5.4.1.1" targetFramework="net461" />
<package id="MvvmLightLibs" version="5.4.1.1" targetFramework="net461" />
<package id="NetworkCommsDotNet" version="3.0.3" targetFramework="net461" />
<package id="Newtonsoft.Json" version="12.0.3" targetFramework="net461" />
<package id="Panuon.UI.Silver" version="1.1.3" targetFramework="net461" />
<package id="System.Data.DataSetExtensions" version="4.6.0-preview3.19128.7" targetFramework="net461" />
<package id="System.Windows.Interactivity.WPF" version="2.0.20525" targetFramework="net461" />
<package id="WebSocketSharp-netstandard" version="1.0.1" targetFramework="net461" />
</packages>
\ No newline at end of file
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" />
</startup>
</configuration>
\ No newline at end of file
using JmpPrintService.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace JmpPrintService.Basic
{
public class CmdAnalysis
{
protected PrintState PrintState { get; set; }
public PrintState GetPrintState()
{
return PrintState;
}
public void SetPrintState(PrintState state)
{
this.PrintState = state;
}
public void ToshibaSerialportMsg(byte[] buffers)
{
List<byte> bufferList = new List<byte>();
StringBuilder builderList = new StringBuilder();
List<string> resultList = new List<string>();
bufferList.AddRange(buffers);
#region 数据完整性判断
//至少要包含头尾 01 02 03 04 0D 0A
while (bufferList.Count >= 6)
{
#region 查找数据头尾
if (bufferList[0] == 0x01 && bufferList[1] == 0x02)
{
//找到头
for (int i = 2; i < bufferList.Count - 3; i++)
{
if (bufferList[i] == 0x03 && bufferList[i + 1] == 0x04 && bufferList[i + 2] == 0x0D && bufferList[i + 3] == 0x0A)
{//找到尾
for (int j = 2; j < i; j++)
{
builderList.Append(bufferList[j].ToString("X2"));
}
resultList.Add(builderList.ToString());
builderList.Clear();
bufferList.RemoveRange(0, i + 4);
}
}
}
else
{
bufferList.RemoveAt(0);
}
#endregion
}
#endregion
foreach (string item in resultList)
{
string str_normal_head = item.ToString().Substring(0, 1);
string str_tag_head = item.ToString().Substring(0, 2);
string str_msg_ontent = string.Empty;
string str_msg_code = string.Empty;
var sss = item.ToString().Substring(0, 4);
Log.WorkLog(item, "cmd");
JmpZbModel.MessageType messageType = JmpZbModel.MessageType.;
if (str_normal_head == "3")
{
string str_status_src = item.ToString().Substring(0, 4);
var str_status_vle = str_status_src.Substring(1, 1) + str_status_src.Substring(3, 1);
switch (str_status_vle)
{
case "00":
{
//messageType = JmpZbModel.MessageType.通知;
//str_msg_ontent = "ON LINE";
PrintState = PrintState.正常;
break;
}
case "01":
{
//messageType = JmpZbModel.MessageType.异常;
//str_msg_ontent = "打印头未关闭";
PrintState = PrintState.异常;
break;
}
case "02":
{
//messageType = JmpZbModel.MessageType.通知;
//str_msg_ontent = "ON LINE";
PrintState = PrintState.正常;
break;
}
case "04":
{
//messageType = JmpZbModel.MessageType.异常;
//str_msg_ontent = "PAUSE ****";
PrintState = PrintState.异常;
break;
}
case "05":
{
//messageType = JmpZbModel.MessageType.通知;
//str_msg_ontent = "ON LINE";
PrintState = PrintState.正常;
break;
}
case "06":
{
//messageType = JmpZbModel.MessageType.异常;
//str_msg_ontent = "指令错误";
PrintState = PrintState.异常;
break;
}
case "07":
{
//messageType = JmpZbModel.MessageType.异常;
//str_msg_ontent = "COMMS ERROR";
PrintState = PrintState.异常;
break;
}
case "11":
{
//messageType = JmpZbModel.MessageType.异常;
//str_msg_ontent = "打印机卡纸";
PrintState = PrintState.异常;
break;
}
case "12":
{
//messageType = JmpZbModel.MessageType.异常;
//str_msg_ontent = "CUTTER ERROR ****";
PrintState = PrintState.异常;
break;
}
case "13":
{
//messageType = JmpZbModel.MessageType.异常;
//str_msg_ontent = "打印机缺纸";
PrintState = PrintState.异常;
break;
}
case "14":
{
//messageType = JmpZbModel.MessageType.异常;
//str_msg_ontent = "打印机无碳带";
PrintState = PrintState.异常;
break;
}
case "15":
{
//messageType = JmpZbModel.MessageType.异常;
//str_msg_ontent = "打印头未关闭 ****";
PrintState = PrintState.异常;
break;
}
case "17":
{
//messageType = JmpZbModel.MessageType.异常;
//str_msg_ontent = "HEAD ERROR ****";
PrintState = PrintState.异常;
break;
}
case "18":
{
//messageType = JmpZbModel.MessageType.异常;
//str_msg_ontent = "EXCESS HEAD TEMP";
PrintState = PrintState.异常;
break;
}
case "21":
{
//messageType = JmpZbModel.MessageType.异常;
//str_msg_ontent = "打印机碳带异常 ****";
PrintState = PrintState.异常;
break;
}
case "22":
{
//messageType = JmpZbModel.MessageType.异常;
//str_msg_ontent = "REWIND FULL ****";
PrintState = PrintState.异常;
break;
}
case "23":
{
//messageType = JmpZbModel.MessageType.异常;
//str_msg_ontent = "REWIND FULL ****";
PrintState = PrintState.异常;
break;
}
case "36":
{
//messageType = JmpZbModel.MessageType.通知;
//str_msg_ontent = "ON LINE";
PrintState = PrintState.异常;
break;
}
case "40":
{
//messageType = JmpZbModel.MessageType.通知;
//str_msg_ontent = "ON LINE";
PrintState = PrintState.正常;
break;
}
case "41":
{
//messageType = JmpZbModel.MessageType.通知;
//str_msg_ontent = "ON LINE";
PrintState = PrintState.正常;
break;
}
case "50":
{
//messageType = JmpZbModel.MessageType.异常;
//str_msg_ontent = "FLASH WRITE ERR.";
PrintState = PrintState.异常;
break;
}
case "51":
{
//messageType = JmpZbModel.MessageType.异常;
//str_msg_ontent = "FORMAT ERROR";
PrintState = PrintState.异常;
break;
}
case "54":
{
//messageType = JmpZbModel.MessageType.异常;
//str_msg_ontent = "FLASH CARD FULL";
PrintState = PrintState.异常;
break;
}
case "60":
{
PrintState = PrintState.正常;
break;
}
case "61":
{
//messageType = JmpZbModel.MessageType.异常;
//str_msg_ontent = "数据写入失败";
PrintState = PrintState.异常;
break;
}
case "62":
{
//messageType = JmpZbModel.MessageType.异常;
//str_msg_ontent = "RFID ERROR";
PrintState = PrintState.异常;
break;
}
case "65":
{
//messageType = JmpZbModel.MessageType.异常;
//str_msg_ontent = "RFID CONFIG ERR";
PrintState = PrintState.异常;
break;
}
}
//PrintCache.EnPrintMsg(new JmpZbModel.PrintMessage()
//{
// MessageCode = str_msg_code,
// MessageContent = str_msg_ontent,
// MessageType = messageType
//});
}
else if (str_tag_head == "46")
{
str_msg_code = item.ToString().Substring(2, 4);
switch (str_msg_code)
{
case "3030":
{
//str_msg_ontent = "RFID 读取失败";
//PrintCache.EnPrintMsg(new JmpZbModel.PrintMessage()
//{
// MessageCode = str_msg_code,
// MessageContent = str_msg_ontent,
// MessageType = JmpZbModel.MessageType.异常
//});
break;
}
case "3234":
{
var content = item.Substring(6);
PrintCache.EnTagMsg(content);
break;
}
}
}
else { Log.WorkLog(item, "else"); }
}
}
}
}
using JmpPrintService.Model;
using RJCP.IO.Ports;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace JmpPrintService.Basic
{
public class ComConnect : ConnectBase
{
protected SerialPortStream serialPort = null;
private Action<byte[]> onAnalysisReciveMsg;
public ComConnect(Action<byte[]> onAnalysisReciveMsg, int baudRate = 115200)
{
serialPort = new SerialPortStream(PrintCache.ComPort, baudRate, 8, Parity.None, StopBits.One);
serialPort.Handshake = Handshake.None;
serialPort.RtsEnable = true;
serialPort.DataReceived += new EventHandler<SerialDataReceivedEventArgs>(OnReviceData);
serialPort.ErrorReceived += OnErrorReceived;
serialPort.PinChanged += OnPinChanged;
this.onAnalysisReciveMsg = onAnalysisReciveMsg;
}
private void OnPinChanged(object sender, SerialPinChangedEventArgs e)
{
}
private void OnErrorReceived(object sender, SerialErrorReceivedEventArgs e)
{
}
/// <summary>
///开始读取打印数据
/// </summary>
protected void OnReviceData(object sender, SerialDataReceivedEventArgs e)
{
try
{
if (!serialPort.IsOpen)
{
return;
}
else
{
//Thread.Sleep(500);
int src_len = serialPort.BytesToRead;//数据长度
byte[] buffer = new byte[src_len];//声明一个临时数组,存储当前来的串口数据
serialPort.Read(buffer, 0, src_len);//读取缓冲数据
onAnalysisReciveMsg?.BeginInvoke(buffer, default, default);
serialPort.Flush();
}
}
catch (Exception ex)
{
Log.ErrorLog(ex.ToString(), MethodBase.GetCurrentMethod().Name);
}
}
/// <summary>
/// 打开Com口
/// </summary>
/// <param name="isSuccess"></param>
/// <param name="msg"></param>
public override bool Connection()
{
try
{
if (serialPort.IsOpen)
{
serialPort.Close();
}
//serialPort.ReadTimeout = 2000;
serialPort.Open();
if (serialPort.IsOpen)
{
return true;
}
else
{
return false;
}
}
catch (Exception ex)
{
Log.ErrorLog(ex.ToString(), MethodBase.GetCurrentMethod().Name);
return false;
}
}
/// <summary>
/// 断开串口连接
/// </summary>
/// <returns></returns>
public override bool DisConnection()
{
try
{
if (serialPort == null)
{
return true;
}
if (serialPort.IsOpen)
{
serialPort.Close();
return true;
}
return false;
}
catch (Exception ex)
{
Log.ErrorLog(ex.ToString(), MethodBase.GetCurrentMethod().Name);
return false;
}
}
/// <summary>
/// 发送指令
/// </summary>
/// <param name="sSendText"></param>
/// <returns></returns>
public override bool SendMsg(string sSendText)
{
try
{
if (serialPort == null)
{
return false;
}
if (!serialPort.IsOpen)
{
return false;
}
byte[] tmp1 = System.Text.Encoding.Default.GetBytes(sSendText);
serialPort.Write(tmp1, 0, tmp1.Length);
return true;
}
catch (Exception ex)
{
Log.ErrorLog(ex.ToString(), MethodBase.GetCurrentMethod().Name);
return false;
}
}
}
}
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using ZXing;
using ZXing.QrCode;
namespace JmpZbService.Basic
{
public static class CommonHelper
{
private static List<string> listNo1 = new List<string>() { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", ":", ";", "<", "=", ">", "?" };
public static string PhotoImageInsert(string strText)
{
string strInfo = "";
//设置QR二维码的规格
QrCodeEncodingOptions option = new QrCodeEncodingOptions();
//设置编码格式,否则中文乱码
option.CharacterSet = "UTF-8";
//设置宽和高
option.Height = 250;
option.Width = 250;
//设置周围空白边距
option.Margin = 1;
BarcodeWriter writer = new BarcodeWriter();
//二维码
writer.Format = BarcodeFormat.QR_CODE;
writer.Options = option;
//生成二维码
Bitmap image = writer.Write(strText);
byte[] byte1 = ConvertTo1Bpp1(image, 1);
string s = "";
int n = 0;
//打印机图片点阵宽度
int d = ((image.Width + 7) / 8) * 8;
for (int j = 0; j < image.Height; j++)
{
for (int i = 0; i < d; i++)
{
if (i >= image.Width)
{
s += "0";
}
else
{
s += byte1[j * image.Width + i].ToString();
}
if (n == 3)
{
int xjDenary = Convert.ToInt32(s, 2);
strInfo += listNo1[xjDenary];
n = 0;
s = "";
}
else
{
n++;
}
}
}
return strInfo;
}
public static string Image2String(Bitmap bitmap)
{
//生成二维码
byte[] byte1 = ConvertTo1Bpp1(bitmap, 1);
string s = "";
string strInfo = "";
int n = 0;
//打印机图片点阵宽度
int d = ((bitmap.Width + 7) / 8) * 8;
for (int j = 0; j < bitmap.Height; j++)
{
for (int i = 0; i < d; i++)
{
if (i >= bitmap.Width)
{
s += "0";
}
else
{
s += byte1[j * bitmap.Width + i].ToString();
}
if (n == 3)
{
int xjDenary = Convert.ToInt32(s, 2);
strInfo += listNo1[xjDenary];
n = 0;
s = "";
}
else
{
n++;
}
}
}
return strInfo;
}
/// <summary>
/// 图像二值化1:取图片的平均灰度作为阈值,低于该值的全都为0,高于该值的全都为255
/// </summary>
/// <param name="bmp">原图</param>
/// <param name="nType">放到倍数</param>
/// <returns></returns>
private static byte[] ConvertTo1Bpp1(Bitmap bmp, int nType)
{
byte[] b = new byte[(bmp.Width * bmp.Height)];
for (int i = 0; i < bmp.Width; i++)
{
for (int j = 0; j < bmp.Height; j++)
{
//获取该点的像素的RGB的颜色
Color color = bmp.GetPixel(i, j);
//Color newColor = value > average ? Color.FromArgb(0, 0, 0) : Color.FromArgb(255, 255, 255);
b[j * bmp.Width + i] = (new byte[] { color.R, color.G, color.B }).Max() > 60 ? (byte)0 : (byte)1;
//bmp.SetPixel(i, j, newColor);
}
}
return b;
}
}
}
using JmpPrintService.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace JmpPrintService.Basic
{
public abstract class ConnectBase
{
public abstract bool Connection();
public abstract bool DisConnection();
public abstract bool SendMsg(string strCmd);
}
}
using JmpPrintService.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
namespace JmpPrintService.Basic
{
public class JmpTagInit
{
public static void JmpPrintEncrypt(string Ver, ref TAG_INFO tag)
{
switch (Ver)
{
case "00":
{
tag.TAG_EPC = Ver;
break;
}
case "01":
{
try
{
tag.TAG_EPC = Ver + Ascii.StringToAscii(PrintDECL.Encrypt(tag.TAG_TID.Substring(12, 12), PrintDECL.Decrypt(Ascii.AsciiToString("6e4274452b682f587467553d"), "202005")));
}
catch
{
}
break;
}
case "02":
{
try
{
tag.TAG_EPC = Ver + Ascii.StringToAscii(PrintDECL.Encrypt(tag.TAG_TID.Substring(12, 12), PrintDECL.Decrypt(Ascii.AsciiToString("705a6241464a52324732673d"), "201314")));
// bl = true;
}
catch (Exception ex)
{
// bl = false;
}
break;
}
case "03":
{
try
{
tag.TAG_EPC = Ver + Ascii.StringToAscii(PrintDECL.Encrypt(tag.TAG_TID.Substring(16, 12), PrintDECL.Decrypt(Ascii.AsciiToString("705a6241464a52324732673d"), "201314")));
// bl = true;
}
catch (Exception ex)
{
// bl = false;
}
break;
}
}
}
}
public class Ascii
{
public Ascii()
{
}
public static string StringToAscii(string strInMsg)
{
byte[] array = System.Text.Encoding.ASCII.GetBytes(strInMsg);
string strOutMsg = "";
foreach (byte b in array)
{
int asciicode = (int)b;
strOutMsg += Convert.ToString(asciicode, 16);
}
return strOutMsg;
}
public static string AsciiToString(string strInMsg)
{
string strOutMsg = "";
char[] carray = strInMsg.ToCharArray();
string temp = "";
List<byte> bList = new List<byte>();
for (int i = 0; i < carray.Length; i++)
{
temp += carray[i].ToString();
if (i % 2 == 1)
{
int asciicode = Convert.ToInt32(temp, 16);
strOutMsg += System.Text.Encoding.ASCII.GetString(new byte[] { (byte)asciicode });
temp = "";
}
}
return strOutMsg;
}
}
public class PrintDECL
{
public PrintDECL()
{
}
#region 使用 缺省密钥字符串 加密/解密string
/// <summary>
/// 使用缺省密钥字符串加密string
/// </summary>
/// <param name="original">明文</param>
/// <returns>密文</returns>
public static string Encrypt(string original)
{
return Encrypt(original, "MATICSOFT");
}
/// <summary>
/// 使用缺省密钥字符串解密string
/// </summary>
/// <param name="original">密文</param>
/// <returns>明文</returns>
public static string Decrypt(string original)
{
return Decrypt(original, "MATICSOFT", System.Text.Encoding.Default);
}
#endregion
#region 使用 给定密钥字符串 加密/解密string
/// <summary>
/// 使用给定密钥字符串加密string
/// </summary>
/// <param name="original">原始文字</param>
/// <param name="key">密钥</param>
/// <param name="encoding">字符编码方案</param>
/// <returns>密文</returns>
public static string Encrypt(string original, string key)
{
byte[] buff = System.Text.Encoding.Default.GetBytes(original);
byte[] kb = System.Text.Encoding.Default.GetBytes(key);
return Convert.ToBase64String(Encrypt(buff, kb));
}
/// <summary>
/// 使用给定密钥字符串解密string
/// </summary>
/// <param name="original">密文</param>
/// <param name="key">密钥</param>
/// <returns>明文</returns>
public static string Decrypt(string original, string key)
{
return Decrypt(original, key, System.Text.Encoding.Default);
}
/// <summary>
/// 使用给定密钥字符串解密string,返回指定编码方式明文
/// </summary>
/// <param name="encrypted">密文</param>
/// <param name="key">密钥</param>
/// <param name="encoding">字符编码方案</param>
/// <returns>明文</returns>
public static string Decrypt(string encrypted, string key, Encoding encoding)
{
byte[] buff = Convert.FromBase64String(encrypted);
byte[] kb = System.Text.Encoding.Default.GetBytes(key);
return encoding.GetString(Decrypt(buff, kb));
}
#endregion
#region 使用 缺省密钥字符串 加密/解密/byte[]
/// <summary>
/// 使用缺省密钥字符串解密byte[]
/// </summary>
/// <param name="encrypted">密文</param>
/// <param name="key">密钥</param>
/// <returns>明文</returns>
public static byte[] Decrypt(byte[] encrypted)
{
byte[] key = System.Text.Encoding.Default.GetBytes("MATICSOFT");
return Decrypt(encrypted, key);
}
/// <summary>
/// 使用缺省密钥字符串加密
/// </summary>
/// <param name="original">原始数据</param>
/// <param name="key">密钥</param>
/// <returns>密文</returns>
public static byte[] Encrypt(byte[] original)
{
byte[] key = System.Text.Encoding.Default.GetBytes("MATICSOFT");
return Encrypt(original, key);
}
#endregion
#region 使用 给定密钥 加密/解密/byte[]
/// <summary>
/// 生成MD5摘要
/// </summary>
/// <param name="original">数据源</param>
/// <returns>摘要</returns>
public static byte[] MakeMD5(byte[] original)
{
MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider();
byte[] keyhash = hashmd5.ComputeHash(original);
hashmd5 = null;
return keyhash;
}
/// <summary>
/// 使用给定密钥加密
/// </summary>
/// <param name="original">明文</param>
/// <param name="key">密钥</param>
/// <returns>密文</returns>
public static byte[] Encrypt(byte[] original, byte[] key)
{
TripleDESCryptoServiceProvider des = new TripleDESCryptoServiceProvider();
des.Key = MakeMD5(key);
des.Mode = CipherMode.ECB;
return des.CreateEncryptor().TransformFinalBlock(original, 0, original.Length);
}
/// <summary>
/// 使用给定密钥解密数据
/// </summary>
/// <param name="encrypted">密文</param>
/// <param name="key">密钥</param>
/// <returns>明文</returns>
public static byte[] Decrypt(byte[] encrypted, byte[] key)
{
TripleDESCryptoServiceProvider des = new TripleDESCryptoServiceProvider();
des.Key = MakeMD5(key);
des.Mode = CipherMode.ECB;
return des.CreateDecryptor().TransformFinalBlock(encrypted, 0, encrypted.Length);
}
#endregion
}
}
using JmpZbModel;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace JmpPrintService.Basic
{
public static class PrintCache
{
public static string ComPort { get; set; } = "COM1";
private static object msgObj = new object();
private static object epcObj = new object();
//private static Queue<PrintMessage> PrintMsg { get; set; } = new Queue<PrintMessage>();
private static Queue<string> EpcMsg { get; set; } = new Queue<string>();
//public static void EnPrintMsg(PrintMessage strMsg)
//{
// lock (msgObj)
// {
// PrintMsg?.Enqueue(strMsg);
// }
//}
//public static PrintMessage DePrintMsg()
//{
// lock (msgObj)
// {
// return PrintMsg?.Dequeue();
// }
//}
public static void EnTagMsg(string strMsg)
{
lock (epcObj)
{
EpcMsg?.Enqueue(strMsg);
}
}
public static string DeTagMsg()
{
lock (epcObj)
{
if (EpcMsg.Count > 0)
{
return EpcMsg?.Dequeue();
}
else { return ""; }
}
}
public static void ClearTagMsg()
{
lock (epcObj)
{
EpcMsg?.Clear();
}
}
//public static int PrintMsgCount()
//{
// lock (msgObj)
// {
// return PrintMsg?.Count ?? 0;
// }
//}
public static int EpcMsgCount()
{
lock (epcObj)
{
return EpcMsg?.Count ?? 0;
}
}
}
public class TagInfo
{
public string Content { get; set; }
public MessageType Type { get; set; }
}
}
using JmpZbModel;
using JmpPrintService.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace JmpPrintService.Basic
{
public abstract class PrinterBase
{
public abstract bool OnStart(ConnectType connectType = ConnectType.COM);
public abstract bool OnStop();
public abstract bool SendMsg(string strMsg);
public abstract bool SendQueryMsg();
public bool IsWork { get; set; }
protected ConnectType ConnectType { get; set; }
protected PrintState PrintState { get; set; }
public abstract PrintState GetPrintState();
public abstract void SetPrintState(PrintState state);
}
}
using JmpZbModel;
using JmpPrintService.Model;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace JmpPrintService.Basic
{
public class ToshibaPrinter : PrinterBase
{
private ConnectBase printer = default;
private CmdAnalysis cmdAnalysis = new CmdAnalysis();
public ToshibaPrinter()
{
}
public override bool SendMsg(string strMsg)
{
if (IsWork)
{
return printer?.SendMsg(strMsg) ?? false;
}
else { return false; }
}
public override bool OnStart(ConnectType connectType = ConnectType.COM)
{
ConnectType = connectType;
if (ConnectType == ConnectType.COM)
{
printer = new ComConnect(cmdAnalysis.ToshibaSerialportMsg);
}
if (ConnectType == ConnectType.USB)
{
printer = new UsbConnect(cmdAnalysis.ToshibaSerialportMsg);
}
IsWork = printer?.Connection() ?? false;
return IsWork;
}
public override bool OnStop()
{
IsWork = false;
return printer?.DisConnection() ?? false;
}
public override bool SendQueryMsg()
{
string strCmd = "{C|}" + "{WS|}";
return printer?.SendMsg(strCmd) ?? false;
}
public override PrintState GetPrintState()
{
return cmdAnalysis.GetPrintState();
}
public override void SetPrintState(PrintState state)
{
cmdAnalysis.SetPrintState(state);
}
}
}
using LibUsbDotNet;
using LibUsbDotNet.DeviceNotify;
using LibUsbDotNet.Main;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace JmpPrintService.Basic
{
public class UsbConnect : ConnectBase
{
private Dictionary<string, ushort> dic_device = new Dictionary<string, ushort>();
private UsbDeviceFinder usbFinder;
private UsbDevice usbDevice;
private UsbEndpointWriter writer;
private UsbEndpointReader reader;
private Action<byte[]> onAnalysisReciveMsg;
public IDeviceNotifier notifier = DeviceNotifier.OpenDeviceNotifier();
public UsbConnect(Action<byte[]> onAnalysisReciveMsg = null)
{
this.onAnalysisReciveMsg = onAnalysisReciveMsg;
}
protected void OnDataReceived(object sender, EndpointDataEventArgs e)
{
try
{
if (onAnalysisReciveMsg == null)
{
}
else
{
onAnalysisReciveMsg?.BeginInvoke(e.Buffer, default, default);
}
}
catch (Exception ex)
{
Log.ErrorLog(ex.ToString(), MethodBase.GetCurrentMethod().Name);
}
}
/// <summary>
/// 初始化打印程序
/// </summary>
/// <returns></returns>
public override bool Connection()
{
try
{
UsbRegistry usbRegistry = default;
foreach (UsbRegistry item in UsbDevice.AllLibUsbDevices)
{
//东芝打印机设备标志
if (item.Device.Info.Descriptor.VendorID == 2214 && item.Device.Info.Descriptor.ProductID == 83)
{
usbRegistry = item;
break;
}
}
if (usbRegistry == null)
{
return false;
}
else
{
//尝试连接打印机
usbRegistry.Open(out UsbDevice usbDevice);
IUsbDevice wholeUsbDevice = usbDevice as IUsbDevice;
if (wholeUsbDevice != null)
{
//这是一个“完整的”USB设备。在使用之前,
//必须选择所需的配置和接口。
//选择config #1
wholeUsbDevice.SetConfiguration(1);
// 接口地址重置 #0
wholeUsbDevice.ClaimInterface(0);
}
if (usbDevice != null)
{
writer = usbDevice.OpenEndpointWriter(WriteEndpointID.Ep01);
reader = usbDevice.OpenEndpointReader(ReadEndpointID.Ep02);
reader.DataReceivedEnabled = true;
reader.DataReceived += OnDataReceived; ;
return usbDevice.Open();
}
else
{
return false;
}
}
}
catch (Exception ex)
{
Log.ErrorLog(ex.ToString(), MethodBase.GetCurrentMethod().Name);
return false;
}
}
/// <summary>
/// 发送打印机指令
/// </summary>
/// <param name="strMsg"></param>
/// <returns></returns>
public override bool SendMsg(string strMsg)
{
try
{
byte[] temp = System.Text.Encoding.GetEncoding("GB18030").GetBytes(strMsg);
ErrorCode ec = ErrorCode.None;
ec = writer?.Write(temp, 20000, out int transferLength) ?? ErrorCode.UnknownError;
if (ec != ErrorCode.None)
{
return false;
}
else
{
return true;
}
}
catch (Exception ex)
{
Log.ErrorLog(ex.ToString(), MethodBase.GetCurrentMethod().Name);
return false;
}
}
/// <summary>
/// 停止打印程序
/// </summary>
public override bool DisConnection()
{
if (usbDevice != null)
{
if (usbDevice?.IsOpen ?? false)
{
writer.Abort();
reader.Abort();
usbDevice?.Close();
return true;
}
return false;
}
else
{
return true;
}
}
}
}
using System;
using System.Collections.Generic;
using System.IO.Ports;
using System.Reflection;
using System.Text;
using System.Threading;
namespace JmpPrintService.ComSet
{
class ComPrint
{
/// <summary>
/// 停止位
/// </summary>
private System.IO.Ports.StopBits _stopBits = System.IO.Ports.StopBits.One;
/// <summary>
/// 检验位
/// </summary>
private System.IO.Ports.Parity _checkBits = System.IO.Ports.Parity.None;
/// <summary>
/// 流控制
/// </summary>
private System.IO.Ports.Handshake _flowControl = System.IO.Ports.Handshake.None;
/// <summary>
/// 波特率
/// </summary>
private int _baudRate = 115200;
/// <summary>
/// 数据位
/// </summary>
private int _dataBits = 8;
/// <summary>
/// 串口名称
/// </summary>
private string _portName = "COM1";
public static int ReadFlag = 0;//读写标志
public static bool RFIDFlag = false;
public static int PrintFlag = 0;//打印标志
public static Queue<string> PrintMsg = new Queue<string>();
public static Queue<string> EpcMsg = new Queue<string>();
private SerialPort serialPort = new SerialPort();
private List<byte> buffer = new List<byte>(4096);//默认分配1页内存
private StringBuilder builder = new StringBuilder();
private List<PrintStatusModel> printModelList = new List<PrintStatusModel>();
private PrintStatusModel printModel = new PrintStatusModel();
public void SetComName(string comName)
{
_portName = comName;
}
public ComPrint()
{
this.serialPort.DataReceived += new SerialDataReceivedEventHandler(StartRead);
}
/// <summary>
/// 设置读写标志
/// </summary>
public void SetReadFlag()
{
if (!serialPort.IsOpen)
{
ReadFlag = 1;
serialPort.PortName = "COM1";
serialPort.BaudRate = 115200;//
serialPort.Parity = Parity.None;// Parity.None;
serialPort.DataBits = 8;// 8;
serialPort.StopBits = StopBits.One;// StopBits.One;
serialPort.Handshake = Handshake.None;// Handshake.None;
serialPort.RtsEnable = true;
}
}
public void Init()
{
}
/// <summary>
///开始读取打印数据
/// </summary>
public void StartRead(object sender, SerialDataReceivedEventArgs e)
{
try
{
Thread.Sleep(500);
//int len = 10;//数据长度
if (!serialPort.IsOpen) return;
int len = serialPort.BytesToRead;//数据长度
byte[] buf = new byte[len];//声明一个临时数组,存储当前来的串口数据
//string msga= serialPort.ReadExisting();
int PortResult = serialPort.Read(buf, 0, len);//读取缓冲数据
bool data_1_catched = false;//缓存记录数据是否捕获到
//builder.Remove(0, builder.Length);//清楚字符串构造器的内容
builder.Clear();
buffer.AddRange(buf);
List<string> builderList = new List<string>();
printModelList.Clear();
#region //2.完整性判断
while (buffer.Count >= 6) //至少要包含头尾 01 02 03 04 0D 0A
{
#region //2.1 New查找数据头尾
if (buffer[0] == 0x01 && buffer[1] == 0x02)
{//找到头
for (int i = 2; i < buffer.Count - 3; i++)
{
if (buffer[i] == 0x03 && buffer[i + 1] == 0x04 && buffer[i + 2] == 0x0D && buffer[i + 3] == 0x0A)
{//找到尾
for (int j = 2; j < i; j++)
{
builder.Append(buffer[j].ToString("X2"));
}
builderList.Add(builder.ToString());
builder.Clear();
//builder.Remove(0, builder.Length);
data_1_catched = true;
buffer.RemoveRange(0, i + 4);
}
}
}
else
{
buffer.RemoveAt(0);
}
#endregion
}
#endregion
#region //3.分析数据
if (data_1_catched)
{
foreach (string sbuilder in builderList)
{
if (sbuilder.Length > 36)
{
EpcMsg.Enqueue(sbuilder);
}
printModel = new PrintStatusModel();
printModel.TagReadData = "";
printModel.SPortData = sbuilder.ToString();
#region sbuilder
string sStatus = sbuilder.ToString().Substring(0, 4);
string sStatusType = sbuilder.ToString().Substring(4, 2);
string sData = sbuilder.ToString().Substring(6);
string sReturnMsg = "";
bool IsError = false;
if (sbuilder.ToString().Substring(0, 1) == "3")
{
printModel.PrintStatus = sStatus.Substring(1, 1) + sStatus.Substring(3, 1);
#region Status
switch (printModel.PrintStatus)
{
case "00":
{
IsError = false;
sReturnMsg = "ON LINE";
break;
}
case "01":
{
IsError = true;
sReturnMsg = "打印头未关闭";
break;
}
case "02":
{
IsError = false;
sReturnMsg = "ON LINE";
break;
}
case "04":
{
IsError = true;
sReturnMsg = "PAUSE ****";
break;
}
case "05":
{
IsError = false;
sReturnMsg = "ON LINE";
break;
}
case "06":
{
IsError = true;
sReturnMsg = "指令错误";
break;
}
case "07":
{
IsError = true;
sReturnMsg = "COMMS ERROR";
break;
}
case "11":
{
IsError = true;
sReturnMsg = "打印机卡纸";
break;
}
case "12":
{
IsError = true;
sReturnMsg = "CUTTER ERROR ****";
break;
}
case "13":
{
IsError = true;
sReturnMsg = "打印机缺纸";
break;
}
case "14":
{
IsError = true;
sReturnMsg = "打印机无碳带";
break;
}
case "15":
{
IsError = true;
sReturnMsg = "打印头未关闭 ****";
break;
}
case "17":
{
IsError = true;
sReturnMsg = "HEAD ERROR ****";
break;
}
case "18":
{
IsError = true;
sReturnMsg = "EXCESS HEAD TEMP";
break;
}
case "21":
{
IsError = true;
sReturnMsg = "打印机碳带异常 ****";
break;
}
case "22":
{
IsError = true;
sReturnMsg = "REWIND FULL ****";
break;
}
case "40":
{
IsError = false;
sReturnMsg = "ON LINE";
break;
}
case "41":
{
IsError = false;
sReturnMsg = "ON LINE";
break;
}
case "50":
{
IsError = true;
sReturnMsg = "FLASH WRITE ERR.";
break;
}
case "51":
{
IsError = true;
sReturnMsg = "FORMAT ERROR";
break;
}
case "54":
{
IsError = true;
sReturnMsg = "FLASH CARD FULL";
break;
}
case "60":
{
sReturnMsg = " ";
break;
}
case "61":
{
IsError = true;
sReturnMsg = "数据写入失败";
break;
}
case "62":
{
IsError = true;
sReturnMsg = "RFID ERROR";
break;
}
case "63":
{
IsError = false;
sReturnMsg = "Writing data succeeded";
break;
}
case "64":
{
IsError = true;
sReturnMsg = "Writing data failed.";
break;
}
case "65":
{
IsError = true;
sReturnMsg = "RFID CONFIG ERR";
break;
}
}
#endregion
#region Status Type
switch (sStatusType)
{
case "31":
{
sReturnMsg = "状态请求命令 : " + sReturnMsg;
break;
}
case "32":
{
sReturnMsg = "自动状态传输 : " + sReturnMsg;
break;
}
case "33":
{
sReturnMsg = "接收缓存可用空间状态请求 : " + sReturnMsg;
break;
}
case "34":
{
sReturnMsg = "RFID数据读取状态 : " + sReturnMsg;
break;
}
case "35":
{
sReturnMsg = "RFID数据写入状态 : " + sReturnMsg;
break;
}
}
#endregion
}
else if (sbuilder.ToString().Substring(0, 2) == "46")
{
switch (sbuilder.ToString().Substring(2, 4))
{
case "3030":
{
sReturnMsg = "RFID 读取失败";
printModel.TagReadData = "";
printModel.TagReadSuccess = false;
break;
}
case "3234":
{
sReturnMsg = "RFID 读取成功 : " + sData;
printModel.TagReadData = sData;
printModel.TagReadSuccess = true;
break;
}
}
}
#endregion
printModel.IsReceived = true;
printModel.IsError = IsError;
printModel.PrintStatusMsg = sReturnMsg;
printModel.PrintMsg = sReturnMsg;
printModelList.Add(printModel);
ComPrint.PrintMsg.Enqueue(printModel.PrintStatus);
}
}
#endregion
}
catch (Exception ex)
{
Log.ErrorLog(ex.ToString(), MethodBase.GetCurrentMethod().Name);
}
}
/// <summary>
/// 打开Com口
/// </summary>
/// <param name="isSuccess"></param>
/// <param name="msg"></param>
public void OpenComm(out bool isSuccess, out String msg)
{
try
{
if (this.serialPort.IsOpen)
{
this.serialPort.Close();
}
//设置参数打开串口信息
this.serialPort.PortName = this._portName;
//波特率
this.serialPort.BaudRate = this._baudRate;
//数据位
this.serialPort.DataBits = this._dataBits;
//停止位
this.serialPort.StopBits = this._stopBits;
//检验位
this.serialPort.Parity = this._checkBits;
//流控制
this.serialPort.Handshake = this._flowControl;
this.serialPort.ReadTimeout = 2000;
this.serialPort.Open();
if (this.serialPort.IsOpen)
{
isSuccess = true;
msg = ("串口打开成功!");
ReadFlag = 1;
}
else
{
isSuccess = false;
ReadFlag = 0;
msg = ("串口打开失败!");
}
}
catch (Exception ex)
{
isSuccess = false;
ReadFlag = 0;
msg = ("请确保打印机连接正常.Error:" + ex.Message);
Log.ErrorLog(ex.ToString(), MethodBase.GetCurrentMethod().Name);
}
}
public void CloseComm(out bool isSuccess, out string msg)
{
try
{
isSuccess = false;
msg = string.Empty;
if (this.serialPort == null)
{
msg = ("无对应的串口信息!");
isSuccess = false;
}
if (this.serialPort.IsOpen)
{
this.serialPort.Close();
msg = ("串口关闭成功!");
isSuccess = true;
}
}
catch (Exception ex)
{
isSuccess = false;
msg = ("请联系管理员.Error:" + ex.Message);
Log.ErrorLog(ex.ToString(), MethodBase.GetCurrentMethod().Name);
}
}
public void SendCmd2Print(string sSendText, out bool isSuccess, out String msg)
{
try
{
if (this.serialPort == null)
{
msg = ("无串口信息!");
isSuccess = false;
return;
}
if (!this.serialPort.IsOpen)
{
msg = ("串口没有打开!");
isSuccess = false;
return;
}
byte[] temp = System.Text.ASCIIEncoding.Default.GetBytes(sSendText);
Char[] temp2 = System.Text.Encoding.GetEncoding("GB18030").GetChars(temp);
Byte[] data = System.Text.Encoding.GetEncoding("GB18030").GetBytes(temp2);
this.serialPort.Write(data, 0, data.Length);
msg = ("串口已打开!");
isSuccess = true;
}
catch (Exception ex)
{
msg = ("btn_Send_Click.Error:" + ex.Message);
isSuccess = false;
Log.ErrorLog(ex.ToString(), MethodBase.GetCurrentMethod().Name);
}
}
public class PrintStatusModel
{
private bool _IsError = false;
/// <summary>
/// 是否发生错误
/// </summary>
public bool IsError
{
get { return _IsError; }
set { _IsError = value; }
}
private bool _IsSuccess = false;
/// <summary>
/// 是否成功通过验证
/// </summary>
public bool IsSuccess
{
get { return _IsSuccess; }
set { _IsSuccess = value; }
}
private bool _IsReceived = false;
/// <summary>
/// 是否接收数据成功
/// </summary>
public bool IsReceived
{
get { return _IsReceived; }
set { _IsReceived = value; }
}
private bool _TagReadSuccess = false;
/// <summary>
/// 标签读取是否成功
/// </summary>
public bool TagReadSuccess
{
get { return _TagReadSuccess; }
set { _TagReadSuccess = value; }
}
private string _TagReadData = "";
/// <summary>
/// 标签读取的数据
/// </summary>
public string TagReadData
{
get { return _TagReadData; }
set { _TagReadData = value; }
}
private string _PrintStatus = "00";
/// <summary>
/// 打印机状态
/// </summary>
public string PrintStatus
{
get { return _PrintStatus; }
set { _PrintStatus = value; }
}
private string _PrintStatusMsg = "";
/// <summary>
/// 打印机状态注释
/// </summary>
public string PrintStatusMsg
{
get { return _PrintStatusMsg; }
set { _PrintStatusMsg = value; }
}
private string _PrintMsg = "";
/// <summary>
/// 打印机反馈信息
/// </summary>
public string PrintMsg
{
get { return _PrintMsg; }
set { _PrintMsg = value; }
}
private string _sPortData = "";
/// <summary>
/// 串口返回数据
/// </summary>
public string SPortData
{
get { return _sPortData; }
set { _sPortData = value; }
}
}
}
}
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ZXing;
using ZXing.QrCode;
namespace JmpPrintService
{
public static class CommonHelper
{
private static List<string> listNo1 = new List<string>() { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", ":", ";", "<", "=", ">", "?" };
public static string PhotoImageInsert(string strText)
{
string strInfo = "";
//设置QR二维码的规格
QrCodeEncodingOptions option = new QrCodeEncodingOptions();
//设置编码格式,否则中文乱码
option.CharacterSet = "UTF-8";
//设置宽和高
option.Height = 250;
option.Width = 250;
//设置周围空白边距
option.Margin = 1;
BarcodeWriter writer = new BarcodeWriter();
//二维码
writer.Format = BarcodeFormat.QR_CODE;
writer.Options = option;
//生成二维码
Bitmap image = writer.Write(strText);
byte[] byte1 = ConvertTo1Bpp1(image, 1);
string s = "";
int n = 0;
//打印机图片点阵宽度
int d = ((image.Width + 7) / 8) * 8;
for (int j = 0; j < image.Height; j++)
{
for (int i = 0; i < d; i++)
{
if (i >= image.Width)
{
s += "0";
}
else
{
s += byte1[j * image.Width + i].ToString();
}
if (n == 3)
{
int xjDenary = Convert.ToInt32(s, 2);
strInfo += listNo1[xjDenary];
n = 0;
s = "";
}
else
{
n++;
}
}
}
return strInfo;
}
public static string Image2String(Bitmap bitmap)
{
//生成二维码
byte[] byte1 = ConvertTo1Bpp1(bitmap, 1);
string s = "";
string strInfo = "";
int n = 0;
//打印机图片点阵宽度
int d = ((bitmap.Width + 7) / 8) * 8;
for (int j = 0; j < bitmap.Height; j++)
{
for (int i = 0; i < d; i++)
{
if (i >= bitmap.Width)
{
s += "0";
}
else
{
s += byte1[j * bitmap.Width + i].ToString();
}
if (n == 3)
{
int xjDenary = Convert.ToInt32(s, 2);
strInfo += listNo1[xjDenary];
n = 0;
s = "";
}
else
{
n++;
}
}
}
return strInfo;
}
/// <summary>
/// 图像二值化1:取图片的平均灰度作为阈值,低于该值的全都为0,高于该值的全都为255
/// </summary>
/// <param name="bmp">原图</param>
/// <param name="nType">放到倍数</param>
/// <returns></returns>
private static byte[] ConvertTo1Bpp1(Bitmap bmp, int nType)
{
byte[] b = new byte[(bmp.Width * bmp.Height)];
for (int i = 0; i < bmp.Width; i++)
{
for (int j = 0; j < bmp.Height; j++)
{
//获取该点的像素的RGB的颜色
Color color = bmp.GetPixel(i, j);
//Color newColor = value > average ? Color.FromArgb(0, 0, 0) : Color.FromArgb(255, 255, 255);
b[j * bmp.Width + i] = (new byte[] { color.R, color.G, color.B }).Max() > 60 ? (byte)0 : (byte)1;
//bmp.SetPixel(i, j, newColor);
}
}
return b;
}
}
}
using System;
namespace JmpPrintService.DBContent
{
public class tb_jp_plan_detail
{
/// <summary>
/// 主键
/// </summary>
public string Id { get; set; }
/// <summary>
/// 单号
/// </summary>
public string localNo { get; set; }
/// <summary>
/// 信息
/// </summary>
public string information1 { get; set; }
/// <summary>
/// 信息
/// </summary>
public string information2 { get; set; }
/// <summary>
/// 信息
/// </summary>
public string information3 { get; set; }
/// <summary>
/// 信息
/// </summary>
public string information4 { get; set; }
/// <summary>
/// 信息
/// </summary>
public string information5 { get; set; }
/// <summary>
/// 信息
/// </summary>
public string information6 { get; set; }
/// <summary>
/// 信息
/// </summary>
public string information7 { get; set; }
/// <summary>
/// 信息
/// </summary>
public string information8 { get; set; }
/// <summary>
/// 信息
/// </summary>
public string information9 { get; set; }
/// <summary>
/// 打印模板
/// </summary>
public int printModel { get; set; }
/// <summary>
/// 计划打印数量
/// </summary>
public int planNum { get; set; }
/// <summary>
/// 当前打印模板
/// </summary>
public int currentNum { get; set; }
/// <summary>
/// 打印状态
/// </summary>
public int Status { get; set; }
/// <summary>
/// 创建时间
/// </summary>
public DateTime CreateTime { get; set; }
}
}
using System;
namespace JmpPrintService.DBContent
{
public class tb_jp_print_plan
{
/// <summary>
/// 打印表ID
/// </summary>
public string id { get; set; }
/// <summary>
/// 打印表ID
/// </summary>
public string LocalNo { get; set; }
/// <summary>
/// 计划表完成状态
/// </summary>
public int State { get; set; }
/// <summary>
/// 创建时间
/// </summary>
public DateTime CreateTime { get; set; }
/// <summary>
/// 最后一次打印时间
/// </summary>
public DateTime UpdateTime { get; set; }
}
}
using LiteDB;
using System.Collections.Generic;
using System.Linq;
namespace JmpPrintService.DBContent
{
public static class ReadDB
{
/// <summary>
/// 获取数据库路径
/// </summary>
/// <returns></returns>
public static string Path()
{
var path = System.IO.Path.GetFullPath(
System.AppDomain.CurrentDomain.BaseDirectory +
string.Format("/litedb-{0}.db", "litedb-2f6d864e-7f00-412d-aa5d-58593ad2f15d"));
return path;
}
/// <summary>
/// 增加
/// </summary>
/// <typeparam name="tb_Batch"></typeparam>
/// <param name="obj"></param>
/// <returns></returns>
public static int SaveTPrintInfo<T>(T type, string dbName) where T : new()
{
using (var db = new LiteDatabase(Path()))
{
var col = db.GetCollection<T>(dbName);
var value = col.Insert(type);
return value.AsInt32;
}
}
/// <summary>
/// 更新信息(泛型通用)
/// </summary>
/// <typeparam name="tb_Batch"></typeparam>
/// <param name="obj"></param>
/// <returns></returns>
public static bool UpdateBatch<T>(T type, string dbName) where T : new()
{
using (var db = new LiteDatabase(Path()))
{
var col = db.GetCollection<T>(dbName);
var success = col.Update(type);
return success;
}
}
/// <summary>
/// 删除信息(泛型通用)
/// </summary>
/// <param name="docId"></param>
/// <returns></returns>
public static bool DeleteBatch<T>(int docId, string dbName)
{
// Open data file (or create, if not exits)
using (var db = new LiteDatabase(Path()))
{
// Get a collectoin (or create, if not exits)
var col = db.GetCollection<T>(dbName);
var success = col.Delete(docId);
return success;
}
}
/// <summary>
/// 获取全部信息(泛型通用)
/// </summary>
/// <returns></returns>
public static List<T> GetBatch<T>(string dbName)
{
using (var db = new LiteDatabase(Path()))
{
var col = db.GetCollection<T>(dbName);
var data = col.FindAll();
List<T> batchList = data.ToList<T>();
return batchList;
}
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LocalPrint.DBContent
{
public class tb_PrintInfo
{
/// <summary>
/// 主键
/// </summary>
public int Id { get; set; }
/// <summary>
/// 本地打印计划编号
/// </summary>
public string LocalNo { get; set; }
/// <summary>
/// 前置编号
/// </summary>
public string PrefixNo { get; set; }
/// <summary>
/// 号型码
/// </summary>
public string ProductCode { get; set; }
/// <summary>
/// 产品名称
/// </summary>
public string Name { get; set; }
/// <summary>
/// 供应商名称
/// </summary>
public string Supplier { get; set; }
/// <summary>
/// 号型
/// </summary>
public string Hx { get; set; }
/// <summary>
/// 打印计划数
/// </summary>
public int PlanNum { get; set; }
/// <summary>
/// 当前打印数量
/// </summary>
public int CurrentNum { get; set; }
/// <summary>
/// 创建时间
/// </summary>
public DateTime CreateTime { get; set; }
}
}
<?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>{4EA469D8-1A2C-4B3C-965F-DBE85C4414BC}</ProjectGuid>
<OutputType>Exe</OutputType>
<RootNamespace>JmpPrintService</RootNamespace>
<AssemblyName>JmpPrintService</AssemblyName>
<TargetFrameworkVersion>v4.6.1</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
<Deterministic>true</Deterministic>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>..\Programe\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup>
<StartupObject />
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|x86'">
<DebugSymbols>true</DebugSymbols>
<OutputPath>bin\x86\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<DebugType>full</DebugType>
<PlatformTarget>x86</PlatformTarget>
<ErrorReport>prompt</ErrorReport>
<CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet>
<Prefer32Bit>true</Prefer32Bit>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|x86'">
<OutputPath>bin\x86\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<Optimize>true</Optimize>
<DebugType>pdbonly</DebugType>
<PlatformTarget>x86</PlatformTarget>
<ErrorReport>prompt</ErrorReport>
<CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet>
<Prefer32Bit>true</Prefer32Bit>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|x64'">
<DebugSymbols>true</DebugSymbols>
<OutputPath>bin\x64\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<DebugType>full</DebugType>
<PlatformTarget>x64</PlatformTarget>
<ErrorReport>prompt</ErrorReport>
<CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet>
<Prefer32Bit>true</Prefer32Bit>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|x64'">
<OutputPath>bin\x64\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<Optimize>true</Optimize>
<DebugType>pdbonly</DebugType>
<PlatformTarget>x64</PlatformTarget>
<ErrorReport>prompt</ErrorReport>
<CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet>
<Prefer32Bit>true</Prefer32Bit>
</PropertyGroup>
<PropertyGroup>
<ApplicationIcon>service.ico</ApplicationIcon>
</PropertyGroup>
<ItemGroup>
<Reference Include="Fleck, Version=1.1.0.0, Culture=neutral, processorArchitecture=MSIL">
<HintPath>..\packages\Fleck.1.1.0\lib\net45\Fleck.dll</HintPath>
</Reference>
<Reference Include="LibUsbDotNet.LibUsbDotNet, Version=2.2.0.0, Culture=neutral, PublicKeyToken=c677239abe1e02a9, processorArchitecture=MSIL">
<HintPath>..\packages\LibUsbDotNet.2.2.29\lib\net45\LibUsbDotNet.LibUsbDotNet.dll</HintPath>
</Reference>
<Reference Include="LiteDB">
<HintPath>packages\LiteDB.dll</HintPath>
</Reference>
<Reference Include="Microsoft.Win32.Registry, Version=4.1.3.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
<HintPath>..\packages\Microsoft.Win32.Registry.4.7.0\lib\net461\Microsoft.Win32.Registry.dll</HintPath>
</Reference>
<Reference Include="Newtonsoft.Json, Version=12.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL">
<HintPath>..\packages\Newtonsoft.Json.12.0.3\lib\net45\Newtonsoft.Json.dll</HintPath>
</Reference>
<Reference Include="RJCP.SerialPortStream, Version=2.2.1.0, Culture=neutral, PublicKeyToken=5f5e7b70c6a74deb, processorArchitecture=MSIL">
<HintPath>..\packages\SerialPortStream.2.2.1.1\lib\net45\RJCP.SerialPortStream.dll</HintPath>
</Reference>
<Reference Include="System" />
<Reference Include="System.Collections.Specialized, Version=4.0.2.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
<HintPath>..\packages\System.Collections.Specialized.4.3.0\lib\net46\System.Collections.Specialized.dll</HintPath>
</Reference>
<Reference Include="System.ComponentModel.DataAnnotations" />
<Reference Include="System.Configuration" />
<Reference Include="System.Configuration.Install" />
<Reference Include="System.Core" />
<Reference Include="System.Data.OracleClient" />
<Reference Include="System.Diagnostics.FileVersionInfo, Version=4.0.1.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
<HintPath>..\packages\System.Diagnostics.FileVersionInfo.4.3.0\lib\net46\System.Diagnostics.FileVersionInfo.dll</HintPath>
</Reference>
<Reference Include="System.Diagnostics.TraceSource, Version=4.0.1.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
<HintPath>..\packages\System.Diagnostics.TraceSource.4.3.0\lib\net46\System.Diagnostics.TraceSource.dll</HintPath>
</Reference>
<Reference Include="System.Drawing" />
<Reference Include="System.IO.FileSystem, Version=4.0.2.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
<HintPath>..\packages\System.IO.FileSystem.4.3.0\lib\net46\System.IO.FileSystem.dll</HintPath>
</Reference>
<Reference Include="System.IO.FileSystem.Primitives, Version=4.0.2.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
<HintPath>..\packages\System.IO.FileSystem.Primitives.4.3.0\lib\net46\System.IO.FileSystem.Primitives.dll</HintPath>
</Reference>
<Reference Include="System.Management" />
<Reference Include="System.Net" />
<Reference Include="System.Numerics" />
<Reference Include="System.Runtime.InteropServices.RuntimeInformation, Version=4.0.1.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
<HintPath>..\packages\System.Runtime.InteropServices.RuntimeInformation.4.3.0\lib\net45\System.Runtime.InteropServices.RuntimeInformation.dll</HintPath>
</Reference>
<Reference Include="System.Security" />
<Reference Include="System.Security.AccessControl, Version=4.1.3.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
<HintPath>..\packages\System.Security.AccessControl.4.7.0\lib\net461\System.Security.AccessControl.dll</HintPath>
</Reference>
<Reference Include="System.Security.Principal.Windows, Version=4.1.3.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
<HintPath>..\packages\System.Security.Principal.Windows.4.7.0\lib\net461\System.Security.Principal.Windows.dll</HintPath>
</Reference>
<Reference Include="System.Threading.Overlapped, Version=4.0.2.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
<HintPath>..\packages\System.Threading.Overlapped.4.3.0\lib\net46\System.Threading.Overlapped.dll</HintPath>
</Reference>
<Reference Include="System.Threading.Thread, Version=4.0.1.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
<HintPath>..\packages\System.Threading.Thread.4.3.0\lib\net46\System.Threading.Thread.dll</HintPath>
</Reference>
<Reference Include="System.Threading.ThreadPool, Version=4.0.11.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
<HintPath>..\packages\System.Threading.ThreadPool.4.3.0\lib\net46\System.Threading.ThreadPool.dll</HintPath>
</Reference>
<Reference Include="System.Transactions" />
<Reference Include="System.Windows.Forms" />
<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.ServiceProcess" />
<Reference Include="System.Xml" />
<Reference Include="zxing, Version=0.16.5.0, Culture=neutral, PublicKeyToken=4e88037ac681fe60, processorArchitecture=MSIL">
<HintPath>..\packages\ZXing.Net.0.16.5\lib\net461\zxing.dll</HintPath>
</Reference>
<Reference Include="zxing.presentation, Version=0.16.5.0, Culture=neutral, PublicKeyToken=4e88037ac681fe60, processorArchitecture=MSIL">
<HintPath>..\packages\ZXing.Net.0.16.5\lib\net461\zxing.presentation.dll</HintPath>
</Reference>
</ItemGroup>
<ItemGroup>
<Compile Include="Basic\JmpTagInit.cs" />
<Compile Include="Basic\CmdAnalysis.cs" />
<Compile Include="Basic\ComConnect.cs" />
<Compile Include="Basic\ConnectBase.cs" />
<Compile Include="Basic\PrinterBase.cs" />
<Compile Include="Basic\PrintCache.cs" />
<Compile Include="Basic\ToshibaPrinter.cs" />
<Compile Include="Basic\UsbConnect.cs" />
<Compile Include="CommonHelper.cs" />
<Compile Include="Log.cs" />
<Compile Include="PrintModel\PrintState.cs" />
<Compile Include="PrintModel\TAG_INFO.cs" />
<Compile Include="PrintModel\ToshibaTemplate.cs" />
<Compile Include="PrintServiceInstaller.cs">
<SubType>Component</SubType>
</Compile>
<Compile Include="PrintServiceInstaller.Designer.cs">
<DependentUpon>PrintServiceInstaller.cs</DependentUpon>
</Compile>
<Compile Include="PrintService.cs">
<SubType>Component</SubType>
</Compile>
<Compile Include="PrintService.Designer.cs">
<DependentUpon>PrintService.cs</DependentUpon>
</Compile>
<Compile Include="Program.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="UsbBaseWMI.cs" />
</ItemGroup>
<ItemGroup>
<None Include="App.config" />
<None Include="packages.config" />
<None Include="PrintConfig.config" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="PrintServiceInstaller.resx">
<DependentUpon>PrintServiceInstaller.cs</DependentUpon>
</EmbeddedResource>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\JmpModel\JmpModel.csproj">
<Project>{7e4c3e44-3418-43d0-915b-57f76cf4cab4}</Project>
<Name>JmpModel</Name>
</ProjectReference>
</ItemGroup>
<ItemGroup>
<Content Include="service.ico" />
</ItemGroup>
<ItemGroup />
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
</Project>
\ No newline at end of file
<?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>{4EA469D8-1A2C-4B3C-965F-DBE85C4414BC}</ProjectGuid>
<OutputType>WinExe</OutputType>
<RootNamespace>JmpZbService</RootNamespace>
<AssemblyName>JmpZbService</AssemblyName>
<TargetFrameworkVersion>v4.6.1</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
<Deterministic>true</Deterministic>
<IsWebBootstrapper>false</IsWebBootstrapper>
<PublishUrl>publish\</PublishUrl>
<Install>true</Install>
<InstallFrom>Disk</InstallFrom>
<UpdateEnabled>false</UpdateEnabled>
<UpdateMode>Foreground</UpdateMode>
<UpdateInterval>7</UpdateInterval>
<UpdateIntervalUnits>Days</UpdateIntervalUnits>
<UpdatePeriodically>false</UpdatePeriodically>
<UpdateRequired>false</UpdateRequired>
<MapFileExtensions>true</MapFileExtensions>
<ApplicationRevision>0</ApplicationRevision>
<ApplicationVersion>1.0.0.%2a</ApplicationVersion>
<UseApplicationTrust>false</UseApplicationTrust>
<BootstrapperEnabled>true</BootstrapperEnabled>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<PlatformTarget>x86</PlatformTarget>
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>..\Programe\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>..\Programe\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup>
<StartupObject />
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|x86'">
<DebugSymbols>true</DebugSymbols>
<OutputPath>bin\x86\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<DebugType>full</DebugType>
<PlatformTarget>x86</PlatformTarget>
<ErrorReport>prompt</ErrorReport>
<CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet>
<Prefer32Bit>true</Prefer32Bit>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|x86'">
<OutputPath>bin\x86\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<Optimize>true</Optimize>
<DebugType>pdbonly</DebugType>
<PlatformTarget>x86</PlatformTarget>
<ErrorReport>prompt</ErrorReport>
<CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet>
<Prefer32Bit>true</Prefer32Bit>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Debug|x64'">
<DebugSymbols>true</DebugSymbols>
<OutputPath>bin\x64\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<DebugType>full</DebugType>
<PlatformTarget>x64</PlatformTarget>
<ErrorReport>prompt</ErrorReport>
<CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet>
<Prefer32Bit>true</Prefer32Bit>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release|x64'">
<OutputPath>bin\x64\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<Optimize>true</Optimize>
<DebugType>pdbonly</DebugType>
<PlatformTarget>x64</PlatformTarget>
<ErrorReport>prompt</ErrorReport>
<CodeAnalysisRuleSet>MinimumRecommendedRules.ruleset</CodeAnalysisRuleSet>
<Prefer32Bit>true</Prefer32Bit>
</PropertyGroup>
<PropertyGroup>
<ApplicationIcon>service.ico</ApplicationIcon>
</PropertyGroup>
<ItemGroup>
<Reference Include="LibUsbDotNet.LibUsbDotNet, Version=2.2.0.0, Culture=neutral, PublicKeyToken=c677239abe1e02a9, processorArchitecture=MSIL">
<HintPath>..\packages\LibUsbDotNet.2.2.29\lib\net45\LibUsbDotNet.LibUsbDotNet.dll</HintPath>
</Reference>
<Reference Include="LiteDB">
<HintPath>packages\LiteDB.dll</HintPath>
</Reference>
<Reference Include="Microsoft.Win32.Registry, Version=4.0.1.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
<HintPath>..\packages\Microsoft.Win32.Registry.4.3.0\lib\net46\Microsoft.Win32.Registry.dll</HintPath>
</Reference>
<Reference Include="NetworkCommsDotNet, Version=3.0.0.0, Culture=neutral, PublicKeyToken=f58108eb6480f6ec, processorArchitecture=MSIL">
<HintPath>..\packages\NetworkCommsDotNet.3.0.3\lib\NetworkCommsDotNet.dll</HintPath>
</Reference>
<Reference Include="Newtonsoft.Json, Version=12.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL">
<HintPath>..\packages\Newtonsoft.Json.12.0.3\lib\net45\Newtonsoft.Json.dll</HintPath>
</Reference>
<Reference Include="RJCP.SerialPortStream, Version=2.2.0.0, Culture=neutral, PublicKeyToken=5f5e7b70c6a74deb, processorArchitecture=MSIL">
<HintPath>..\packages\SerialPortStream.2.2.0\lib\net45\RJCP.SerialPortStream.dll</HintPath>
</Reference>
<Reference Include="System" />
<Reference Include="System.Collections.Specialized, Version=4.0.2.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
<HintPath>..\packages\System.Collections.Specialized.4.3.0\lib\net46\System.Collections.Specialized.dll</HintPath>
</Reference>
<Reference Include="System.ComponentModel.DataAnnotations" />
<Reference Include="System.Configuration" />
<Reference Include="System.Configuration.Install" />
<Reference Include="System.Core" />
<Reference Include="System.Data.OracleClient" />
<Reference Include="System.Diagnostics.FileVersionInfo, Version=4.0.1.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
<HintPath>..\packages\System.Diagnostics.FileVersionInfo.4.3.0\lib\net46\System.Diagnostics.FileVersionInfo.dll</HintPath>
</Reference>
<Reference Include="System.Diagnostics.TraceSource, Version=4.0.1.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
<HintPath>..\packages\System.Diagnostics.TraceSource.4.3.0\lib\net46\System.Diagnostics.TraceSource.dll</HintPath>
</Reference>
<Reference Include="System.Drawing" />
<Reference Include="System.IO.FileSystem, Version=4.0.2.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
<HintPath>..\packages\System.IO.FileSystem.4.3.0\lib\net46\System.IO.FileSystem.dll</HintPath>
</Reference>
<Reference Include="System.IO.FileSystem.Primitives, Version=4.0.2.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
<HintPath>..\packages\System.IO.FileSystem.Primitives.4.3.0\lib\net46\System.IO.FileSystem.Primitives.dll</HintPath>
</Reference>
<Reference Include="System.Management" />
<Reference Include="System.Net" />
<Reference Include="System.Numerics" />
<Reference Include="System.Runtime.InteropServices.RuntimeInformation, Version=4.0.1.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
<HintPath>..\packages\System.Runtime.InteropServices.RuntimeInformation.4.3.0\lib\net45\System.Runtime.InteropServices.RuntimeInformation.dll</HintPath>
</Reference>
<Reference Include="System.Security" />
<Reference Include="System.Threading.Overlapped, Version=4.0.2.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
<HintPath>..\packages\System.Threading.Overlapped.4.3.0\lib\net46\System.Threading.Overlapped.dll</HintPath>
</Reference>
<Reference Include="System.Threading.Thread, Version=4.0.1.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
<HintPath>..\packages\System.Threading.Thread.4.3.0\lib\net46\System.Threading.Thread.dll</HintPath>
</Reference>
<Reference Include="System.Threading.ThreadPool, Version=4.0.11.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
<HintPath>..\packages\System.Threading.ThreadPool.4.3.0\lib\net46\System.Threading.ThreadPool.dll</HintPath>
</Reference>
<Reference Include="System.Transactions" />
<Reference Include="System.Windows.Forms" />
<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.ServiceProcess" />
<Reference Include="System.Xml" />
<Reference Include="zxing, Version=0.16.5.0, Culture=neutral, PublicKeyToken=4e88037ac681fe60, processorArchitecture=MSIL">
<HintPath>..\packages\ZXing.Net.0.16.5\lib\net461\zxing.dll</HintPath>
</Reference>
<Reference Include="zxing.presentation, Version=0.16.5.0, Culture=neutral, PublicKeyToken=4e88037ac681fe60, processorArchitecture=MSIL">
<HintPath>..\packages\ZXing.Net.0.16.5\lib\net461\zxing.presentation.dll</HintPath>
</Reference>
</ItemGroup>
<ItemGroup>
<Compile Include="Basic\CmdAnalysis.cs" />
<Compile Include="Basic\ComConnect.cs" />
<Compile Include="Basic\ConnectBase.cs" />
<Compile Include="Basic\JmpTagInit.cs" />
<Compile Include="Basic\PrinterBase.cs" />
<Compile Include="Basic\PrintCache.cs" />
<Compile Include="Basic\ToshibaPrinter.cs" />
<Compile Include="Basic\UsbConnect.cs" />
<Compile Include="Basic\CommonHelper.cs" />
<Compile Include="Log.cs" />
<Compile Include="Model\ResponeMsg.cs" />
<Compile Include="Model\PrintState.cs" />
<Compile Include="Model\TAG_INFO.cs" />
<Compile Include="Model\ToshibaTemplate.cs" />
<Compile Include="PrintServiceInstaller.cs">
<SubType>Component</SubType>
</Compile>
<Compile Include="PrintServiceInstaller.Designer.cs">
<DependentUpon>PrintServiceInstaller.cs</DependentUpon>
</Compile>
<Compile Include="PrintService.cs">
<SubType>Component</SubType>
</Compile>
<Compile Include="PrintService.Designer.cs">
<DependentUpon>PrintService.cs</DependentUpon>
</Compile>
<Compile Include="Program.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
<Compile Include="Properties\Resource.Designer.cs">
<AutoGen>True</AutoGen>
<DesignTime>True</DesignTime>
<DependentUpon>Resource.resx</DependentUpon>
</Compile>
<Compile Include="UsbBaseWMI.cs" />
</ItemGroup>
<ItemGroup>
<None Include="App.config" />
<None Include="packages.config" />
<None Include="PrintConfig.config" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="PrintService.resx">
<DependentUpon>PrintService.cs</DependentUpon>
</EmbeddedResource>
<EmbeddedResource Include="PrintServiceInstaller.resx">
<DependentUpon>PrintServiceInstaller.cs</DependentUpon>
</EmbeddedResource>
<EmbeddedResource Include="Properties\Resource.resx">
<Generator>ResXFileCodeGenerator</Generator>
<LastGenOutput>Resource.Designer.cs</LastGenOutput>
<SubType>Designer</SubType>
</EmbeddedResource>
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\JmpZbModel\JmpZbModel.csproj">
<Project>{7e4c3e44-3418-43d0-915b-57f76cf4cab4}</Project>
<Name>JmpZbModel</Name>
</ProjectReference>
</ItemGroup>
<ItemGroup>
<None Include="Resources\piece.txt" />
<None Include="Resources\pieceXB.txt" />
<None Include="Resources\pieceBag.txt" />
<Content Include="service.ico" />
</ItemGroup>
<ItemGroup>
<BootstrapperPackage Include=".NETFramework,Version=v4.6.1">
<Visible>False</Visible>
<ProductName>Microsoft .NET Framework 4.6.1 %28x86 和 x64%29</ProductName>
<Install>true</Install>
</BootstrapperPackage>
<BootstrapperPackage Include="Microsoft.Net.Framework.3.5.SP1">
<Visible>False</Visible>
<ProductName>.NET Framework 3.5 SP1</ProductName>
<Install>false</Install>
</BootstrapperPackage>
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
</Project>
\ No newline at end of file
using System;
using System.IO;
using System.Text;
namespace JmpPrintService
{
public class Log
{
//private static
private static StreamWriter sr;
private static readonly object syncWorkObj = new object();
private static readonly object syncErrorObj = new object();
private static readonly object syncDebugObj = new object();
private static bool bEnableWorkLog = true;
private static bool bEnableErrorLog = true;
private static bool bEnableDebugLog = true;
public Log()
{
}
/// <summary>
/// Log 启用
/// </summary>
/// <param name="enable"></param>
public static void EnableWorkLog(bool enable)
{
bEnableWorkLog = enable;
}
/// <summary>
/// Log 启用
/// </summary>
/// <param name="enable"></param>
public static void EnableErrorLog(bool enable)
{
bEnableErrorLog = enable;
}
/// <summary>
/// Log 启用
/// </summary>
/// <param name="enable"></param>
public static void EnableDebugLog(bool enable)
{
bEnableDebugLog = enable;
}
/// <summary>
/// 工作日志
/// </summary>
/// <param name="logTxt"></param>
/// <param name="ModuleName"></param>
public static void WorkLog(string logTxt, string ModuleName)
{
lock (syncWorkObj)
{
if (bEnableWorkLog)
{
WriteLine(logTxt, ModuleName, "WorkLog/");
}
}
}
/// <summary>
/// 异常日志
/// </summary>
/// <param name="logTxt"></param>
/// <param name="ModuleName"></param>
public static void ErrorLog(string logTxt, string ModuleName)
{
lock (syncErrorObj)
{
if (bEnableErrorLog)
{
WriteLine(logTxt, ModuleName, "ErrorLog/");
}
}
}
/// <summary>
/// 异常日志
/// </summary>
/// <param name="logTxt"></param>
/// <param name="ModuleName"></param>
public static void DebugLog(string logTxt, string ModuleName)
{
lock (syncDebugObj)
{
if (bEnableDebugLog)
{
WriteLine(logTxt, ModuleName, "DebugLog/");
}
}
}
/// <summary>
/// 写日志
/// </summary>
/// <param name="logTxt"></param>
/// <param name="ModuleName"></param>
/// <param name="pathName"></param>
private static void WriteLine(string logTxt, string ModuleName, string pathName)
{
try
{
string logPath = AppDomain.CurrentDomain.SetupInformation.ApplicationBase + pathName
+ DateTime.Now.ToString("yyyyMMdd");
ClearFile(AppDomain.CurrentDomain.SetupInformation.ApplicationBase + pathName);
logTxt = string.Format(" {0}|{1}|{2}",
DateTime.Now.ToString("yyyy-MM-dd HH:mm"),
ModuleName,
logTxt);
sr = new StreamWriter(logPath, true, Encoding.Default);
sr.WriteLine(logTxt);
sr.Close();
}
catch { }
}
/// <summary>
/// 日志清除文件
/// </summary>
/// <param name="FilePath"></param>
private static void ClearFile(string FilePath)
{
if (!Directory.Exists(FilePath))
{
Directory.CreateDirectory(FilePath);
}
String[] Files = Directory.GetFiles(FilePath);
if (Files.Length > 30)
{
for (int i = 0; i < 1; i++)
{
try
{
File.Delete(Files[i]);
}
catch
{
}
}
}
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace JmpPrintService.Model
{
public enum PrintState
{
正常,
异常,
暂停
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace JmpZbService.Model
{
public class ResponeMsg
{
public bool Success { get; set; }
public string Message { get; set; }
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace JmpPrintService.Model
{
public class TAG_INFO
{
public string TAG_TID { get; set; }
public string TAG_EPC { get; set; }
public string TAG_USER { get; set; }
public string TAG_PASS { get; set; }
public string TAG_VER { get; set; }
}
}
using JmpZbService.Basic;
using System;
using System.Drawing;
using System.IO;
namespace JmpZbService.Model
{
public static class ToshibaTemplate
{
public static int Version { get; set; } = 2;
/// <summary>
/// 供应商列最大字数
/// </summary>
private static int TitleMaxWord { get; set; } = 17;
/// <summary>
/// 单个字间隔
/// </summary>
private static int TitleWordLen { get; set; } = 55;
private static string PieceImgString { get; set; }
private static string BoxImgString { get; set; }
/// <summary>
/// RFID物料命令
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="entity"></param>
/// <param name="strModelType"></param>
/// <returns></returns>
public static string GetRfidPrintCmd<T>(T entity, string strModelType)
{
string strTemplate = Properties.Resource.ResourceManager.GetString(strModelType);
if (strTemplate==null)
{
//未找到模板
return null;
}
var property = typeof(T);
foreach (var property_item in property.GetProperties())
{
var property_value = property_item.GetValue(entity)?.ToString() ?? "";
strTemplate = strTemplate.Replace(property_item.Name, property_value);
}
return strTemplate;
}
/// <summary>
/// 读当前标签的EPC信息
/// </summary>
public static string ReadTagTID()
{
string sCommand = string.Empty;//"{C|}"+ "{WF;T24,I2|}";
if (Version == 1)//东芝打印机B-SX5T旧版本
{
sCommand += "{C|}{WF;T24,I1|}";
}
if (Version == 2)//东芝打印机B-EX4T1-G新版本
{
sCommand += "{C|}{WF;A000,T24,I4,U1|}";
}
return sCommand;
}
/// <summary>
/// 读当前标签的EPC信息
/// </summary>
public static string ReadTagEpc()
{
return "{C|}{WF;T24,I2|}";
}
/// <summary>
/// 写EPC信息,不使用碳带 {D0580,1000,0500|}{C|}{@003;+0000|}{XB00;0000,0000,r,T24,G2,V1,B01=" + epc + "|}{XS;I,0001,0002C5301|}
/// </summary>
/// <param name="epc"></param>
public static string WriteTag(string epc)
{
string sCommand = "{D0580,1000,0500|}"
+ "{C|}"
+ "{@003;+0000|}"
+ "{XB00;0000,0000,r,T24,G2,V1,B01=" + epc + "|}"
+ "{XS;I,0001,0002C5301|}";
return epc;
}
private static string GetTitleMarginLeft(string strValue)
{
var str_len = strValue.Length;
var total_margin = TitleMaxWord - str_len;
if (total_margin <= 0) { return "0"; }
else
{
return $"{total_margin / 2 * TitleWordLen}";
}
}
private static string GetPieceImageString()
{
if (string.IsNullOrEmpty(PieceImgString))
{
PieceImgString = CommonHelper.Image2String((Bitmap)Image.FromFile(AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "piece_logo.jpg"));
}
return PieceImgString;
}
private static string GetBoxImageString()
{
if (string.IsNullOrEmpty(BoxImgString))
{
BoxImgString = CommonHelper.Image2String((Bitmap)Image.FromFile(AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "box_logo.jpg"));
}
return BoxImgString;
}
}
}
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
</configuration>
\ No newline at end of file
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LocalPrint
{
public class PrintInfo
{
/// <summary>
/// 停止位
/// </summary>
private System.IO.Ports.StopBits _stopBits = System.IO.Ports.StopBits.One;
/// <summary>
/// 检验位
/// </summary>
private System.IO.Ports.Parity _checkBits = System.IO.Ports.Parity.None;
/// <summary>
/// 流控制
/// </summary>
private System.IO.Ports.Handshake _flowControl = System.IO.Ports.Handshake.None;
/// <summary>
/// 波特率
/// </summary>
private int _baudRate = 115200;
/// <summary>
/// 数据位
/// </summary>
private int _dataBits = 8;
/// <summary>
/// 串口名称
/// </summary>
private string _portName = "COM4" +
"";
/// <summary>
/// 串口类
/// </summary>
public System.IO.Ports.SerialPort sSerialPort = new System.IO.Ports.SerialPort();
/// <summary>
/// 连接Com口
/// </summary>
/// <param name="isSuccess"></param>
/// <param name="msg"></param>
public void OpenComm(ref bool isSuccess, ref String msg)
{
try
{
if (this.sSerialPort.IsOpen)
{
this.sSerialPort.Close();
}
//设置参数打开串口信息
this.sSerialPort.PortName = "COM4";
//波特率
this.sSerialPort.BaudRate = this._baudRate;
//数据位
this.sSerialPort.DataBits = this._dataBits;
//停止位
this.sSerialPort.StopBits = this._stopBits;
//检验位
this.sSerialPort.Parity = this._checkBits;
//流控制
this.sSerialPort.Handshake = this._flowControl;
this.sSerialPort.Open();
if (this.sSerialPort.IsOpen)
{
isSuccess = true;
msg = ("串口打开成功!");
}
else
{
isSuccess = false;
}
}
catch (Exception ex)
{
isSuccess = false;
msg = ("请确保打印机连接正常.Error:" + ex.Message);
}
}
/// <summary>
/// 关闭连接
/// </summary>
/// <param name="isSuccess"></param>
/// <param name="msg"></param>
public void CloseComm(ref bool isSuccess, ref string msg)
{
try
{
if (this.sSerialPort == null)
{
msg = ("无对应的串口信息!");
isSuccess = false;
}
if (this.sSerialPort.IsOpen)
{
this.sSerialPort.Close();
msg = ("串口关闭成功!");
isSuccess = true;
}
}
catch (Exception ex)
{
isSuccess = false;
msg = ("请联系管理员.Error:" + ex.Message);
}
}
/// <summary>
/// 发送打印指令
/// </summary>
/// <param name="sSendText"></param>
/// <param name="isSuccess"></param>
/// <param name="msg"></param>
public void SendPrintCmd(string sSendText, ref bool isSuccess, ref String msg)
{
try
{
if (this.sSerialPort == null)
{
msg = ("无串口信息!");
isSuccess = false;
return;
}
if (!this.sSerialPort.IsOpen)
{
msg = ("串口没有打开!");
isSuccess = false;
return;
}
byte[] temp = System.Text.ASCIIEncoding.Default.GetBytes(sSendText);
Char[] temp2 = System.Text.Encoding.GetEncoding("GB18030").GetChars(temp);
Byte[] data = System.Text.Encoding.GetEncoding("GB18030").GetBytes(temp2);
this.sSerialPort.Write(data, 0, data.Length);
}
catch (Exception ex)
{
msg = ("btn_Send_Click.Error:" + ex.Message);
isSuccess = false;
}
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace JmpPrintService.PrintModel
{
public enum PrintState
{
正常,
异常,
暂停
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace JmpPrintService.PrintModel
{
public class TAG_INFO
{
public string TAG_TID { get; set; }
public string TAG_EPC { get; set; }
public string TAG_USER { get; set; }
public string TAG_PASS { get; set; }
public string TAG_VER { get; set; }
}
}
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
namespace JmpPrintService.PrintModel
{
public static class ToshibaTemplate
{
public static int Version { get; set; } = 2;
/// <summary>
/// 供应商列最大字数
/// </summary>
private static int TitleMaxWord { get; set; } = 17;
/// <summary>
/// 单个字间隔
/// </summary>
private static int TitleWordLen { get; set; } = 55;
//private static string PieceImgString { get; set; }
//private static string BoxImgString { get; set; }
private static Dictionary<string, string> dic_remplate = new Dictionary<string, string>();
/// <summary>
/// RFID物料命令
/// </summary>
/// <param name="str1"></param>
/// <param name="str2"></param>
/// <param name="str3"></param>
/// <param name="str4"></param>
/// <param name="str5"></param>
/// <param name="str6"></param>
/// <param name="strEpc"></param>
/// <returns></returns>
public static string GetRfidPrintCmd<T>(T entity, string strModelType)
{
string strTemplate = string.Empty;//File.ReadAllText(AppDomain.CurrentDomain.BaseDirectory + "Template\\1.txt");
string strPath = string.Empty;
switch (strModelType)
{
case "51":
strPath = AppDomain.CurrentDomain.BaseDirectory + "Template\\1.txt";
break;
case "52":
strPath = AppDomain.CurrentDomain.BaseDirectory + "Template\\2.txt";
break;
case "53":
strPath = AppDomain.CurrentDomain.BaseDirectory + "Template\\3.txt";
break;
}
if (!File.Exists(strPath)) { return string.Empty; }
else
{
if (dic_remplate.ContainsKey(strModelType))
{
strTemplate = dic_remplate[strModelType];
}
else
{
strTemplate = File.ReadAllText(strPath);
dic_remplate.Add(strModelType, strTemplate);
}
var property = typeof(T);
foreach (var property_item in property.GetProperties())
{
var property_value = property_item.GetValue(entity)?.ToString() ?? "";
if (property_item.Name == "Info1" && strModelType == "52")
{
//个人箱二维码处理
var strQrCode = CommonHelper.PhotoImageInsert(property_value);
strTemplate = strTemplate.Replace(property_item.Name, strQrCode);
}
//特体件标加警号
else if (property_item.Name == "Info3" && strModelType == "53")
{
var police_no = property.GetProperty("Info5")?.GetValue(entity)?.ToString() ?? "";
strTemplate = strTemplate.Replace(property_item.Name, string.IsNullOrEmpty(police_no) ? property_value : $"{property_value}{police_no})");
}
else if (property_item.Name == "Info1" && strModelType == "51")
{
var info_x = GetTitleMarginLeft(property_value);
strTemplate = strTemplate.Replace(property_item.Name, property_value);
strTemplate = strTemplate.Replace("InfoX", info_x.PadLeft(4, '0'));
}
else
{
//if (strModelType == "53" && property_item.Name == "Info6")
//{
// strTemplate = strTemplate.Replace("Info6", GetPieceImageString());
//}
//if (strModelType == "51" && property_item.Name == "Info6")
//{
// strTemplate = strTemplate.Replace("Info6", GetBoxImageString());
//}
strTemplate = strTemplate.Replace(property_item.Name, property_value);
}
}
return strTemplate;
}
}
public static string GetPrintCmd<T>(T entity, string strModel)
{
return string.Empty;
}
/// <summary>
/// 读当前标签的EPC信息
/// </summary>
public static string ReadTagTID()
{
string sCommand = string.Empty;//"{C|}"+ "{WF;T24,I2|}";
if (Version == 1)//东芝打印机B-SX5T旧版本
{
sCommand += "{C|}{WF;T24,I1|}";
}
if (Version == 2)//东芝打印机B-EX4T1-G新版本
{
sCommand += "{C|}{WF;A000,T24,I4,U1|}";
}
return sCommand;
}
/// <summary>
/// 读当前标签的EPC信息
/// </summary>
public static string ReadTagEpc()
{
return "{C|}{WF;T24,I2|}";
}
/// <summary>
/// 写EPC信息,不使用碳带 {D0580,1000,0500|}{C|}{@003;+0000|}{XB00;0000,0000,r,T24,G2,V1,B01=" + epc + "|}{XS;I,0001,0002C5301|}
/// </summary>
/// <param name="epc"></param>
public static string WriteTag(string epc)
{
string sCommand = "{D0580,1000,0500|}"
+ "{C|}"
+ "{@003;+0000|}"
+ "{XB00;0000,0000,r,T24,G2,V1,B01=" + epc + "|}"
+ "{XS;I,0001,0002C5301|}";
return epc;
}
private static string GetTitleMarginLeft(string strValue)
{
var str_len = strValue.Length;
var total_margin = TitleMaxWord - str_len;
if (total_margin <= 0) { return "0"; }
else
{
return $"{total_margin / 2 * TitleWordLen}";
}
}
//private static string GetPieceImageString()
//{
// if (string.IsNullOrEmpty(PieceImgString))
// {
// PieceImgString = CommonHelper.Image2String((Bitmap)Image.FromFile(AppDomain.CurrentDomain.BaseDirectory + "piece_logo.jpg"));
// }
// return PieceImgString;
//}
//private static string GetBoxImageString()
//{
// if (string.IsNullOrEmpty(BoxImgString))
// {
// BoxImgString = CommonHelper.Image2String((Bitmap)Image.FromFile(AppDomain.CurrentDomain.BaseDirectory + "box_logo.jpg"));
// }
// return BoxImgString;
//}
}
}
namespace JmpPrintService
{
partial class PrintService
{
/// <summary>
/// 必需的设计器变量。
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// 清理所有正在使用的资源。
/// </summary>
/// <param name="disposing">如果应释放托管资源,为 true;否则为 false。</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region 组件设计器生成的代码
/// <summary>
/// 设计器支持所需的方法 - 不要修改
/// 使用代码编辑器修改此方法的内容。
/// </summary>
private void InitializeComponent()
{
components = new System.ComponentModel.Container();
this.ServiceName = "Service1";
}
#endregion
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceProcess;
using LibUsbDotNet.Main;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using JmpPrintService.Model;
using System.Threading.Tasks;
using System.Reflection;
using JmpZbModel;
using JmpPrintService.Basic;
using System.Threading;
using System.IO;
using LibUsbDotNet.DeviceNotify;
using JmpZbService.Model;
using JmpZbService.Basic;
using System.Net;
using NetworkCommsDotNet.Connections;
using NetworkCommsDotNet;
using System.Diagnostics;
namespace JmpPrintService
{
public partial class PrintService : ServiceBase
{
//private Dictionary<string, IWebSocketConnection> dic_client = new Dictionary<string, IWebSocketConnection>();
private DeviceInfo deviceInfo;
private PrinterBase printerBase;
public PrintService(string[] args)
{
InitializeComponent();
try
{
var path = AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "cfg.txt";
if (File.Exists(path))
{
var com = File.ReadAllLines(path)?.FirstOrDefault() ?? "";
if (com.ToUpper().Contains("COM"))
{
PrintCache.ComPort = com.ToUpper();
}
else { PrintCache.ComPort = "COM5"; }
}
else
{
File.CreateText(path);
}
//notifier.Enabled = false;
}
catch (Exception ex)
{
Log.ErrorLog(ex.ToString(), MethodBase.GetCurrentMethod().Name);
}
}
/// <summary>
/// 服务启动
/// </summary>
/// <param name="args"></param>
protected override void OnStart(string[] args)
{
try
{
//初始化设备信息
deviceInfo = new DeviceInfo();
//启动网络服务
//StartWs();
StartTcp();
}
catch (Exception ex)
{
Log.ErrorLog(ex.ToString(), MethodBase.GetCurrentMethod().Name);
}
}
/// <summary>
/// 打印单条任务
/// </summary>
/// <param name="mission"></param>
public async void PrintSingle(SingleInfo singleInfo, Connection client)
{
if (printerBase == null)
{
//发送打印状态
OnSendMsg(client, "RPrintLabel", "打印机未启动", false);
return;
}
else if (!printerBase.SendQueryMsg())
{
OnSendMsg(client, "RPrintLabel", "打印机未连接", false);
}
else if (await GetStateInfo(PrintState.正常) != PrintState.正常)
{
OnSendMsg(client, "RPrintLabel", "打印机异常", false);
}
else
{
//带RFID模板
string strWrite = @ToshibaTemplate.GetRfidPrintCmd(singleInfo, singleInfo.ModelType);
if (string.IsNullOrEmpty(strWrite))
{
//发送打印状态
OnSendMsg(client, "RPrintLabel", "未找到打印模板", false);
}
else
{
printerBase.SendMsg(strWrite + "{WS|}");
//延时,给够足够的时间走纸;否则可能导致RFID写入失败
Thread.Sleep(2500);
var status = await GetStateInfo(PrintState.正常);
if (status == PrintState.正常)
{
OnSendMsg(client, "RPrintLabel", singleInfo.Info9, true);
}
else
{
OnSendMsg(client, "RPrintLabel", "标签打印失败", false);
}
}
}
}
/// <summary>
/// 启动打印机
/// </summary>
/// <param name="client"></param>
/// <param name="deviceInfo"></param>
protected void StartPrint(Connection client, DeviceInfo deviceInfo)
{
try
{
if (printerBase == null && deviceInfo.PrintType == PrintType.东芝)
{
printerBase = new ToshibaPrinter();
printerBase.IsWork = false;
}
if (!printerBase?.IsWork ?? false)
{
if (printerBase.OnStart(deviceInfo.ConnectType))//程序启动成功
{
if (printerBase.SendQueryMsg())
{
OnSendMsg(client, "RStartPrint", "打印机启动成功", true);
}
else
{
OnSendMsg(client, "RStartPrint", "打印机启动失败", false);
}
}
else
{
OnSendMsg(client, "RStartPrint", "打印机启动失败", false);
}
}
else
{
OnSendMsg(client, "RStartPrint", "打印机启动成功", true);
}
}
catch (Exception ex)
{
OnSendMsg(client, "RStartPrint", "打印机启动失败", false);
Log.ErrorLog(ex.ToString(), MethodBase.GetCurrentMethod().Name);
}
}
private async Task<string> GetTagInfo()
{
PrintCache.ClearTagMsg();
DateTime startTime = DateTime.Now;
return await Task.Run(() =>
{
while (true)
{
if (Math.Abs(DateTime.Now.Subtract(startTime).TotalSeconds) > 5)
{
return string.Empty;
}
else if (PrintCache.EpcMsgCount() > 0)
{
var msg = PrintCache.DeTagMsg();
if (!string.IsNullOrEmpty(msg))
{
return msg;
}
else
{
continue;
}
}
else { continue; }
}
});
}
private async Task<PrintState> GetStateInfo(PrintState state = PrintState.异常)
{
DateTime startTime = DateTime.Now;
return await Task.Run(() =>
{
while (true)
{
if (Math.Abs(DateTime.Now.Subtract(startTime).Milliseconds) > 2000 || printerBase.GetPrintState() == state)
{
return printerBase.GetPrintState();
}
else { continue; }
}
});
}
/// <summary>
/// 校验TID,EPC是否读取完整(禁用)
/// </summary>
/// <param name="tid"></param>
/// <param name="epc"></param>
/// <returns></returns>
private bool IsGood(string tid, string epc)
{
return true;
//if (string.IsNullOrEmpty(tid) || string.IsNullOrEmpty(epc))
//{
// return true;
//}
//else
//{
// if (tid.Length > 12)
// {
// if (epc.Length < 2)
// {
// epc = "FF";
// }
// TAG_INFO tag = new TAG_INFO();
// tag.TAG_TID = tid;
// JmpTagInit.JmpPrintEncrypt("02", ref tag);
// tag.TAG_EPC = tag.TAG_EPC.PadRight(epc.Length, '0').ToUpper();
// if (tag.TAG_EPC.Equals(epc))
// {
// return true;
// }
// else
// {
// return false;
// }
// }
// else
// {
// return false;
// }
//}
}
public void TestStartupAndStop(string[] args)
{
this.OnStart(args);
Console.ReadKey();
this.OnStop();
}
/// <summary>
/// 停止服务
/// </summary>
protected override void OnStop()
{
try
{
NetworkComms.CloseAllConnections();
Connection.StopListening();
printerBase?.OnStop();
NetworkComms.Shutdown();
Process.GetCurrentProcess().Kill();
}
catch (Exception ex)
{
Log.ErrorLog(ex.ToString(), MethodBase.GetCurrentMethod().Name);
}
}
/// <summary>
/// 关闭服务
/// </summary>
protected override void OnShutdown()
{
try
{
NetworkComms.CloseAllConnections();
Connection.StopListening();
printerBase?.OnStop();
NetworkComms.Shutdown();
Process.GetCurrentProcess().Kill();
}
catch (Exception ex)
{
Log.ErrorLog(ex.ToString(), MethodBase.GetCurrentMethod().Name);
}
}
#region Tcp服务相关
protected void StartTcp(int port = 8656)
{
//IP地址和端口
IPEndPoint thePoint = new IPEndPoint(IPAddress.Parse("127.0.0.1"), port);
//开始监听此IP和端口 使用TCP协议
Connection.StartListening(ConnectionType.TCP, thePoint);
//打印标签
NetworkComms.AppendGlobalIncomingPacketHandler<string>("PrintLabel", OnPrintLabel);
//
NetworkComms.AppendGlobalIncomingPacketHandler<string>("StartPrint", OnStartPrint);
//
NetworkComms.AppendGlobalIncomingPacketHandler<string>("PrintNotice", OnPrintNotice);
//客户端连接
NetworkComms.AppendGlobalConnectionEstablishHandler(ClientLinkSuc);
//客户端断开连接
NetworkComms.AppendGlobalConnectionCloseHandler(ClientDisLink);
}
/// <summary>
/// 打印标签
/// </summary>
/// <param name="srvUrl"></param>
/// <param name="cmd"></param>
private void OnPrintLabel(PacketHeader header, Connection connection, string message)
{
try
{
if (string.IsNullOrEmpty(message))
{
SendCmdError(connection, "RPrintLabel");
return;
}
else
{
JObject jObj = JObject.Parse(message);
if (!jObj.HasValues)
{
SendCmdError(connection, "RPrintLabel");
return;
}
else
{
PrintCmdInfo cmdInfo = JsonConvert.DeserializeObject<PrintCmdInfo>(message);
if (cmdInfo.CmdType == PrintCmdType.printMsg)
{
var singleInfo = JsonConvert.DeserializeObject<SingleInfo>(cmdInfo.Message);
PrintSingle(singleInfo, connection);
}
else
{
SendCmdError(connection, "RPrintLabel");
}
}
}
}
catch (Exception ex)
{
SendCmdError(connection, "RPrintLabel");
Log.ErrorLog(ex.ToString(), MethodBase.GetCurrentMethod().Name);
}
}
private void OnStartPrint(PacketHeader header, Connection connection, string message)
{
PrintCmdInfo cmdInfo = JsonConvert.DeserializeObject<PrintCmdInfo>(message);
if (cmdInfo.CmdType == PrintCmdType.startPrint)
{
deviceInfo = JsonConvert.DeserializeObject<DeviceInfo>(cmdInfo.Message);
StartPrint(connection, deviceInfo);
}
else
{
SendCmdError(connection, "RStartPrint");
}
}
private void OnPrintNotice(PacketHeader header, Connection connection, string json)
{
}
/// <summary>
/// 客户端连接成功
/// </summary>
/// <param name="connection"></param>
private void ClientLinkSuc(Connection connection)
{
EndPoint p = connection.ConnectionInfo.RemoteEndPoint;
//Console.WriteLine($"客户端连接{p.ToString()}");
}
/// <summary>
/// 客户端断开连接
/// </summary>
/// <param name="connection"></param>
private void ClientDisLink(Connection connection)
{
EndPoint p = connection.ConnectionInfo.RemoteEndPoint;
printerBase?.OnStop();
}
private void SendCmdError(Connection connection, string route)
{
var json = JsonConvert.SerializeObject(new ResponeMsg
{
Success = false,
Message = "不被允许的指令"
});
if (connection != null &&
(connection.ConnectionInfo.ConnectionState == ConnectionState.Established
|| connection.ConnectionInfo.ConnectionState == ConnectionState.Establishing))
{
connection.SendObject(route, json);
}
}
protected void OnSendMsg(Connection client, string route, string msg, bool flag)
{
try
{
if (client != null &&
client.ConnectionInfo.ConnectionState == ConnectionState.Established ||
client.ConnectionInfo.ConnectionState == ConnectionState.Establishing)
{
{
var cmdInfo = new
{
Success = flag,
Message = msg
};
client.SendObject(route, JsonConvert.SerializeObject(cmdInfo));
}
}
}
catch (Exception ex)
{
Log.ErrorLog(ex.ToString(), MethodBase.GetCurrentMethod().Name);
}
}
#endregion
#region Websocket服务相关 (未启用)
///// <summary>
///// 启动Ws服务
///// </summary>
///// <param name="strPort"></param>
//protected void StartWs(string strPort = "8089")
//{
// var server = new WebSocketServer($"ws://0.0.0.0:{strPort}");
// server.Start(socket =>
// {
// socket.OnOpen = () =>
// {
// OnNewConnection($"{socket.ConnectionInfo.ClientIpAddress}:{socket.ConnectionInfo.ClientPort}", socket);
// };
// socket.OnClose = () =>
// {
// OnDisConnection($"{socket.ConnectionInfo.ClientIpAddress}:{socket.ConnectionInfo.ClientPort}");
// };
// socket.OnMessage = message =>
// {
// Task.Run(() =>
// {
// OnReciveData($"{socket.ConnectionInfo.ClientIpAddress}:{socket.ConnectionInfo.ClientPort}", message);
// });
// };
// });
//}
///// <summary>
/////客户端连入
///// </summary>
///// <param name="client"></param>
///// <param name="connectionInfo"></param>
//protected void OnNewConnection(string client, IWebSocketConnection connectionInfo)
//{
// if (dic_client.Count == 0)
// {
// dic_client.Add(client, connectionInfo);
// }
// else
// {
// connectionInfo.Send(JsonConvert.SerializeObject(new CmdInfo() { CmdType = CmdType.printUsed, Message = "打印机被占用,连接关闭", Success = false }));
// connectionInfo.Close();
// }
//}
///// <summary>
///// 客户端断开
///// </summary>
///// <param name="client"></param>
//protected void OnDisConnection(string client)
//{
// if (dic_client.ContainsKey(client))
// {
// dic_client.Remove(client);
// }
// printerBase?.OnStop();
//}
///// <summary>
///// 接受客户端数据
///// </summary>
///// <param name="client"></param>
///// <param name="message"></param>
//protected void OnReciveData(string client, string message)
//{
// try
// {
// if (string.IsNullOrEmpty(message)) { return; }
// JObject jObj = JObject.Parse(message);
// if (!jObj.HasValues) { return; }
// CmdInfo cmdInfo = JsonConvert.DeserializeObject<CmdInfo>(message);
// switch (cmdInfo.CmdType)
// {
// case CmdType.devQuery://查询打印机状态
// if (printerBase == null && !printerBase.IsWork)
// {
// //发送打印机未启动
// OnSendMsg(client, CmdType.devQuery, "打印机未启动", false);
// }
// else
// {
// QueryPrint(client);
// }
// break;
// case CmdType.printMsg://打印单条数据
// var singleInfo = JsonConvert.DeserializeObject<SingleInfo>(cmdInfo.Message);
// PrintSingle(singleInfo, client);
// //打印结束,释放缓存
// //printerBase.ClearFlush();
// break;
// case CmdType.startPrint://启动打印机
// deviceInfo = JsonConvert.DeserializeObject<DeviceInfo>(cmdInfo.Message);
// StartPrint(client, deviceInfo);
// break;
// default:
// break;
// }
// }
// catch (Exception ex)
// {
// Log.ErrorLog(ex.ToString(), MethodBase.GetCurrentMethod().Name);
// }
//}
//protected void OnSendMsg(string client, CmdType cmdType, string msg, bool flag)
//{
// try
// {
// if (dic_client.ContainsKey(client))
// {
// var ws_connection = dic_client[client];
// if (ws_connection != null)
// {
// CmdInfo cmdInfo = new CmdInfo()
// {
// CmdType = cmdType,
// Message = msg,
// Success = flag
// };
// ws_connection.Send(JsonConvert.SerializeObject(cmdInfo));
// }
// }
// }
// catch (Exception ex)
// {
// Log.ErrorLog(ex.ToString(), MethodBase.GetCurrentMethod().Name);
// }
//}
#endregion
}
}
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<metadata name="$this.TrayLargeIcon" type="System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>False</value>
</metadata>
</root>
\ No newline at end of file
namespace JmpPrintService
{
partial class PrintServiceInstaller
{
/// <summary>
/// 必需的设计器变量。
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// 清理所有正在使用的资源。
/// </summary>
/// <param name="disposing">如果应释放托管资源,为 true;否则为 false。</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region 组件设计器生成的代码
/// <summary>
/// 设计器支持所需的方法 - 不要修改
/// 使用代码编辑器修改此方法的内容。
/// </summary>
private void InitializeComponent()
{
this.serviceProcessInstaller = new System.ServiceProcess.ServiceProcessInstaller();
this.serviceInstaller = new System.ServiceProcess.ServiceInstaller();
//
// serviceProcessInstaller
//
this.serviceProcessInstaller.Account = System.ServiceProcess.ServiceAccount.LocalService;
this.serviceProcessInstaller.Password = null;
this.serviceProcessInstaller.Username = null;
//
// serviceInstaller
//
this.serviceInstaller.Description = "钧普科技打印服务,为打印程序提供打印支持。";
this.serviceInstaller.DisplayName = "PrintService";
this.serviceInstaller.ServiceName = "PrintService";
this.serviceInstaller.StartType = System.ServiceProcess.ServiceStartMode.Automatic;
//
// PrintServiceInstaller
//
this.Installers.AddRange(new System.Configuration.Install.Installer[] {
this.serviceProcessInstaller,
this.serviceInstaller});
}
#endregion
private System.ServiceProcess.ServiceProcessInstaller serviceProcessInstaller;
private System.ServiceProcess.ServiceInstaller serviceInstaller;
}
}
\ No newline at end of file
using System.Collections;
using System.ComponentModel;
using System.ServiceProcess;
namespace JmpPrintService
{
[RunInstaller(true)]
public partial class PrintServiceInstaller : System.Configuration.Install.Installer
{
public PrintServiceInstaller()
{
InitializeComponent();
}
public override void Commit(IDictionary savedState)
{
base.Commit(savedState);
ServiceController sc = new ServiceController("JunmpPrintService");
//判断服务状态
if (sc.Status.Equals(ServiceControllerStatus.Stopped))
{
sc.Start();
}
}
//protected override void OnAfterInstall(IDictionary savedState)
//{
// base.OnAfterInstall(savedState);
// //MessageBox.Show("是安装完成后才出现的吗?"); // 这个可以执行一个 .bat(net start XXX)来开启Windows服务,不过需要管理员权限;
//}
}
}
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<metadata name="serviceProcessInstaller.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>17, 55</value>
</metadata>
<metadata name="serviceInstaller.TrayLocation" type="System.Drawing.Point, System.Drawing, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a">
<value>208, 17</value>
</metadata>
<metadata name="$this.TrayLargeIcon" type="System.Boolean, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<value>False</value>
</metadata>
</root>
\ No newline at end of file
using System;
using System.ServiceProcess;
namespace JmpPrintService
{
static class Program
{
/// <summary>
/// 应用程序的主入口点。
/// </summary>
static void Main(string[] args)
{
ServiceBase[] ServicesToRun = new ServiceBase[]
{
new PrintService(args)
};
ServiceBase.Run(ServicesToRun);
//if (Environment.UserInteractive)//调试时开启下面
//{
// PrintService printService = new PrintService(args);
// printService.TestStartupAndStop(args);
//}
//else
//{
// //Put the body of your old Main method here.
//}
}
}
}
using System.Reflection;
using System.Runtime.InteropServices;
// 有关程序集的一般信息由以下
// 控制。更改这些特性值可修改
// 与程序集关联的信息。
[assembly: AssemblyTitle("JmpPrintService")]
[assembly: AssemblyDescription("JmpPrintService")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("JmpPrintService")]
[assembly: AssemblyCopyright("Copyright © Junmp 2020")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// 将 ComVisible 设置为 false 会使此程序集中的类型
//对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型
//请将此类型的 ComVisible 特性设置为 true。
[assembly: ComVisible(false)]
// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID
[assembly: Guid("4ea469d8-1a2c-4b3c-965f-dbe85c4414bb")]
// 程序集的版本信息由下列四个值组成:
//
// 主版本
// 次版本
// 生成号
// 修订号
//
// 可以指定所有值,也可以使用以下所示的 "*" 预置版本号和修订号
// 方法是按如下所示使用“*”: :
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.1.21")]
[assembly: AssemblyFileVersion("1.0.1.21")]
//------------------------------------------------------------------------------
// <auto-generated>
// 此代码由工具生成。
// 运行时版本:4.0.30319.42000
//
// 对此文件的更改可能会导致不正确的行为,并且如果
// 重新生成代码,这些更改将会丢失。
// </auto-generated>
//------------------------------------------------------------------------------
namespace JmpZbService.Properties {
using System;
/// <summary>
/// 一个强类型的资源类,用于查找本地化的字符串等。
/// </summary>
// 此类是由 StronglyTypedResourceBuilder
// 类通过类似于 ResGen 或 Visual Studio 的工具自动生成的。
// 若要添加或移除成员,请编辑 .ResX 文件,然后重新运行 ResGen
// (以 /str 作为命令选项),或重新生成 VS 项目。
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "16.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Resource {
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Resource() {
}
/// <summary>
/// 返回此类使用的缓存的 ResourceManager 实例。
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager {
get {
if (object.ReferenceEquals(resourceMan, null)) {
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("JmpZbService.Properties.Resource", typeof(Resource).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// 重写当前线程的 CurrentUICulture 属性,对
/// 使用此强类型资源类的所有资源查找执行重写。
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
/// <summary>
/// 查找类似 {C|}
///{D0580,1016,0508|}
///{XB00;0000,0000,r,T24,G2,V1,B01=Info9|}
///{PC01;0150,0130,20,20,e,00,B=装备名称:Info1|}
///{PC01;0150,0190,20,20,e,00,B=装备型号:Info2|}
///{PC01;0150,0250,20,20,e,00,B=件序号:Info4|}
///{PC01;0150,0310,20,20,e,00,B=生产日期:Info5|}
///{PC01;0150,0370,20,20,e,00,B=供应商:Info3|}
///{XS;I,0001,0002C7200|}
/// 的本地化字符串。
/// </summary>
internal static string piece {
get {
return ResourceManager.GetString("piece", resourceCulture);
}
}
/// <summary>
/// 查找类似 {C|}
///{D0580,1016,0508|}
///{XB00;0000,0000,r,T24,G2,V1,B01=Info9|}
///{PC01;0150,0130,20,20,e,00,B=装备名称:Info1|}
/////{PC01;0150,0190,20,20,e,00,B=装备型号:Info2|}
///{PC01;0150,0250,20,20,e,00,B=编号:Info5|}
///{PC01;0150,0310,20,20,e,00,B=打印日期:Info6|}
/////{PC01;0150,0370,20,20,e,00,B=供应商:Info3|}
///{PC01;0800,0130,40,40,e,00,B= 包|}
///{XS;I,0001,0002C7200|}
/// 的本地化字符串。
/// </summary>
internal static string pieceBag {
get {
return ResourceManager.GetString("pieceBag", resourceCulture);
}
}
/// <summary>
/// 查找类似 {C|}
///{D0580,1016,0508|}
///{XB00;0000,0000,r,T24,G2,V1,B01=Info9|}
///{PC01;0150,0130,20,20,e,00,B=装备名称:Info1|}
///{PC01;0150,0190,20,20,e,00,B=装备型号:Info2|}
///{PC01;0150,0250,20,20,e,00,B=箱序号:Info5 箱内数量:Info4|}
///{PC01;0150,0310,20,20,e,00,B=打印日期:Info6|}
///{PC01;0150,0370,20,20,e,00,B=供应商:Info3|}
///{PC01;0800,0130,40,40,e,00,B=箱|}
///{XS;I,0001,0002C7200|}
/// 的本地化字符串。
/// </summary>
internal static string pieceXB {
get {
return ResourceManager.GetString("pieceXB", resourceCulture);
}
}
}
}
<?xml version="1.0" encoding="utf-8"?>
<root>
<!--
Microsoft ResX Schema
Version 2.0
The primary goals of this format is to allow a simple XML format
that is mostly human readable. The generation and parsing of the
various data types are done through the TypeConverter classes
associated with the data types.
Example:
... ado.net/XML headers & schema ...
<resheader name="resmimetype">text/microsoft-resx</resheader>
<resheader name="version">2.0</resheader>
<resheader name="reader">System.Resources.ResXResourceReader, System.Windows.Forms, ...</resheader>
<resheader name="writer">System.Resources.ResXResourceWriter, System.Windows.Forms, ...</resheader>
<data name="Name1"><value>this is my long string</value><comment>this is a comment</comment></data>
<data name="Color1" type="System.Drawing.Color, System.Drawing">Blue</data>
<data name="Bitmap1" mimetype="application/x-microsoft.net.object.binary.base64">
<value>[base64 mime encoded serialized .NET Framework object]</value>
</data>
<data name="Icon1" type="System.Drawing.Icon, System.Drawing" mimetype="application/x-microsoft.net.object.bytearray.base64">
<value>[base64 mime encoded string representing a byte array form of the .NET Framework object]</value>
<comment>This is a comment</comment>
</data>
There are any number of "resheader" rows that contain simple
name/value pairs.
Each data row contains a name, and value. The row also contains a
type or mimetype. Type corresponds to a .NET class that support
text/value conversion through the TypeConverter architecture.
Classes that don't support this are serialized and stored with the
mimetype set.
The mimetype is used for serialized objects, and tells the
ResXResourceReader how to depersist the object. This is currently not
extensible. For a given mimetype the value must be set accordingly:
Note - application/x-microsoft.net.object.binary.base64 is the format
that the ResXResourceWriter will generate, however the reader can
read any of the formats listed below.
mimetype: application/x-microsoft.net.object.binary.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Binary.BinaryFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.soap.base64
value : The object must be serialized with
: System.Runtime.Serialization.Formatters.Soap.SoapFormatter
: and then encoded with base64 encoding.
mimetype: application/x-microsoft.net.object.bytearray.base64
value : The object must be serialized into a byte array
: using a System.ComponentModel.TypeConverter
: and then encoded with base64 encoding.
-->
<xsd:schema id="root" xmlns="" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">
<xsd:import namespace="http://www.w3.org/XML/1998/namespace" />
<xsd:element name="root" msdata:IsDataSet="true">
<xsd:complexType>
<xsd:choice maxOccurs="unbounded">
<xsd:element name="metadata">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" />
</xsd:sequence>
<xsd:attribute name="name" use="required" type="xsd:string" />
<xsd:attribute name="type" type="xsd:string" />
<xsd:attribute name="mimetype" type="xsd:string" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="assembly">
<xsd:complexType>
<xsd:attribute name="alias" type="xsd:string" />
<xsd:attribute name="name" type="xsd:string" />
</xsd:complexType>
</xsd:element>
<xsd:element name="data">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
<xsd:element name="comment" type="xsd:string" minOccurs="0" msdata:Ordinal="2" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" msdata:Ordinal="1" />
<xsd:attribute name="type" type="xsd:string" msdata:Ordinal="3" />
<xsd:attribute name="mimetype" type="xsd:string" msdata:Ordinal="4" />
<xsd:attribute ref="xml:space" />
</xsd:complexType>
</xsd:element>
<xsd:element name="resheader">
<xsd:complexType>
<xsd:sequence>
<xsd:element name="value" type="xsd:string" minOccurs="0" msdata:Ordinal="1" />
</xsd:sequence>
<xsd:attribute name="name" type="xsd:string" use="required" />
</xsd:complexType>
</xsd:element>
</xsd:choice>
</xsd:complexType>
</xsd:element>
</xsd:schema>
<resheader name="resmimetype">
<value>text/microsoft-resx</value>
</resheader>
<resheader name="version">
<value>2.0</value>
</resheader>
<resheader name="reader">
<value>System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<resheader name="writer">
<value>System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089</value>
</resheader>
<assembly alias="System.Windows.Forms" name="System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" />
<data name="piece" type="System.Resources.ResXFileRef, System.Windows.Forms">
<value>..\Resources\piece.txt;System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089;utf-8</value>
</data>
<data name="pieceBag" type="System.Resources.ResXFileRef, System.Windows.Forms">
<value>..\Resources\pieceBag.txt;System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089;utf-8</value>
</data>
<data name="pieceXB" type="System.Resources.ResXFileRef, System.Windows.Forms">
<value>..\resources\piecexb.txt;System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089;utf-8</value>
</data>
</root>
\ No newline at end of file
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LocalPrint
{
public class QRHelper
{
public static List<string> listNo1 = new List<string>() { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", ":", ";", "<", "=", ">", "?" };
/// <summary>
/// 图像二值化1:取图片的平均灰度作为阈值,低于该值的全都为0,高于该值的全都为255
/// </summary>
/// <param name="bmp">原图</param>
/// <param name="nType">放到倍数</param>
/// <returns></returns>
public static Byte[] ConvertTo1Bpp1(Bitmap bmp, int nType)
{
byte[] b = new byte[(bmp.Width * bmp.Height)];
for (int i = 0; i < bmp.Width; i++)
{
for (int j = 0; j < bmp.Height; j++)
{
//获取该点的像素的RGB的颜色
Color color = bmp.GetPixel(i, j);
//Color newColor = value > average ? Color.FromArgb(0, 0, 0) : Color.FromArgb(255, 255, 255);
b[j * bmp.Width + i] = (new byte[] { color.R, color.G, color.B }).Max() > 60 ? (byte)0 : (byte)1;
//bmp.SetPixel(i, j, newColor);
}
}
return b;
}
/// <summary>
/// 生成二维码图片
/// </summary>
/// <param name="strMessage">要生成二维码的字符串</param>
/// <param name="width">二维码图片宽度</param>
/// <param name="height">二维码图片高度</param>
/// <returns></returns>
public static string GenByZXingNet(string msg,int hight,int Width)
{
string strInfo = "";
//设置QR二维码的规格
QrCodeEncodingOptions qrEncodeOption = new QrCodeEncodingOptions();
//设置编码格式,否则中文乱码
qrEncodeOption.CharacterSet = "UTF-8";
//设置宽和高
qrEncodeOption.Height = hight;
qrEncodeOption.Width = Width;
//设置周围空白边距
qrEncodeOption.Margin = 1;
BarcodeWriter wr = new BarcodeWriter();
//二维码
wr.Format = BarcodeFormat.QR_CODE;
wr.Options = qrEncodeOption;
//生成二维码
Bitmap img = wr.Write(msg);
StringBuilder sb = new StringBuilder();
int b = 0;
long n = 0;
long clr;
sb.Append("~DGR:ZLOGO.GRF,");
BarcodeWriter writer = new BarcodeWriter();
writer.Format = BarcodeFormat.QR_CODE;
writer.Options.Hints.Add(EncodeHintType.CHARACTER_SET, "UTF-8");//编码问题
writer.Options.Hints.Add(
EncodeHintType.ERROR_CORRECTION,
ZXing.QrCode.Internal.ErrorCorrectionLevel.H
);
//const int codeSizeInPixels = hight; //设置图片长宽
writer.Options.Height = writer.Options.Width = hight;
writer.Options.Margin = 0;//设置边框
ZXing.Common.BitMatrix bm = writer.Encode(msg);
//Bitmap img = writer.Write(bm);
int w = ((img.Size.Width / 8 + ((img.Size.Width % 8 == 0) ? 0 : 1)) * img.Size.Height);
int h = (img.Size.Width / 8 + ((img.Size.Width % 8 == 0) ? 0 : 1));
sb.Append(w.ToString().PadLeft(5, '0') + "," + h.ToString().PadLeft(3, '0') + ",\n");
using (Bitmap bmp = new Bitmap(img.Size.Width, img.Size.Height))
{
for (int y = 0; y < img.Size.Height; y++)
{
for (int x = 0; x < img.Size.Width; x++)
{
b = b * 2;
clr = img.GetPixel(x, y).ToArgb();
string s = clr.ToString("X");
if (s.Substring(s.Length - 6, 6).CompareTo("BBBBBB") < 0)
{
bmp.SetPixel(x, y, img.GetPixel(x, y));
b++;
}
n++;
if (x == (img.Size.Width - 1))
{
if (n < 8)
{
b = b * (2 ^ (8 - (int)n));
sb.Append(b.ToString("X").PadLeft(2, '0'));
b = 0;
n = 0;
}
}
if (n >= 8)
{
sb.Append(b.ToString("X").PadLeft(2, '0'));
b = 0;
n = 0;
}
}
}
sb.Append(string.Format("^FO{0},{1}^XGR:ZLOGO.GRF,2,2^FS", 20, 60));
}
return sb.ToString();
}
public static string PhotoImageInsert(string QRtext,ref int Count)
{
string strInfo = "";
//设置QR二维码的规格
QrCodeEncodingOptions qrEncodeOption = new QrCodeEncodingOptions();
//设置编码格式,否则中文乱码
qrEncodeOption.CharacterSet = "UTF-8";
//设置宽和高
qrEncodeOption.Height = 330;
qrEncodeOption.Width = 330;
//设置周围空白边距
qrEncodeOption.Margin = 1;
BarcodeWriter wr = new BarcodeWriter();
//二维码
wr.Format = BarcodeFormat.QR_CODE;
wr.Options = qrEncodeOption;
//生成二维码
Bitmap image = wr.Write(QRtext);
byte[] byte1 = ConvertTo1Bpp1(image, 1);
string s = "";
int n = 0;
//打印机图片点阵宽度
int d = ((image.Width + 7) / 8) * 8;
for (int j = 0; j < image.Height; j++)
{
for (int i = 0; i < d; i++)
{
if (i >= image.Width)
{
s += "0";
}
else
{
s += byte1[j * image.Width + i].ToString();
}
if (n == 3)
{
int xjDenary = Convert.ToInt32(s, 2);
strInfo += listNo1[xjDenary];
n = 0;
s = "";
}
else
{
n++;
}
}
}
Count = strInfo.Length;
return strInfo;
}
}
}
{C|}
{D0580,1016,0508|}
{XB00;0000,0000,r,T24,G2,V1,B01=Info9|}
{PC01;0150,0130,20,20,e,00,B=装备名称:Info1|}
{PC01;0150,0190,20,20,e,00,B=装备型号:Info2|}
{PC01;0150,0250,20,20,e,00,B=件序号:Info4|}
{PC01;0150,0310,20,20,e,00,B=生产日期:Info5|}
{PC01;0150,0370,20,20,e,00,B=供应商:Info3|}
{XS;I,0001,0002C7200|}
{C|}
{D0580,1016,0508|}
{XB00;0000,0000,r,T24,G2,V1,B01=Info9|}
{PC01;0150,0190,20,20,e,00,B=装备名称:Info1|}
{PC01;0150,0250,20,20,e,00,B=编号:Info5|}
{PC01;0150,0310,20,20,e,00,B=打印日期:Info6|}
{PC01;0800,0130,40,40,e,00,B= 包|}
{XS;I,0001,0002C7200|}
{C|}
{D0580,1016,0508|}
{XB00;0000,0000,r,T24,G2,V1,B01=Info9|}
{PC01;0150,0130,20,20,e,00,B=装备名称:Info1|}
{PC01;0150,0190,20,20,e,00,B=装备型号:Info2|}
{PC01;0150,0250,20,20,e,00,B=箱序号:Info5 箱内数量:Info4|}
{PC01;0150,0310,20,20,e,00,B=打印日期:Info6|}
{PC01;0150,0370,20,20,e,00,B=供应商:Info3|}
{PC01;0800,0130,40,40,e,00,B=箱|}
{XS;I,0001,0002C7200|}
namespace LocalPrint
{
partial class Service1
{
/// <summary>
/// 必需的设计器变量。
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// 清理所有正在使用的资源。
/// </summary>
/// <param name="disposing">如果应释放托管资源,为 true;否则为 false。</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region 组件设计器生成的代码
/// <summary>
/// 设计器支持所需的方法 - 不要修改
/// 使用代码编辑器修改此方法的内容。
/// </summary>
private void InitializeComponent()
{
components = new System.ComponentModel.Container();
this.ServiceName = "Service1";
}
#endregion
}
}
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Management;
using System.Net;
using System.Net.Sockets;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.ServiceProcess;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using LibUsbDotNet;
using LibUsbDotNet.DeviceNotify;
using LibUsbDotNet.DeviceNotify.Linux;
using LibUsbDotNet.Main;
using LibUsbDotNet.LibUsb;
using Newtonsoft.Json;
using LibUsbDotNet.Info;
using System.Threading;
using static System.Windows.Forms.VisualStyles.VisualStyleElement.TaskbarClock;
namespace LocalPrint
{
public partial class Service1 : ServiceBase
{
private Dictionary<string, Session> SessionPool = new Dictionary<string, Session>();
private Dictionary<string, string> MsgPool = new Dictionary<string, string>();
public UsbRegDeviceList mRegDevices;
public Service1(string[] args)
{
InitializeComponent();
//if (Environment.UserInteractive)
//{
// Service1 service1 = new Service1(args);
// service1.TestStartupAndStop(args);
//}
//else
//{
// Put the body of your old Main method here.
//}
}
private IntPtr myHidPtr = new IntPtr();
protected override void OnStart(string[] args)
{
this.WriteLog("Junmp客户端数据同步服务:【服务启动】");
try
{
start(8080);///与WebSocket建立通讯
USBPrint Usb = new USBPrint();
bool InitRes= Usb.Init();
int QRCount = 0;
string QRCode = QRHelper.GenByZXingNet("BZWBZQR|07女绒背心|180/92:20|1|20190514|依翎公司");
string sSendText =
//"~DGR:abc.GRF," +QRCount + ",020," + QRCode +
QRCode+
"^XA" +
"^SEE:GB18030.DAT^FS" +
"^CWZ,E:SIMSUN.FNT" +
"^CI26" +
"^JMB^LL200^PW680^MD10^RP2^PON^LRN^LH0,0" +
"^FO5,10" +
"^AZN,35,35" +
"^FD01女绒背心 180/92 依翎公司^FS" +
"^FO80,25^XGR:ZLOGO.GRF,1,1^FS " +
"^PQ1"+
"^FO30,180^BY2," +
"^BCN,80,Y,N,N" +
"^FD868471268^FS" +
"^XZ";
string sSendText1 =
//"~DGR:abc.GRF," +QRCount + ",020," + QRCode +
"^XA" +
"^SEE:GB18030.DAT^FS" +
"^CWZ,E:SIMSUN.FNT" +
"^CI26" +
"^JMB^LL200^PW680^MD10^RP2^PON^LRN^LH0,0" +
"^FO5,10" +
"^AZN,35,35" +
"^FD01女绒背心 180/92 依翎公司^FS" +
"^PQ1" +
"^FO30,40^BY2," +
"^BCN,80,Y,N,N" +
"^FD868471268^FS" +
"^FO5,150" +
"^AZN,35,35" +
"^FD01女绒背心 180/92 依翎公司^FS" +
"^PQ1" +
"^FO30,180^BY2," +
"^BCN,80,Y,N,N" +
"^FD868471268^FS" +
"^XZ";
string ZPL = "~HS";
if (InitRes)
{
//Usb.SetReadFlag();
//Thread Read = new Thread(Usb.StartRead);
//Read.Start();
bool reesult1 = Usb.SendMsg(ZPL);
//Thread.Sleep(2000);
bool Reesult= Usb.SendMsg(sSendText1);
}
Thread.Sleep(5000);
Usb.StopPrint();
}
catch (Exception ex)
{
//ShowMsg("Error:" + ex.Message);
}
}
public void GetMsgInfo()
{
while (USBPrint.ReadFlag==1)
{
if (USBPrint.PrintMsg.Count>0)
{
string newMsg= USBPrint.PrintMsg.Dequeue();
byte[] msgBuffer= PackageServerData(newMsg);
Session currentClient = SessionPool[IP];
currentClient.SockeClient.Send(msgBuffer, msgBuffer.Length, SocketFlags.None);
}
}
}
private Hid myHid = new Hid();
private static void OnDeviceNotify(object sender, DeviceNotifyEventArgs e)
{
Console.WriteLine($"插入设备的 Pid {e.Device.IdProduct} vid {e.Device.IdVendor}");
}
protected override void OnStop()
{
this.WriteLog("Junmp客户端数据同步服务:【服务停止】");
}
protected override void OnShutdown()
{
this.WriteLog("Junmp客户端数据同步服务:【计算机关闭】");
}
internal void TestStartupAndStop(string[] args)
{
this.OnStart(args);
Console.ReadLine();
this.OnStop();
}
#region 启动WebSocket服务
/// <summary>
/// 启动WebSocket服务
/// </summary>
public void start(int port)
{
Socket SockeServer = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
SockeServer.Bind(new IPEndPoint(IPAddress.Any, port));
SockeServer.Listen(20);
SockeServer.BeginAccept(new AsyncCallback(Accept), SockeServer);
}
#region 处理客户端连接请求
/// <summary>
/// 处理客户端连接请求
/// </summary>
/// <param name="result"></param>
private void Accept(IAsyncResult socket)
{
// 还原传入的原始套接字
Socket SockeServer = (Socket)socket.AsyncState;
// 在原始套接字上调用EndAccept方法,返回新的套接字
Socket SockeClient = SockeServer.EndAccept(socket);
byte[] buffer = new byte[4096];
try
{
//接收客户端的数据
SockeClient.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback(Recieve), SockeClient);
//保存登录的客户端
Session session = new Session();
session.SockeClient = SockeClient;
session.IP = SockeClient.RemoteEndPoint.ToString();
session.buffer = buffer;
lock (SessionPool)
{
if (SessionPool.ContainsKey(session.IP))
{
this.SessionPool.Remove(session.IP);
}
this.SessionPool.Add(session.IP, session);
}
//准备接受下一个客户端
SockeServer.BeginAccept(new AsyncCallback(Accept), SockeServer);
}
catch (Exception ex)
{
}
}
#endregion
#endregion
#region 打包请求连接数据
/// <summary>
/// 打包请求连接数据
/// </summary>
/// <param name="handShakeBytes"></param>
/// <param name="length"></param>
/// <returns></returns>
private byte[] PackageHandShakeData(byte[] handShakeBytes, int length)
{
string handShakeText = Encoding.UTF8.GetString(handShakeBytes, 0, length);
string key = string.Empty;
Regex reg = new Regex(@"Sec\-WebSocket\-Key:(.*?)\r\n");
Match m = reg.Match(handShakeText);
if (m.Value != "")
{
key = Regex.Replace(m.Value, @"Sec\-WebSocket\-Key:(.*?)\r\n", "$1").Trim();
}
byte[] secKeyBytes = SHA1.Create().ComputeHash(Encoding.ASCII.GetBytes(key + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"));
string secKey = Convert.ToBase64String(secKeyBytes);
var responseBuilder = new StringBuilder();
responseBuilder.Append("HTTP/1.1 101 Switching Protocols" + "\r\n");
responseBuilder.Append("Upgrade: websocket" + "\r\n");
responseBuilder.Append("Connection: Upgrade" + "\r\n");
responseBuilder.Append("Sec-WebSocket-Accept: " + secKey + "\r\n\r\n");
return Encoding.UTF8.GetBytes(responseBuilder.ToString());
}
#endregion
#region 处理接收的数据
public string IP = string.Empty;
/// <summary>
/// 处理接受的数据
/// </summary>
/// <param name="socket"></param>
private void Recieve(IAsyncResult socket)
{
Socket SockeClient = (Socket)socket.AsyncState;
IP = SockeClient.RemoteEndPoint.ToString();
if (SockeClient == null || !SessionPool.ContainsKey(IP))
{
return;
}
try
{
int length = SockeClient.EndReceive(socket);
byte[] buffer = SessionPool[IP].buffer;
SockeClient.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback(Recieve), SockeClient);
string msg = Encoding.UTF8.GetString(buffer, 0, length);
// websocket建立连接的时候,除了TCP连接的三次握手,websocket协议中客户端与服务器想建立连接需要一次额外的握手动作
if (msg.Contains("Sec-WebSocket-Key"))
{
SockeClient.Send(PackageHandShakeData(buffer, length));
SessionPool[IP].isWeb = true;
return;
}
if (SessionPool[IP].isWeb)
{
msg = AnalyzeClientData(buffer, length);
}
if (msg.Equals(1))//测试打印程序
{
}
byte[] msgBuffer = PackageServerData(msg);
//foreach (Session se in SessionPool.Values)
//{
// se.SockeClient.Send(msgBuffer, msgBuffer.Length, SocketFlags.None);
//}
Session currentClient = SessionPool[IP];
currentClient.SockeClient.Send(msgBuffer, msgBuffer.Length, SocketFlags.None);
}
catch
{
//SockeClient.Disconnect(true);
SessionPool.Remove(IP);
}
}
#endregion
/// <summary>
/// 把发送给客户端消息打包处理(拼接上谁什么时候发的什么消息)
/// </summary>
/// <returns>The data.</returns>
/// <param name="message">Message.</param>
private byte[] PackageServerData(string msg)
{
byte[] content = null;
object oj = new { States = 0, Count = 0 }; // 0:没有通知,1:有通知
oj = new { States = 0 }; // 0:没有通知,1:有通知
if (!string.IsNullOrWhiteSpace(msg))
{
oj = new
{
States = 1,
NContent = "您有新消息"+ msg, //消息内容
PublisherName = "Admin", //发布消息的人
PublisherImage = "/Upload/Images/20180131/测试.png", //发布消息人头像
};
}
string json = JsonConvert.SerializeObject(oj);
byte[] temp = Encoding.UTF8.GetBytes(json);
if (temp.Length < 126)
{
content = new byte[temp.Length + 2];
content[0] = 0x81;
content[1] = (byte)temp.Length;
Buffer.BlockCopy(temp, 0, content, 2, temp.Length);
}
else if (temp.Length < 0xFFFF)
{
content = new byte[temp.Length + 4];
content[0] = 0x81;
content[1] = 126;
content[2] = (byte)(temp.Length >> 8 & 0xFF);
content[3] = (byte)(temp.Length & 0xFF);
Buffer.BlockCopy(temp, 0, content, 4, temp.Length);
}
return content;
}
/// <summary>
/// 处理接收的数据
/// </summary>
/// <param name="recBytes"></param>
/// <param name="length"></param>
/// <returns></returns>
private string AnalyzeClientData(byte[] recBytes, int length)
{
int start = 0;
// 如果有数据则至少包括3位
if (length < 2) return "";
// 判断是否为结束针
bool IsEof = (recBytes[start] >> 7) > 0;
// 暂不处理超过一帧的数据
if (!IsEof) return "";
start++;
// 是否包含掩码
bool hasMask = (recBytes[start] >> 7) > 0;
// 不包含掩码的暂不处理
if (!hasMask) return "";
// 获取数据长度
UInt64 mPackageLength = (UInt64)recBytes[start] & 0x7F;
start++;
// 存储4位掩码值
byte[] Masking_key = new byte[4];
// 存储数据
byte[] mDataPackage;
if (mPackageLength == 126)
{
// 等于126 随后的两个字节16位表示数据长度
mPackageLength = (UInt64)(recBytes[start] << 8 | recBytes[start + 1]);
start += 2;
}
if (mPackageLength == 127)
{
// 等于127 随后的八个字节64位表示数据长度
mPackageLength = (UInt64)(recBytes[start] << (8 * 7) | recBytes[start] << (8 * 6) | recBytes[start] << (8 * 5) | recBytes[start] << (8 * 4) | recBytes[start] << (8 * 3) | recBytes[start] << (8 * 2) | recBytes[start] << 8 | recBytes[start + 1]);
start += 8;
}
mDataPackage = new byte[mPackageLength];
for (UInt64 i = 0; i < mPackageLength; i++)
{
mDataPackage[i] = recBytes[i + (UInt64)start + 4];
}
Buffer.BlockCopy(recBytes, start, Masking_key, 0, 4);
for (UInt64 i = 0; i < mPackageLength; i++)
{
mDataPackage[i] = (byte)(mDataPackage[i] ^ Masking_key[i % 4]);
}
return Encoding.UTF8.GetString(mDataPackage);
}
public class Session
{
public Socket SockeClient{get;set;}
public string IP { get; set; }
public byte[] buffer { get; set; }
public bool isWeb { get; set; }
}
#region 记录日志
/// <summary>
/// 记录日志
/// </summary>
/// <param name="msg"></param>
private void WriteLog(string msg)
{
//string path = @"C:\log.txt";
//该日志文件会存在windows服务程序目录下
string path = AppDomain.CurrentDomain.BaseDirectory + "\\log.txt";
FileInfo file = new FileInfo(path);
if (!file.Exists)
{
FileStream fs;
fs = File.Create(path);
fs.Close();
}
using (FileStream fs = new FileStream(path, FileMode.Append, FileAccess.Write))
{
using (StreamWriter sw = new StreamWriter(fs))
{
sw.WriteLine(DateTime.Now.ToString() + " " + msg);
}
}
}
#endregion
}
}
using LibUsbDotNet;
using LibUsbDotNet.Main;
using System;
using System.Collections.Generic;
using System.Reflection;
using System.Text;
using System.Threading;
namespace JmpPrintService
{
public class USBPrint
{
//UsbRegDeviceList allDevices = UsbDevice.AllDevices;//获取全部USB设备
private Dictionary<string, ushort> dic_device = new Dictionary<string, ushort>();
private UsbDeviceFinder usbFinder;
private UsbDevice usbDevice;
private UsbEndpointWriter writer;
private UsbEndpointReader reader;
//ErrorCode ecWrite;
//ErrorCode ecRead;
public static Queue<string> PrintMsg = new Queue<string>();
public static int ReadFlag = 0;//读写标志
public static int PrintFlag = 0;//打印标志
/// <summary>
/// 初始化打印程序
/// </summary>
/// <returns></returns>
public bool Init()
{
try
{
//获取斑马打印机连接
dic_device = UsbBaseWMI.GetAllUsbDevInfo();
if (dic_device.Count > 0)
{
UsbRegDeviceList mRegDevices = UsbDevice.AllDevices;
usbFinder = new UsbDeviceFinder(dic_device["VID"], dic_device["PID"]);
this.usbDevice = UsbDevice.OpenUsbDevice(usbFinder);//打开斑马打印机
Guid deviceID = new Guid();
UsbDevice.OpenUsbDevice(ref deviceID, out UsbDevice usbDevice);
IUsbDevice wholeUsbDevice = this.usbDevice as IUsbDevice;
if (!ReferenceEquals(wholeUsbDevice, null))
{
//这是一个“完整的”USB设备。在使用之前,
//必须选择所需的配置和接口。
//选择config #1
wholeUsbDevice.SetConfiguration(1);
// 接口地址重置 #0
wholeUsbDevice.ClaimInterface(0);
}
if (this.usbDevice != null)
{
writer = this.usbDevice.OpenEndpointWriter(WriteEndpointID.Ep01);
reader = this.usbDevice.OpenEndpointReader(ReadEndpointID.Ep02);
reader.DataReceivedEnabled = true;
reader.DataReceived += OnDataReceived;
bool result = this.usbDevice.Open();
return result;
}
else
{
return false;
}
}
else
{
return false;
}
}
catch (Exception ex)
{
Log.ErrorLog(ex.ToString(), MethodBase.GetCurrentMethod().Name);
return false;
}
}
private void OnDataReceived(object sender, EndpointDataEventArgs e)
{
try
{
if (ReadFlag.Equals(1))
{
string res_msg = Encoding.Default.GetString(e.Buffer);
string de_msg = System.Text.RegularExpressions.Regex.Replace(res_msg, @"[^0-9]+", "");
PrintMsg.Enqueue(de_msg);
}
//byte[] readBuffer = new byte[1024];
//int bytesRead;
//while (ReadFlag.Equals(1))
//{
// ecRead = reader.Read(readBuffer, 5000, out bytesRead);
// if (bytesRead > 0)
// {
// string ReturnMsg = Encoding.Default.GetString(readBuffer);
// string result = System.Text.RegularExpressions.Regex.Replace(ReturnMsg, @"[^0-9]+", "");
// PrintMsg.Enqueue(result);
// readBuffer = new byte[1024];
// }
// if (ecRead != ErrorCode.None)
// {
// if (ecRead.Equals(ErrorCode.IoTimedOut))
// {
// continue;
// }
// else
// {
// PrintMsg.Enqueue("logout");
// break;
// }
// }
// //WaitHandle.WaitAll(new WaitHandle[] { usbReadTransfer.AsyncWaitHandle }, 200, false);
//}
}
catch (Exception ex)
{
Log.ErrorLog(ex.ToString(), MethodBase.GetCurrentMethod().Name);
}
}
/// <summary>
///
/// </summary>
public void SetReadFlag()
{
ReadFlag = 1;
}
//private List<byte> buffer = new List<byte>(4096);//默认分配1页内存
///// <summary>
/////开始读取打印数据
///// </summary>
//public void StartRead()
//{
// try
// {
// byte[] readBuffer = new byte[1024];
// int bytesRead;
// while (ReadFlag.Equals(1))
// {
// ecRead = reader.Read(readBuffer, 5000, out bytesRead);
// if (bytesRead > 0)
// {
// string ReturnMsg = Encoding.Default.GetString(readBuffer);
// string result = System.Text.RegularExpressions.Regex.Replace(ReturnMsg, @"[^0-9]+", "");
// PrintMsg.Enqueue(result);
// readBuffer = new byte[1024];
// }
// if (ecRead != ErrorCode.None)
// {
// if (ecRead.Equals(ErrorCode.IoTimedOut))
// {
// continue;
// }
// else
// {
// PrintMsg.Enqueue("logout");
// break;
// }
// }
// //WaitHandle.WaitAll(new WaitHandle[] { usbReadTransfer.AsyncWaitHandle }, 200, false);
// }
// }
// catch (Exception ex)
// {
// Log.ErrorLog(ex.ToString(), MethodBase.GetCurrentMethod().Name);
// }
// //ecRead = usbReadTransfer.Wait(out transferredIn);
//}
/// <summary>
/// 发送打印机指令
/// </summary>
/// <param name="SendText"></param>
/// <returns></returns>
public bool SendMsg(string SendText)
{
try
{
byte[] temp = System.Text.ASCIIEncoding.Default.GetBytes(SendText);
char[] temp2 = System.Text.Encoding.GetEncoding("GB18030").GetChars(temp);
Byte[] data = System.Text.Encoding.GetEncoding("GB18030").GetBytes(temp2);
ErrorCode ec = ErrorCode.None;
UsbTransfer usbWriteTransfer;
ec = writer?.SubmitAsyncTransfer(data, 0, data.Length, 100, out usbWriteTransfer) ?? ErrorCode.None;
Thread.Sleep(2000);
if (ec != ErrorCode.None)
{
ReadFlag = 0;
return false;
//throw new Exception("打印机发送指令失败.");
}
else
{
return true;
}
}
catch (Exception ex)
{
Log.ErrorLog(ex.ToString(), MethodBase.GetCurrentMethod().Name);
return false;
}
}
/// <summary>
/// 停止打印程序
/// </summary>
public void StopPrint()
{
ReadFlag = 0;
Thread.Sleep(500);
if (usbDevice != null)
{
if (usbDevice?.IsOpen ?? false)
{
usbDevice?.Close();
}
}
else
{
usbDevice = null;
}
}
public void Send()
{
try
{
string sSendText = "^XA" +
"^JMA^LL200^PW680^MD10^PR2^PON^LRN^LH0,0" +
"^FO10,30" +
"^A0N,72,72" +
"^FD Hello World!^FS" +
"^XZ";
byte[] temp = System.Text.ASCIIEncoding.Default.GetBytes(sSendText);
Char[] temp2 = System.Text.Encoding.GetEncoding("GB18030").GetChars(temp);
Byte[] data = System.Text.Encoding.GetEncoding("GB18030").GetBytes(temp2);
ErrorCode ec = ErrorCode.None;
UsbTransfer usbWriteTransfer;
ec = writer.SubmitAsyncTransfer(data, 0, data.Length, 100, out usbWriteTransfer);
}
catch (Exception ex)
{
Log.ErrorLog(ex.ToString(), MethodBase.GetCurrentMethod().Name);
}
}
//打印机可用状态集合
//public enum enum_printerS_status
//{
// / <summary>
// / 故障
// / </summary>
// warn = 0,
// / <summary>
// / 打印中
// / </summary>
// print,
// / <summary>
// / 空闲中
// / </summary>
// ready,
// / <summary>
// / 其他状态
// / </summary>
// other
//}
}
}
using System;
using System.Collections.Generic;
using System.Management;
using System.Text.RegularExpressions;
namespace JmpPrintService
{
/// <summary>
/// 基于WMI获取USB设备信息
/// </summary>
public class UsbBaseWMI
{
#region UsbDevice
/// <summary>
/// 获取所有的USB设备实体(过滤没有VID和PID的设备)
/// </summary>
public static PnPEntityInfo[] AllUsbDevices
{
get
{
return WhoUsbDevice(UInt16.MinValue, UInt16.MinValue, Guid.Empty);
}
}
/// <summary>
/// 查询USB设备实体(设备要求有VID和PID)
/// </summary>
/// <param name="VendorID">供应商标识,MinValue忽视</param>
/// <param name="ProductID">产品编号,MinValue忽视</param>
/// <param name="ClassGuid">设备安装类Guid,Empty忽视</param>
/// <returns>设备列表</returns>
public static PnPEntityInfo[] WhoUsbDevice(UInt16 VendorID, UInt16 ProductID, Guid ClassGuid)
{
List<PnPEntityInfo> UsbDevices = new List<PnPEntityInfo>();
// 获取USB控制器及其相关联的设备实体
ManagementObjectCollection USBControllerDeviceCollection = new ManagementObjectSearcher("SELECT * FROM Win32_USBControllerDevice").Get();
if (USBControllerDeviceCollection != null)
{
foreach (ManagementObject USBControllerDevice in USBControllerDeviceCollection)
{ // 获取设备实体的DeviceID
String Dependent = (USBControllerDevice["Dependent"] as String).Split(new Char[] { '=' })[1];
// 过滤掉没有VID和PID的USB设备
Match match = Regex.Match(Dependent, "VID_[0-9|A-F]{4}&PID_[0-9|A-F]{4}");
if (match.Success)
{
UInt16 theVendorID = Convert.ToUInt16(match.Value.Substring(4, 4), 16); // 供应商标识
if (VendorID != UInt16.MinValue && VendorID != theVendorID) continue;
UInt16 theProductID = Convert.ToUInt16(match.Value.Substring(13, 4), 16); // 产品编号
if (ProductID != UInt16.MinValue && ProductID != theProductID) continue;
ManagementObjectCollection PnPEntityCollection = new ManagementObjectSearcher("SELECT * FROM Win32_PnPEntity WHERE DeviceID=" + Dependent).Get();
if (PnPEntityCollection != null)
{
foreach (ManagementObject Entity in PnPEntityCollection)
{
Guid theClassGuid = new Guid(Entity["ClassGuid"] as String); // 设备安装类GUID
if (ClassGuid != Guid.Empty && ClassGuid != theClassGuid) continue;
PnPEntityInfo Element;
Element.PNPDeviceID = Entity["PNPDeviceID"] as String; // 设备ID
Element.Name = Entity["Name"] as String; // 设备名称
Element.Description = Entity["Description"] as String; // 设备描述
Element.Service = Entity["Service"] as String; // 服务
Element.Status = Entity["Status"] as String; // 设备状态
Element.VendorID = theVendorID; // 供应商标识
Element.ProductID = theProductID; // 产品编号
Element.ClassGuid = theClassGuid; // 设备安装类GUID
UsbDevices.Add(Element);
}
}
}
}
}
if (UsbDevices.Count == 0) return null; else return UsbDevices.ToArray();
}
/// <summary>
/// 查询USB设备实体(设备要求有VID和PID)
/// </summary>
/// <param name="VendorID">供应商标识,MinValue忽视</param>
/// <param name="ProductID">产品编号,MinValue忽视</param>
/// <returns>设备列表</returns>
public static PnPEntityInfo[] WhoUsbDevice(UInt16 VendorID, UInt16 ProductID)
{
return WhoUsbDevice(VendorID, ProductID, Guid.Empty);
}
/// <summary>
/// 查询USB设备实体(设备要求有VID和PID)
/// </summary>
/// <param name="ClassGuid">设备安装类Guid,Empty忽视</param>
/// <returns>设备列表</returns>
public static PnPEntityInfo[] WhoUsbDevice(Guid ClassGuid)
{
return WhoUsbDevice(UInt16.MinValue, UInt16.MinValue, ClassGuid);
}
/// <summary>
/// 查询USB设备实体(设备要求有VID和PID)
/// </summary>
/// <param name="PNPDeviceID">设备ID,可以是不完整信息</param>
/// <returns>设备列表</returns>
public static PnPEntityInfo[] WhoUsbDevice(String PNPDeviceID)
{
List<PnPEntityInfo> UsbDevices = new List<PnPEntityInfo>();
// 获取USB控制器及其相关联的设备实体
ManagementObjectCollection USBControllerDeviceCollection = new ManagementObjectSearcher("SELECT * FROM Win32_USBControllerDevice").Get();
if (USBControllerDeviceCollection != null)
{
foreach (ManagementObject USBControllerDevice in USBControllerDeviceCollection)
{ // 获取设备实体的DeviceID
String Dependent = (USBControllerDevice["Dependent"] as String).Split(new Char[] { '=' })[1];
if (!String.IsNullOrEmpty(PNPDeviceID))
{ // 注意:忽视大小写
if (Dependent.IndexOf(PNPDeviceID, 1, PNPDeviceID.Length - 2, StringComparison.OrdinalIgnoreCase) == -1) continue;
}
// 过滤掉没有VID和PID的USB设备
Match match = Regex.Match(Dependent, "VID_[0-9|A-F]{4}&PID_[0-9|A-F]{4}");
if (match.Success)
{
ManagementObjectCollection PnPEntityCollection = new ManagementObjectSearcher("SELECT * FROM Win32_PnPEntity WHERE DeviceID=" + Dependent).Get();
if (PnPEntityCollection != null)
{
foreach (ManagementObject Entity in PnPEntityCollection)
{
PnPEntityInfo Element;
Element.PNPDeviceID = Entity["PNPDeviceID"] as String; // 设备ID
Element.Name = Entity["Name"] as String; // 设备名称
Element.Description = Entity["Description"] as String; // 设备描述
Element.Service = Entity["Service"] as String; // 服务
Element.Status = Entity["Status"] as String; // 设备状态
Element.VendorID = Convert.ToUInt16(match.Value.Substring(4, 4), 16); // 供应商标识
Element.ProductID = Convert.ToUInt16(match.Value.Substring(13, 4), 16); // 产品编号 // 产品编号
Element.ClassGuid = new Guid(Entity["ClassGuid"] as String); // 设备安装类GUID
UsbDevices.Add(Element);
}
}
}
}
}
if (UsbDevices.Count == 0) return null; else return UsbDevices.ToArray();
}
/// <summary>
/// 根据服务定位USB设备
/// </summary>
/// <param name="ServiceCollection">要查询的服务集合</param>
/// <returns>设备列表</returns>
public static PnPEntityInfo[] WhoUsbDevice(String[] ServiceCollection)
{
if (ServiceCollection == null || ServiceCollection.Length == 0)
return WhoUsbDevice(UInt16.MinValue, UInt16.MinValue, Guid.Empty);
List<PnPEntityInfo> UsbDevices = new List<PnPEntityInfo>();
// 获取USB控制器及其相关联的设备实体
ManagementObjectCollection USBControllerDeviceCollection = new ManagementObjectSearcher("SELECT * FROM Win32_USBControllerDevice").Get();
if (USBControllerDeviceCollection != null)
{
foreach (ManagementObject USBControllerDevice in USBControllerDeviceCollection)
{ // 获取设备实体的DeviceID
String Dependent = (USBControllerDevice["Dependent"] as String).Split(new Char[] { '=' })[1];
// 过滤掉没有VID和PID的USB设备
Match match = Regex.Match(Dependent, "VID_[0-9|A-F]{4}&PID_[0-9|A-F]{4}");
if (match.Success)
{
ManagementObjectCollection PnPEntityCollection = new ManagementObjectSearcher("SELECT * FROM Win32_PnPEntity WHERE DeviceID=" + Dependent).Get();
if (PnPEntityCollection != null)
{
foreach (ManagementObject Entity in PnPEntityCollection)
{
String theService = Entity["Service"] as String; // 服务
if (String.IsNullOrEmpty(theService)) continue;
foreach (String Service in ServiceCollection)
{ // 注意:忽视大小写
if (String.Compare(theService, Service, true) != 0) continue;
PnPEntityInfo Element;
Element.PNPDeviceID = Entity["PNPDeviceID"] as String; // 设备ID
Element.Name = Entity["Name"] as String; // 设备名称
Element.Description = Entity["Description"] as String; // 设备描述
Element.Service = theService; // 服务
Element.Status = Entity["Status"] as String; // 设备状态
Element.VendorID = Convert.ToUInt16(match.Value.Substring(4, 4), 16); // 供应商标识
Element.ProductID = Convert.ToUInt16(match.Value.Substring(13, 4), 16); // 产品编号
Element.ClassGuid = new Guid(Entity["ClassGuid"] as String); // 设备安装类GUID
UsbDevices.Add(Element);
break;
}
}
}
}
}
}
if (UsbDevices.Count == 0) return null; else return UsbDevices.ToArray();
}
#endregion
#region PnPEntity
/// <summary>
/// 所有即插即用设备实体(过滤没有VID和PID的设备)
/// </summary>
public static PnPEntityInfo[] AllPnPEntities
{
get
{
return WhoPnPEntity(UInt16.MinValue, UInt16.MinValue, Guid.Empty);
}
}
/// <summary>
/// 根据VID和PID及设备安装类GUID定位即插即用设备实体
/// </summary>
/// <param name="VendorID">供应商标识,MinValue忽视</param>
/// <param name="ProductID">产品编号,MinValue忽视</param>
/// <param name="ClassGuid">设备安装类Guid,Empty忽视</param>
/// <returns>设备列表</returns>
/// <remarks>
/// HID:{745a17a0-74d3-11d0-b6fe-00a0c90f57da}
/// Imaging Device:{6bdd1fc6-810f-11d0-bec7-08002be2092f}
/// Keyboard:{4d36e96b-e325-11ce-bfc1-08002be10318}
/// Mouse:{4d36e96f-e325-11ce-bfc1-08002be10318}
/// Network Adapter:{4d36e972-e325-11ce-bfc1-08002be10318}
/// USB:{36fc9e60-c465-11cf-8056-444553540000}
/// </remarks>
public static PnPEntityInfo[] WhoPnPEntity(UInt16 VendorID, UInt16 ProductID, Guid ClassGuid)
{
List<PnPEntityInfo> PnPEntities = new List<PnPEntityInfo>();
// 枚举即插即用设备实体
String VIDPID;
if (VendorID == UInt16.MinValue)
{
if (ProductID == UInt16.MinValue)
VIDPID = "'%VID[_]____&PID[_]____%'";
else
VIDPID = "'%VID[_]____&PID[_]" + ProductID.ToString("X4") + "%'";
}
else
{
if (ProductID == UInt16.MinValue)
VIDPID = "'%VID[_]" + VendorID.ToString("X4") + "&PID[_]____%'";
else
VIDPID = "'%VID[_]" + VendorID.ToString("X4") + "&PID[_]" + ProductID.ToString("X4") + "%'";
}
String QueryString;
if (ClassGuid == Guid.Empty)
QueryString = "SELECT * FROM Win32_PnPEntity WHERE PNPDeviceID LIKE" + VIDPID;
else
QueryString = "SELECT * FROM Win32_PnPEntity WHERE PNPDeviceID LIKE" + VIDPID + " AND ClassGuid='" + ClassGuid.ToString("B") + "'";
ManagementObjectCollection PnPEntityCollection = new ManagementObjectSearcher(QueryString).Get();
if (PnPEntityCollection != null)
{
foreach (ManagementObject Entity in PnPEntityCollection)
{
String PNPDeviceID = Entity["PNPDeviceID"] as String;
Match match = Regex.Match(PNPDeviceID, "VID_[0-9|A-F]{4}&PID_[0-9|A-F]{4}");
if (match.Success)
{
PnPEntityInfo Element;
Element.PNPDeviceID = PNPDeviceID; // 设备ID
Element.Name = Entity["Name"] as String; // 设备名称
Element.Description = Entity["Description"] as String; // 设备描述
Element.Service = Entity["Service"] as String; // 服务
Element.Status = Entity["Status"] as String; // 设备状态
Element.VendorID = Convert.ToUInt16(match.Value.Substring(4, 4), 16); // 供应商标识
Element.ProductID = Convert.ToUInt16(match.Value.Substring(13, 4), 16); // 产品编号
Element.ClassGuid = new Guid(Entity["ClassGuid"] as String); // 设备安装类GUID
PnPEntities.Add(Element);
}
}
}
if (PnPEntities.Count == 0) return null; else return PnPEntities.ToArray();
}
/// <summary>
/// 根据VID和PID定位即插即用设备实体
/// </summary>
/// <param name="VendorID">供应商标识,MinValue忽视</param>
/// <param name="ProductID">产品编号,MinValue忽视</param>
/// <returns>设备列表</returns>
public static PnPEntityInfo[] WhoPnPEntity(UInt16 VendorID, UInt16 ProductID)
{
return WhoPnPEntity(VendorID, ProductID, Guid.Empty);
}
/// <summary>
/// 根据设备安装类GUID定位即插即用设备实体
/// </summary>
/// <param name="ClassGuid">设备安装类Guid,Empty忽视</param>
/// <returns>设备列表</returns>
public static PnPEntityInfo[] WhoPnPEntity(Guid ClassGuid)
{
return WhoPnPEntity(UInt16.MinValue, UInt16.MinValue, ClassGuid);
}
/// <summary>
/// 根据设备ID定位设备
/// </summary>
/// <param name="PNPDeviceID">设备ID,可以是不完整信息</param>
/// <returns>设备列表</returns>
/// <remarks>
/// 注意:对于下划线,需要写成“[_]”,否则视为任意字符
/// </remarks>
public static PnPEntityInfo[] WhoPnPEntity(String PNPDeviceID)
{
List<PnPEntityInfo> PnPEntities = new List<PnPEntityInfo>();
// 枚举即插即用设备实体
String QueryString;
if (String.IsNullOrEmpty(PNPDeviceID))
{
QueryString = "SELECT * FROM Win32_PnPEntity WHERE PNPDeviceID LIKE '%VID[_]____&PID[_]____%'";
}
else
{ // LIKE子句中有反斜杠字符将会引发WQL查询异常
QueryString = "SELECT * FROM Win32_PnPEntity WHERE PNPDeviceID LIKE '%" + PNPDeviceID.Replace('\\', '_') + "%'";
}
ManagementObjectCollection PnPEntityCollection = new ManagementObjectSearcher(QueryString).Get();
if (PnPEntityCollection != null)
{
foreach (ManagementObject Entity in PnPEntityCollection)
{
String thePNPDeviceID = Entity["PNPDeviceID"] as String;
Match match = Regex.Match(thePNPDeviceID, "VID_[0-9|A-F]{4}&PID_[0-9|A-F]{4}");
if (match.Success)
{
PnPEntityInfo Element;
Element.PNPDeviceID = thePNPDeviceID; // 设备ID
Element.Name = Entity["Name"] as String; // 设备名称
Element.Description = Entity["Description"] as String; // 设备描述
Element.Service = Entity["Service"] as String; // 服务
Element.Status = Entity["Status"] as String; // 设备状态
Element.VendorID = Convert.ToUInt16(match.Value.Substring(4, 4), 16); // 供应商标识
Element.ProductID = Convert.ToUInt16(match.Value.Substring(13, 4), 16); // 产品编号
Element.ClassGuid = new Guid(Entity["ClassGuid"] as String); // 设备安装类GUID
PnPEntities.Add(Element);
}
}
}
if (PnPEntities.Count == 0) return null; else return PnPEntities.ToArray();
}
/// <summary>
/// 根据服务定位设备
/// </summary>
/// <param name="ServiceCollection">要查询的服务集合,null忽视</param>
/// <returns>设备列表</returns>
/// <remarks>
/// 跟服务相关的类:
/// Win32_SystemDriverPNPEntity
/// Win32_SystemDriver
/// </remarks>
public static PnPEntityInfo[] WhoPnPEntity(String[] ServiceCollection)
{
if (ServiceCollection == null || ServiceCollection.Length == 0)
return WhoPnPEntity(UInt16.MinValue, UInt16.MinValue, Guid.Empty);
List<PnPEntityInfo> PnPEntities = new List<PnPEntityInfo>();
// 枚举即插即用设备实体
String QueryString = "SELECT * FROM Win32_PnPEntity WHERE PNPDeviceID LIKE '%VID[_]____&PID[_]____%'";
ManagementObjectCollection PnPEntityCollection = new ManagementObjectSearcher(QueryString).Get();
if (PnPEntityCollection != null)
{
foreach (ManagementObject Entity in PnPEntityCollection)
{
String PNPDeviceID = Entity["PNPDeviceID"] as String;
Match match = Regex.Match(PNPDeviceID, "VID_[0-9|A-F]{4}&PID_[0-9|A-F]{4}");
if (match.Success)
{
String theService = Entity["Service"] as String; // 服务
if (String.IsNullOrEmpty(theService)) continue;
foreach (String Service in ServiceCollection)
{ // 注意:忽视大小写
if (String.Compare(theService, Service, true) != 0) continue;
PnPEntityInfo Element;
Element.PNPDeviceID = PNPDeviceID; // 设备ID
Element.Name = Entity["Name"] as String; // 设备名称
Element.Description = Entity["Description"] as String; // 设备描述
Element.Service = theService; // 服务
Element.Status = Entity["Status"] as String; // 设备状态
Element.VendorID = Convert.ToUInt16(match.Value.Substring(4, 4), 16); // 供应商标识
Element.ProductID = Convert.ToUInt16(match.Value.Substring(13, 4), 16); // 产品编号
Element.ClassGuid = new Guid(Entity["ClassGuid"] as String); // 设备安装类GUID
PnPEntities.Add(Element);
break;
}
}
}
}
if (PnPEntities.Count == 0) return null; else return PnPEntities.ToArray();
}
#endregion
/// <summary>
/// 获取全部USB设备
/// </summary>
/// <returns></returns>
public static Dictionary<string, UInt16> GetAllUsbDevInfo()
{
PnPEntityInfo[] pnPEntityInfos = UsbBaseWMI.AllPnPEntities;
if (pnPEntityInfos == null) return null;
Dictionary<string, UInt16> UsbdevList = new Dictionary<string, UInt16>();
int i = 0;
foreach (PnPEntityInfo pnPEntityInfo in pnPEntityInfos)
{
if (pnPEntityInfo.Service!=null)
{
if (pnPEntityInfo.Service.Equals("usbprint"))
{
if (pnPEntityInfo.VendorID!=null&& pnPEntityInfo.ProductID!=null)
{
UsbdevList.Add("VID", pnPEntityInfo.VendorID);
UsbdevList.Add("PID", pnPEntityInfo.ProductID);
}
}
}
//PrintService.WriteLog(i++.ToString());
}
return UsbdevList;
}
public static Dictionary<string,Guid> GetAllUsbDevInfoGuid()
{
PnPEntityInfo[] pnPEntityInfos = UsbBaseWMI.AllPnPEntities;
//if (pnPEntityInfos == null) return null;
Dictionary<string, Guid> UsbdevList = new Dictionary<string, Guid>();
foreach (PnPEntityInfo pnPEntityInfo in pnPEntityInfos)
{
if (pnPEntityInfo.Name.Contains("打印"))
{
//UsbdevList.Add("PNPDeviceID:" , pnPEntityInfo.PNPDeviceID);
//UsbdevList.Add("Name:" , pnPEntityInfo.Name);
//UsbdevList.Add("Description:" , pnPEntityInfo.Description);
//UsbdevList.Add("Service:" , pnPEntityInfo.Service);
//UsbdevList.Add("Status:" , pnPEntityInfo.Status);
//UsbdevList.Add("VID", pnPEntityInfo.VendorID);
//UsbdevList.Add("PID", pnPEntityInfo.ProductID);
UsbdevList.Add("ClassGuid" , pnPEntityInfo.ClassGuid);
}
}
return UsbdevList;
}
/// <summary>
/// 即插即用设备信息结构
/// </summary>
public struct PnPEntityInfo
{
public String PNPDeviceID; // 设备ID
public String Name; // 设备名称
public String Description; // 设备描述
public String Service; // 服务
public String Status; // 设备状态
public UInt16 VendorID; // 供应商标识
public UInt16 ProductID; // 产品编号
public Guid ClassGuid; // 设备安装类GUID
}
}
}
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="LibUsbDotNet" version="2.2.29" targetFramework="net461" />
<package id="Microsoft.Win32.Registry" version="4.7.0" targetFramework="net461" />
<package id="NetworkCommsDotNet" version="3.0.3" targetFramework="net461" />
<package id="Newtonsoft.Json" version="12.0.3" targetFramework="net461" />
<package id="SerialPortStream" version="2.2.1.1" targetFramework="net461" />
<package id="System.Collections" version="4.3.0" targetFramework="net461" />
<package id="System.Collections.Specialized" version="4.3.0" targetFramework="net461" />
<package id="System.Diagnostics.Debug" version="4.3.0" targetFramework="net461" />
<package id="System.Diagnostics.FileVersionInfo" version="4.3.0" targetFramework="net461" />
<package id="System.Diagnostics.Tools" version="4.3.0" targetFramework="net461" />
<package id="System.Diagnostics.TraceSource" version="4.3.0" targetFramework="net461" />
<package id="System.IO" version="4.3.0" targetFramework="net461" />
<package id="System.IO.FileSystem" version="4.3.0" targetFramework="net461" />
<package id="System.IO.FileSystem.Primitives" version="4.3.0" targetFramework="net461" />
<package id="System.Runtime.Extensions" version="4.3.1" targetFramework="net461" />
<package id="System.Runtime.Handles" version="4.3.0" targetFramework="net461" />
<package id="System.Runtime.InteropServices" version="4.3.0" targetFramework="net461" />
<package id="System.Runtime.InteropServices.RuntimeInformation" version="4.3.0" targetFramework="net461" />
<package id="System.Security.AccessControl" version="4.7.0" targetFramework="net461" />
<package id="System.Security.Principal.Windows" version="4.7.0" targetFramework="net461" />
<package id="System.Text.Encoding" version="4.3.0" targetFramework="net461" />
<package id="System.Threading" version="4.3.0" targetFramework="net461" />
<package id="System.Threading.Overlapped" version="4.3.0" targetFramework="net461" />
<package id="System.Threading.Thread" version="4.3.0" targetFramework="net461" />
<package id="System.Threading.ThreadPool" version="4.3.0" targetFramework="net461" />
<package id="ZXing.Net" version="0.16.5" targetFramework="net461" />
</packages>
\ No newline at end of file
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1"/>
</startup>
</configuration>
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace JmpUhfService
{
public class InitializeModel
{
public string Epc { get; set; }
public ushort Len { get; set; }
public ushort Offset { get; set; }
public string Password { get; set; }
}
}
<?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>{111435B9-7C04-4AE7-A9E0-FF7052D9F196}</ProjectGuid>
<OutputType>WinExe</OutputType>
<RootNamespace>JmpUhfService</RootNamespace>
<AssemblyName>JmpUhfService</AssemblyName>
<TargetFrameworkVersion>v4.6.1</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<Deterministic>true</Deterministic>
<TargetFrameworkProfile />
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<PlatformTarget>x86</PlatformTarget>
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>..\Programe\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<PlatformTarget>AnyCPU</PlatformTarget>
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>..\Programe\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup>
<StartupObject />
</PropertyGroup>
<PropertyGroup>
<ApplicationIcon>fix.ico</ApplicationIcon>
</PropertyGroup>
<ItemGroup>
<Reference Include="ControlzEx, Version=4.0.0.0, Culture=neutral, PublicKeyToken=69f1c32f803d307e, processorArchitecture=MSIL">
<HintPath>..\packages\ControlzEx.4.3.2\lib\net45\ControlzEx.dll</HintPath>
</Reference>
<Reference Include="Fleck, Version=1.1.0.0, Culture=neutral, processorArchitecture=MSIL">
<HintPath>..\packages\Fleck.1.1.0\lib\net45\Fleck.dll</HintPath>
</Reference>
<Reference Include="JmpRfidLp">
<HintPath>Lib\JmpRfidLp.dll</HintPath>
</Reference>
<Reference Include="Microsoft.Xaml.Behaviors, Version=1.1.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL">
<HintPath>..\packages\Microsoft.Xaml.Behaviors.Wpf.1.1.19\lib\net45\Microsoft.Xaml.Behaviors.dll</HintPath>
</Reference>
<Reference Include="Newtonsoft.Json, Version=12.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed, processorArchitecture=MSIL">
<HintPath>..\packages\Newtonsoft.Json.12.0.3\lib\net45\Newtonsoft.Json.dll</HintPath>
</Reference>
<Reference Include="PresentationCore" />
<Reference Include="PresentationFramework" />
<Reference Include="System" />
<Reference Include="System.ComponentModel.DataAnnotations" />
<Reference Include="System.Configuration" />
<Reference Include="System.Core" />
<Reference Include="System.Web" />
<Reference Include="System.Web.Extensions" />
<Reference Include="System.Xaml" />
<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.ServiceProcess" />
<Reference Include="System.Xml" />
<Reference Include="WindowsBase" />
</ItemGroup>
<ItemGroup>
<Compile Include="InitializeModel.cs" />
<Compile Include="Log.cs" />
<Compile Include="UhfService.cs">
<SubType>Component</SubType>
</Compile>
<Compile Include="UhfService.Designer.cs">
<DependentUpon>UhfService.cs</DependentUpon>
</Compile>
<Compile Include="Program.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup>
<ItemGroup>
<None Include="App.config" />
<None Include="packages.config" />
</ItemGroup>
<ItemGroup>
<Content Include="fix.ico" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\JmpZbModel\JmpZbModel.csproj">
<Project>{7e4c3e44-3418-43d0-915b-57f76cf4cab4}</Project>
<Name>JmpZbModel</Name>
</ProjectReference>
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
</Project>
\ No newline at end of file
[Database]
;是否保存(0不保存,1保存)
Save =0
;数据库IP地址
Source=172.18.77.25
;数据库名称
DB=RFIDReader_Data
;用户名
User=sa
;密码
Pwd=sa
;保存间隔时间(秒)
Upd=5
[RunMode]
mode=0
[ShowScoreboard]
show=True
[ShowSpeedCurve]
curveshow=False
[MacErr]
InterruptFWDPWRLEVERROR=True
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace JmpUhfService
{
public class Log
{
//private static
private static StreamWriter sr;
private static readonly object syncWorkObj = new object();
private static readonly object syncErrorObj = new object();
private static readonly object syncDebugObj = new object();
private static bool bEnableWorkLog = true;
private static bool bEnableErrorLog = true;
private static bool bEnableDebugLog = true;
public Log()
{
}
/// <summary>
/// Log 启用
/// </summary>
/// <param name="enable"></param>
public static void EnableWorkLog(bool enable)
{
bEnableWorkLog = enable;
}
/// <summary>
/// Log 启用
/// </summary>
/// <param name="enable"></param>
public static void EnableErrorLog(bool enable)
{
bEnableErrorLog = enable;
}
/// <summary>
/// Log 启用
/// </summary>
/// <param name="enable"></param>
public static void EnableDebugLog(bool enable)
{
bEnableDebugLog = enable;
}
/// <summary>
/// 工作日志
/// </summary>
/// <param name="logTxt"></param>
/// <param name="ModuleName"></param>
public static void WorkLog(string logTxt, string ModuleName)
{
lock (syncWorkObj)
{
if (bEnableWorkLog)
{
WriteLine(logTxt, ModuleName, "WorkLog/");
}
}
}
/// <summary>
/// 异常日志
/// </summary>
/// <param name="logTxt"></param>
/// <param name="ModuleName"></param>
public static void ErrorLog(string logTxt, string ModuleName)
{
lock (syncErrorObj)
{
if (bEnableErrorLog)
{
WriteLine(logTxt, ModuleName, "ErrorLog/");
}
}
}
/// <summary>
/// 异常日志
/// </summary>
/// <param name="logTxt"></param>
/// <param name="ModuleName"></param>
public static void DebugLog(string logTxt, string ModuleName)
{
lock (syncDebugObj)
{
if (bEnableDebugLog)
{
WriteLine(logTxt, ModuleName, "DebugLog/");
}
}
}
/// <summary>
/// 写日志
/// </summary>
/// <param name="logTxt"></param>
/// <param name="ModuleName"></param>
/// <param name="pathName"></param>
private static void WriteLine(string logTxt, string ModuleName, string pathName)
{
try
{
string logPath = AppDomain.CurrentDomain.SetupInformation.ApplicationBase + pathName
+ DateTime.Now.ToString("yyyyMMdd") + ".log";
ClearFile(AppDomain.CurrentDomain.SetupInformation.ApplicationBase + pathName);
logTxt = string.Format(" {0}|{1}|{2}",
DateTime.Now.ToString("yyyy-MM-dd HH:mm"),
ModuleName,
logTxt);
sr = new StreamWriter(logPath, true, Encoding.Default);
sr.WriteLine(logTxt);
sr.Close();
}
catch { }
}
/// <summary>
/// 日志清除文件
/// </summary>
/// <param name="FilePath"></param>
private static void ClearFile(string FilePath)
{
if (!Directory.Exists(FilePath))
{
Directory.CreateDirectory(FilePath);
}
String[] Files = Directory.GetFiles(FilePath);
if (Files.Length > 30)
{
for (int i = 0; i < 1; i++)
{
try
{
File.Delete(Files[i]);
}
catch
{
}
}
}
}
}
}
using System;
using System.ServiceProcess;
namespace JmpUhfService
{
static class Program
{
/// <summary>
/// 应用程序的主入口点。
/// </summary>
static void Main()
{
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[]
{
new JmpUhfService()
};
ServiceBase.Run(ServicesToRun);
//new JmpUhfService().TestService();
//Console.ReadKey();
}
}
}
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// 有关程序集的一般信息由以下
// 控制。更改这些特性值可修改
// 与程序集关联的信息。
[assembly: AssemblyTitle("JmpUhfService")]
[assembly: AssemblyDescription("JmpUhfService")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("Junmp")]
[assembly: AssemblyProduct("JmpUhfService")]
[assembly: AssemblyCopyright("Copyright © Junmp 2020")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// 将 ComVisible 设置为 false 会使此程序集中的类型
//对 COM 组件不可见。如果需要从 COM 访问此程序集中的类型
//请将此类型的 ComVisible 特性设置为 true。
[assembly: ComVisible(false)]
// 如果此项目向 COM 公开,则下列 GUID 用于类型库的 ID
[assembly: Guid("111435b9-7c04-4ae7-a9e0-ff7052d9f196")]
// 程序集的版本信息由下列四个值组成:
//
// 主版本
// 次版本
// 生成号
// 修订号
//
//可以指定所有这些值,也可以使用“生成号”和“修订号”的默认值
//通过使用 "*",如下所示:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.1.21")]
[assembly: AssemblyFileVersion("1.0.1.21")]
namespace JmpUhfService
{
partial class JmpUhfService
{
/// <summary>
/// 必需的设计器变量。
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// 清理所有正在使用的资源。
/// </summary>
/// <param name="disposing">如果应释放托管资源,为 true;否则为 false。</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region 组件设计器生成的代码
/// <summary>
/// 设计器支持所需的方法 - 不要修改
/// 使用代码编辑器修改此方法的内容。
/// </summary>
private void InitializeComponent()
{
components = new System.ComponentModel.Container();
this.ServiceName = "Service1";
}
#endregion
}
}
using Fleck;
using JmpRfidLp;
using JmpZbModel;
using Newtonsoft.Json;
//using rfidLink.Extend;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Globalization;
using System.IO.Ports;
using System.Linq;
using System.Reflection;
using System.ServiceProcess;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace JmpUhfService
{
public partial class JmpUhfService : ServiceBase
{
public JmpUhfService()
{
InitializeComponent();
}
//private LinkageExtend link = new LinkageExtend();
//private List<rfidLink.Extend.RadioInformation> radios;
private Reader reader;
private Task taskDevice;
private CancellationTokenSource cDeviceToken;
private WebSocketServer server;
private Dictionary<string, LinkInfo> dic_client = new Dictionary<string, LinkInfo>();
private List<string> epcList = new List<string>();
private object syncObj = new object();
private DeviceStatus deviceStatus = DeviceStatus.未连接;
private AutoResetEvent resetEvent = new AutoResetEvent(false);
private string used_client = string.Empty;
protected override void OnStart(string[] args)
{
try
{
StartWs();
//建立轮询线程
cDeviceToken = new CancellationTokenSource();
taskDevice = new Task(LinkDevice);
taskDevice.Start();
}
catch (Exception ex)
{
Log.ErrorLog(ex.ToString(), MethodBase.GetCurrentMethod().Name);
}
}
public void TestService()
{
OnStart(default);
}
protected override void OnStop()
{
try
{
resetEvent.Set();
cDeviceToken?.Cancel();
StopInv();
server?.Dispose();
if (reader?.IsOpen() ?? false)
{
reader?.Close();
}
reader = null;
Process.GetCurrentProcess().Kill();
}
catch { }
}
protected override void OnShutdown()
{
try
{
resetEvent.Set();
cDeviceToken?.Cancel();
StopInv();
server?.Dispose();
if (reader?.IsOpen() ?? false)
{
reader?.Close();
}
reader = null;
Process.GetCurrentProcess().Kill();
}
catch { }
}
#region ws server method
protected void OnSendMsg(string client, InitializeCmdType cmdType, string msg)
{
try
{
if (dic_client.ContainsKey(client))
{
var ws_connection = dic_client[client];
if (ws_connection != null)
{
InitializeCmdInfo cmdInfo = new InitializeCmdInfo()
{
CmdType = cmdType,
Content = msg
};
ws_connection.Connection.Send(JsonConvert.SerializeObject(cmdInfo));
}
}
}
catch (Exception ex)
{
Log.ErrorLog(ex.ToString(), MethodBase.GetCurrentMethod().Name);
}
}
protected void OnSendMsg(IWebSocketConnection client, InitializeCmdType cmdType, string msg)
{
try
{
if (client != null)
{
InitializeCmdInfo cmdInfo = new InitializeCmdInfo()
{
CmdType = cmdType,
Content = msg
};
client.Send(JsonConvert.SerializeObject(cmdInfo));
}
}
catch (Exception ex)
{
Log.ErrorLog(ex.ToString(), MethodBase.GetCurrentMethod().Name);
}
}
protected void OnSendBusy(IWebSocketConnection client)
{
try
{
if (client != null)
{
InitializeCmdInfo cmdInfo = new InitializeCmdInfo()
{
CmdType = InitializeCmdType.Busy,
Content = "设备正忙,请检查设备是否被占用"
};
client.Send(JsonConvert.SerializeObject(cmdInfo));
}
}
catch (Exception ex)
{
Log.ErrorLog(ex.ToString(), MethodBase.GetCurrentMethod().Name);
}
}
/// <summary>
/// 接受客户端数据
/// </summary>
/// <param name="client"></param>
/// <param name="message"></param>
protected void OnReciveData(string client, string message, IWebSocketConnection connection)
{
try
{
if (client == used_client)
{
InitializeCmdInfo cmd = JsonConvert.DeserializeObject<InitializeCmdInfo>(message);
if (cmd == null)
{
OnSendMsg(client, InitializeCmdType.Initialize, "操作失败,不正确的指令");
}
else if (deviceStatus == DeviceStatus.未连接)
{
OnSendMsg(client, InitializeCmdType.Initialize, "操作失败,设备未连接");
}
else
{
switch (cmd.CmdType)
{
case InitializeCmdType.StartInventory:
StartInv(client);
break;
case InitializeCmdType.StopInventory:
StopInv();
break;
case InitializeCmdType.Initialize:
InitializeEpc(client, cmd.Content);
break;
case InitializeCmdType.ReadInventorySingle:
ReadInventorySingle(client);
break;
case InitializeCmdType.InitializeV2:
InitializeEpcV2(client, cmd.Content);
break;
}
}
}
else
{
OnSendBusy(connection);
}
}
catch (Exception ex)
{
SendLinkError(client);
Log.ErrorLog(ex.ToString(), MethodBase.GetCurrentMethod().Name);
}
}
/// <summary>
/// 启动Ws服务
/// </summary>
/// <param name="strPort"></param>
protected void StartWs(string strPort = "8081")
{
server = new WebSocketServer($"ws://0.0.0.0:{strPort}");
server.Start(socket =>
{
socket.OnOpen = () =>
{
OnNewConnection($"{socket.ConnectionInfo.ClientIpAddress}:{socket.ConnectionInfo.ClientPort}", socket);
};
socket.OnClose = () =>
{
OnDisConnection($"{socket.ConnectionInfo.ClientIpAddress}:{socket.ConnectionInfo.ClientPort}");
};
socket.OnMessage = message =>
{
OnReciveData($"{socket.ConnectionInfo.ClientIpAddress}:{socket.ConnectionInfo.ClientPort}", message, socket);
};
});
}
/// <summary>
///客户端连入
/// </summary>
/// <param name="client"></param>
/// <param name="connectionInfo"></param>
protected void OnNewConnection(string client, IWebSocketConnection connectionInfo)
{
if (used_client == string.Empty || dic_client.Count == 0)
{
used_client = client;
dic_client.Add(client, new LinkInfo { Connection = connectionInfo, LinkDate = DateTime.Now });
if (deviceStatus == DeviceStatus.已连接)
{
SendLinked(used_client);
}
else
{
SendLinkError(client);
}
}
else
{
if (!dic_client.ContainsKey(client))
{
dic_client.Add(client, new LinkInfo { Connection = connectionInfo, LinkDate = DateTime.Now });
}
OnSendBusy(connectionInfo);
}
}
/// <summary>
/// 客户端断开
/// </summary>
/// <param name="client"></param>
protected void OnDisConnection(string client)
{
if (dic_client.ContainsKey(client))
{
dic_client.Remove(client);
}
if (!string.IsNullOrEmpty(used_client) && client == used_client)
{
StopInv();
used_client = string.Empty;
var next_client = dic_client.ToList().OrderBy(t => t.Value.LinkDate).FirstOrDefault();
if (next_client.Value?.Connection != null)
{
used_client = next_client.Value.Connection.ConnectionInfo.ClientIpAddress + ":" + next_client.Value.Connection.ConnectionInfo.ClientPort;
if (deviceStatus == DeviceStatus.已连接)
{
SendLinked(used_client);
}
else
{
SendLinkError(used_client);
}
}
}
}
#endregion
#region epc initialize method
protected void InitializeEpc(string client, string json)
{
if (deviceStatus == DeviceStatus.已连接)
{
var data = JsonConvert.DeserializeObject<InitializeModel>(json);
if (data == null)
{
OnSendMsg(client, InitializeCmdType.Initialize, "绑定失败,非法数据");
}
else
{
//将EPC长度改成位字符串
//48/6400
//24/3400
//64/8000
//先停止盘点,否则会卡死。
reader.InventoryStop();
//单次盘点,确认无其他标签
var tmpList = new List<TagInfo>();
for (int i = 0; i < 4; i++)
{
reader.InventorySingle(50).ForEach(s =>
{
if (!tmpList.Any(t => t.EPC == s.EPC))
{
tmpList.Add(s);
}
});
}
if (tmpList.Count > 1)
{
OnSendMsg(client, InitializeCmdType.Initialize, "绑定失败,存在其他标签");
}
else if (tmpList.Count == 0)
{
OnSendMsg(client, InitializeCmdType.Initialize, "绑定失败,标签未放置");
}
//else if (tmpList.FirstOrDefault().EPC.Length == 64)
//{
// OnSendMsg(client, InitializeCmdType.Initialize, "绑定失败,标签已被初始化");
//}
else
{
OperData _oper = new OperData
{
EPC = "",
DATA = "8000" + data.Epc,
Offset = data.Offset,
Length = data.Len,
Bank = BankType.EPC,
Access = "00000000"
};
var res = reader.WriteTag(_oper);
if (res == OperResult.OK)
{
OnSendMsg(client, InitializeCmdType.Initialize, "成功" + data.Epc);
}
else
{
OnSendMsg(client, InitializeCmdType.Initialize, "绑定失败,写入异常");
}
}
}
}
else
{
deviceStatus = DeviceStatus.未连接;
OnSendMsg(client, InitializeCmdType.ErrorMsg, "设备未连接");
}
}
protected void InitializeEpcV2(string client, string json)
{
if (deviceStatus == DeviceStatus.已连接)
{
var data = JsonConvert.DeserializeObject<InitializeModel>(json);
if (data == null)
{
OnSendMsg(client, InitializeCmdType.Initialize, "绑定失败,非法数据");
}
else
{
//将EPC长度改成位字符串
//48/6400
//24/3400
//64/8000
//先停止盘点,否则会卡死。
reader.InventoryStop();
//不进行盘点,认为无其他标签(调用之前自行判断是否能写入)
OperData _oper = new OperData
{
EPC = "",
DATA = "8000" + data.Epc,
Offset = data.Offset,
Length = data.Len,
Bank = BankType.EPC,
Access = "00000000"
};
var res = reader.WriteTag(_oper);
if (res == OperResult.OK)
{
OnSendMsg(client, InitializeCmdType.Initialize, "成功" + data.Epc);
}
else
{
OnSendMsg(client, InitializeCmdType.Initialize, "绑定失败,写入异常");
}
}
}
else
{
deviceStatus = DeviceStatus.未连接;
OnSendMsg(client, InitializeCmdType.ErrorMsg, "设备未连接");
}
}
protected void ReadInventorySingle(string client)
{
var tmpList = new List<TagInfo>();
for (int i = 0; i < 4; i++)
{
reader.InventorySingle(50).ForEach(s =>
{
if (tmpList.All(t => t.EPC != s.EPC))
{
tmpList.Add(s);
}
});
}
if (tmpList.Count > 1)
{
OnSendMsg(client, InitializeCmdType.ReadInventorySingleError, "存在其他标签");
}
else if (tmpList.Count == 0)
{
OnSendMsg(client, InitializeCmdType.ReadInventorySingleError, "标签未放置");
}
else
{
OnSendMsg(client, InitializeCmdType.ReadInventorySingle, tmpList.First().EPC);
}
}
#endregion
#region uhf inventory method
private void ConnectReader()
{
try
{
reader = new Reader("COM4");
reader.OnInventory += OnRadioInventory;
var state = reader.Open();
deviceStatus = state ? DeviceStatus.已连接 : DeviceStatus.未连接;
if (state)
{
reader.InventoryStop();
reader.SetPALevel(1);
reader.SetTxPower(0, true, 24);
SendLinked(used_client);
}
}
catch (Exception ex)
{
reader = null;
SendLinkError(used_client);
Log.ErrorLog(ex.ToString(), MethodBase.GetCurrentMethod().Name);
}
}
private void OnRadioInventory(TagInfo args)
{
if (!epcList.Contains(args.EPC))
{
epcList.Add(args.EPC);
OnSendMsg(used_client, InitializeCmdType.InventoryInfo, args.EPC);
}
}
private void StartInv(string client)
{
lock (syncObj)
{
epcList.Clear();
if (deviceStatus == DeviceStatus.已连接)
{
reader.InventoryStart();
}
else
{
deviceStatus = DeviceStatus.未连接;
OnSendMsg(client, InitializeCmdType.ErrorMsg, "设备未连接");
}
}
}
private void StopInv()
{
lock (syncObj)
{
reader?.InventoryStop();
deviceStatus = DeviceStatus.已连接;
}
}
private void LinkDevice()
{
while (!cDeviceToken.IsCancellationRequested)
{
try
{
if (SerialPort.GetPortNames().Any(t => t.ToLower().Contains("com4")))
{
if (reader == null)
{
ConnectReader();
}
else if (deviceStatus == DeviceStatus.未连接)
{
var state = reader?.Open() ?? false;
if (state)
{
//设置功率
reader.SetPALevel(1);
reader.SetTxPower(0, true, 24);
SendLinked(used_client);
}
else
{
reader = null;
deviceStatus = DeviceStatus.未连接;
}
}
else { }
}
else
{
SendLinkError(used_client);
reader?.InventoryStop();
reader?.Close();
reader = null;
}
if (resetEvent.WaitOne(5000))
{
break;
}
}
catch (Exception ex)
{
SendLinkError(used_client);
reader?.Close();
Log.ErrorLog(ex.ToString(), MethodBase.GetCurrentMethod().Name);
}
}
}
private void SendLinkError(string client)
{
deviceStatus = DeviceStatus.未连接;
OnSendMsg(client, InitializeCmdType.ErrorMsg, "初始化设备未连接");
}
private void SendLinked(string client)
{
deviceStatus = DeviceStatus.已连接;
OnSendMsg(client, InitializeCmdType.Linked, "初始化设备已连接");
}
#endregion
}
public enum DeviceStatus
{
未连接,
已连接
}
public class LinkInfo
{
public IWebSocketConnection Connection { get; set; }
public DateTime LinkDate { get; set; }
}
}
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="ControlzEx" version="4.3.2" targetFramework="net461" />
<package id="Fleck" version="1.1.0" targetFramework="net461" />
<package id="Microsoft.Xaml.Behaviors.Wpf" version="1.1.19" targetFramework="net461" />
<package id="Newtonsoft.Json" version="12.0.3" targetFramework="net45" />
</packages>
\ No newline at end of file
单警柜 10000
单警柜 10000
打印程序 10002
通道程序 10001
充电台出入 10003
Markdown 格式
0%
您添加了 0 到此讨论。请谨慎行事。
请先完成此评论的编辑!
注册 或者 后发表评论