Commit 5aaac275 by zxw

Merge branch 'release/0510'

parents 8956b014 f79026d7
......@@ -67,9 +67,6 @@
</PropertyGroup>
<ItemGroup>
<Reference Include="DevComponents.DotNetBar2, Version=12.1.0.0, Culture=neutral, PublicKeyToken=c39c3242a43eee2b, processorArchitecture=MSIL" />
<Reference Include="Impinj.OctaneSdk, Version=3.4.0.0, Culture=neutral, processorArchitecture=MSIL">
<HintPath>..\packages\OctaneSDK.3.4.0\lib\net461\Impinj.OctaneSdk.dll</HintPath>
</Reference>
<Reference Include="JmpDehumidifierLib">
<HintPath>..\Lib\JmpDehumidifierLib.dll</HintPath>
</Reference>
......@@ -79,24 +76,9 @@
<Reference Include="LitJSON">
<HintPath>..\Lib\LitJSON.dll</HintPath>
</Reference>
<Reference Include="LLRP, Version=10.40.0.0, Culture=neutral, processorArchitecture=MSIL">
<HintPath>..\packages\libltknet-sdk.10.40.0\lib\net461\LLRP.dll</HintPath>
</Reference>
<Reference Include="LLRP.Impinj, Version=10.40.0.0, Culture=neutral, processorArchitecture=MSIL">
<HintPath>..\packages\libltknet-sdk.10.40.0\lib\net461\LLRP.Impinj.dll</HintPath>
</Reference>
<Reference Include="MercuryAPI">
<HintPath>..\Lib\MercuryAPI.dll</HintPath>
</Reference>
<Reference Include="MQTTnet, Version=3.1.2.0, Culture=neutral, PublicKeyToken=b69712f52770c0a7, processorArchitecture=MSIL">
<HintPath>..\packages\MQTTnet.3.1.2\lib\net461\MQTTnet.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="Renci.SshNet, Version=2016.1.0.0, Culture=neutral, PublicKeyToken=1cee9f8bde3db106, processorArchitecture=MSIL">
<HintPath>..\packages\SSH.NET.2016.1.0\lib\net40\Renci.SshNet.dll</HintPath>
</Reference>
<Reference Include="SReaderAPI">
<HintPath>..\Lib\SReaderAPI.dll</HintPath>
</Reference>
......@@ -181,7 +163,6 @@
<DependentUpon>RfidConfig.cs</DependentUpon>
</EmbeddedResource>
<None Include="config.json" />
<None Include="packages.config" />
<None Include="Properties\app.manifest" />
<None Include="Properties\Settings.settings">
<Generator>SettingsSingleFileGenerator</Generator>
......@@ -275,6 +256,20 @@
<Install>false</Install>
</BootstrapperPackage>
</ItemGroup>
<ItemGroup>
<PackageReference Include="MQTTnet">
<Version>3.1.2</Version>
</PackageReference>
<PackageReference Include="Newtonsoft.Json">
<Version>12.0.3</Version>
</PackageReference>
<PackageReference Include="OctaneSDK">
<Version>3.4.0</Version>
</PackageReference>
<PackageReference Include="System.Management">
<Version>5.0.0</Version>
</PackageReference>
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<PropertyGroup>
<PostBuildEvent>xcopy $(ProjectDir)ThirdPackages\* $(TargetDir) /S /Y
......
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="libltknet-sdk" version="10.40.0" targetFramework="net461" />
<package id="MQTTnet" version="3.1.2" targetFramework="net461" />
<package id="Newtonsoft.Json" version="12.0.3" targetFramework="net461" />
<package id="OctaneSDK" version="3.4.0" targetFramework="net461" />
<package id="SSH.NET" version="2016.1.0" targetFramework="net461" />
<package id="System.Management" version="5.0.0" targetFramework="net461" />
</packages>
\ No newline at end of file
......@@ -19,6 +19,8 @@ Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "TransmitterService", "Trans
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "LiteChannelDJB", "LiteChannelDJB\LiteChannelDJB.csproj", "{105D4340-4411-4B91-AD04-7A1EF2F7D3C8}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "LiteChannelCore", "LiteChannelCore\LiteChannelCore.csproj", "{16D024DA-097A-4553-88FE-3280C0AD4D65}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
......@@ -57,6 +59,10 @@ Global
{105D4340-4411-4B91-AD04-7A1EF2F7D3C8}.Debug|Any CPU.Build.0 = Debug|Any CPU
{105D4340-4411-4B91-AD04-7A1EF2F7D3C8}.Release|Any CPU.ActiveCfg = Release|Any CPU
{105D4340-4411-4B91-AD04-7A1EF2F7D3C8}.Release|Any CPU.Build.0 = Release|Any CPU
{16D024DA-097A-4553-88FE-3280C0AD4D65}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{16D024DA-097A-4553-88FE-3280C0AD4D65}.Debug|Any CPU.Build.0 = Debug|Any CPU
{16D024DA-097A-4553-88FE-3280C0AD4D65}.Release|Any CPU.ActiveCfg = Release|Any CPU
{16D024DA-097A-4553-88FE-3280C0AD4D65}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
......
<pu:WindowX x:Class="LiteChannel.OutWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:pu="clr-namespace:Panuon.UI.Silver;assembly=Panuon.UI.Silver"
xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:LiteChannel"
xmlns:usControl="clr-namespace:LiteChannel.UsControl"
mc:Ignorable="d" Icon="1.ico"
Height="720" Width="1024" Loaded="MainWindowLoaded" ResizeMode="NoResize"
AllowsTransparency="True" WindowStyle="None" WindowStartupLocation="CenterScreen"
WindowState="Maximized" pu:WindowXCaption.DisableCloseButton="True">
<Grid x:Name="g_main">
<Grid.RowDefinitions>
<RowDefinition Height="0.3*"/>
<RowDefinition Height="0.3*"/>
<RowDefinition Height="0.3*"/>
<RowDefinition Height="0.3*"/>
<RowDefinition Height="0.3*"/>
<RowDefinition Height="0.3*"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="0.5*"/>
<ColumnDefinition Width="0.5*"/>
<ColumnDefinition Width="0.5*"/>
<ColumnDefinition Width="0.5*"/>
</Grid.ColumnDefinitions>
<Button Grid.Row="1" Grid.Column="1" Grid.ColumnSpan="2" Margin="10,10,10,10" Click="OnOutStoreNoOrder_Click" pu:ButtonHelper.Icon="&#xf085;" Content="无单据出库" FontFamily="{StaticResource FontAwesome}" pu:ButtonHelper.CornerRadius="5" FontSize="30"></Button>
<Button Grid.Row="2" Grid.Column="1" Margin="10,10,10,10" Click="OnOutStoreJY_Click" pu:ButtonHelper.Icon="&#xf085;" Content="借用" FontFamily="{StaticResource FontAwesome}" pu:ButtonHelper.CornerRadius="5" FontSize="30"></Button>
<Button Grid.Row="2" Grid.Column="2" Margin="10,10,10,10" Click="OnOutStoreLY_Click" pu:ButtonHelper.Icon="&#xf085;" Content="领用" FontFamily="{StaticResource FontAwesome}" pu:ButtonHelper.CornerRadius="5" FontSize="30"></Button>
<Button Grid.Row="3" Grid.Column="1" Margin="10,10,10,10" Click="OnOutStoreDB_Click" pu:ButtonHelper.Icon="&#xf085;" Content="调拨" FontFamily="{StaticResource FontAwesome}" pu:ButtonHelper.CornerRadius="5" FontSize="30"></Button>
<Button Grid.Row="3" Grid.Column="2" Margin="10,10,10,10" Click="OnOutStoreKK_Click" pu:ButtonHelper.Icon="&#xf085;" Content="跨库" FontFamily="{StaticResource FontAwesome}" pu:ButtonHelper.CornerRadius="5" FontSize="30"></Button>
<Button Grid.Row="4" Grid.Column="1" Grid.ColumnSpan="2" Click="OnClose_Click" pu:ButtonHelper.Icon="&#xf2d3;" Margin="10,10,10,10" Content="返回上级" FontFamily="{StaticResource FontAwesome}" pu:ButtonHelper.CornerRadius="5" FontSize="24" Background="#C8FF0000" pu:ButtonHelper.HoverBrush="#FF0000" ></Button>
</Grid>
</pu:WindowX>
<UserControl x:Class="LiteChannel.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:LiteChannel.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 LiteChannel.UsControl
{
/// <summary>
/// WaitDialog.xaml 的交互逻辑
/// </summary>
public partial class InputDialog : UserControl
{
public InputDialog()
{
InitializeComponent();
}
}
}
<UserControl x:Class="LiteChannel.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:LiteChannel.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 LiteChannel.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="LiteChannel.AddInvWindow"
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:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:LiteChannel"
mc:Ignorable="d" Icon="1.ico"
Title="添加装备" Height="300" Width="400" WindowState="Normal" FontSize="24"
WindowStartupLocation="CenterScreen"
ResizeMode="NoResize" Loaded="OnWindow_Loaded" >
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="0.2*"></RowDefinition>
<RowDefinition Height="*"></RowDefinition>
<RowDefinition Height="*"></RowDefinition>
<RowDefinition Height="*"></RowDefinition>
<RowDefinition Height="*"></RowDefinition>
<RowDefinition Height="0.2*"></RowDefinition>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"></ColumnDefinition>
<ColumnDefinition Width="8*"></ColumnDefinition>
<ColumnDefinition Width="*"></ColumnDefinition>
</Grid.ColumnDefinitions>
<TextBlock Grid.Row="1" Grid.Column="1" Text="装备名称:" HorizontalAlignment="Left" VerticalAlignment="Center"/>
<ComboBox Grid.Row="1" Grid.Column="1" x:Name="cbo_inv"
Width="200" Height="40" Margin="5,0,5,0" FontSize="24"
HorizontalAlignment="Right" VerticalAlignment="Center"
pu:ComboBoxHelper.HoverBackground="#1EB5B5B5"
pu:ComboBoxHelper.SelectedBackground="#32B5B5B5"
pu:ComboBoxHelper.Watermark="请选择装备名称" PreviewMouseDown="cbo_inv_MouseDown"></ComboBox>
<TextBlock Grid.Row="2" Grid.Column="1" Text="在库数量:" HorizontalAlignment="Left" VerticalAlignment="Center" FontSize="24"/>
<TextBlock Grid.Row="2" Grid.Column="1" Name="tb_count" Margin="120,0,5,0" Text="0" HorizontalAlignment="Left" VerticalAlignment="Center"/>
<TextBlock Grid.Row="3" Grid.Column="1" Text="申请数量:" HorizontalAlignment="Left" VerticalAlignment="Center"/>
<TextBox Grid.Row="3" Grid.Column="1" Height="40" Text="1" InputMethod.IsInputMethodEnabled="False" PreviewTextInput="TextBox_PreviewTextInput" x:Name="txt_count" Width="auto" Margin="110,0,5,0" HorizontalAlignment="Stretch" VerticalAlignment="Center" MaxLength="5" FontSize="24"/>
<Button pu:ButtonHelper.CornerRadius="4" Grid.Row="4" Grid.ColumnSpan="2" HorizontalAlignment="Right" Width="90" Height="35" Margin="0,0,150,0" Click="OnSave_Click" FontSize="24">添加</Button>
<Button pu:ButtonHelper.CornerRadius="4" Grid.Row="4" Grid.ColumnSpan="2" HorizontalAlignment="Right" Background="#C8FF7F00" Click="OnExit_Click" pu:ButtonHelper.HoverBrush="#FF7F00" Width="90" Height="35" Margin="0,0,50,0" FontSize="24">取消</Button>
</Grid>
</pu:WindowX>
using JmpRfidLp;
using LiteChannel.Commons;
using LiteChannel.Models;
using Panuon.UI.Silver;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
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.Markup;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Windows.Threading;
using Panuon.UI.Silver.Core;
namespace LiteChannel
{
/// <summary>
/// StoreWindow.xaml 的交互逻辑
/// </summary>
public partial class AddInvWindow : WindowX, IComponentConnector
{
private List<inventory_info> InventoryList { get; set; }
private inventory_info inventory = null;
private ObservableCollection<scan_info> RefreshSourcesList;
private bool editFlag = false;
public AddInvWindow(ObservableCollection<scan_info> _RefreshSourcesList, inventory_info info = null)
{
InitializeComponent();
RefreshSourcesList = _RefreshSourcesList;
if (info != null)
{
//编辑模式
inventory = info;
cbo_inv.IsEnabled = false;
txt_count.Text = info.detailCount.ToString();
editFlag = true;
}
}
private void OnWindow_Loaded(object sender, RoutedEventArgs e)
{
cbo_inv.DisplayMemberPath = "equipmentDetailName";
cbo_inv.SelectedValuePath = "equipmentDetailId";
cbo_inv.SelectedIndex = -1;
InventoryList = HttpHelper.GetAllInventoryList();
if (editFlag)
{
cbo_inv.ItemsSource = InventoryList
.Where(x => x.equipmentDetailId == inventory.equipmentDetailId)
.ToList();
cbo_inv.SelectedIndex = 0;
tb_count.Text = (cbo_inv.SelectedItem as inventory_info)?.detailCount.ToString();
}
else
{
cbo_inv.ItemsSource = InventoryList;
}
}
private void OnSave_Click(object sender, RoutedEventArgs e)
{
try
{
if (inventory == null)
{
MessageBox.Show("未选择装备");
return;
}
if (Convert.ToInt32(txt_count.Text) > Convert.ToInt32(tb_count.Text))
{
MessageBox.Show("装备数量大于库存数");
return;
}
var checkItem = RefreshSourcesList.FirstOrDefault(x => x.equCode == inventory.equipmentDetailId);
if (checkItem == null)
{
//新增装备
RefreshSourcesList.Add(new scan_info()
{
equName = inventory.equipmentDetailName,
equCode = inventory.equipmentDetailId,
equCount = Convert.ToInt32(txt_count.Text)
});
}
else
{
if (editFlag)
{
//更新数量
checkItem.equCount = Convert.ToInt32(txt_count.Text);
}
else
{
MessageBox.Show("不允许重复添加装备");
return;
}
}
this.Close();
}
catch (Exception exception)
{
Log.ErrorLog(exception.ToString());
}
}
private void OnExit_Click(object sender, RoutedEventArgs e)
{
this.Close();
}
private void TextBox_PreviewTextInput(object sender, System.Windows.Input.TextCompositionEventArgs e)
{
e.Handled = new Regex("[^0-9]+").IsMatch(e.Text);
}
private void cbo_inv_MouseDown(object sender, MouseButtonEventArgs e)
{
cbo_inv.IsDropDownOpen = false;
var select = new SelectInvWindow(InventoryList);
select.ShowDialog();
inventory = select.inventory;
if (inventory != null)
{
cbo_inv.SelectedItem = inventory;
tb_count.Text = inventory.detailCount.ToString();
var checkItem = RefreshSourcesList.FirstOrDefault(x => x.equCode == inventory.equipmentDetailId);
if (checkItem != null)
{
txt_count.Text = checkItem.equCount.ToString();
}
}
}
}
}
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6" />
</startup>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<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>
\ No newline at end of file
<Application x:Class="LiteChannel.App"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:LiteChannel"
StartupUri="LoginWindow.xaml">
<Application.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="pack://application:,,,/Panuon.UI.Silver;component/Control.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>
using LiteChannel.Commons;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Threading;
namespace LiteChannel
{
/// <summary>
/// App.xaml 的交互逻辑
/// </summary>
public partial class App : Application
{
private System.Threading.Mutex _mutex;
public App()
{
this.Startup += App_Startup;
}
void App_Startup(object sender, StartupEventArgs e)
{
_mutex = new System.Threading.Mutex(true, Process.GetCurrentProcess().ProcessName, out var ret);
if (!ret)
{
MessageBox.Show("已有另一个程序在运行!", "提示", MessageBoxButton.OK, MessageBoxImage.Information);//弹出提示信息
Environment.Exit(0);
}
//UI线程未捕获异常处理事件
this.DispatcherUnhandledException += App_DispatcherUnhandledException;
//Task线程内未捕获异常处理事件
TaskScheduler.UnobservedTaskException += TaskScheduler_UnobservedTaskException;
//非UI线程未捕获异常处理事件
AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
}
void App_DispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)
{
Log.ErrorLog(e.Exception.ToString(), "UI线程未捕获异常");
}
void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
Log.ErrorLog(e.ExceptionObject.ToString(), "非UI线程未捕获异常");
}
void TaskScheduler_UnobservedTaskException(object sender, UnobservedTaskExceptionEventArgs e)
{
//task线程内未处理捕获
Log.ErrorLog(e.Exception.ToString(), "Task线程内未捕获异常");
e.SetObserved();//设置该异常已察觉(这样处理后就不会引起程序崩溃)
}
protected override void OnStartup(StartupEventArgs e)
{
base.OnStartup(e);
LiteCaChe.SysConfig = LiteCaChe.LoadSystemStep();
if (LiteCaChe.SysConfig == null)
{
//MessageBox.Show("配置文件加载失败,请检查", "文件错误", MessageBoxButton.OK, MessageBoxImage.Error);
//Process.GetCurrentProcess().Kill();
MessageBox.Show("配置文件加载失败,创建默认配置文件");
LiteCaChe.SysConfig = new Config();
LiteCaChe.SaveSystemStep(LiteCaChe.SysConfig);
}
else
{
var update = HttpHelper.GetUpdate(LiteCaChe.SysConfig?.AppCode ?? "");
if (update == null)
{
}
else
{
if (Version.TryParse(update.version2, out var version) && version > new Version(LiteCaChe.SysConfig.AppVersion))
{
if (MessageBox.Show("检测到新版本,是否更新?", "更新提示", MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.Yes)
{
System.Diagnostics.Process.Start("explorer.exe", LiteCaChe.SysConfig.DomainUrl.TrimEnd('/') + "/" + update.address.TrimStart('/'));
Process.GetCurrentProcess().Kill();
}
else { }
}
}
}
//获取供应商
LiteCaChe.EquInfos = HttpHelper.GetEquInfos();
}
}
}
<pu:WindowX x:Class="LiteChannel.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:LiteChannel"
Title="标题" Height="250" Width="400" Loaded="Window_Loaded" ResizeMode="NoResize" WindowStartupLocation="CenterScreen" FontSize="14" >
<Window.Effect>
<DropShadowEffect BlurRadius="10" Color="#FF858484" Direction="90" ShadowDepth="2"/>
</Window.Effect>
<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="0,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>
using LiteChannel.Commons;
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 LiteChannel
{
/// <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--;
}
}
}
This source diff could not be displayed because it is too large. You can view the blob instead.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LiteChannel.Commons
{
public class Analyzingepc
{
public byte Header; // 标头(8bits): JY物资专用标头 0x11(00010001b)
public byte IssuerId; // 发行机构标识符(6bits):GA组织机构: 0x01(000001b) 国家组织机构:0x02(000010b)
public string OrganizationCode; // 组织机构代码(54bits):JY物资生产厂商使用GA或国家组织机构代码, 英文字母及数字的每一个字符转换为六位二进制
public byte WzdmLen; // 物资代码长度(4bits): 指定物资代码的长度(N*8bits), 此处为0x7
public UInt64 Wzdm; // 物资代码(56bits): 使用警用物资编目数据的物资代码,按十进制转换成十六进制存储
public UInt64 Hxdm;
public byte SerialLen; // 序列号长度(4bits): 指定序列号长度(N*8bits), 此处为0xD
public byte Ver; // 版本号(8bits): 0x01
public byte TagType; // 标签类型(8bits): 0x00 件标 0x01 箱标
public byte PackingType; // 包装类型(4bits): 0x1 单品, 0x2 外包装, 0x3 内包装, 0xF 零头配箱
public UInt32 ProductionDate; // 生产日期(24bits): 0x161201
public byte ExpiryDate; // 有效期值(6bits): 0-63
public byte ExpiryDateUnit; // 有效期时间单位(2bits): 1:01b-日, 2:10b-月, 3:11b-年
public byte SubPackageNum; // 下级包装内数量(8bits):最大255
public UInt16 WzCount; // 包装数量(12bits): MAX:4095, 每箱内产品总数
public UInt32 BoxNo; // 包装箱序列号(20bits): MAX:65535
public UInt16 NoInBox; // 箱内序列号(12bits): 每箱内产品序号, MAX4095
}
public static class EpcConvert
{
private readonly static string strKeyWords = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"; // 无源标签6位字段对应表
/// <summary>
/// 此方法用于将普通字符串转换成16进制的字符串。
/// </summary>
/// <param name="_str">要转换的字符串。</param>
/// <returns></returns>
public static string StringToHex16String(string _str)
{
//将字符串转换成字节数组。
byte[] buffer = System.Text.Encoding.UTF8.GetBytes(_str);
//定义一个string类型的变量,用于存储转换后的值。
string result = string.Empty;
for (int i = 0; i < buffer.Length; i++)
{
//将每一个字节数组转换成16进制的字符串,以空格相隔开。
result += Convert.ToString(buffer[i], 16) + " ";
}
return result;
}
/// <summary>
/// 此方法用于将16进制的字节数组转换成16进制的字符串。
/// </summary>
/// <param name="_hex16Byte">要转换的16进制的字节数组。</param>
/// <returns></returns>
public static string Hex16ByteToHex16String(byte[] _hex16Byte)
{
string result = string.Empty;
//如果字节数组不为空。
if (_hex16Byte != null)
{
for (int i = 0; i < _hex16Byte.Length; i++)
{
//将每一个字节数组转换成16进制string类型的字符串,用空格分隔开。
result += _hex16Byte[i].ToString("X2") + " ";
}
}
return result;
}
public static byte[] ToHexByte(string hexString)
{
hexString = hexString.Replace(" ", "");
if ((hexString.Length % 2) != 0)
{
hexString = hexString + " ";
}
byte[] buffer = new byte[hexString.Length / 2];
for (int i = 0; i < buffer.Length; i++)
{
buffer[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 0x10);
}
return buffer;
}
/// <summary>
/// 生成EPC
/// </summary>
/// <param name="epc"></param>
/// <returns></returns>
public static byte[] EpcGen(Analyzingepc epc)
{
byte[] buf = new byte[40];
int pos = 0;
SetData(ref buf, pos, 8, epc.Header);
pos += 8;
SetData(ref buf, pos, 6, epc.IssuerId);
pos += 6;
SetData(ref buf, pos, 54, OrganizationCodeTo6Bin(epc.OrganizationCode.ToUpper()));
pos += 54;
SetData(ref buf, pos, 4, epc.WzdmLen);
pos += 4;
var wzlen = ((epc.WzdmLen - 1) % 8) * 8;
SetData(ref buf, pos, wzlen, epc.Wzdm); // 物资代码暂时定义最长为64bits
pos += wzlen;
SetData(ref buf, pos, 8, epc.Hxdm); // 物资代码暂时定义最长为64bits
pos += 8;
SetData(ref buf, pos, 4, epc.SerialLen);
pos += 4;
SetData(ref buf, pos, 8, epc.Ver);
pos += 8;
SetData(ref buf, pos, 8, epc.TagType);
pos += 8;
SetData(ref buf, pos, 4, epc.PackingType);
pos += 4;
SetData(ref buf, pos, 24, epc.ProductionDate);
pos += 24;
SetData(ref buf, pos, 6, epc.ExpiryDate);
pos += 6;
SetData(ref buf, pos, 2, epc.ExpiryDateUnit);
pos += 2;
SetData(ref buf, pos, 8, epc.SubPackageNum);
pos += 8;
SetData(ref buf, pos, 12, epc.WzCount);
pos += 12;
SetData(ref buf, pos, 20, epc.BoxNo);
pos += 20;
SetData(ref buf, pos, 12, epc.NoInBox);
pos += 12;
// 双字节对齐, 剩余保留区
if (pos % 16 != 0)
{
pos += 16 - pos % 16;
}
// 数据体长度
var len = pos / 8;
var crc = Crc16(buf, len);
SetData(ref buf, pos, 16, crc);
byte[] rtn = new byte[len + 2];
Array.Copy(buf, rtn, len + 2);
return rtn;
}
/// <summary>
/// 解析EPC
/// </summary>
/// <param name="epc"></param>
/// <returns></returns>
public static Analyzingepc EpcAnlysing(byte[] epc)
{
// CRC 校验
var crc_chk = Crc16(epc, epc.Length - 2);
var crc_src = epc[epc.Length - 2] << 8 | epc[epc.Length - 1];
if (crc_src != crc_chk)
{
throw new Exception("CRC校验失败");
}
// 数据解析
Analyzingepc rtn = new Analyzingepc();
int pos = 0;
rtn.Header = (byte)GetData(epc, pos, 8);
pos += 8;
rtn.IssuerId = (byte)GetData(epc, pos, 6);
pos += 6;
var oc = GetData(epc, pos, 54);
rtn.OrganizationCode = OrganizationCodeToStr(oc);
pos += 54;
rtn.WzdmLen = (byte)(GetData(epc, pos, 4));
pos += 4;
var wzlen = ((rtn.WzdmLen - 1) % 8) * 8;
rtn.Wzdm = GetData(epc, pos, wzlen);
pos += wzlen;
rtn.Hxdm = GetData(epc, pos, 8);
pos += 8;
rtn.SerialLen = (byte)GetData(epc, pos, 4);
pos += 4;
rtn.Ver = (byte)GetData(epc, pos, 8);
pos += 8;
rtn.TagType = (byte)GetData(epc, pos, 8);
pos += 8;
rtn.PackingType = (byte)GetData(epc, pos, 4);
pos += 4;
rtn.ProductionDate = (UInt32)GetData(epc, pos, 24);
pos += 24;
rtn.ExpiryDate = (byte)GetData(epc, pos, 6);
pos += 6;
rtn.ExpiryDateUnit = (byte)GetData(epc, pos, 2);
pos += 2;
rtn.SubPackageNum = (byte)GetData(epc, pos, 8);
pos += 8;
rtn.WzCount = (UInt16)GetData(epc, pos, 12);
pos += 12;
rtn.BoxNo = (UInt32)GetData(epc, pos, 20);
pos += 20;
rtn.NoInBox = (UInt16)GetData(epc, pos, 12);
pos += 12;
return rtn;
}
/// <summary>
/// 向目标数组指定位置插入数据
/// </summary>
/// <param name="data">待操作数组</param>
/// <param name="pos">起始位置</param>
/// <param name="len">写入长度bits</param>
/// <param name="value">写入的值</param>
private static void SetData(ref byte[] data, int pos, int len, UInt64 value)
{
int p = pos;
while (--len >= 0)
{
var bitPos = 7 - p % 8;
data[p++ / 8] |= (byte)(((value >> len) & 1) << bitPos);
}
}
/// <summary>
/// 从目标数组获取成员变量
/// </summary>
/// <param name="data"></param>
/// <param name="pos"></param>
/// <param name="len"></param>
/// <returns></returns>
private static UInt64 GetData(byte[] data, int pos, int len)
{
UInt64 rtn = 0;
int p = pos;
while (len-- > 0)
{
var bitPos = 7 - p % 8;
rtn <<= 1;
rtn |= (byte)((data[p++ / 8] >> bitPos) & 1);
}
return rtn;
}
/// <summary>
/// 转换成字符串
/// </summary>
/// <param name="icode"></param>
/// <returns></returns>
private static string OrganizationCodeToStr(UInt64 icode)
{
string code = "";
for (int i = 0; i < 9; i++)
{
var v = (byte)((icode >> (i * 6)) & 0x3f);
code = strKeyWords[v] + code;
}
return code;
}
/// <summary>
/// 生成十六进制组织代码, 6Bin
/// </summary>
/// <param name="code"></param>
/// <returns>0 失败, 其它:正常的组织代码编号</returns>
private static UInt64 OrganizationCodeTo6Bin(string code)
{
UInt64 iCode = 0;
if (code.Length == 9)
{
for (int i = 0; i < code.Length; i++)
{
var index = strKeyWords.IndexOf(code[i]);
if (index == -1)
{
throw new Exception("输入字符非法!");
}
iCode <<= 6;
iCode |= (byte)index;
}
}
else
{
throw new Exception("输入长度非法!");
}
return iCode;
}
/// <summary>
/// CRC运算
/// </summary>
/// <param name="data"></param>
/// <param name="len">必须是偶数</param>
/// <returns></returns>
public static UInt16 Crc16(byte[] data, int lenth)
{
ushort crc = 0x8791;
for (int i = 0; i < lenth; ++i)
{
ushort temp = 0;
ushort a = (ushort)(((crc >> 8) ^ (0xff & data[i])) << 8);
for (int j = 0; j < 8; ++j)
{
if (((temp ^ a) & 0x8000) != 0)
{
temp = (ushort)((temp << 1) ^ 0x1021);
}
else
{
temp <<= 1;
}
a <<= 1;
}
crc = (ushort)((crc << 8) ^ temp);
}
return crc;
}
}
}
using LiteChannel.Models;
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 System.Threading.Tasks;
namespace LiteChannel.Commons
{
/// <summary>
/// 接口调用类
/// </summary>
public class HttpHelper
{
public static string HttpPost(string strUrl, string json = "")
{
try
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(strUrl);
request.Method = "POST";
if (!string.IsNullOrEmpty(json))
{
request.ContentType = "application/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.Message.ToString() + "\r\n" + strUrl);
return string.Empty;
}
}
public static string HttpGet(string strUrl)
{
try
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(strUrl);
request.Method = "GET";
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);
return string.Empty;
}
}
/// <summary>
/// 获取软件更新
/// </summary>
/// <param name="appCode"></param>
/// <returns></returns>
public static soft_update GetUpdate(string appCode)
{
try
{
var parame = JsonConvert.SerializeObject(new
{
appCode = appCode
});
var json = HttpPost(LiteCaChe.SysConfig.DomainUrl + Config.SoftUpdate, parame);
if (string.IsNullOrEmpty(json))
{
Log.WorkLog("获取更新信息失败", "更新失败");
return default;
}
else
{
var res_data = JsonConvert.DeserializeObject<respone<soft_update>>(json);
if (res_data == null || res_data.code != 10000)
{
Log.WorkLog("获取更新信息失败", "更新失败");
return default;
}
else
{
Log.WorkLog("获取更新信息成功", "更新成功");
return res_data.data;
}
}
}
catch (Exception ex)
{
Log.ErrorLog(ex.ToString());
return default;
}
}
/// <summary>
/// 与服务器同步时间
/// </summary>
/// <returns></returns>
public static bool SetLocalTime()
{
try
{
var json = HttpGet(LiteCaChe.SysConfig.DomainUrl + Config.GetServerime);
if (string.IsNullOrEmpty(json))
{
Log.WorkLog("服务器时间获取失败", "获取失败");
return default;
}
else
{
var res_data = JsonConvert.DeserializeObject<respone<DateTime>>(json);
if (res_data == null || res_data.code != 10000)
{
Log.WorkLog("服务器时间获取失败", "获取失败");
return default;
}
else
{
Log.WorkLog("服务器时间获取成功", "获取成功");
if (res_data.data != null && res_data.data != default)
{
SYSTEMTIME _time = new SYSTEMTIME();
_time.FromDateTime(res_data.data);
var res = Win32API.SetLocalTime(ref _time);
if (res)
{
Log.WorkLog("时间同步成功", "同步成功");
}
else
{
Log.WorkLog($"时间同步失败,时间:{res_data.data.ToString("yyyy-MM-dd HH:mm:ss")}", "同步失败");
}
return res;
}
else
{
return false;
}
}
}
}
catch (Exception ex)
{
Log.ErrorLog(ex.ToString());
return false;
}
}
/// <summary>
/// 获取物资信息
/// </summary>
/// <returns></returns>
public static List<equ_info> GetEquInfos()
{
try
{
var body_par = string.Empty;
var body_result = GetBody(body_par);
if (body_result == null)
{
Log.WorkLog("签名值生成失败。");
return new List<equ_info>();
}
else
{
var param = JsonConvert.SerializeObject(new request_sign
{
appKey = LiteCaChe.SysConfig.AppKey,
body = body_result.Item1,
sign = body_result.Item2,
timestamp = body_result.Item3,
version = LiteCaChe.SysConfig.ApiVersion,
orgId = LiteCaChe.OrgId,
});
var json = HttpPost(LiteCaChe.SysConfig.DomainUrl + Config.GetEquInfo, param);
if (string.IsNullOrEmpty(json))
{
Log.WorkLog("获取获取装备基础信息失败", "获取失败");
return default;
}
else
{
var res_data = JsonConvert.DeserializeObject<respone<List<equ_info>>>(json);
if (res_data == null || res_data.code != 10000)
{
Log.WorkLog("获取获取装备基础信息失败", "获取失败");
return default;
}
else
{
Log.WorkLog("获取获取装备基础信息成功", "获取成功");
return res_data.data;
}
}
}
}
catch (Exception ex)
{
Log.ErrorLog(ex.ToString());
return default;
}
}
/// <summary>
/// 获取仓库信息
/// </summary>
/// <returns></returns>
public static List<store_info> GetStoreInfos(string orgId)
{
try
{
var body_par = JsonConvert.SerializeObject(new
{
orgizationId = orgId
});
var body_result = GetBody(body_par);
if (body_result == null)
{
Log.WorkLog("签名值生成失败。");
return new List<store_info>();
}
else
{
var param = JsonConvert.SerializeObject(new request_sign
{
appKey = LiteCaChe.SysConfig.AppKey,
body = body_result.Item1,
sign = body_result.Item2,
timestamp = body_result.Item3,
version = LiteCaChe.SysConfig.ApiVersion,
orgId = LiteCaChe.OrgId,
});
var json = HttpPost(LiteCaChe.SysConfig.DomainUrl + Config.GetStoreInfo, param);
if (string.IsNullOrEmpty(json))
{
Log.WorkLog("获取获取仓库基础信息失败", "获取失败");
return default;
}
else
{
var res_data = JsonConvert.DeserializeObject<respone<List<store_info>>>(json);
if (res_data == null || res_data.code != 10000)
{
Log.WorkLog("获取获取仓库基础信息失败", "获取失败");
return default;
}
else
{
Log.WorkLog("获取获取仓库基础信息成功", "获取成功");
return res_data.data;
}
}
}
}
catch (Exception ex)
{
Log.ErrorLog(ex.ToString());
return default;
}
}
/// <summary>
/// 获取单据信息
/// </summary>
/// <returns></returns>
public static PagedList<order_info> GetOrderInfos(int page = 1, int size = 10, string orderType = "")
{
try
{
var body_par = JsonConvert.SerializeObject(new
{
page = page - 1,
size = size,
orderType = orderType,
warehouseId = LiteCaChe.SysConfig.WarehouseID
});
var body_result = GetBody(body_par);
if (body_result == null)
{
Log.WorkLog("签名值生成失败。");
return new PagedList<order_info>();
}
else
{
var param = JsonConvert.SerializeObject(new request_sign
{
appKey = LiteCaChe.SysConfig.AppKey,
body = body_result.Item1,
sign = body_result.Item2,
timestamp = body_result.Item3,
version = LiteCaChe.SysConfig.ApiVersion,
orgId = LiteCaChe.OrgId,
});
var json = HttpPost(LiteCaChe.SysConfig.DomainUrl + Config.GetOrderInfo, param);
if (string.IsNullOrEmpty(json))
{
Log.WorkLog("获取获取单据信息失败", "获取失败");
return default;
}
else
{
var res_data = JsonConvert.DeserializeObject<respone>(json);
if (res_data == null || res_data.code != 10000)
{
Log.WorkLog("获取获取单据信息失败", "获取失败");
return default;
}
else
{
Log.WorkLog("获取获取单据信息成功", "获取成功");
JObject obj = JObject.Parse(json);
var orders = JsonConvert.DeserializeObject<PagedList<order_info>>(obj["data"].ToString());
return orders;
}
}
}
}
catch (Exception ex)
{
Log.ErrorLog(ex.ToString());
return default;
}
}
/// <summary>
/// 获取单据信息
/// </summary>
/// <returns></returns>
public static List<order_detail> GetOrderDetails(string orderid, string type)
{
try
{
var body_par = JsonConvert.SerializeObject(new
{
id = orderid,
warehouseId = LiteCaChe.SysConfig.WarehouseID,
type = type
});
var body_result = GetBody(body_par);
if (body_result == null)
{
Log.WorkLog("签名值生成失败。");
return new List<order_detail>();
}
else
{
var param = JsonConvert.SerializeObject(new request_sign
{
appKey = LiteCaChe.SysConfig.AppKey,
body = body_result.Item1,
sign = body_result.Item2,
timestamp = body_result.Item3,
version = LiteCaChe.SysConfig.ApiVersion,
orgId = LiteCaChe.OrgId,
});
var json = HttpPost(LiteCaChe.SysConfig.DomainUrl + Config.GetOrderDetail, param);
if (string.IsNullOrEmpty(json))
{
Log.WorkLog("获取获取单据明细信息失败", "获取失败");
return default;
}
else
{
var res_data = JsonConvert.DeserializeObject<respone<List<order_detail>>>(json);
if (res_data == null || res_data.code != 10000)
{
Log.WorkLog("获取获取单据明细信息失败", "获取失败");
return default;
}
else
{
Log.WorkLog("获取获取单据明细信息成功", "获取成功");
return res_data.data;
}
}
}
}
catch (Exception ex)
{
Log.ErrorLog(ex.ToString());
return default;
}
}
/// <summary>
/// 用户登录
/// </summary>
/// <param name="userName"></param>
/// <param name="userPwd"></param>
/// <returns></returns>
public static respone_user UserLogin(string userName, string userPwd)
{
try
{
var param = JsonConvert.SerializeObject(new { username = userName, password = userPwd });
var json = HttpPost(LiteCaChe.SysConfig.UserLogin, param);
if (string.IsNullOrEmpty(json))
{
return null;
}
else
{
var res_data = JObject.Parse(json);
var jobj = JObject.Parse(json);
if (!jobj.HasValues)
{
return null;
}
else
{
var user = JsonConvert.DeserializeObject<respone_user>(json);
return user;
}
}
}
catch (Exception ex)
{
Log.ErrorLog(ex.ToString() + "\r\n", MethodBase.GetCurrentMethod().Name);
return default;
}
}
/// <summary>
/// 获取平台警员信息
/// </summary>
/// <returns></returns>
public static List<sync_police> GetPoliceInfo()
{
try
{
if (string.IsNullOrEmpty(LiteCaChe.OrgId ?? ""))
{
Log.WorkLog($"平台人员同步信息获取失败,组织机构为空");
return default;
}
else
{
var body_par = JsonConvert.SerializeObject(new { orgId = LiteCaChe.OrgId });
var body_result = GetBody(body_par);
if (body_result == null)
{
Log.WorkLog("签名值生成失败。");
return new List<sync_police>();
}
else
{
var param = JsonConvert.SerializeObject(new request_sign
{
appKey = LiteCaChe.SysConfig.AppKey,
body = body_result.Item1,
sign = body_result.Item2,
timestamp = body_result.Item3,
version = LiteCaChe.SysConfig.ApiVersion,
orgId = LiteCaChe.OrgId,
});
var json = HttpPost(LiteCaChe.SysConfig.DomainUrl + Config.GetPolices, param);
if (string.IsNullOrEmpty(json))
{
return default;
}
else
{
var res_data = JsonConvert.DeserializeObject<respone<List<sync_police>>>(json);
if (res_data == null || res_data.code != 10000)
{
Log.WorkLog($"平台人员同步信息获取失败,{json}");
return default;
}
else
{
return res_data.data;
}
}
}
}
}
catch (Exception ex)
{
Log.ErrorLog(ex.ToString() + "\r\n");
return default;
}
}
/// <summary>
/// 获取当前仓库库存信息
/// </summary>
/// <returns></returns>
public static List<inventory_info> GetAllInventoryList()
{
try
{
if (string.IsNullOrEmpty(LiteCaChe.SysConfig.WarehouseID ?? ""))
{
Log.WorkLog($"获取当前仓库库存信息失败,仓库为空");
return default;
}
else
{
var body_par = JsonConvert.SerializeObject(new
{
warehouseId = LiteCaChe.SysConfig.WarehouseID
});
var body_result = GetBody(body_par);
if (body_result == null)
{
Log.WorkLog("签名值生成失败。");
return new List<inventory_info>();
}
else
{
var param = JsonConvert.SerializeObject(new request_sign
{
appKey = LiteCaChe.SysConfig.AppKey,
body = body_result.Item1,
sign = body_result.Item2,
timestamp = body_result.Item3,
version = LiteCaChe.SysConfig.ApiVersion,
orgId = LiteCaChe.OrgId,
});
var json = HttpPost(LiteCaChe.SysConfig.DomainUrl + Config.GetAllInventoryList, param);
if (string.IsNullOrEmpty(json))
{
return default;
}
else
{
var res_data = JsonConvert.DeserializeObject<respone<List<inventory_info>>>(json);
if (res_data == null || res_data.code != 10000)
{
Log.WorkLog($"获取当前仓库库存信息失败,{json}");
return default;
}
else
{
return res_data.data;
}
}
}
}
}
catch (Exception ex)
{
Log.ErrorLog(ex.ToString() + "\r\n");
return default;
}
}
/// <summary>
/// 获取警员图片
/// </summary>
/// <returns></returns>
public static byte[] GetPoliceImg(string url)
{
try
{
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(LiteCaChe.SysConfig.DomainUrl + url);
request.Method = "GET";
using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
{
using (Stream st = response.GetResponseStream())
{
using (MemoryStream ms = new MemoryStream())
{
st.CopyTo(ms);
var buffer = ms.GetBuffer();
st.Close();
ms.Close();
response.Close();
return buffer;
}
}
}
}
catch (Exception ex)
{
Log.ErrorLog(ex.ToString());
return default;
}
}
/// <summary>
/// 上传人脸照片
/// </summary>
/// <param name="buffer"></param>
/// <param name="fileName"></param>
/// <param name="directoy"></param>
/// <returns></returns>
public static bool UploadFace(byte[] buffer, string fileName, string id)
{
try
{
if (buffer == null || buffer.Length == 0)
{
return false;
}
else if (string.IsNullOrEmpty(id))
{
return false;
}
else
{
var _url = LiteCaChe.SysConfig.DomainUrl + Config.UploadFace;
using (HttpClient client = new HttpClient())
{
var postContent = new MultipartFormDataContent();
string boundary = string.Format("--{0}", DateTime.Now.Ticks.ToString("x"));
postContent.Headers.Add("ContentType", $"multipart/form-data, boundary={boundary}");
postContent.Add(new ByteArrayContent(buffer), "picture", fileName);
postContent.Add(new StringContent(id), "id");
using (HttpResponseMessage response = client.PostAsync(_url, postContent).Result)
{
var str = response.Content.ReadAsStringAsync().Result;
var res = JsonConvert.DeserializeObject<respone_upload>(str);
if (res.code == 10000)
{
Log.WorkLog("人脸图片上传成功", "图片上传");
return true;
}
else
{
Log.WorkLog(res.msg);
return false;
}
}
}
}
}
catch (Exception ex)
{
Log.ErrorLog(ex.ToString());
return false;
}
}
/// <summary>
/// 更新指纹信息
/// </summary>
/// <param name="fingerList"></param>
/// <param name="policeId"></param>
/// <returns></returns>
public static bool UpdateFinger(string policeId, List<FingerInfo> fingerList)
{
try
{
if (fingerList == null || fingerList.Count == 0)
{
return false;
}
else if (string.IsNullOrEmpty(policeId))
{
return false;
}
else
{
var body_par = JsonConvert.SerializeObject(new
{
policeId = policeId,
fingerList = fingerList
});
var body_result = GetBody(body_par);
if (body_result == null)
{
Log.WorkLog("签名值生成失败。");
return false;
}
else
{
var param = JsonConvert.SerializeObject(new request_sign
{
appKey = LiteCaChe.SysConfig.AppKey,
body = body_result.Item1,
sign = body_result.Item2,
timestamp = body_result.Item3,
version = LiteCaChe.SysConfig.ApiVersion,
orgId = LiteCaChe.OrgId,
});
var json = HttpPost(LiteCaChe.SysConfig.DomainUrl + Config.UpdateFinger, param);
if (string.IsNullOrEmpty(json))
{
return false;
}
else
{
var res_data = JsonConvert.DeserializeObject<respone>(json);
if (res_data == null || res_data.code != 10000)
{
Log.WorkLog($"指纹数据更新失败,JSON\r\n {json} ");
return false;
}
else
{
return true;
}
}
}
}
}
catch (Exception ex)
{
Log.ErrorLog(ex.ToString());
return false;
}
}
/// <summary>
/// 提交入库
/// </summary>
/// <param name="type"></param>
/// <param name="eps"></param>
/// <returns></returns>
public static Tuple<bool, string> RfidInStore(string type, List<rfid_info> eps)
{
try
{
var body_par = JsonConvert.SerializeObject(new upload_info
{
orgId = LiteCaChe.OrgId,
currentState = "1",
picUrl = string.Empty,
policeId = LiteCaChe.PoliceId,
RFIDList = eps,
warehouseId = LiteCaChe.SysConfig.WarehouseID
});
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 = LiteCaChe.SysConfig.AppKey,
body = body_result.Item1,
sign = body_result.Item2,
timestamp = body_result.Item3,
version = LiteCaChe.SysConfig.ApiVersion,
orgId = LiteCaChe.OrgId,
});
var json = HttpPost(LiteCaChe.SysConfig.DomainUrl + Config.UploadUrl, param);
if (string.IsNullOrEmpty(json))
{
Log.WorkLog("装备入库失败", "入库失败");
return new Tuple<bool, string>(false, "装备入库失败");
}
else
{
var res_data = JsonConvert.DeserializeObject<respone<List<rfid_res>>>(json);
if (res_data == null || res_data.code != 10000
|| res_data.data == null || res_data.data.Count == 0)
{
Log.WorkLog($"装备入库失败,{json}", "入库失败");
if (res_data != null && res_data.code != 10000)
{
return new Tuple<bool, string>(false, "装备入库失败:" + res_data.msg);
}
else
{
return new Tuple<bool, string>(false, "装备入库失败");
}
}
else
{
var successCount = res_data.data.Count(x => x.currentState == 0);
var failCount = eps.Count - successCount;
var failEpcList = eps.Where(x =>
res_data.data.Where(y => y.currentState == 0).Count(y => y.epc == x.RFID) == 0)
.Select(x => x.RFID);
Log.WorkLog(
$"装备入库成功{successCount}条,失败{failCount}条:{JsonConvert.SerializeObject(failEpcList)}",
"入库成功");
//智能货架推送
if (LiteCaChe.SysConfig.IsEnabledShelf && successCount > 0)
{
var epcListRes = GetInvListByEpc(res_data.data.Where(x => x.currentState == 0).Select(x => x.epc).ToList());
if (epcListRes.Item1)
{
//直接推送
var shelfRes = HttpPost(LiteCaChe.SysConfig.ShelfAddress, epcListRes.Item2);
if (string.IsNullOrEmpty(shelfRes))
{
Log.WorkLog("智能货架推送响应失败", "智能货架推送失败");
return new Tuple<bool, string>(true, $"装备入库成功{successCount}条,失败{failCount}条,智能货架推送响应失败");
}
else
{
var shelfRes_data = JsonConvert.DeserializeObject<respone>(shelfRes);
if (shelfRes_data == null || shelfRes_data.code != 1000)
{
Log.WorkLog($"智能货架推送响应失败,{shelfRes_data}", "智能货架推送失败");
return new Tuple<bool, string>(true, $"装备入库成功{successCount}条,失败{failCount}条,智能货架推送响应失败");
}
else
{
return new Tuple<bool, string>(true, $"装备入库成功{successCount}条,失败{failCount}条,智能货架推送成功");
}
}
}
else
{
Log.WorkLog($"获取物资信息失败", "智能货架推送失败");
return new Tuple<bool, string>(true, $"装备入库成功{successCount}条,失败{failCount}条,,获取物资信息失败");
}
}
return new Tuple<bool, string>(true, $"装备入库成功{successCount}条,失败{failCount}条");
}
}
}
}
catch (Exception ex)
{
Log.ErrorLog(ex.ToString());
return default;
}
}
/// <summary>
/// 提交出库
/// </summary>
/// <param name="order"></param>
/// <param name="eps"></param>
/// <returns></returns>
public static Tuple<bool, string> RfidOutStore(string order, string type, List<rfid_info> eps)
{
try
{
var body_par = JsonConvert.SerializeObject(new upload_info
{
orgId = LiteCaChe.OrgId,
currentState = "0",
picUrl = string.Empty,
policeId = LiteCaChe.PoliceId,
RFIDList = eps,
warehouseId = LiteCaChe.SysConfig.WarehouseID
});
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 = LiteCaChe.SysConfig.AppKey,
body = body_result.Item1,
sign = body_result.Item2,
timestamp = body_result.Item3,
version = LiteCaChe.SysConfig.ApiVersion,
orgId = LiteCaChe.OrgId,
});
var json = HttpPost(LiteCaChe.SysConfig.DomainUrl + Config.UploadUrl, param);
//Log.DebugLog("jsonres" + json);
//Log.DebugLog("jsonreq" + param);
//Log.DebugLog("url" + LiteCaChe.SysConfig.DomainUrl + LiteCaChe.SysConfig.UploadUrl);
if (string.IsNullOrEmpty(json))
{
Log.WorkLog("装备出库失败", "出库失败");
return new Tuple<bool, string>(false, "装备出库失败");
}
else
{
var res_data = JsonConvert.DeserializeObject<respone<List<rfid_res>>>(json);
if (res_data == null || res_data.code != 10000
|| res_data.data == null || res_data.data.Count == 0)
{
Log.WorkLog($"装备出库失败,{json}", "出库失败");
if (res_data != null && res_data.code != 10000)
{
return new Tuple<bool, string>(false, "装备出库失败:" + res_data.msg);
}
else
{
return new Tuple<bool, string>(false, "装备出库失败");
}
}
else
{
var successCount = res_data.data.Count(x => new[] { 1, 2, 7, 8, 14, 15, 17 }.Contains(x.currentState));
var bfCount = res_data.data.Count(x => new[] { 6 }.Contains(x.currentState));
var failCount = eps.Count - successCount - bfCount;
var failEpcList = eps.Where(x =>
res_data.data.Where(y => new[] { 1, 2, 7, 8, 14, 15, 17 }.Contains(y.currentState)).Count(y => y.epc == x.RFID) == 0)
.Select(x => x.RFID);
var message = $"装备出库成功{successCount}条,失败{failCount}条";
if (bfCount > 0)
{
message += $",已报废物资{bfCount}条";
}
//过滤已报废物资
var safeWarringList = res_data.data.Where(x => x.safeLevel == 1 && x.currentState != 6).ToList();
var safeDangerList = res_data.data.Where(x => x.safeLevel == 2 && x.currentState != 6).ToList();
if (safeDangerList.Count > 0)
{
message += $"\r\n警告:存在已过期装备{safeDangerList.Count}件。装备名:{string.Join(",", safeDangerList.Select(x => x.name).Distinct())},请立即联系仓管员处理";
}
if (safeWarringList.Count > 0)
{
message += $"\r\n提醒:存在即将过期装备{safeWarringList.Count}件。装备名:{string.Join(",", safeWarringList.Select(x => x.name).Distinct())}";
}
Log.WorkLog($"{message}:{JsonConvert.SerializeObject(failEpcList)}", "出库成功");
return new Tuple<bool, string>(true, message);
}
}
}
}
catch (Exception ex)
{
Log.ErrorLog(ex.ToString());
return default;
}
}
/// <summary>
/// 获取箱标内epc信息
/// </summary>
/// <param name="appCode"></param>
/// <returns></returns>
public static List<response_BoxMarkModel> GetEpcListByBoxMarkEpc(List<string> boxMarkEpcList)
{
try
{
var body_par = JsonConvert.SerializeObject(new
{
epcList = boxMarkEpcList.Select(x => new
{
epc = x
})
});
var body_result = GetBody(body_par);
if (body_result == null)
{
Log.WorkLog("签名值生成失败。");
return default;
}
else
{
var param = JsonConvert.SerializeObject(new request_sign
{
appKey = LiteCaChe.SysConfig.AppKey,
body = body_result.Item1,
sign = body_result.Item2,
timestamp = body_result.Item3,
version = LiteCaChe.SysConfig.ApiVersion,
orgId = LiteCaChe.OrgId,
});
var json = HttpPost(LiteCaChe.SysConfig.DomainUrl + Config.GetEpcListByBoxMarkEpc, param);
if (string.IsNullOrEmpty(json))
{
return default;
}
else
{
var res_data = JsonConvert.DeserializeObject<respone<List<response_BoxMarkModel>>>(json);
if (res_data == null || res_data.code != 10000)
{
Log.WorkLog($"箱标获取失败,JSON\r\n {json} ");
return default;
}
else
{
return res_data.data;
}
}
}
}
catch (Exception ex)
{
Log.ErrorLog(ex.ToString());
return default;
}
}
/// <summary>
/// 获取仓库信息(锁库情况)
/// </summary>
/// <returns></returns>
public static BaseJpWarehouse GetWarehouseState()
{
try
{
if (string.IsNullOrEmpty(LiteCaChe.SysConfig.WarehouseID ?? ""))
{
Log.WorkLog($"仓库信息获取失败,仓库id为空");
return default;
}
var body_par = JsonConvert.SerializeObject(new { id = LiteCaChe.SysConfig.WarehouseID });
var body_result = GetBody(body_par);
if (body_result == null)
{
Log.WorkLog("签名值生成失败。");
return default;
}
else
{
var param = JsonConvert.SerializeObject(new request_sign
{
appKey = LiteCaChe.SysConfig.AppKey,
body = body_result.Item1,
sign = body_result.Item2,
timestamp = body_result.Item3,
version = LiteCaChe.SysConfig.ApiVersion,
orgId = LiteCaChe.OrgId,
});
var json = HttpPost(LiteCaChe.SysConfig.DomainUrl + Config.GetWarehouseById, param);
if (string.IsNullOrEmpty(json))
{
return default;
}
else
{
var res_data = JsonConvert.DeserializeObject<respone<BaseJpWarehouse>>(json);
if (res_data == null || res_data.code != 10000)
{
Log.WorkLog($"仓库信息获取失败,{json}");
return default;
}
else
{
return res_data.data;
}
}
}
}
catch (Exception ex)
{
Log.ErrorLog(ex.ToString() + "\r\n");
return default;
}
}
/// <summary>
/// 设置仓库锁库状态
/// </summary>
/// <param name="isLocked">0:解除锁库,1:锁库</param>
/// <returns></returns>
public static bool SetWarehouseState(int isLocked)
{
try
{
if (string.IsNullOrEmpty(LiteCaChe.SysConfig.WarehouseID ?? ""))
{
Log.WorkLog($"设置仓库锁库状态,仓库id为空");
return default;
}
var body_par = JsonConvert.SerializeObject(new
{
warehouseId = LiteCaChe.SysConfig.WarehouseID,
isLocked = isLocked
});
var body_result = GetBody(body_par);
if (body_result == null)
{
Log.WorkLog("签名值生成失败。");
return default;
}
else
{
var param = JsonConvert.SerializeObject(new request_sign
{
appKey = LiteCaChe.SysConfig.AppKey,
body = body_result.Item1,
sign = body_result.Item2,
timestamp = body_result.Item3,
version = LiteCaChe.SysConfig.ApiVersion,
orgId = LiteCaChe.OrgId,
});
var json = HttpPost(LiteCaChe.SysConfig.DomainUrl + Config.SetWarehouseState, param);
if (string.IsNullOrEmpty(json))
{
return default;
}
else
{
var res_data = JsonConvert.DeserializeObject<respone>(json);
if (res_data == null || res_data.code != 10000)
{
Log.WorkLog($"设置仓库锁库状态,{json}");
return default;
}
else
{
return true;
}
}
}
}
catch (Exception ex)
{
Log.ErrorLog(ex.ToString() + "\r\n");
return default;
}
}
/// <summary>
/// 根据EPC集合获取物资信息
/// </summary>
/// <param name="type"></param>
/// <param name="eps"></param>
/// <returns></returns>
public static Tuple<bool, string> GetInvListByEpc(List<string> eps)
{
try
{
var data = new
{
EPCList = new List<dynamic>()
};
foreach (var epc in eps)
{
data.EPCList.Add(new { epc = epc });
}
var body_par = JsonConvert.SerializeObject(data);
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 = LiteCaChe.SysConfig.AppKey,
body = body_result.Item1,
sign = body_result.Item2,
timestamp = body_result.Item3,
version = LiteCaChe.SysConfig.ApiVersion,
orgId = LiteCaChe.OrgId,
});
var json = HttpPost(LiteCaChe.SysConfig.DomainUrl + Config.GetInvListByEpc, param);
if (string.IsNullOrEmpty(json))
{
Log.WorkLog("根据EPC集合获取物资信息失败", "入库失败");
return new Tuple<bool, string>(false, "根据EPC集合获取物资信息失败");
}
else
{
var res_data = JsonConvert.DeserializeObject<respone<List<dynamic>>>(json);
if (res_data == null || res_data.code != 10000
|| res_data.data == null || res_data.data.Count == 0)
{
Log.WorkLog($"根据EPC集合获取物资信息失败,{json}", "入库失败");
return new Tuple<bool, string>(false, "根据EPC集合获取物资信息失败");
}
else
{
//返回json
return new Tuple<bool, string>(true, json);
}
}
}
}
catch (Exception ex)
{
Log.ErrorLog(ex.ToString());
return default;
}
}
/// <summary>
/// 开启单据(出库用)
/// </summary>
/// <param name="order"></param>
/// <param name="eps"></param>
/// <returns></returns>
public static bool OpenOrderWork(order_info order)
{
try
{
var body_par = JsonConvert.SerializeObject(new
{
id = order.id,
type = order.orderType,
warehouseId = LiteCaChe.SysConfig.WarehouseID
});
var body_result = GetBody(body_par);
if (body_result == null)
{
Log.WorkLog("签名值生成失败。");
return false;
}
else
{
var param = JsonConvert.SerializeObject(new request_sign
{
appKey = LiteCaChe.SysConfig.AppKey,
body = body_result.Item1,
sign = body_result.Item2,
timestamp = body_result.Item3,
version = LiteCaChe.SysConfig.ApiVersion,
orgId = LiteCaChe.OrgId,
});
var json = HttpPost(LiteCaChe.SysConfig.DomainUrl + Config.OpenOrderWorkUrl, param);
if (string.IsNullOrEmpty(json))
{
Log.WorkLog("开启单据失败,请重试", "开启单据失败");
return false;
}
else
{
var res_data = JsonConvert.DeserializeObject<respone>(json);
if (res_data == null || res_data.code != 10000)
{
Log.WorkLog($"$开启单据失败:{res_data?.msg},请重试", "开启单据失败");
return false;
}
else
{
//Log.WorkLog($"开启单据成功,{json}", "开启单据成功");
return true;
}
}
}
}
catch (Exception ex)
{
Log.ErrorLog(ex.ToString());
return default;
}
}
/// <summary>
/// 关闭单据(借用 调拨使用)
/// </summary>
/// <param name="id"></param>
/// <returns></returns>
public static bool CloseOrder(string id, string type)
{
try
{
var body_par = JsonConvert.SerializeObject(new
{
id = id,
organizationId = LiteCaChe.OrgId,
userId = LiteCaChe.UserId,
type = type,
});
var body_result = GetBody(body_par);
if (body_result == null)
{
Log.WorkLog("签名值生成失败。");
return false;
}
else
{
var param = JsonConvert.SerializeObject(new request_sign
{
appKey = LiteCaChe.SysConfig.AppKey,
body = body_result.Item1,
sign = body_result.Item2,
timestamp = body_result.Item3,
version = LiteCaChe.SysConfig.ApiVersion,
orgId = LiteCaChe.OrgId,
});
var json = HttpPost(LiteCaChe.SysConfig.DomainUrl + Config.CloseOrderUrl, param);
if (string.IsNullOrEmpty(json))
{
Log.WorkLog("关闭单据失败,请重试", "关闭单据失败");
return false;
}
else
{
var res_data = JsonConvert.DeserializeObject<respone>(json);
if (res_data == null || res_data.code != 10000)
{
Log.WorkLog($"$关闭单据失败:{res_data?.msg},请重试", "关闭单据失败");
return false;
}
else
{
//Log.WorkLog($"开启单据成功,{json}", "开启单据成功");
return true;
}
}
}
}
catch (Exception ex)
{
Log.ErrorLog(ex.ToString());
return default;
}
}
/// <summary>
/// 创建借用单据
/// </summary>
/// <param name="policeId"></param>
/// <param name="invInfoList"></param>
/// <param name="msg"></param>
/// <returns></returns>
public static bool CreateBorrowJYOrder(string policeId, List<scan_info> invInfoList, out string msg)
{
try
{
var body_par = JsonConvert.SerializeObject(new
{
id = "",
warehouseId = LiteCaChe.SysConfig.WarehouseID,
orgId = LiteCaChe.OrgId,
orgCode = LiteCaChe.OrgCode,
policeId = policeId,
applyId = LiteCaChe.UserId,
applyName = LiteCaChe.UserName,
expectedTime = DateTime.Now.AddDays(7), //借用默认7天
flowId = "4028b881731221ba0173128662a40003",
flowName = "本库借用流程",
flowState = true,
flowType = "borrowMy",
nextStepId = "",
userInfo = "",
userType = "",
currentStepName = "",
dataScope = "",
detailList = invInfoList.Select(x => new
{
equipmentName = x.equName,
equipmentId = x.equCode,
quantity = x.equCount
})
});
var body_result = GetBody(body_par);
if (body_result == null)
{
msg = "签名值生成失败。";
Log.WorkLog("签名值生成失败。");
return false;
}
else
{
var param = JsonConvert.SerializeObject(new request_sign
{
appKey = LiteCaChe.SysConfig.AppKey,
body = body_result.Item1,
sign = body_result.Item2,
timestamp = body_result.Item3,
version = LiteCaChe.SysConfig.ApiVersion,
orgId = LiteCaChe.OrgId,
});
var json = HttpPost(LiteCaChe.SysConfig.DomainUrl + Config.AddAndApprovalBorrowJYOrder, param);
if (string.IsNullOrEmpty(json))
{
msg = "创建单据失败,请重试";
Log.WorkLog("创建单据失败,请重试", "创建单据失败");
return false;
}
else
{
var res_data = JsonConvert.DeserializeObject<respone>(json);
if (res_data == null || res_data.code != 10000)
{
msg = $"创建单据失败:{res_data?.msg},请重试";
Log.WorkLog($"创建单据失败:{res_data?.msg},请重试", "创建单据失败");
return false;
}
else
{
//Log.WorkLog($"开启单据成功,{json}", "开启单据成功");
msg = "创建单据成功";
return true;
}
}
}
}
catch (Exception ex)
{
msg = "创建单据异常";
Log.ErrorLog(ex.ToString());
return default;
}
}
/// <summary>
/// 创建领用单据
/// </summary>
/// <param name="policeId"></param>
/// <param name="invInfoList"></param>
/// <param name="isBindCabinet"></param>
/// <param name="msg"></param>
/// <returns></returns>
public static bool CreateBorrowLYOrder(string policeId, List<scan_info> invInfoList, bool isBindCabinet, out string msg)
{
try
{
var body_par = JsonConvert.SerializeObject(new
{
id = "",
warehouseId = LiteCaChe.SysConfig.WarehouseID,
orgId = LiteCaChe.OrgId,
orgCode = LiteCaChe.OrgCode,
policeId = policeId,
applyId = LiteCaChe.UserId,
applyName = LiteCaChe.UserName,
isBindCabinet = isBindCabinet,
detailList = invInfoList.Select(x => new
{
equipmentName = x.equName,
equipmentDetailId = x.equCode,
quantity = x.equCount
})
});
var body_result = GetBody(body_par);
if (body_result == null)
{
msg = "签名值生成失败。";
Log.WorkLog("签名值生成失败。");
return false;
}
else
{
var param = JsonConvert.SerializeObject(new request_sign
{
appKey = LiteCaChe.SysConfig.AppKey,
body = body_result.Item1,
sign = body_result.Item2,
timestamp = body_result.Item3,
version = LiteCaChe.SysConfig.ApiVersion,
orgId = LiteCaChe.OrgId,
});
var json = HttpPost(LiteCaChe.SysConfig.DomainUrl + Config.AddAndApprovalBorrowOrder, param);
if (string.IsNullOrEmpty(json))
{
msg = "创建单据失败,请重试";
Log.WorkLog("创建单据失败,请重试", "创建单据失败");
return false;
}
else
{
var res_data = JsonConvert.DeserializeObject<respone>(json);
if (res_data == null || res_data.code != 10000)
{
msg = $"创建单据失败:{res_data?.msg},请重试";
Log.WorkLog($"创建单据失败:{res_data?.msg},请重试", "创建单据失败");
return false;
}
else
{
//Log.WorkLog($"开启单据成功,{json}", "开启单据成功");
msg = "创建单据成功";
return true;
}
}
}
}
catch (Exception ex)
{
msg = "创建单据异常";
Log.ErrorLog(ex.ToString());
return default;
}
}
/// <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 = $"{LiteCaChe.SysConfig.SecretKey}{timespan}{LiteCaChe.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.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
namespace LiteChannel.Commons
{
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.IO;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
namespace LiteChannel.Commons
{
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 = default)
{
lock (syncErrorObj)
{
if (bEnableErrorLog)
{
WriteLine(logTxt, ModuleName, "ErrorLog/");
}
}
}
/// <summary>
/// 异常日志
/// </summary>
/// <param name="logTxt"></param>
/// <param name="ModuleName"></param>
public static void DebugLog(string logTxt, [CallerMemberName] string ModuleName = null)
{
lock (syncDebugObj)
{
if (bEnableDebugLog)
{
WriteLine(logTxt, ModuleName, "WorkLog/");
}
}
}
/// <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 = System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase + pathName
+ DateTime.Now.ToString("yyyyMMdd") + ".log";
ClearFile(System.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 JmpRfidLp;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace LiteChannel.Commons
{
public interface IReaderHelper : IDisposable
{
event InvDelegate OnInventory;
delegate void InvDelegate(TagInfoData args);
bool Open();
bool Close();
bool IsOpen();
string GetFWVerion();
void InventoryStart();
void InventoryStop();
bool SetPALevel(byte level);
bool SetTxPower(byte port, bool enable, double power);
List<TagInfoData> InventorySingle();
Tuple<int, string> ReadTag(ref OperatingData tag);
Tuple<int, string> WriteTag(OperatingData tag);
}
public class TagInfoData
{
public string EPC { get; set; }
public int RSSI { get; set; }
public byte AntennaPort { get; set; }
public int SeenCount { get; set; }
}
public class OperatingData
{
public string EPC { get; set; }
public string DATA { get; set; }
public ushort Offset { get; set; }
public ushort Length { get; set; }
public RfidBankType Bank { get; set; }
public string Access { get; set; }
}
public enum RfidBankType
{
[Description("RFU")] RFU,
[Description("EPC")] EPC,
[Description("TID")] TID,
[Description("USER")] USER,
}
/// <summary>
/// 钧普读写器
/// </summary>
public class JmpRfidLpReaderHelper : IReaderHelper
{
public event IReaderHelper.InvDelegate OnInventory;
private Reader _reader;
public JmpRfidLpReaderHelper(string comPort = "COM3")
{
_reader = new Reader(comPort);
_reader.OnInventory += OnOnInventory;
}
public bool Open()
{
return _reader.Open();
}
public bool Close()
{
return _reader.Close();
}
public bool IsOpen()
{
return _reader.IsOpen();
}
public string GetFWVerion()
{
return _reader.GetFWVerion();
}
public void InventoryStart()
{
_reader.InventoryStart();
}
public void InventoryStop()
{
_reader.InventoryStop();
}
public bool SetPALevel(byte level)
{
return _reader.SetPALevel(level) == 0;
}
public bool SetTxPower(byte port, bool enable, double power)
{
return _reader.SetTxPower(port, enable, power) == 0;
}
public List<TagInfoData> InventorySingle()
{
return _reader.InventorySingle(50).Select(x => new TagInfoData
{
AntennaPort = x.AntennaPort,
EPC = x.EPC,
RSSI = x.RSSI,
SeenCount = x.SeenCount
}).ToList();
}
public Tuple<int, string> ReadTag(ref OperatingData tag)
{
var data = new OperData
{
Access = tag.Access ?? "00000000",
Bank = (BankType)tag.Bank,
DATA = tag.DATA ?? "",
EPC = tag.EPC ?? "",
Length = tag.Length,
Offset = tag.Offset
};
var res = _reader.ReadTag(ref data);
tag.Access = data.Access;
tag.Bank = (RfidBankType)data.Bank;
tag.DATA = data.DATA;
tag.EPC = data.EPC;
tag.Length = data.Length;
tag.Offset = data.Offset;
return new Tuple<int, string>((int)res, typeof(OperResult).GetEnumDesc((int)res));
}
public Tuple<int, string> WriteTag(OperatingData tag)
{
var data = new OperData
{
Access = tag.Access ?? "00000000",
Bank = (BankType)tag.Bank,
DATA = tag.DATA ?? "",
EPC = tag.EPC ?? "",
Length = tag.Length,
Offset = tag.Offset
};
var res = _reader.WriteTag(data);
return new Tuple<int, string>((int)res, typeof(OperResult).GetEnumDesc((int)res));
}
protected virtual void OnOnInventory(TagInfo args)
{
OnInventory?.Invoke(new TagInfoData()
{
AntennaPort = args.AntennaPort,
EPC = args.EPC,
RSSI = args.RSSI,
SeenCount = args.SeenCount
});
}
public void Dispose()
{
_reader.OnInventory -= OnOnInventory;
_reader = null;
}
}
/// <summary>
/// 索力得USBRFID读写器
/// </summary>
public class USBRFIDReaderHelper : IReaderHelper
{
private int _portHandle = -1;
private bool _isOpen = false;
private ManualResetEvent inventoryEvent = new ManualResetEvent(true);
private CancellationTokenSource _token;
public event IReaderHelper.InvDelegate OnInventory;
public USBRFIDReaderHelper()
{
}
public bool Open()
{
var res = OpenUSBPort(null, ref _portHandle);
if (res == 0)
{
_isOpen = true;
return true;
}
else
{
_isOpen = false;
Log.WorkLog("连接读写器失败:0x" + res.ToString("X2"), "读写器启动失败");
return false;
}
}
public bool Close()
{
_isOpen = false;
return CloseUSBPort(_portHandle) == 0;
}
public bool IsOpen()
{
return _isOpen;
}
public string GetFWVerion()
{
byte TrType = 0;
byte[] VersionInfo = new byte[2];
byte ReaderType = 0;
byte ScanTime = 0;
byte dfreband = 0;
byte dmaxfre = 0;
byte dminfre = 0;
byte powerdBm = 0;
byte Ant = 0;
byte BeepEn = 0;
byte CheckAnt = 0;
var res = GetReaderInfo(VersionInfo, ref ReaderType, ref TrType, ref dfreband, ref dmaxfre, ref dminfre, ref powerdBm, ref ScanTime, ref Ant, ref BeepEn, ref CheckAnt, _portHandle);
if (res == 0)
{
return string.Format("{0}.{1:d2}", VersionInfo[0], VersionInfo[1]);
}
else
{
if (res == 0x30)
{
//通讯失败,掉线
_isOpen = false;
}
return "";
}
}
public void InventoryStart()
{
//开启盘点线程
_token = new CancellationTokenSource();
Task.Run(() =>
{
int totalLen = 0, cardNum = 0, fCmdRet = 0x30;
int cardIdx = 0, epcLen = 0;
int i;
byte MaskMem = 0;
byte[] MaskAdr = new byte[2];
byte MaskLen = 0;
byte[] MaskData = null;
byte MaskFlag = 0;
byte[] EPCList = new byte[30000];
byte Ant = 0;
byte AdrTID = 0;
byte LenTID = 0;
byte TIDFlag = 0;
byte FastFlag = 1;
byte QValue = 4; //Q值 4
byte Session = 0; //Session 0
byte Target = 0; //Target A
byte Scantime = 3; //巡查时间 10*100ms
inventoryEvent = new ManualResetEvent(false);
while (!_token.IsCancellationRequested)
{
try
{
if (!_isOpen)
{
return;
}
fCmdRet = Inventory_G2(QValue, Session, MaskMem, MaskAdr, MaskLen, MaskData, MaskFlag, AdrTID,
LenTID, TIDFlag, Target, 0x80, Scantime, FastFlag, EPCList, ref Ant, ref totalLen,
ref cardNum, _portHandle);
if ((fCmdRet == 1) | (fCmdRet == 2) | (fCmdRet == 3) | (fCmdRet == 4)) //代表已查找结束,
{
if (cardNum > 0)
{
i = 0;
epcLen = 0;
for (cardIdx = 0; cardIdx < cardNum; cardIdx++)
{
epcLen = EPCList[i];
byte[] epcNo = new byte[epcLen];
Array.Copy(EPCList, i + 1, epcNo, 0, epcLen);
String strEpcNo = ByteArrToHexStr(epcNo);
byte rssi = EPCList[i + epcLen + 1];
i += epcLen + 2;
OnOnInventory(new TagInfo()
{
AntennaPort = 0,
EPC = strEpcNo,
RSSI = rssi,
SeenCount = 1
});
//AddTagToInvRealTable(strEpcNo, rssi);
}
}
}
else
{
if (fCmdRet == 0x30)
{
//通讯失败,掉线
_isOpen = false;
}
}
}
catch (Exception e)
{
Log.ErrorLog(e.Message, nameof(USBRFIDReaderHelper));
}
}
inventoryEvent.Set();
}, _token.Token);
}
public void InventoryStop()
{
//关闭盘点线程
_token?.Cancel();
inventoryEvent.WaitOne(1000);
}
public bool SetPALevel(byte level)
{
//索力得读写器无天线使能设置
return true;
}
public bool SetTxPower(byte port, bool enable, double power)
{
var res = SetRfPower((byte)Convert.ToInt32(power), _portHandle);
if (res == 0)
{
return true;
}
else
{
if (res == 0x30)
{
//通讯失败,掉线
_isOpen = false;
}
Log.ErrorLog("设置功率失败:0x" + res.ToString("X2"), nameof(USBRFIDReaderHelper));
return false;
}
}
public List<TagInfoData> InventorySingle()
{
var list = new List<TagInfoData>();
//只盘点一轮
int totalLen = 0, cardNum = 0, fCmdRet = 0x30;
int cardIdx = 0, epcLen = 0;
int i;
byte MaskMem = 0;
byte[] MaskAdr = new byte[2];
byte MaskLen = 0;
byte[] MaskData = null;
byte MaskFlag = 0;
byte[] EPCList = new byte[30000];
byte Ant = 0;
byte AdrTID = 0;
byte LenTID = 0;
byte TIDFlag = 0;
byte FastFlag = 1;
byte QValue = 1; //Q值 Q 值的设置应为场内的标签数量约等亍2的Q次方
byte Session = 0; //Session 0 建议单张或者少量标签查询选 S0
byte Target = 0; //Target A
byte Scantime = 3; //巡查时间 3*100ms
try
{
fCmdRet = Inventory_G2(QValue, Session, MaskMem, MaskAdr, MaskLen, MaskData, MaskFlag, AdrTID, LenTID, TIDFlag, Target, 0x80, Scantime, FastFlag, EPCList, ref Ant, ref totalLen, ref cardNum, _portHandle);
if ((fCmdRet == 1) | (fCmdRet == 2) | (fCmdRet == 3) | (fCmdRet == 4)) //代表已查找结束,
{
if (cardNum > 0)
{
i = 0;
epcLen = 0;
for (cardIdx = 0; cardIdx < cardNum; cardIdx++)
{
epcLen = EPCList[i];
byte[] epcNo = new byte[epcLen];
Array.Copy(EPCList, i + 1, epcNo, 0, epcLen);
String strEpcNo = ByteArrToHexStr(epcNo);
byte rssi = EPCList[i + epcLen + 1];
i += epcLen + 2;
list.Add(new TagInfoData()
{
AntennaPort = 0,
EPC = strEpcNo,
RSSI = rssi,
SeenCount = 1
});
}
}
}
else
{
if (fCmdRet == 0x30)
{
//通讯失败,掉线
_isOpen = false;
}
}
}
catch (Exception e)
{
Log.ErrorLog(e.Message, nameof(USBRFIDReaderHelper));
}
return list;
}
public Tuple<int, string> ReadTag(ref OperatingData tag)
{
byte ENum;
byte[] opWordPtr = null;
byte opLen = 0;
byte opMem = 0;
byte[] accPwd = null;
string str = "";
byte[] MaskEPC = null;
byte MaskMem = 0;
byte[] MaskAdr = null;
byte MaskLen = 0;
byte[] MaskData = null;
ENum = (byte)(str.Length / 4);
MaskEPC = new byte[ENum * 2];
MaskEPC = HexStrToByteArr(str);
opMem = (byte)tag.Bank; //0x00:保留区;0x01:EPC 存储区;0x02:TID 存储区;0x03:用户存储区。
opWordPtr = HexStrToByteArr(tag.Offset.ToString("X4"));
opLen = Convert.ToByte(tag.Length);
accPwd = HexStrToByteArr(tag.Access);
byte[] TagData = new byte[opLen * 2];
var errcode = 0;
var res = 0;
for (int retry = 0; retry < 3; retry++)
{
res = ExtReadData_G2(MaskEPC, ENum, opMem, opWordPtr, opLen, accPwd, MaskMem, MaskAdr, MaskLen, MaskData, TagData, ref errcode, _portHandle);
if (res == 0)
break;
}
if (res == 0)
{
tag.DATA = ByteArrToHexStr(TagData);
return new Tuple<int, string>((int)res, typeof(OperResult).GetEnumDesc(res));
}
else
{
if (res == 0x30)
{
//通讯失败,掉线
_isOpen = false;
}
if (res != 0xFC)
{
return new Tuple<int, string>((int)res, typeof(OperResult).GetEnumDesc(res));
}
else
{
return new Tuple<int, string>((int)res, typeof(ErrorCodeEnum).GetEnumDesc(errcode));
}
}
}
public Tuple<int, string> WriteTag(OperatingData tag)
{
byte ENum;
byte WNum = 0;
byte[] opWordPtr = null;
byte opMem = 0;
byte[] opData = null;
byte[] accPwd = null;
string str = "";
byte[] MaskEPC = null;
byte MaskMem = 0;
byte[] MaskAdr = null;
byte MaskLen = 0;
byte[] MaskData = null;
ENum = (byte)(str.Length / 4);
MaskEPC = new byte[ENum * 2];
MaskEPC = HexStrToByteArr(str);
opMem = (byte)tag.Bank; //0x00:保留区;0x01:EPC 存储区;0x02:TID 存储区;0x03:用户存储区。
opWordPtr = HexStrToByteArr(tag.Offset.ToString("X4"));
accPwd = HexStrToByteArr(tag.Access);
opData = HexStrToByteArr(tag.DATA);
WNum = (byte)(opData.Length / 2);
var errcode = 0;
var res = 0;
for (int retry = 0; retry < 3; retry++)
{
res = ExtWriteData_G2(MaskEPC, WNum, ENum, opMem, opWordPtr, opData, accPwd, MaskMem, MaskAdr, MaskLen, MaskData, ref errcode, _portHandle);
if (res == 0)
break;
}
if (res == 0)
{
return new Tuple<int, string>((int)res, typeof(OperResult).GetEnumDesc(res));
}
else
{
if (res == 0x30)
{
//通讯失败,掉线
_isOpen = false;
}
if (res != 0xFC)
{
return new Tuple<int, string>((int)res, typeof(OperResult).GetEnumDesc(res));
}
else
{
return new Tuple<int, string>((int)res, typeof(ErrorCodeEnum).GetEnumDesc(errcode));
}
}
}
protected virtual void OnOnInventory(TagInfo args)
{
OnInventory?.Invoke(new TagInfoData()
{
AntennaPort = args.AntennaPort,
EPC = args.EPC,
RSSI = args.RSSI,
SeenCount = args.SeenCount
});
}
public void Dispose()
{
}
/// <summary>
/// 字符串转16进制字节数组
/// </summary>
/// <param name="hexString"></param>
/// <returns></returns>
public static byte[] HexStrToByteArr(string hexString)
{
hexString = hexString.Replace(" ", "");
if ((hexString.Length % 2) != 0)
hexString += "0";
byte[] returnBytes = new byte[hexString.Length / 2];
for (int i = 0; i < returnBytes.Length; i++)
returnBytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16);
return returnBytes;
}
/// <summary>
/// 字节数组转16进制字符串
/// </summary>
/// <param name="bytes"></param>
/// <returns></returns>
public static string ByteArrToHexStr(byte[] bytes)
{
string returnStr = "";
if (bytes != null)
{
for (int i = 0; i < bytes.Length; i++)
{
returnStr += bytes[i].ToString("X2");
}
}
return returnStr;
}
#region USBUHFPlatform
private const string DLLNAME = @"USBUHFPlatform.dll";
[DllImport(DLLNAME, CallingConvention = CallingConvention.StdCall)]
public static extern int OpenUSBPort(string DevSnr, ref int FrmHandle);
[DllImport(DLLNAME, CallingConvention = CallingConvention.StdCall)]
public static extern int CloseUSBPort(int FrmHandle);
[DllImport(DLLNAME, CallingConvention = CallingConvention.StdCall)]
public static extern int CompDevInterfaceName(string DevInterfaceName, int FrmHandle);
[DllImport(DLLNAME, CallingConvention = CallingConvention.StdCall)]
public static extern int GetReaderInfo(
byte[] VersionInfo,
ref byte ReaderType,
ref byte TrType,
ref byte dfreband,
ref byte dmaxfre,
ref byte dminfre,
ref byte powerdBm,
ref byte ScanTime,
ref byte Ant,
ref byte BeepEn,
ref byte CheckAnt,
int FrmHandle);
[DllImport(DLLNAME, CallingConvention = CallingConvention.StdCall)]
public static extern int SetRegion(
byte dfreband,
byte dmaxfre,
byte dminfre,
int FrmHandle);
[DllImport(DLLNAME, CallingConvention = CallingConvention.StdCall)]
public static extern int SetInventoryScanTime(
byte ScanTime,
int FrmHandle);
[DllImport(DLLNAME, CallingConvention = CallingConvention.StdCall)]
public static extern int SetRfPower(
byte PowerDbm,
int FrmHandle);
[DllImport(DLLNAME, CallingConvention = CallingConvention.StdCall)]
public static extern int GetLedStatus(
ref byte LedPin,
int FrmHandle);
[DllImport(DLLNAME, CallingConvention = CallingConvention.StdCall)]
public static extern int SetLedCtrl(
byte LedPin,
int FrmHandle);
[DllImport(DLLNAME, CallingConvention = CallingConvention.StdCall)]
public static extern int SetBeep(
byte AvtiveTime,
byte SilentTime,
byte Times,
int FrmHandle);
[DllImport(DLLNAME, CallingConvention = CallingConvention.StdCall)]
public static extern int GetSerialNo(
StringBuilder SeriaNo,
int FrmHandle);
[DllImport(DLLNAME, CallingConvention = CallingConvention.StdCall)]
public static extern int SetSaveLen(
byte SaveLen,
int FrmHandle);
[DllImport(DLLNAME, CallingConvention = CallingConvention.StdCall)]
public static extern int GetSaveLen(
ref byte SaveLen,
int FrmHandle);
[DllImport(DLLNAME, CallingConvention = CallingConvention.StdCall)]
public static extern int ReadBuffer_G2(
ref int Totallen,
ref int CardNum,
byte[] pEPCList,
int FrmHandle);
[DllImport(DLLNAME, CallingConvention = CallingConvention.StdCall)]
public static extern int ClearBuffer_G2(int FrmHandle);
[DllImport(DLLNAME, CallingConvention = CallingConvention.StdCall)]
public static extern int GetBufferCnt_G2(
ref int Count,
int FrmHandle);
[DllImport(DLLNAME, CallingConvention = CallingConvention.StdCall)]
public static extern int SetTagCustomFunction(
ref byte InlayType,
int FrmHandle);
[DllImport(DLLNAME, CallingConvention = CallingConvention.StdCall)]
public static extern int Inventory_G2(
byte QValue,
byte Session,
byte MaskMem,
byte[] MaskAdr,
byte MaskLen,
byte[] MaskData,
byte MaskFlag,
byte AdrTID,
byte LenTID,
byte TIDFlag,
byte Target,
byte InAnt,
byte Scantime,
byte FastFlag,
byte[] pEPCList,
ref byte Ant,
ref int Totallen,
ref int CardNum,
int FrmHandle);
[DllImport(DLLNAME, CallingConvention = CallingConvention.StdCall)]
public static extern int ExtReadData_G2(
byte[] EPC,
byte ENum,
byte Mem,
byte[] WordPtr,
byte Num,
byte[] Password,
byte MaskMem,
byte[] MaskAdr,
byte MaskLen,
byte[] MaskData,
byte[] Data,
ref int Errorcode,
int FrmHandle);
[DllImport(DLLNAME, CallingConvention = CallingConvention.StdCall)]
public static extern int ExtWriteData_G2(
byte[] EPC,
byte WNum,
byte ENum,
byte Mem,
byte[] WordPtr,
byte[] Wdt,
byte[] Password,
byte MaskMem,
byte[] MaskAdr,
byte MaskLen,
byte[] MaskData,
ref int Errorcode,
int FrmHandle);
[DllImport(DLLNAME, CallingConvention = CallingConvention.StdCall)]
public static extern int WriteEPC_G2(
byte[] Password,
byte[] WriteEPC,
byte ENum,
ref int Errorcode,
int FrmHandle);
[DllImport(DLLNAME, CallingConvention = CallingConvention.StdCall)]
public static extern int BlockWrite_G2(
byte[] EPC,
byte WNum,
byte ENum,
byte Mem,
byte WordPtr,
byte[] Wdt,
byte[] Password,
byte MaskMem,
byte[] MaskAdr,
byte MaskLen,
byte[] MaskData,
ref int Errorcode,
int FrmHandle);
[DllImport(DLLNAME, CallingConvention = CallingConvention.StdCall)]
public static extern int BlockErase_G2(
byte[] EPC,
byte ENum,
byte Mem,
byte WordPtr,
byte Num,
byte[] Password,
byte MaskMem,
byte[] MaskAdr,
byte MaskLen,
byte[] MaskData,
ref int Errorcode,
int FrmHandle);
[DllImport(DLLNAME, CallingConvention = CallingConvention.StdCall)]
public static extern int Lock_G2(
byte[] EPC,
byte ENum,
byte select,
byte setprotect,
byte[] Password,
byte MaskMem,
byte[] MaskAdr,
byte MaskLen,
byte[] MaskData,
ref int Errorcode,
int FrmHandle);
[DllImport(DLLNAME, CallingConvention = CallingConvention.StdCall)]
public static extern int KillTag_G2(
byte[] EPC,
byte ENum,
byte[] Killpwd,
byte MaskMem,
byte[] MaskAdr,
byte MaskLen,
byte[] MaskData,
ref int Errorcode,
int FrmHandle);
[DllImport(DLLNAME, CallingConvention = CallingConvention.StdCall)]
public static extern int SetPrivacyByEPC_G2(
byte[] EPC,
byte ENum,
byte[] Password,
byte MaskMem,
byte[] MaskAdr,
byte MaskLen,
byte[] MaskData,
ref int Errorcode,
int FrmHandle);
[DllImport(DLLNAME, CallingConvention = CallingConvention.StdCall)]
public static extern int SetPrivacyWithoutEPC_G2(
byte[] Password,
ref int Errorcode,
int FrmHandle);
[DllImport(DLLNAME, CallingConvention = CallingConvention.StdCall)]
public static extern int ResetPrivacy_G2(
byte[] Password,
ref int Errorcode,
int FrmHandle);
[DllImport(DLLNAME, CallingConvention = CallingConvention.StdCall)]
public static extern int CheckPrivacy_G2(
ref byte readpro,
ref int Errorcode,
int FrmHandle);
[DllImport(DLLNAME, CallingConvention = CallingConvention.StdCall)]
public static extern int EASConfigure_G2(
byte[] EPC,
byte ENum,
byte[] Password,
byte EAS,
byte MaskMem,
byte[] MaskAdr,
byte MaskLen,
byte[] MaskData,
ref int Errorcode,
int FrmHandle);
[DllImport(DLLNAME, CallingConvention = CallingConvention.StdCall)]
public static extern int EASAlarm_G2(
ref int Errorcode,
int FrmHandle);
[DllImport(DLLNAME, CallingConvention = CallingConvention.StdCall)]
public static extern int GetMonza4QTWorkParamter_G2(
byte[] EPC,
byte ENum,
byte[] Password,
byte MaskMem,
byte[] MaskAdr,
byte MaskLen,
byte[] MaskData,
ref byte QTcontrol,
ref int Errorcode,
int FrmHandle);
[DllImport(DLLNAME, CallingConvention = CallingConvention.StdCall)]
public static extern int SetMonza4QTWorkParamter_G2(
byte[] EPC,
byte ENum,
byte QTcontrol,
byte[] Password,
byte MaskMem,
byte[] MaskAdr,
byte MaskLen,
byte[] MaskData,
ref int Errorcode,
int FrmHandle);
[DllImport(DLLNAME, CallingConvention = CallingConvention.StdCall)]
public static extern int InventoryBuffer_G2(
byte QValue,
byte Session,
byte MaskMem,
byte[] MaskAdr,
byte MaskLen,
byte[] MaskData,
byte MaskFlag,
byte AdrTID,
byte LenTID,
byte TIDFlag,
byte Target,
byte InAnt,
byte Scantime,
byte FastFlag,
ref int BufferCount,
ref int TagNum,
int FrmHandle);
#endregion
public enum OperResult
{
[Description("执行成功")] OK = 0x00,
[Description("扫描时间结束前返回")] Error1 = 0x01,
[Description("指定的扫描时间溢出")] Error2 = 0x02,
[Description("本条消息之后,还有消息")] Error3 = 0x03,
[Description("读写模块存储空间已满")] Error4 = 0x04,
[Description("访问密码错误")] Error5 = 0x05,
[Description("销毁密码错误")] Error9 = 0x09,
[Description("销毁密码丌能为全 0")] Error10 = 0x0A,
[Description("电子标签丌支持该命令")] Error11 = 0x0B,
[Description("对亍特定命令,访问密码丌能为 0")] Error12 = 0x0C,
[Description("电子标签已经被设置了读保护,丌能再次设置")] Error13 = 0x0D,
[Description("电子标签没有被设置读保护,丌需要解锁")] Error14 = 0x0E,
[Description("参数保存失败,设置的值仅在读写器断电前有效")] Error19 = 0x13,
[Description("无法调整功率")] Error20 = 0x14,
[Description("电子丌支持该命令或者访问密码丌能为 0")] Error25 = 0x19,
[Description("标签自定义功能执行错误")] Error26 = 0x1A,
[Description("返回指令错误")] Error238 = 0xEE,
[Description("检测丌到天线连接")] Error248 = 0xF8,
[Description("命令执行出错")] Error249 = 0xF9,
[Description("扫描到电子标签,但由亍通信丌畅,导致操作失败")] Error250 = 0xFA,
[Description("无电子标签可操作")] Error251 = 0xFB,
[Description("电子标签返回错误代码")] Error252 = 0xFC,
[Description("命令长度错误")] Error253 = 0xFD,
[Description("命令非法")] Error254 = 0xFE,
[Description("参数错误")] Error255 = 0xFF,
[Description("通讯错误")] Error48 = 0x30,
[Description("CRC 错误")] Error49 = 0x31,
[Description("通讯繁忙,设备正在执行其他命令")] Error51 = 0x33,
[Description("端口已打开")] Error53 = 0x35,
[Description("端口已关闭")] Error54 = 0x36,
[Description("无效句柄")] Error55 = 0x37,
[Description("已打开设备过多,空间丌足")] Error57 = 0x39,
}
public enum ErrorCodeEnum
{
[Description("其它错误,全部捕捉未被其它代码覆盖的错误")] Error0 = 0x00,
[Description("存储器超限或丌被支持的 PC 值,规定存储位置丌存在或标签丌支持 PC 值")] Error3 = 0x03,
[Description("存储器锁定,存储位置锁定永久锁定,且丌可写入")] Error4 = 0x04,
[Description("电源丌足,标签电源丌足,无法执行存储写入操作")] Error11 = 0x0B,
[Description("非特定错误,标签丌支持特定错误代码")] Error15 = 0x0F,
}
}
public static class EnumExtension
{
/// <summary>
/// 根据值得到中文备注
/// </summary>
/// <param name="e"></param>
/// <param name="value"></param>
/// <returns></returns>
public static string GetEnumDesc(this System.Type e, int? value)
{
string result;
try
{
System.Reflection.FieldInfo[] fields = e.GetFields();
int i = 1;
int count = fields.Length;
while (i < count)
{
if ((int)System.Enum.Parse(e, fields[i].Name) == value)
{
DescriptionAttribute[] EnumAttributes = (DescriptionAttribute[])fields[i].GetCustomAttributes(typeof(DescriptionAttribute), false);
if (EnumAttributes.Length > 0)
{
result = EnumAttributes[0].Description;
return result;
}
}
i++;
}
result = "";
}
catch
{
result = "";
}
return result;
}
}
}
\ No newline at end of file
using System;
using System.Runtime.InteropServices;
namespace LiteChannel.Commons
{
public class Win32API
{
[DllImport("Kernel32.dll")]
public static extern bool SetLocalTime(ref SYSTEMTIME Time);
[DllImport("Kernel32.dll")]
public static extern void GetLocalTime(ref SYSTEMTIME Time);
}
/// <summary>
///
/// </summary>
public struct SYSTEMTIME
{
public ushort wYear;
public ushort wMonth;
public ushort wDayOfWeek;
public ushort wDay;
public ushort wHour;
public ushort wMinute;
public ushort wSecond;
public ushort wMilliseconds;
/// <summary>
/// 从System.DateTime转换。
/// </summary>
/// <param name="time">System.DateTime类型的时间。</param>
public void FromDateTime(DateTime time)
{
wYear = (ushort)time.Year;
wMonth = (ushort)time.Month;
wDayOfWeek = (ushort)time.DayOfWeek;
wDay = (ushort)time.Day;
wHour = (ushort)time.Hour;
wMinute = (ushort)time.Minute;
wSecond = (ushort)time.Second;
wMilliseconds = (ushort)time.Millisecond;
}
/// <summary>
/// 转换为System.DateTime类型。
/// </summary>
/// <returns></returns>
public DateTime ToDateTime()
{
return new DateTime(wYear, wMonth, wDay, wHour, wMinute, wSecond, wMilliseconds);
}
/// <summary>
/// 静态方法。转换为System.DateTime类型。
/// </summary>
/// <param name="time">SYSTEMTIME类型的时间。</param>
/// <returns></returns>
public static DateTime ToDateTime(SYSTEMTIME time)
{
return time.ToDateTime();
}
}
}
using LiteChannel.Commons;
using LiteChannel.Models;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using CommunityToolkit.Mvvm.ComponentModel;
namespace LiteChannel
{
public static class LiteCaChe
{
public static List<sync_police> PoliceList { get; set; }
public static string OrgId { get; set; }
public static string OrgCode { get; set; }
public static string PoliceId { get; set; }
public static string UserId { get; set; }
public static string UserName { get; set; }
public static List<equ_info> EquInfos { get; set; }
public static Config SysConfig { get; set; }
public static Config LoadSystemStep()
{
var v_path = AppDomain.CurrentDomain.BaseDirectory + "config.json";
if (!File.Exists(v_path))
{
return null;
}
else
{
var v_json = File.ReadAllText(v_path, Encoding.Default);
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.BaseDirectory + "config.json", JmpDes.Encrypt(json), Encoding.UTF8);
return true;
}
}
}
catch (Exception ex)
{
Log.ErrorLog(ex.ToString(), MethodBase.GetCurrentMethod().Name);
return false;
}
}
}
public class Config : ObservableObject
{
public const string SoftUpdate = "/api/SoftUpdate/GetLastUpdate";
public const string GetEquInfo = "/api/EquipmentDetail/GetListEquipmentDetail";
public const string GetStoreInfo = "/api/Warehouse/GetListOrgWarehouse";
public const string GetOrderInfo = "/api/Inventory/GetOrderInfo";
public const string GetOrderDetail = "/api/Inventory/GetOrderDetail";
public const string OpenOrderWorkUrl = "/api/Inventory/OpenThisOrderAndCloseOther";
public const string UploadUrl = "/api/Inventory/UploadRFIDNew";
public const string CloseOrderUrl = "/api/Inventory/CloseOrder";
public const string GetPolices = "/api/ChannelCfg/GetOrgStaff";
public const string UploadFace = "/api/ChannelCfg/UploadFace";
public const string UpdateFinger = "/api/ChannelCfg/UpdateFinger";
public const string GetInvListByEpc = "/api/Inventory/GetInvListByEpc";
public const string GetWarehouseById = "/api/Warehouse/GetWarehouseById";
public const string SetWarehouseState = "/api/Inventory/SetWarehouseState";
public const string GetEpcListByBoxMarkEpc = "/api/EquipmentBoxMark/GetEpcListByBoxMarkEpc";
public const string GetAllInventoryList = "/api/Inventory/GetAllInventoryList";
public const string AddAndApprovalBorrowOrder = "/api/Borrow/AddAndApprovalBorrowOrder";
public const string AddAndApprovalBorrowJYOrder = "/api/Borrow/AddAndApprovalBorrowJYOrder";
public const string GetServerime = "/api/ChannelCfg/GetServerTime";
public Config()
{
AppTitle = "充电台出入库v" + Application.ResourceAssembly.GetName().Version;
AppVersion = Application.ResourceAssembly.GetName().Version.ToString();
AppCode = "10003";
DomainUrl = "http://41.190.20.132:18761/api/service";
UserLogin = "http://41.190.20.132:10004/auth/userLogin";
ComMouth = "COM4";
WarehouseID = "d8192b23-0ec9-4b2e-a47d-f6780a66a880";
ApiVersion = "1.0";
AppKey = "q6t0lEKOmMg5Tm+dg3XdZQ==";
SecretKey = "ba4d855b3b83eab441a51ea9bd9d9671";
FaceAddress = "192.168.8.35";
FaceUser = "admin";
FacePwd = "junmp123";
FacePort = "8000";
IsUseFace = true;
IsEnabledShelf = false;
ShelfAddress = "http://192.168.3.128:38080/api/BoundDocuments";
IsAutoUpdate = true;
AutoUpdateTime = 0;
ReaderType = 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; }
[JsonIgnore]
public string AppCode { get; set; }
public string ComMouth { get; set; }
public string WarehouseID { get; set; }
public string ApiVersion { get; set; }
public string AppKey { get; set; }
public string SecretKey { get; set; }
public string FaceAddress { get; set; }
public string FaceUser { get; set; }
public string FacePwd { get; set; }
public string FacePort { get; set; }
public bool IsUseFace { get; set; }
public bool IsEnabledShelf { get; set; }
public string ShelfAddress { get; set; }
/// <summary>
/// 是否自动更新
/// </summary>
public bool IsAutoUpdate { get; set; }
/// <summary>
/// 自动更新时间(小时)
/// </summary>
public int AutoUpdateTime { get; set; }
/// <summary>
/// 读写器类型
/// 0 钧普
/// 1 索力得
/// </summary>
public int ReaderType { get; set; }
[JsonIgnore]
public static new bool IsInDesignModeStatic { get; }
}
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 respone_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 respone_policeman
{
public string id { get; set; }
public string name { get; set; }
public string policeCode { get; set; }
}
}
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>WinExe</OutputType>
<TargetFramework>net6.0-windows</TargetFramework>
<UseWPF>true</UseWPF>
</PropertyGroup>
<PropertyGroup>
<ApplicationIcon>1.ico</ApplicationIcon>
</PropertyGroup>
<PropertyGroup>
<TargetZone>LocalIntranet</TargetZone>
</PropertyGroup>
<PropertyGroup>
<GenerateManifests>false</GenerateManifests>
</PropertyGroup>
<PropertyGroup>
<ApplicationManifest>Properties\app.manifest</ApplicationManifest>
</PropertyGroup>
<ItemGroup>
<Resource Include="Font\iconfont.ttf" />
</ItemGroup>
<ItemGroup>
<Resource Include="Resources\1.png" />
</ItemGroup>
<ItemGroup>
<Resource Include="1.ico" />
</ItemGroup>
<ItemGroup>
<Resource Include="Resources\3.png" />
</ItemGroup>
<ItemGroup>
<Resource Include="Resources\4.png" />
</ItemGroup>
<ItemGroup>
<Resource Include="Resources\2.png" />
</ItemGroup>
<ItemGroup>
<Content Include="ThirdPackages\msc.dll" />
<Content Include="ThirdPackages\msc_x64.dll" />
<Content Include="ThirdPackages\plugin\hik\AudioRender.dll" />
<Content Include="ThirdPackages\plugin\hik\EagleEyeRender.dll" />
<Content Include="ThirdPackages\plugin\hik\gdiplus.dll" />
<Content Include="ThirdPackages\plugin\hik\HCCore.dll" />
<Content Include="ThirdPackages\plugin\hik\HCNetSDK.dll" />
<Content Include="ThirdPackages\plugin\hik\HCNetSDKCom\AnalyzeData.dll" />
<Content Include="ThirdPackages\plugin\hik\HCNetSDKCom\AudioIntercom.dll" />
<Content Include="ThirdPackages\plugin\hik\HCNetSDKCom\HCAlarm.dll" />
<Content Include="ThirdPackages\plugin\hik\HCNetSDKCom\HCCoreDevCfg.dll" />
<Content Include="ThirdPackages\plugin\hik\HCNetSDKCom\HCDisplay.dll" />
<Content Include="ThirdPackages\plugin\hik\HCNetSDKCom\HCGeneralCfgMgr.dll" />
<Content Include="ThirdPackages\plugin\hik\HCNetSDKCom\HCIndustry.dll" />
<Content Include="ThirdPackages\plugin\hik\HCNetSDKCom\HCPlayBack.dll" />
<Content Include="ThirdPackages\plugin\hik\HCNetSDKCom\HCPreview.dll" />
<Content Include="ThirdPackages\plugin\hik\HCNetSDKCom\HCVoiceTalk.dll" />
<Content Include="ThirdPackages\plugin\hik\HCNetSDKCom\libiconv2.dll" />
<Content Include="ThirdPackages\plugin\hik\HCNetSDKCom\msvcr90.dll" />
<Content Include="ThirdPackages\plugin\hik\HCNetSDKCom\OpenAL32.dll" />
<Content Include="ThirdPackages\plugin\hik\HCNetSDKCom\StreamTransClient.dll" />
<Content Include="ThirdPackages\plugin\hik\HCNetSDKCom\SystemTransform.dll" />
<Content Include="ThirdPackages\plugin\hik\hlog.dll" />
<Content Include="ThirdPackages\plugin\hik\hpr.dll" />
<Content Include="ThirdPackages\plugin\hik\HXVA.dll" />
<Content Include="ThirdPackages\plugin\hik\libeay32.dll" />
<Content Include="ThirdPackages\plugin\hik\MP_Render.dll" />
<Content Include="ThirdPackages\plugin\hik\MP_VIE.dll" />
<Content Include="ThirdPackages\plugin\hik\NPQos.dll" />
<Content Include="ThirdPackages\plugin\hik\PlayCtrl.dll" />
<Content Include="ThirdPackages\plugin\hik\ssleay32.dll" />
<Content Include="ThirdPackages\plugin\hik\SuperRender.dll" />
<Content Include="ThirdPackages\plugin\hik\YUVProcess.dll" />
<Content Include="ThirdPackages\plugin\hik\zlib1.dll" />
<Content Include="ThirdPackages\USBUHFPlatform.dll" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="CommunityToolkit.Mvvm" Version="8.1.0" />
<PackageReference Include="MaterialDesignColors" Version="1.2.6" />
<PackageReference Include="MaterialDesignThemes" Version="3.1.3" />
<PackageReference Include="Microsoft.Xaml.Behaviors.Wpf" Version="1.1.19" />
<PackageReference Include="Panuon.UI.Silver" Version="1.1.3.2" />
<PackageReference Include="SerialPortStream" Version="2.4.1" />
<PackageReference Include="System.ComponentModel.Annotations" Version="5.0.0" />
<PackageReference Include="System.Data.DataSetExtensions" Version="4.5.0" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.3" />
<PackageReference Include="System.Configuration.ConfigurationManager" Version="7.0.0" />
</ItemGroup>
<ItemGroup>
<Reference Include="JmpRfidLp">
<HintPath>..\..\Junmp\JYZB\发卡器\JunmpRfidLpLibCore\bin\Release\netstandard2.1\JmpRfidLp.dll</HintPath>
</Reference>
</ItemGroup>
<PropertyGroup>
<PlatformTarget>x86</PlatformTarget>
<AssemblyVersion>1.3.1.04110</AssemblyVersion>
<FileVersion>1.3.1.04110</FileVersion>
</PropertyGroup>
<Target Name="CopyMyFolder" BeforeTargets="PrepareForBuild">
<ItemGroup>
<SomeFolder Include="ThirdPackages\**" />
</ItemGroup>
<Copy SourceFiles="@(SomeFolder)" DestinationFiles="$(OutputPath)\%(RecursiveDir)%(Filename)%(Extension)" SkipUnchangedFiles="True">
</Copy>
</Target>
</Project>
\ No newline at end of file
<pu:WindowX x:Class="LiteChannel.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: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:LiteChannel"
mc:Ignorable="d" Icon="1.ico"
Title="射频出入库系统" Height="250" Width="400" Loaded="Window_Loaded" ResizeMode="NoResize" WindowStartupLocation="CenterScreen" >
<Window.Resources>
<ResourceDictionary>
<RoutedUICommand x:Key="OnShowConfig" Text="配置管理"/>
</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>
<Grid >
<Grid x:Name="g_body" Grid.Row="1">
<Grid.RowDefinitions>
<RowDefinition Height="20"/>
<RowDefinition Height="60"/>
<RowDefinition Height="60"/>
<RowDefinition Height="*"/>
</Grid.RowDefinitions>
<StackPanel Grid.Row="1" Orientation="Horizontal" Margin="0 0 0 0" VerticalAlignment="Center" HorizontalAlignment="Center" Width="300">
<TextBox Height="30" Name="txtUser"
Width="300"
pu:TextBoxHelper.Watermark="请输入用户名"
pu:TextBoxHelper.Icon="&#xf11c;"
FontFamily="/Font/#iconfont"
pu:TextBoxHelper.FocusedBorderBrush="#B5B5B5"
pu:TextBoxHelper.FocusedShadowColor="#B5B5B5"
pu:TextBoxHelper.IsClearButtonVisible="True" />
</StackPanel>
<StackPanel Margin="0 0 0 0" Grid.Row="2" Orientation="Horizontal" VerticalAlignment="Center" HorizontalAlignment="Center" Width="300">
<PasswordBox Height="30" Name="txtPwd" KeyDown="OnKeyDown"
Width="300"
FontFamily="/Font/#iconfont"
pu:PasswordBoxHelper.Watermark="请输入密码"
pu:PasswordBoxHelper.Icon="&#xf11c;"
pu:PasswordBoxHelper.FocusedBorderBrush="#B5B5B5"
pu:PasswordBoxHelper.FocusedShadowColor="#B5B5B5"
pu:PasswordBoxHelper.IsShowPwdButtonVisible="True" />
</StackPanel>
<Button Grid.Row="3" pu:ButtonHelper.CornerRadius="4" FontSize="20" Content="登录" Margin="127,10,116.6,0" Height="45" Width="150" HorizontalAlignment="Center" VerticalAlignment="Top" Click="OnLoginClick"/>
</Grid>
</Grid>
</pu:WindowX>
using LiteChannel.Commons;
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 LiteChannel
{
/// <summary>
/// Login.xaml 的交互逻辑
/// </summary>
public partial class LoginWindow : WindowX, IComponentConnector
{
private bool bLogin = false;
public LoginWindow()
{
InitializeComponent();
txtUser.Focus();
}
private void Window_Loaded(object sender, RoutedEventArgs e)
{
ReadHistory();
}
private void Sb_Completed(object sender, EventArgs e)
{
this.Close();
Process.GetCurrentProcess().Kill();
}
private async void OnLoginClick(object sender, RoutedEventArgs e)
{
if (bLogin) { return; }
if (string.IsNullOrEmpty(txtUser.Text))
{
bLogin = false;
MessageBox.Show(this, "用户名未填写", "提示", MessageBoxButton.OK, MessageBoxImage.Warning);
return;
}
if (string.IsNullOrEmpty(txtPwd.Password))
{
bLogin = false;
MessageBox.Show(this, "密码未填写", "提示", MessageBoxButton.OK, MessageBoxImage.Warning);
return;
}
var handler = PendingBox.Show("系统登录中...", "", false, Application.Current.MainWindow, new PendingBoxConfigurations()
{
LoadingForeground = "#5DBBEC".ToColor().ToBrush(),
MaxWidth = 250,
MinHeight = 110,
MinWidth = 250,
MaxHeight = 110,
ButtonBrush = "#5DBBEC".ToColor().ToBrush(),
});
var user = txtUser.Text;
var pwd = txtPwd.Password;
var lg_res = await Task.Run(() =>
{
var result = HttpHelper.UserLogin(user, pwd);
return result;
});
if (lg_res != null)
{
SaveHistory();
handler.UpdateMessage("系统登录成功!");
LiteCaChe.OrgId = lg_res.baseJpOrganization?.id ?? "";
LiteCaChe.OrgCode = lg_res.baseJpOrganization?.code?.Substring(0, 6) ?? "";
LiteCaChe.PoliceId = lg_res.policeman?.id ?? "";
LiteCaChe.UserId = lg_res.id;
LiteCaChe.UserName = lg_res.username;
new MainWindow().Show();
this.ShowInTaskbar = false;
this.Hide();
}
else
{
handler.UpdateMessage("系统登录失败!");
}
await Task.Delay(500);
handler.Close();
}
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)
{
Setting settings = new Setting();
settings.ShowDialog();
}
private void SaveHistory()
{
var path = AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "history.txt";
if (!File.Exists(path))
{
File.Create(path);
}
var txt = txtUser.Text + "|" + txtPwd.Password;
File.WriteAllText(path, txt, Encoding.UTF8);
}
public void ReadHistory()
{
var path = AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "history.txt";
if (!File.Exists(path))
{
File.CreateText(path).Dispose();
}
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];
}
}
}
}
}
<pu:WindowX x:Class="LiteChannel.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:pu="clr-namespace:Panuon.UI.Silver;assembly=Panuon.UI.Silver"
xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:LiteChannel"
xmlns:usControl="clr-namespace:LiteChannel.UsControl"
mc:Ignorable="d"
Height="720" Width="1024" ResizeMode="NoResize" WindowState="Maximized"
Loaded="MainWindowLoaded" AllowsTransparency="True" WindowStyle="None" WindowStartupLocation="CenterScreen"
Closing="OnWindow_Closing" pu:WindowXCaption.DisableCloseButton="True">
<pu:WindowX.Background>
<ImageBrush ImageSource="Resources/1.png"/>
</pu:WindowX.Background>
<Grid x:Name="g_main">
<Grid.RowDefinitions>
<RowDefinition Height="0.18*"/>
<RowDefinition Height="0.06*"/>
<RowDefinition Height="0.1*"/>
<RowDefinition Height="0.4*"/>
<RowDefinition Height="0.28*"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="4*"/>
<ColumnDefinition Width="6*"/>
<ColumnDefinition Width="6*"/>
<ColumnDefinition Width="6*"/>
<ColumnDefinition Width="4*"/>
</Grid.ColumnDefinitions>
<ComboBox Grid.Row="1" Grid.Column="1" Grid.ColumnSpan="3" x:Name="cbo_warehouse"
Width="auto" Height="50" Margin="10,0,10,0"
HorizontalAlignment="Stretch" VerticalAlignment="Center"
FontSize="20"
MaxDropDownHeight="400"
pu:ComboBoxHelper.ItemHeight="50"
pu:ComboBoxHelper.HoverBackground="#1EB5B5B5"
pu:ComboBoxHelper.SelectedBackground="#32B5B5B5"
pu:ComboBoxHelper.IsSearchTextBoxVisible="True"
pu:ComboBoxHelper.SearchTextChanged="cbo_warehouse_SearchTextChanged"
pu:ComboBoxHelper.SearchTextBoxWatermark="在此搜索仓库..." SelectionChanged="cbo_warehouse_SelectionChanged"></ComboBox>
<Border Grid.Row="3" Grid.Column="1" Margin="25,0,25,0">
<Border.BorderBrush>
<ImageBrush ImageSource="Resources/3.png"/>
</Border.BorderBrush>
<Border.Background>
<ImageBrush ImageSource="Resources/3.png"/>
</Border.Background>
<Button Click="OnInStore_Click" FontFamily="{StaticResource FontAwesome}" FontSize="30" Foreground="{x:Null}" Margin="0,75,0,0">
<pu:ButtonHelper.ButtonStyle>
<pu:ButtonStyle>Link</pu:ButtonStyle>
</pu:ButtonHelper.ButtonStyle>
</Button>
</Border>
<Border Grid.Row="3" Grid.Column="2" Margin="25,0,25,0">
<Border.BorderBrush>
<ImageBrush ImageSource="Resources/4.png"/>
</Border.BorderBrush>
<Border.Background>
<ImageBrush ImageSource="Resources/4.png"/>
</Border.Background>
<Button Click="OnOutStore_Click" FontFamily="{StaticResource FontAwesome}" FontSize="30" Foreground="{x:Null}" Margin="0,75,0,0">
<pu:ButtonHelper.ButtonStyle>
<pu:ButtonStyle>Link</pu:ButtonStyle>
</pu:ButtonHelper.ButtonStyle>
</Button>
</Border>
<Border Grid.Row="3" Grid.Column="3" Margin="25,0,25,0">
<Border.BorderBrush>
<ImageBrush ImageSource="Resources/2.png"/>
</Border.BorderBrush>
<Border.Background>
<ImageBrush ImageSource="Resources/2.png"/>
</Border.Background>
<Button Click="OnClose_Click" FontFamily="{StaticResource FontAwesome}" FontSize="30" Foreground="{x:Null}" Margin="0,75,0,0">
<pu:ButtonHelper.ButtonStyle>
<pu:ButtonStyle>Link</pu:ButtonStyle>
</pu:ButtonHelper.ButtonStyle>
</Button>
</Border>
</Grid>
</pu:WindowX>
using LiteChannel.Commons;
using LiteChannel.Models;
using Panuon.UI.Silver;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
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.Markup;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.ComponentModel;
namespace LiteChannel
{
/// <summary>
/// Window1.xaml 的交互逻辑
/// </summary>
public partial class MainWindow : WindowX, IComponentConnector
{
private List<store_info> StoreList { get; set; }
public MainWindow()
{
InitializeComponent();
CHCNetSDK.NET_DVR_Init();
//检查软件更新
if (LiteCaChe.SysConfig.IsAutoUpdate)
{
var date = DateTime.Now.Date;
Task.Run(() =>
{
while (true)
{
try
{
if (DateTime.Now.Date > date && DateTime.Now.Hour == LiteCaChe.SysConfig.AutoUpdateTime)
{
//检查更新
var update = HttpHelper.GetUpdate(LiteCaChe.SysConfig?.AppCode ?? "");
if (update == null)
{
Log.ErrorLog("获取更新信息失败 AppCode=" + LiteCaChe.SysConfig?.AppCode);
}
else
{
if (Version.TryParse(update.autoUpdateVersion2, out var version) && version > new Version(LiteCaChe.SysConfig.AppVersion))
{
var fullFile = AppDomain.CurrentDomain.BaseDirectory + update.autoUpdateAddress.TrimStart('/').Replace('/', '\\');
if (!File.Exists(fullFile))
{
//下载新版本
var downloadRes = HttpHelper.HttpDownload(
LiteCaChe.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);
}
});
}
//设置系统时间
HttpHelper.SetLocalTime();
}
private void MainWindowLoaded(object sender, RoutedEventArgs e)
{
StoreList = HttpHelper.GetStoreInfos(LiteCaChe.OrgId);
cbo_warehouse.ItemsSource = StoreList;
cbo_warehouse.DisplayMemberPath = "name";
cbo_warehouse.SelectedValuePath = "id";
cbo_warehouse.SelectedIndex = 0;
//开始同步人员
if (LiteCaChe.SysConfig.IsUseFace)
{
Task.Run(() =>
{
if (InitialFace() && LoginFace())
{
//启动同步线程
cDoorSync = new CancellationTokenSource();
taskSyncDoor = new Task(PollingDoorUser);
taskSyncDoor.Start();
Log.WorkLog("门禁连接成功,开始同步!");
}
else { Log.WorkLog("门禁设备初始化失败!"); }
});
}
}
private void cbo_warehouse_SearchTextChanged(object sender, Panuon.UI.Silver.Core.SearchTextChangedEventArgs e)
{
if (!IsLoaded)
return;
cbo_warehouse.ItemsSource = StoreList.Where(t => t.name.Contains(e.Text));
}
private void cbo_warehouse_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
LiteCaChe.SysConfig.WarehouseID = cbo_warehouse.SelectedValue?.ToString() ?? "";
}
private void OnOutStore_Click(object sender, RoutedEventArgs e)
{
var from = new MainWindow2();
from.Owner = this;
//from.OnApplySuc += LoadData;
from.ShowDialog();
}
private void OnWindow_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
Process.GetCurrentProcess().Kill();
}
private void OnInStore_Click(object sender, RoutedEventArgs e)
{
var from = new StoreInWindow();
from.Owner = this;
//from.OnApplySuc += LoadData;
from.ShowDialog();
}
private void OnClose_Click(object sender, RoutedEventArgs e)
{
Application.Current.Shutdown();
//Process.GetCurrentProcess().Kill();
}
#region 海康门禁
private CancellationTokenSource cDoorSync;
private Task taskSyncDoor;
private AutoResetEvent doorEvent = new AutoResetEvent(false);
private bool isExistFace = false;
private ManualResetEvent setFaceEvent = new ManualResetEvent(true);
private ManualResetEvent faceEvent = new ManualResetEvent(true);
//人脸是否下发成功
private bool isSended = false;
private CHCNetSDK.RemoteConfigCallback onGetGatewayCardCallback = default;
public CHCNetSDK.LOGINRESULTCALLBACK LoginCallBack = default;
private CHCNetSDK.EXCEPYIONCALLBACK onExceptionCallBack = default;
private CHCNetSDK.MSGCallBack_V31 onDVRMessageCallBackV31 = default;
private int hikHwnd = -1;
private int alarmHwnd = -1;
private int cardCfgHwnd = -1;
private string adminCard = "838668";
private IntPtr winHwnd = IntPtr.Zero;
/// <summary>
/// 初始化门禁
/// </summary>
/// <returns></returns>
private bool InitialFace()
{
try
{
byte[] strIP = new byte[16 * 16];
//设置透传报警信息类型
CHCNetSDK.NET_DVR_LOCAL_GENERAL_CFG struLocalCfg = new CHCNetSDK.NET_DVR_LOCAL_GENERAL_CFG();
struLocalCfg.byAlarmJsonPictureSeparate = 1;//控制JSON透传报警数据和图片是否分离,0-不分离(COMM_VCA_ALARM返回),1-分离(分离后走COMM_ISAPI_ALARM回调返回)
int nSize = Marshal.SizeOf(struLocalCfg);
IntPtr ptrLocalCfg = Marshal.AllocHGlobal(nSize);
Marshal.StructureToPtr(struLocalCfg, ptrLocalCfg, false);
if (!CHCNetSDK.NET_DVR_SetSDKLocalCfg(17, ptrLocalCfg)) //NET_DVR_LOCAL_CFG_TYPE_GENERAL
{
Log.WorkLog("门禁初始化失败");
return false;
}
Marshal.FreeHGlobal(ptrLocalCfg);
//设置异常消息回调函数
if (onExceptionCallBack == null)
{
onExceptionCallBack = new CHCNetSDK.EXCEPYIONCALLBACK(DVRExceptionCB);
}
CHCNetSDK.NET_DVR_SetExceptionCallBack_V30(0, IntPtr.Zero, onExceptionCallBack, IntPtr.Zero);
//设置报警回调函数
if (onDVRMessageCallBackV31 == null)
{
onDVRMessageCallBackV31 = new CHCNetSDK.MSGCallBack_V31(DVRMessageCallBackV31);
}
CHCNetSDK.NET_DVR_SetDVRMessageCallBack_V31(onDVRMessageCallBackV31, IntPtr.Zero);
return true;
}
catch (Exception ex)
{
Log.ErrorLog(ex.ToString());
return false;
}
}
/// <summary>
/// 登录至门禁
/// </summary>
/// <returns></returns>
private bool LoginFace()
{
try
{
CHCNetSDK.NET_DVR_USER_LOGIN_INFO struLogInfo = new CHCNetSDK.NET_DVR_USER_LOGIN_INFO();
//设备IP地址或者域名
byte[] byIP = System.Text.Encoding.Default.GetBytes(LiteCaChe.SysConfig.FaceAddress);
struLogInfo.sDeviceAddress = new byte[129];
byIP.CopyTo(struLogInfo.sDeviceAddress, 0);
//设备用户名
byte[] byUserName = System.Text.Encoding.Default.GetBytes(LiteCaChe.SysConfig.FaceUser);
struLogInfo.sUserName = new byte[64];
byUserName.CopyTo(struLogInfo.sUserName, 0);
//设备密码
byte[] byPassword = System.Text.Encoding.Default.GetBytes(LiteCaChe.SysConfig.FacePwd);
struLogInfo.sPassword = new byte[64];
byPassword.CopyTo(struLogInfo.sPassword, 0);
struLogInfo.wPort = ushort.Parse(LiteCaChe.SysConfig.FacePort);//设备服务端口号
struLogInfo.cbLoginResult = LoginCallBack;
struLogInfo.bUseAsynLogin = false; //是否异步登录:0- 否,1- 是
if ((struLogInfo.bUseAsynLogin == true) && (LoginCallBack == null))
{
LoginCallBack = new CHCNetSDK.LOGINRESULTCALLBACK(HikLoginCallBack);//注册回调函数
}
struLogInfo.byLoginMode = 0; //0-Private, 1-ISAPI, 2-自适应
struLogInfo.byHttps = 0; //0-不适用tls,1-使用tls 2-自适应
CHCNetSDK.NET_DVR_DEVICEINFO_V40 DeviceInfo = new CHCNetSDK.NET_DVR_DEVICEINFO_V40();
//登录设备 Login the device
hikHwnd = CHCNetSDK.NET_DVR_Login_V40(ref struLogInfo, ref DeviceInfo);
if (hikHwnd < 0)
{
var errCode = CHCNetSDK.NET_DVR_GetLastError();
Log.WorkLog($"门禁登录失败,错误代码:{errCode}");
return false;
}
else
{
//设置人脸门禁 时间
SetDeivceTime();
return true;
}
}
catch (Exception ex)
{
Log.ErrorLog(ex.ToString());
return false;
}
}
/// <summary>
/// 设置人脸门禁时间和服务器保持一致
/// </summary>
private void SetDeivceTime()
{
if (hikHwnd < 0)
{
return;
}
else
{
var now_time = DateTime.Now;
CHCNetSDK.NET_DVR_TIME CurTime = new CHCNetSDK.NET_DVR_TIME();
CurTime.dwYear = (uint)now_time.Year;
CurTime.dwMonth = (uint)now_time.Month;
CurTime.dwDay = (uint)now_time.Day;
CurTime.dwHour = (uint)now_time.Hour;
CurTime.dwMinute = (uint)now_time.Minute;
CurTime.dwSecond = (uint)now_time.Second;
int dwSize = (int)Marshal.SizeOf(CurTime);
IntPtr ptrCurTime = Marshal.AllocHGlobal(dwSize);
Marshal.StructureToPtr(CurTime, ptrCurTime, true);
bool res = CHCNetSDK.NET_DVR_SetDVRConfig(hikHwnd, CHCNetSDK.NET_DVR_SET_TIMECFG, 0, ptrCurTime, (uint)dwSize);
if (true == res)
{
//SetLogs("设置人脸门禁时间成功");
}
else
{
//SetLogs("设置人脸门禁时间失败");
}
Marshal.FreeHGlobal(ptrCurTime);
}
}
public void HikLoginCallBack(int lUserID, int dwResult, IntPtr lpDeviceInfo, IntPtr pUser)
{
string strLoginCallBack = "登录设备,lUserID:" + lUserID + ",dwResult:" + dwResult;
if (dwResult == 0)
{
uint iErrCode = CHCNetSDK.NET_DVR_GetLastError();
strLoginCallBack = strLoginCallBack + ",错误号:" + iErrCode;
Log.ErrorLog(strLoginCallBack);
}
}
public void DVRExceptionCB(uint dwType, int lUserID, int lHandle, IntPtr pUser)
{
Log.ErrorLog("门禁异常:0x" + Convert.ToString(dwType, 16) + ", lUserID:" + lUserID + ", lHandle:" + lHandle);
}
public bool DVRMessageCallBackV31(int lCommand, ref CHCNetSDK.NET_DVR_ALARMER pAlarmer, IntPtr pAlarmInfo, uint dwBufLen, IntPtr pUser)
{
//通过lCommand来判断接收到的报警信息类型,不同的lCommand对应不同的pAlarmInfo内容
//AlarmMessageHandle(lCommand, ref pAlarmer, pAlarmInfo, dwBufLen, pUser);
switch (lCommand)
{
//门禁主机报警上传,人脸数据
case CHCNetSDK.COMM_ALARM_ACS:
//ProcessCommAlarm_AcsAlarm(ref pAlarmer, pAlarmInfo, dwBufLen, pUser);
AcsAlarm(ref pAlarmer, pAlarmInfo, dwBufLen, pUser);
break;
}
return true; //回调函数需要有返回,表示正常接收到数据
}
private void AcsAlarm(ref CHCNetSDK.NET_DVR_ALARMER pAlarmer, IntPtr pAlarmInfo, uint dwBufLen, IntPtr pUser)
{
CHCNetSDK.NET_DVR_ACS_ALARM_INFO struAcsAlarm = new CHCNetSDK.NET_DVR_ACS_ALARM_INFO();
uint dwSize = (uint)Marshal.SizeOf(struAcsAlarm);
struAcsAlarm = (CHCNetSDK.NET_DVR_ACS_ALARM_INFO)Marshal.PtrToStructure(pAlarmInfo, typeof(CHCNetSDK.NET_DVR_ACS_ALARM_INFO));
//报警设备IP地址
string strIP = System.Text.Encoding.UTF8.GetString(pAlarmer.sDeviceIP).TrimEnd('\0');
//报警时间:年月日时分秒
string strTimeYear = (struAcsAlarm.struTime.dwYear).ToString();
string strTimeMonth = (struAcsAlarm.struTime.dwMonth).ToString("d2");
string strTimeDay = (struAcsAlarm.struTime.dwDay).ToString("d2");
string strTimeHour = (struAcsAlarm.struTime.dwHour).ToString("d2");
string strTimeMinute = (struAcsAlarm.struTime.dwMinute).ToString("d2");
string strTimeSecond = (struAcsAlarm.struTime.dwSecond).ToString("d2");
DateTime time = Convert.ToDateTime(strTimeYear + "-" + strTimeMonth + "-" + strTimeDay + " " + strTimeHour + ":" + strTimeMinute + ":" + strTimeSecond);
if (DateTime.Now.Subtract(time).TotalMinutes <= 5)
{
//var cardNo = Encoding.UTF8.GetString(struAcsAlarm.struAcsEventInfo.byCardNo).TrimEnd('\0');
//if (struAcsAlarm.dwMajor == 5 && (struAcsAlarm.dwMinor == 75 || struAcsAlarm.dwMinor == 38 || struAcsAlarm.dwMinor == 1))
//{
// var user_info = HttpHelper.GetPoliceInfo(cardNo);
// if (user_info != null && !string.IsNullOrEmpty(user_info.policeId))
// {
// SetLogs($"用户[{user_info.policeName}]已获取");
// userId = user_info.policeId;
// if (LiteCaChe.SysConfig.SpecialModel)
// {
// //上报缓存EPC
// lock (cacheList)
// {
// UploadTagEpc(cacheList);
// cacheList.Clear();
// }
// }
// }
// else
// {
// SetLogs("用户数据不存在");
// }
//}
//else
//{
// SetLogs("历史开门信息,已过滤");
//}
}
}
/// <summary>
/// 轮询同步人脸、用户信息
/// </summary>
private void PollingDoorUser()
{
while (!cDoorSync.IsCancellationRequested)
{
var cfg = HttpHelper.GetPoliceInfo();
if (cfg == null || cfg.Count == 0)
{ }
else
{
//更新缓存
LiteCaChe.PoliceList = cfg;
if (hikHwnd >= 0)
{
SyncCards();
Log.WorkLog("用户信息同步完成");
SyncFaces();
Log.WorkLog("用户人脸同步完成");
SyncFinger();
Log.WorkLog("用户指纹同步完成");
}
}
doorEvent.WaitOne(18000000);
}
}
/// <summary>
/// 比对用户信息并同步
/// </summary>
private void SyncCards()
{
if (hikHwnd < 0)
{
return;
}
else
{
//先获取平台人员
if (LiteCaChe.PoliceList == null || LiteCaChe.PoliceList.Count == 0)
{
return;
}
else
{
//下发、更新门禁用户
var tmpList = new List<sync_police>(LiteCaChe.PoliceList);
foreach (var _tmp in tmpList)
{
if (string.IsNullOrEmpty(_tmp.policeCode))
{
continue;
}
else
{
if (!SetDoorUser(_tmp.policeCode, _tmp.name))
{
Log.WorkLog($"人员写入门禁失败,{_tmp.policeCode}{_tmp.name}");
}
}
}
}
}
}
/// <summary>
/// 同步人脸信息
/// </summary>
private void SyncFaces()
{
if (LiteCaChe.PoliceList == null || LiteCaChe.PoliceList.Count == 0 || hikHwnd < 0)
{
return;
}
var policeCards = LiteCaChe.PoliceList;
foreach (var item in policeCards)
{
//校验门禁中是否有人脸信息
var _res = GetUserFace(item.policeCode);
if (_res && string.IsNullOrEmpty(item.photo))
{
//将照片同步至平台
if (!SendFace2Http(item.policeCode, item.id))
{
Log.WorkLog($"人脸照片上传失败,{item.name},{item.policeCode}");
}
}
else if (!_res && string.IsNullOrEmpty(item.photo))
{
//服务端和门禁中都没有人脸信息,忽略
continue;
}
else
{
//尝试下载人脸图片
var buffer = HttpHelper.GetPoliceImg(item.photo);
if (buffer == null)
{
Log.WorkLog("平台人脸图片下载失败");
continue;
}
else
{
//写入至海康
var res = SendFaceImg(item.policeCode, buffer);
if (!res)
{
Log.WorkLog($"人脸写入到门禁失败,{item.name},{item.policeCode}");
}
}
}
}
}
/// <summary>
/// 同步指纹数据
/// </summary>
private void SyncFinger()
{
if (LiteCaChe.PoliceList == null || LiteCaChe.PoliceList.Count == 0 || hikHwnd < 0)
{
return;
}
var policeCards = LiteCaChe.PoliceList.ToList();
foreach (var item in policeCards)
{
//校验门禁中是否有指纹信息(10个手指)
List<FingerInfo> fingerList = new List<FingerInfo>();
for (byte i = 1; i <= 10; i++)
{
var _res = GetUserFinger(item.policeCode, i, out string finger_info);
if (_res && !string.IsNullOrEmpty(finger_info))
{
fingerList.Add(new FingerInfo()
{
fingerInfo = finger_info,
fingerNum = i
});
}
}
var local_nums = fingerList.Select(s => s.fingerNum).ToList();
if (fingerList.Count > 0)
{
//将指纹同步至平台
if (!SendFinger2Http(item.id, fingerList))
{
Log.WorkLog($"指纹上传至平台失败,{item.policeCode},{item.name}");
}
continue;
}
else if (item.fingerList == null || item.fingerList.Count == 0)
{
//服务端和门禁中都没有指纹信息,忽略
continue;
}
else
{
foreach (var finger in item.fingerList)
{
byte[] buffer = Convert.FromBase64String(@finger.fingerInfo);
//写入至海康
var res = SendFingerInfo(item.policeCode, buffer, (byte)finger.fingerNum);
if (!res)
{
Log.WorkLog($"指纹写入到门禁失败,{item.name},{item.policeCode}");
}
}
}
}
}
private bool SendFaceImg(string cardNo, byte[] buffer)
{
try
{
isSended = false;
if (-1 != cardCfgHwnd)
{
if (CHCNetSDK.NET_DVR_StopRemoteConfig(cardCfgHwnd))
{
cardCfgHwnd = -1;
}
}
CHCNetSDK.NET_DVR_FACE_PARAM_COND struCond = new CHCNetSDK.NET_DVR_FACE_PARAM_COND();
struCond.dwSize = (uint)Marshal.SizeOf(struCond);
struCond.dwFaceNum = 1;
struCond.byFaceID = 1;
struCond.byEnableCardReader = new byte[CHCNetSDK.MAX_CARD_READER_NUM_512];
struCond.byEnableCardReader[0] = 1;
struCond.byCardNo = new byte[CHCNetSDK.ACS_CARD_NO_LEN];
byte[] byTempCardNo = Encoding.UTF8.GetBytes(cardNo);
for (int i = 0; i < byTempCardNo.Length; i++)
{
if (i > struCond.byCardNo.Length)
{
Log.WorkLog("卡号长度太长");
return false;
}
struCond.byCardNo[i] = byTempCardNo[i];
}
int dwSize = Marshal.SizeOf(struCond);
IntPtr ptrStruCond = Marshal.AllocHGlobal(dwSize);
Marshal.StructureToPtr(struCond, ptrStruCond, false);
onGetGatewayCardCallback = new CHCNetSDK.RemoteConfigCallback(ProcessSetFaceParamCallback);
cardCfgHwnd = CHCNetSDK.NET_DVR_StartRemoteConfig(hikHwnd, CHCNetSDK.NET_DVR_SET_FACE_PARAM_CFG, ptrStruCond, dwSize, onGetGatewayCardCallback, IntPtr.Zero);
if (-1 == cardCfgHwnd)
{
Marshal.FreeHGlobal(ptrStruCond);
return false;
//g_formList.AddLog(m_lDeviceIndex, AcsDemoPublic.OPERATION_FAIL_T, "NET_DVR_SET_FACE_PARAM_CFG");
}
Marshal.FreeHGlobal(ptrStruCond);
CHCNetSDK.NET_DVR_FACE_PARAM_CFG struFaceParamCfg = new CHCNetSDK.NET_DVR_FACE_PARAM_CFG();
struFaceParamCfg.dwSize = (uint)Marshal.SizeOf(struFaceParamCfg);
struFaceParamCfg.byFaceID = 1;
struFaceParamCfg.byFaceDataType = 1;
struFaceParamCfg.byEnableCardReader = new byte[CHCNetSDK.MAX_CARD_READER_NUM_512];
struFaceParamCfg.byEnableCardReader[0] = 1;
struFaceParamCfg.byCardNo = new byte[CHCNetSDK.ACS_CARD_NO_LEN];
byte[] byTempFaceCardNo = System.Text.Encoding.UTF8.GetBytes(cardNo);
for (int i = 0; i < byTempFaceCardNo.Length; i++)
{
if (i > struFaceParamCfg.byCardNo.Length)
{
Log.WorkLog("卡号长度太长");
return false;
}
struFaceParamCfg.byCardNo[i] = byTempFaceCardNo[i];
}
if (0 == buffer.Length)
{
Log.WorkLog("人脸图片不正确,0kb");
return false;
}
if (200 * 1024 < buffer.Length)
{
Log.WorkLog("人脸图片不正确,大于200kb");
return false;
}
struFaceParamCfg.dwFaceLen = (uint)buffer.Length;
int len = (int)struFaceParamCfg.dwFaceLen;
struFaceParamCfg.pFaceBuffer = Marshal.AllocHGlobal(len);
Marshal.Copy(buffer, 0, struFaceParamCfg.pFaceBuffer, len);
uint dwParamSize = (uint)Marshal.SizeOf(struFaceParamCfg);
IntPtr ptrStruFaceParamCfg = Marshal.AllocHGlobal((int)dwParamSize);
Marshal.StructureToPtr(struFaceParamCfg, ptrStruFaceParamCfg, false);
if (!CHCNetSDK.NET_DVR_SendRemoteConfig(cardCfgHwnd, 9, ptrStruFaceParamCfg, dwParamSize))
{
Log.WorkLog($"设置人脸图片失败");
Marshal.FreeHGlobal(struFaceParamCfg.pFaceBuffer);
Marshal.FreeHGlobal(ptrStruFaceParamCfg);
return false;
}
else
{
setFaceEvent.Reset();
setFaceEvent.WaitOne(5000);
Marshal.FreeHGlobal(struFaceParamCfg.pFaceBuffer);
Marshal.FreeHGlobal(ptrStruFaceParamCfg);
return isSended;
}
}
catch (Exception ex)
{
Log.ErrorLog(ex.ToString());
return false;
}
finally
{
isSended = false;
if (-1 != cardCfgHwnd)
{
if (CHCNetSDK.NET_DVR_StopRemoteConfig(cardCfgHwnd))
{
cardCfgHwnd = -1;
}
}
}
}
private bool SendFingerInfo(string cardNo, byte[] buffer, byte num)
{
if (cardCfgHwnd != -1)
{
CHCNetSDK.NET_DVR_StopRemoteConfig((int)cardCfgHwnd);
cardCfgHwnd = -1;
}
CHCNetSDK.NET_DVR_FINGERPRINT_COND strupond = new CHCNetSDK.NET_DVR_FINGERPRINT_COND();
strupond.init();
int dwSize = Marshal.SizeOf(strupond);
strupond.dwSize = dwSize;
strupond.byFingerPrintID = num;
strupond.dwEnableReaderNo = 1;
strupond.dwFingerprintNum = 1;//指纹数量写死的
byte[] byTempptrRec = System.Text.Encoding.UTF8.GetBytes(cardNo);
for (int i = 0; i < byTempptrRec.Length; i++)
{
strupond.byCardNo[i] = byTempptrRec[i];
}
IntPtr ptrStrucond = Marshal.AllocHGlobal(dwSize);
Marshal.StructureToPtr(strupond, ptrStrucond, false);
cardCfgHwnd = CHCNetSDK.NET_DVR_StartRemoteConfig(hikHwnd, CHCNetSDK.NET_DVR_SET_FINGERPRINT, ptrStrucond, dwSize, null, IntPtr.Zero);
if (-1 == cardCfgHwnd)
{
Marshal.FreeHGlobal(ptrStrucond);
//MessageBox.Show("NET_DVR_SET_FINGERPRINT_CFG_V50 FAIL, ERROR CODE" + CHCNetSDK.NET_DVR_GetLastError().ToString(), "Error", MessageBoxButtons.OK);
Log.WorkLog($"指纹数据设置失败,错误代码:{CHCNetSDK.NET_DVR_GetLastError()}");
return false;
}
bool flag = true;
int dwStatus = 0;
CHCNetSDK.NET_DVR_FINGERPRINT_RECORD StruRecord = new CHCNetSDK.NET_DVR_FINGERPRINT_RECORD();
StruRecord.init();
int dwInBuffSize = Marshal.SizeOf(StruRecord);
StruRecord.dwSize = dwInBuffSize;
StruRecord.byFingerPrintID = num;
StruRecord.dwEnableReaderNo = 1;
StruRecord.dwFingerPrintLen = buffer.Length;
Array.Copy(buffer, 0, StruRecord.byFingerData, 0, buffer.Length);
byte[] byTemp = System.Text.Encoding.UTF8.GetBytes(cardNo);
for (int i = 0; i < byTemp.Length; i++)
{
StruRecord.byCardNo[i] = byTemp[i];
}
CHCNetSDK.NET_DVR_FINGERPRINT_STATUS StruStatus = new CHCNetSDK.NET_DVR_FINGERPRINT_STATUS();
StruStatus.init();
int dwOutBuffSize = Marshal.SizeOf(StruStatus);
StruStatus.dwSize = dwOutBuffSize;
IntPtr ptrOutDataLen = Marshal.AllocHGlobal(sizeof(int));
bool tmp_flage = false;
while (flag)
{
dwStatus = CHCNetSDK.NET_DVR_SendWithRecvRemoteConfig(cardCfgHwnd, ref StruRecord, dwInBuffSize, ref StruStatus, dwOutBuffSize, ptrOutDataLen);
switch (dwStatus)
{
case CHCNetSDK.NET_SDK_GET_NEXT_STATUS_SUCCESS://成功读取到数据,处理完本次数据后需调用next
ProcessSetFingerData(ref StruStatus, ref flag);
tmp_flage = flag;
break;
case CHCNetSDK.NET_SDK_GET_NEXT_STATUS_NEED_WAIT:
break;
case CHCNetSDK.NET_SDK_GET_NEXT_STATUS_FAILED:
CHCNetSDK.NET_DVR_StopRemoteConfig(cardCfgHwnd);
//MessageBox.Show("NET_SDK_GET_NEXT_STATUS_FAILED" + CHCNetSDK.NET_DVR_GetLastError().ToString(), "Error", MessageBoxButtons.OK);
Log.ErrorLog($"指纹设置失败,错误代码:{CHCNetSDK.NET_DVR_GetLastError()}");
flag = false;
break;
case CHCNetSDK.NET_SDK_GET_NEXT_STATUS_FINISH:
CHCNetSDK.NET_DVR_StopRemoteConfig(cardCfgHwnd);
flag = false;
break;
default:
Log.ErrorLog($"指纹设置失败,错误代码:{CHCNetSDK.NET_DVR_GetLastError()}");
//MessageBox.Show("NET_SDK_GET_NEXT_STATUS_UNKOWN" + CHCNetSDK.NET_DVR_GetLastError().ToString(), "Error", MessageBoxButtons.OK);
flag = false;
CHCNetSDK.NET_DVR_StopRemoteConfig(cardCfgHwnd);
break;
}
}
Marshal.FreeHGlobal(ptrStrucond);
Marshal.FreeHGlobal(ptrOutDataLen);
return tmp_flage;
}
/// <summary>
/// 人脸图片上传
/// </summary>
private bool SendFace2Http(string strCard, string id)
{
try
{
var path = $"{System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase}\\FaceImg\\{strCard}.jpg";
if (!File.Exists(path))
{
return false;
}
else
{
var buffer = new byte[] { };
using (MemoryStream ms = new MemoryStream())
{
Bitmap bitmap = new Bitmap(path);
bitmap.Save(ms, ImageFormat.Jpeg);
buffer = ms.GetBuffer();
}
if (buffer == null || buffer.Length == 0)
{
return false;
}
else
{
return HttpHelper.UploadFace(buffer, $"{strCard}.jpg", id);
}
}
}
catch (Exception ex)
{
Log.ErrorLog(ex.ToString());
return false;
}
}
private bool SendFinger2Http(string id, List<FingerInfo> fingerList)
{
try
{
return HttpHelper.UpdateFinger(id, fingerList);
}
catch (Exception ex)
{
Log.ErrorLog(ex.ToString());
return false;
}
}
/// <summary>
/// 发送用户信息至海康
/// </summary>
/// <returns></returns>
private bool SetDoorUser(string cardNo, string name)
{
try
{
if (hikHwnd < 0) { return false; }
if (cardCfgHwnd != -1)
{
if (CHCNetSDK.NET_DVR_StopRemoteConfig(cardCfgHwnd))
{
cardCfgHwnd = -1;
}
}
CHCNetSDK.NET_DVR_CARD_COND struCond = new CHCNetSDK.NET_DVR_CARD_COND();
struCond.Init();
struCond.dwSize = (uint)Marshal.SizeOf(struCond);
struCond.dwCardNum = 1;
IntPtr ptrStruCond = Marshal.AllocHGlobal((int)struCond.dwSize);
Marshal.StructureToPtr(struCond, ptrStruCond, false);
cardCfgHwnd = CHCNetSDK.NET_DVR_StartRemoteConfig(hikHwnd, CHCNetSDK.NET_DVR_SET_CARD, ptrStruCond, (int)struCond.dwSize, null, winHwnd);
if (cardCfgHwnd < 0)
{
Log.WorkLog($"启动远程配置失败,错误代码:{CHCNetSDK.NET_DVR_GetLastError()}");
Marshal.FreeHGlobal(ptrStruCond);
return false;
}
else
{
CHCNetSDK.NET_DVR_CARD_RECORD struData = new CHCNetSDK.NET_DVR_CARD_RECORD();
struData.Init();
struData.dwSize = (uint)Marshal.SizeOf(struData);
struData.byCardType = 1;
byte[] byTempCardNo = new byte[CHCNetSDK.ACS_CARD_NO_LEN];
byTempCardNo = System.Text.Encoding.UTF8.GetBytes(cardNo);
for (int i = 0; i < byTempCardNo.Length; i++)
{
struData.byCardNo[i] = byTempCardNo[i];
}
struData.wCardRightPlan[0] = 1;
var employeeNo = System.Text.RegularExpressions.Regex.Replace(cardNo, @"[^0-9]+", "");
struData.dwEmployeeNo = uint.Parse(employeeNo);
byte[] btyName = new byte[CHCNetSDK.NAME_LEN];
btyName = System.Text.Encoding.UTF8.GetBytes(name);
for (int i = 0; i < btyName.Length; i++)
{
struData.byName[i] = btyName[i];
}
struData.struValid.byEnable = 1;
struData.struValid.struBeginTime.wYear = 2000;
struData.struValid.struBeginTime.byMonth = 1;
struData.struValid.struBeginTime.byDay = 1;
struData.struValid.struBeginTime.byHour = 11;
struData.struValid.struBeginTime.byMinute = 11;
struData.struValid.struBeginTime.bySecond = 11;
struData.struValid.struEndTime.wYear = 2030;
struData.struValid.struEndTime.byMonth = 1;
struData.struValid.struEndTime.byDay = 1;
struData.struValid.struEndTime.byHour = 11;
struData.struValid.struEndTime.byMinute = 11;
struData.struValid.struEndTime.bySecond = 11;
struData.byDoorRight[0] = 1;
struData.wCardRightPlan[0] = 1;
IntPtr ptrStruData = Marshal.AllocHGlobal((int)struData.dwSize);
Marshal.StructureToPtr(struData, ptrStruData, false);
CHCNetSDK.NET_DVR_CARD_STATUS struStatus = new CHCNetSDK.NET_DVR_CARD_STATUS();
struStatus.Init();
struStatus.dwSize = (uint)Marshal.SizeOf(struStatus);
IntPtr ptrdwState = Marshal.AllocHGlobal((int)struStatus.dwSize);
Marshal.StructureToPtr(struStatus, ptrdwState, false);
int dwState = (int)CHCNetSDK.NET_SDK_SENDWITHRECV_STATUS.NET_SDK_CONFIG_STATUS_SUCCESS;
uint dwReturned = 0;
bool res = false;
while (true)
{
dwState = CHCNetSDK.NET_DVR_SendWithRecvRemoteConfig(cardCfgHwnd, ptrStruData, struData.dwSize, ptrdwState, struStatus.dwSize, ref dwReturned);
struStatus = (CHCNetSDK.NET_DVR_CARD_STATUS)Marshal.PtrToStructure(ptrdwState, typeof(CHCNetSDK.NET_DVR_CARD_STATUS));
if (dwState == (int)CHCNetSDK.NET_SDK_SENDWITHRECV_STATUS.NET_SDK_CONFIG_STATUS_NEEDWAIT)
{
Thread.Sleep(10);
continue;
}
else if (dwState == (int)CHCNetSDK.NET_SDK_SENDWITHRECV_STATUS.NET_SDK_CONFIG_STATUS_FAILED)
{
Log.WorkLog($"人员信息写入失败,错误代码:{CHCNetSDK.NET_DVR_GetLastError()}");
}
else if (dwState == (int)CHCNetSDK.NET_SDK_SENDWITHRECV_STATUS.NET_SDK_CONFIG_STATUS_SUCCESS)
{
if (struStatus.dwErrorCode != 0)
{
Log.WorkLog($"人员信息写入失败,错误代码:{struStatus.dwErrorCode}");
}
else
{
Log.WorkLog($"人员信息写入成功");
}
}
else if (dwState == (int)CHCNetSDK.NET_SDK_SENDWITHRECV_STATUS.NET_SDK_CONFIG_STATUS_FINISH)
{
Log.WorkLog($"人员信息写入完成");
res = true;
break;
}
else if (dwState == (int)CHCNetSDK.NET_SDK_SENDWITHRECV_STATUS.NET_SDK_CONFIG_STATUS_EXCEPTION)
{
Log.WorkLog($"人员信息写入失败,错误代码:{CHCNetSDK.NET_DVR_GetLastError()}");
res = false;
break;
}
else
{
Log.WorkLog($"人员信息写入失败,发生未知错误:{CHCNetSDK.NET_DVR_GetLastError()}");
res = false;
break;
}
}
CHCNetSDK.NET_DVR_StopRemoteConfig(cardCfgHwnd);
cardCfgHwnd = -1;
Marshal.FreeHGlobal(ptrStruData);
Marshal.FreeHGlobal(ptrdwState);
Marshal.FreeHGlobal(ptrStruCond);
return res;
}
}
catch (Exception ex)
{
Log.ErrorLog(ex.ToString());
return false;
}
finally
{
if (cardCfgHwnd != -1)
{
if (CHCNetSDK.NET_DVR_StopRemoteConfig(cardCfgHwnd))
{
cardCfgHwnd = -1;
}
}
}
}
/// <summary>
/// 获取用户人脸信息
/// </summary>
/// <param name="cardNo"></param>
/// <returns></returns>
private bool GetUserFace(string cardNo)
{
try
{
isExistFace = false;
if (hikHwnd < 0) { return false; }
if (-1 != cardCfgHwnd)
{
if (CHCNetSDK.NET_DVR_StopRemoteConfig(cardCfgHwnd))
{
cardCfgHwnd = -1;
}
}
CHCNetSDK.NET_DVR_FACE_PARAM_COND struCond = new CHCNetSDK.NET_DVR_FACE_PARAM_COND();
struCond.dwSize = (uint)Marshal.SizeOf(struCond);
struCond.dwFaceNum = 1;
struCond.byFaceID = 1;
struCond.byEnableCardReader = new byte[CHCNetSDK.MAX_CARD_READER_NUM_512];
struCond.byEnableCardReader[0] = 1;
struCond.byCardNo = new byte[CHCNetSDK.ACS_CARD_NO_LEN];
byte[] byTempCardNo = System.Text.Encoding.UTF8.GetBytes(cardNo);
for (int i = 0; i < byTempCardNo.Length; i++)
{
if (i > struCond.byCardNo.Length)
{
Log.WorkLog("卡号长度太长");
return false;
}
struCond.byCardNo[i] = byTempCardNo[i];
}
int dwSize = Marshal.SizeOf(struCond);
IntPtr ptrStruCond = Marshal.AllocHGlobal(dwSize);
Marshal.StructureToPtr(struCond, ptrStruCond, false);
onGetGatewayCardCallback = new CHCNetSDK.RemoteConfigCallback(ProcessGetFaceParamCallback);
cardCfgHwnd = CHCNetSDK.NET_DVR_StartRemoteConfig(hikHwnd, CHCNetSDK.NET_DVR_GET_FACE_PARAM_CFG, ptrStruCond, dwSize, onGetGatewayCardCallback, winHwnd);
if (-1 == cardCfgHwnd)
{
int errCode = 0;
IntPtr ptrFail = CHCNetSDK.NET_DVR_GetErrorMsg(ref errCode);
string strFail = Marshal.PtrToStringAnsi(ptrFail);
Log.WorkLog($"获取人脸异常,错误代码:{CHCNetSDK.NET_DVR_GetLastError()}{strFail}");
Marshal.FreeHGlobal(ptrStruCond);
return false;
//g_formList.AddLog(m_lDeviceIndex, AcsDemoPublic.OPERATION_FAIL_T, "NET_DVR_GET_FACE_PARAM_CFG");
}
else
{
faceEvent.Reset();
faceEvent.WaitOne(5000);
Marshal.FreeHGlobal(ptrStruCond);
return isExistFace;
//g_formList.AddLog(m_lDeviceIndex, AcsDemoPublic.OPERATION_SUCC_T, "NET_DVR_GET_FACE_PARAM_CFG");
}
}
catch (Exception ex)
{
Log.ErrorLog(ex.ToString());
return false;
}
finally
{
//isExistFace = false;
if (-1 != cardCfgHwnd)
{
if (CHCNetSDK.NET_DVR_StopRemoteConfig(cardCfgHwnd))
{
cardCfgHwnd = -1;
}
}
}
}
/// <summary>
/// 获取海康门禁中指纹数据
/// </summary>
/// <param name="cardNo"></param>
/// <returns></returns>
private bool GetUserFinger(string cardNo, byte finger_index, out string finger_info)
{
try
{
finger_info = string.Empty;
if (hikHwnd < 0) { return false; }
if (-1 != cardCfgHwnd)
{
if (CHCNetSDK.NET_DVR_StopRemoteConfig(cardCfgHwnd))
{
cardCfgHwnd = -1;
}
}
CHCNetSDK.NET_DVR_FINGERPRINT_COND struCond = new CHCNetSDK.NET_DVR_FINGERPRINT_COND();
struCond.init();
struCond.dwSize = Marshal.SizeOf(struCond);
struCond.dwFingerprintNum = 1;
struCond.byFingerPrintID = finger_index;
byte[] byTemp = System.Text.Encoding.UTF8.GetBytes(cardNo);
for (int i = 0; i < byTemp.Length; i++)
{
struCond.byCardNo[i] = byTemp[i];
}
struCond.dwEnableReaderNo = 1;
int dwSize = Marshal.SizeOf(struCond);
IntPtr ptrStruCond = Marshal.AllocHGlobal(dwSize);
Marshal.StructureToPtr(struCond, ptrStruCond, false);
cardCfgHwnd = CHCNetSDK.NET_DVR_StartRemoteConfig(hikHwnd, CHCNetSDK.NET_DVR_GET_FINGERPRINT, ptrStruCond, dwSize, null, IntPtr.Zero);
if (-1 == cardCfgHwnd)
{
Marshal.FreeHGlobal(ptrStruCond);
//MessageBox.Show("NET_DVR_GET_FINGERPRINT_CFG_V50 FAIL, ERROR CODE" + CHCNetSDK.NET_DVR_GetLastError().ToString(), "Error", MessageBoxButtons.OK);
Log.WorkLog("指纹数据获取失败");
return false;
}
Boolean flag = true;
CHCNetSDK.NET_DVR_FINGERPRINT_RECORD struOutBuff = new CHCNetSDK.NET_DVR_FINGERPRINT_RECORD();
struOutBuff.init();
int dWsize = Marshal.SizeOf(struOutBuff);
int dwStatus = 0;
while (flag)
{
dwStatus = CHCNetSDK.NET_DVR_GetNextRemoteConfig(cardCfgHwnd, ref struOutBuff, dWsize);
switch (dwStatus)
{
case CHCNetSDK.NET_SDK_GET_NEXT_STATUS_SUCCESS://成功读取到数据,处理完本次数据后需调用next
finger_info = ReaderFingerInfo(struOutBuff);
break;
case CHCNetSDK.NET_SDK_GET_NEXT_STATUS_NEED_WAIT:
break;
case CHCNetSDK.NET_SDK_GET_NEXT_STATUS_FAILED:
CHCNetSDK.NET_DVR_StopRemoteConfig(cardCfgHwnd);
//MessageBox.Show("NET_SDK_GET_NEXT_STATUS_FAILED" + CHCNetSDK.NET_DVR_GetLastError().ToString(), "Error", MessageBoxButtons.OK);
Log.WorkLog($"指纹数据获取失败,错误代码:{CHCNetSDK.NET_DVR_GetLastError()}");
flag = false;
break;
case CHCNetSDK.NET_SDK_GET_NEXT_STATUS_FINISH:
//MessageBox.Show("NET_SDK_GET_NEXT_STATUS_FINISH", "Tips", MessageBoxButtons.OK);
Log.WorkLog($"指纹数据获取成功");
CHCNetSDK.NET_DVR_StopRemoteConfig(cardCfgHwnd);
flag = false;
break;
default:
//MessageBox.Show("NET_SDK_GET_NEXT_STATUS_UNKOWN" + CHCNetSDK.NET_DVR_GetLastError().ToString(), "Error", MessageBoxButtons.OK);
Log.WorkLog($"指纹数据获取失败,错误代码:{CHCNetSDK.NET_DVR_GetLastError()}");
CHCNetSDK.NET_DVR_StopRemoteConfig(cardCfgHwnd);
flag = false;
break;
}
}
Marshal.FreeHGlobal(ptrStruCond);
return !string.IsNullOrEmpty(finger_info);
}
catch (Exception ex)
{
Log.ErrorLog(ex.ToString());
finger_info = string.Empty;
return false;
}
}
private string ReaderFingerInfo(CHCNetSDK.NET_DVR_FINGERPRINT_RECORD struOutBuff)
{
try
{
using (MemoryStream ms = new MemoryStream())
{
ms.Write(struOutBuff.byFingerData, 0, struOutBuff.dwFingerPrintLen);
var base64 = Convert.ToBase64String(ms.ToArray());
ms.Close();
return base64;
}
}
catch (Exception ex)
{
Log.ErrorLog(ex.ToString());
return string.Empty;
}
}
private void ProcessGetFaceParamCallback(uint dwType, IntPtr lpBuffer, uint dwBufLen, IntPtr pUserData)
{
if (pUserData == null)
{
return;
}
if (dwType == (uint)CHCNetSDK.NET_SDK_CALLBACK_TYPE.NET_SDK_CALLBACK_TYPE_STATUS)
{
uint dwStatus = (uint)Marshal.ReadInt32(lpBuffer);
if (dwStatus == (uint)CHCNetSDK.NET_SDK_CALLBACK_STATUS_NORMAL.NET_SDK_CALLBACK_STATUS_PROCESSING)
{
//g_formList.AddLog(m_lDeviceIndex, AcsDemoPublic.OPERATION_SUCC_T, "GetFaceParam Processing");
}
else if (dwStatus == (uint)CHCNetSDK.NET_SDK_CALLBACK_STATUS_NORMAL.NET_SDK_CALLBACK_STATUS_FAILED)
{
faceEvent.Set();
}
else if (dwStatus == (uint)CHCNetSDK.NET_SDK_CALLBACK_STATUS_NORMAL.NET_SDK_CALLBACK_STATUS_SUCCESS)
{
//g_formList.AddLog(m_lDeviceIndex, AcsDemoPublic.OPERATION_SUCC_T, "GetFaceParam Success");
faceEvent.Set();
}
else if (dwStatus == (uint)CHCNetSDK.NET_SDK_CALLBACK_STATUS_NORMAL.NET_SDK_CALLBACK_STATUS_EXCEPTION)
{
//g_formList.AddLog(m_lDeviceIndex, AcsDemoPublic.OPERATION_FAIL_T, "GetFaceParam Exception");
faceEvent.Set();
}
else
{
faceEvent.Set();
}
}
else if (dwType == (uint)CHCNetSDK.NET_SDK_CALLBACK_TYPE.NET_SDK_CALLBACK_TYPE_DATA)
{
var result = Marshal.PtrToStructure(lpBuffer, typeof(CHCNetSDK.NET_DVR_FACE_PARAM_CFG));
var struFaceParamCfg = (CHCNetSDK.NET_DVR_FACE_PARAM_CFG)result;
if (struFaceParamCfg.byEnableCardReader[0] != 1)
{
}
if (struFaceParamCfg.dwFaceLen > 0)
{
var cardNo = Encoding.UTF8.GetString(struFaceParamCfg.byCardNo).Trim('\0');
var dir = $"{System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase}\\FaceImg";
if (!Directory.Exists(dir)) { Directory.CreateDirectory(dir); }
isExistFace = true;
using (FileStream fs = new FileStream($"{System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase}\\FaceImg\\{cardNo}.jpg", FileMode.Create))
{
int len = (int)struFaceParamCfg.dwFaceLen;
byte[] by = new byte[len];
Marshal.Copy(struFaceParamCfg.pFaceBuffer, by, 0, len);
fs.Write(by, 0, len);
fs.Close();
}
}
faceEvent.Set();
}
return;
}
private void ProcessSetFingerData(ref CHCNetSDK.NET_DVR_FINGERPRINT_STATUS ststus, ref bool flag)
{
switch (ststus.byRecvStatus)
{
case 0:
//MessageBox.Show("SetFingegDataSuccessful", "Succeed", MessageBoxButtons.OK);
break;
default:
flag = false;
// MessageBox.Show("NET_SDK_SET_FINGER_DATA_FAILED" + ststus.byRecvStatus.ToString(), "ERROR", MessageBoxButtons.OK);
Log.ErrorLog($"指纹设置失败,错误代码:{ststus.byRecvStatus.ToString()}");
break;
}
}
private void ProcessSetFaceParamCallback(uint dwType, IntPtr lpBuffer, uint dwBufLen, IntPtr pUserData)
{
if (pUserData == null)
{
return;
}
if (dwType == (uint)CHCNetSDK.NET_SDK_CALLBACK_TYPE.NET_SDK_CALLBACK_TYPE_STATUS)
{
uint dwStatus = (uint)Marshal.ReadInt32(lpBuffer);
if (dwStatus == (uint)CHCNetSDK.NET_SDK_CALLBACK_STATUS_NORMAL.NET_SDK_CALLBACK_STATUS_PROCESSING)
{
//g_formList.AddLog(m_lDeviceIndex, AcsDemoPublic.OPERATION_SUCC_T, "SetFaceParam Processing");
}
else if (dwStatus == (uint)CHCNetSDK.NET_SDK_CALLBACK_STATUS_NORMAL.NET_SDK_CALLBACK_STATUS_FAILED)
{
setFaceEvent.Set();
//g_formList.AddLog(m_lDeviceIndex, AcsDemoPublic.OPERATION_FAIL_T, "SetFaceParam Failed");
//CHCNetSDK.PostMessage(pUserData, 1001, 0, 0);
}
else if (dwStatus == (uint)CHCNetSDK.NET_SDK_CALLBACK_STATUS_NORMAL.NET_SDK_CALLBACK_STATUS_SUCCESS)
{
isSended = true;
setFaceEvent.Set();
//g_formList.AddLog(m_lDeviceIndex, AcsDemoPublic.OPERATION_SUCC_T, "SetFaceParam Success");
//CHCNetSDK.PostMessage(pUserData, 1001, 0, 0);
}
else if (dwStatus == (uint)CHCNetSDK.NET_SDK_CALLBACK_STATUS_NORMAL.NET_SDK_CALLBACK_STATUS_EXCEPTION)
{
setFaceEvent.Set();
//g_formList.AddLog(m_lDeviceIndex, AcsDemoPublic.OPERATION_FAIL_T, "SetFaceParam Exception");
//CHCNetSDK.PostMessage(pUserData, 1001, 0, 0);
}
else
{
setFaceEvent.Set();
//g_formList.AddLog(m_lDeviceIndex, AcsDemoPublic.OPERATION_FAIL_T, "Unknown Status");
//CHCNetSDK.PostMessage(pUserData, 1001, 0, 0);
}
}
else if (dwType == (uint)CHCNetSDK.NET_SDK_CALLBACK_TYPE.NET_SDK_CALLBACK_TYPE_DATA)
{
var result = Marshal.PtrToStructure(lpBuffer, typeof(CHCNetSDK.NET_DVR_FACE_PARAM_STATUS));
var struFaceParamStatus = (CHCNetSDK.NET_DVR_FACE_PARAM_STATUS)result;
if (struFaceParamStatus.byCardReaderRecvStatus[0] != 1)
{
isSended = false;
//g_formList.AddLog(m_lDeviceIndex, AcsDemoPublic.OPERATION_FAIL_T, "SetFaceParam Return Failed:byCardReaderRecvStatus " + struFaceParamStatus.byCardReaderRecvStatus[0]);
}
else
{
isSended = true;
}
}
}
#endregion
}
}
<pu:WindowX x:Class="LiteChannel.MainWindow2"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:pu="clr-namespace:Panuon.UI.Silver;assembly=Panuon.UI.Silver"
xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:LiteChannel"
xmlns:usControl="clr-namespace:LiteChannel.UsControl"
xmlns:b="http://schemas.microsoft.com/xaml/behaviors"
mc:Ignorable="d" Icon="1.ico"
Height="720" Width="1024" ResizeMode="NoResize" WindowState="Maximized"
Loaded="MainWindowLoaded" AllowsTransparency="True" WindowStyle="None" WindowStartupLocation="CenterScreen"
Closing="OnWindow_Closing" pu:WindowXCaption.DisableCloseButton="True">
<Grid x:Name="g_main">
<Grid.RowDefinitions>
<RowDefinition Height="60"/>
<RowDefinition Height="*"/>
<RowDefinition Height="80"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="0.6*"/>
<ColumnDefinition Width="0.4*"/>
<ColumnDefinition Width="0.3*"/>
<ColumnDefinition Width="0.3*"/>
</Grid.ColumnDefinitions>
<Button Grid.Row="0" Margin="0,0,10,0" Click="OnInStore_Click" pu:ButtonHelper.Icon="&#xf085;" Content="快捷创建单据" FontFamily="{StaticResource FontAwesome}" pu:ButtonHelper.CornerRadius="5" FontSize="22"></Button>
<Button Grid.Column="1" Margin="0,0,10,0" Click="OnOutStoreNoOrder_Click" pu:ButtonHelper.Icon="&#xf085;" Content="本仓库借用出库" FontFamily="{StaticResource FontAwesome}" pu:ButtonHelper.CornerRadius="5" FontSize="22"></Button>
<Button Grid.Row="0" Grid.Column="2" Click="OnRefresh_Click" pu:ButtonHelper.Icon="&#xf202;" Margin="10,0,10,0" Content="刷新单据" FontFamily="{StaticResource FontAwesome}" pu:ButtonHelper.CornerRadius="5" FontSize="22"></Button>
<Button Grid.Row="0" Grid.Column="3" Click="OnClose_Click" pu:ButtonHelper.Icon="&#xf2d3;" Margin="10,0,10,0" Content="返回主页" FontFamily="{StaticResource FontAwesome}" pu:ButtonHelper.CornerRadius="5" FontSize="22" Background="#C8FF0000" pu:ButtonHelper.HoverBrush="#FF0000" ></Button>
<DataGrid Grid.Row="1" ScrollViewer.HorizontalScrollBarVisibility="Visible" ScrollViewer.VerticalScrollBarVisibility="Visible" EnableRowVirtualization="False" Margin="3 5 3 0" HeadersVisibility="Column"
pu:DataGridHelper.SelectedBackground="#44B5B5B5" pu:DataGridHelper.HoverBackground="#22B5B5B5" CanUserAddRows="False" Grid.ColumnSpan="4"
AutoGenerateColumns="False" LoadingRow="OnDataGridLoadingRow" SelectionMode="Single" Name="dg_order" pu:DataGridHelper.ColumnHorizontalContentAlignment="Center" CanUserSortColumns="True" >
<DataGrid.Columns>
<!--<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 IsReadOnly="True" Header="单据编号(后6位)" Width="115" MinWidth="115" FontSize="18" Binding="{Binding orderCodeLast6}" />
<DataGridTextColumn IsReadOnly="True" Header="单据类型" Width="100" MinWidth="100" FontSize="18" Binding="{Binding orderType}" />
<DataGridTextColumn IsReadOnly="True" Header="借用警员(借用)" Width="*" MinWidth="100" FontSize="18" Binding="{Binding borrowPolice}" />
<DataGridTextColumn IsReadOnly="True" Header="目标仓库(调拨)" Width="*" MinWidth="100" FontSize="18" Binding="{Binding receiveWarehouseName}" />
<DataGridTextColumn IsReadOnly="True" Header="申请日期" Width="*" MinWidth="205" FontSize="18" Binding="{Binding createTime}"/>
<!--<DataGridTextColumn IsReadOnly="True" Header="装备信息" Width="*" MinWidth="100" FontSize="18" Binding="{Binding equNames}"/>-->
<!--<DataGridTextColumn IsReadOnly="True" Header="单据数量" Width="100" MinWidth="100" FontSize="18" Binding="{Binding orderQuantity}"/>-->
<DataGridTemplateColumn Header="操作" Width="250" MinWidth="250" IsReadOnly="True">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal" VerticalAlignment="Center" HorizontalAlignment="Center">
<Button Content="开始出库" pu:ButtonHelper.Icon="&#xf20e;" pu:ButtonHelper.CornerRadius="5" Click="OnOutStore_Click" Padding="8" Margin="5,8,5,8" >
</Button>
<Button Content="查看明细" pu:ButtonHelper.Icon="&#xf1cb;" pu:ButtonHelper.CornerRadius="5" Click="OnShowDetail_Click" Padding="8" Margin="5,8,5,8" >
</Button>
</StackPanel>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
<usControl:PageControl IsEnabled="{Binding BindButton}" x:Name="d_pager" Margin="0,0,0,0" Grid.Row="2" TotalRecord="{Binding TotalRecord,Mode=TwoWay}" TotalPage="{Binding PageTotal,Mode=TwoWay}" PageSize="{Binding PageSize,Mode=TwoWay}" PageIndex="{Binding PageIndex,Mode=TwoWay}" Grid.ColumnSpan="4"
Grid.Column="0">
<b:Interaction.Triggers>
<b:EventTrigger EventName="OnPageChanged">
<b:InvokeCommandAction Command="{Binding OnPageChangeCmd}" />
</b:EventTrigger>
</b:Interaction.Triggers>
</usControl:PageControl>
</Grid>
</pu:WindowX>
using LiteChannel.Commons;
using LiteChannel.Models;
using Panuon.UI.Silver;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
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.Markup;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.ComponentModel;
using CommunityToolkit.Mvvm.Input;
namespace LiteChannel
{
/// <summary>
/// Window1.xaml 的交互逻辑
/// </summary>
public partial class MainWindow2 : WindowX, IComponentConnector
{
private PageControlModel model;
public MainWindow2()
{
InitializeComponent();
model = new PageControlModel(this);
}
private void MainWindowLoaded(object sender, RoutedEventArgs e)
{
DataContext = model;
//加载单据数据
model.PageIndex = 1;
LoadData();
}
public void LoadData()
{
var tmp = HttpHelper.GetOrderInfos(model.PageIndex, model.PageSize);
model.TotalRecord = tmp?.totalElements ?? 0;
model.PageTotal = model.TotalRecord == 0 ? 0 : (model.TotalRecord + model.PageSize - 1) / model.PageSize;
dg_order.ItemsSource = tmp?.content;
}
private void OnDataGridLoadingRow(object sender, DataGridRowEventArgs e)
{
e.Row.Header = e.Row.GetIndex() + 1;
}
private void OnOutStore_Click(object sender, RoutedEventArgs e)
{
if (dg_order.SelectedItem != null)
{
var item = dg_order.SelectedItem as order_info;
var from = new StoreOutWindow(item.id, item.orderType, item);
from.Owner = this;
from.OnApplySuc += LoadData;
from.ShowDialog();
}
}
private void OnOutStoreNoOrder_Click(object sender, RoutedEventArgs e)
{
var from = new StoreOutWindow("", "NoOrder", null);
from.Owner = this;
from.OnApplySuc += LoadData;
from.ShowDialog();
}
private void OnShowDetail_Click(object sender, RoutedEventArgs e)
{
if (dg_order.SelectedItem != null)
{
var item = dg_order.SelectedItem as order_info;
var from = new OrderInfoWindows(item.id, item.orderType);
from.Owner = this;
from.OnApplySuc += LoadData;
from.ShowDialog();
}
}
private void OnWindow_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
}
private void OnInStore_Click(object sender, RoutedEventArgs e)
{
var from = new QuickCreateOrderWindow();
from.Owner = this;
from.ShowDialog();
OnRefresh_Click(null, null);
}
private void OnRefresh_Click(object sender, RoutedEventArgs e)
{
model.PageIndex = 1;
LoadData();
}
private void OnClose_Click(object sender, RoutedEventArgs e)
{
this.Close();
//Application.Current.Shutdown();
//Process.GetCurrentProcess().Kill();
}
}
public class PageControlModel : INotifyPropertyChanged
{
private bool _bindButton = true;
public bool BindButton
{
get { return _bindButton; }
set
{
_bindButton = value;
OnPropertyChanged("BindButton");
}
}
private int _total = 0;
public int TotalRecord
{
get { return _total; }
set
{
_total = value;
OnPropertyChanged("TotalRecord");
}
}
private int _page = 0;
public int PageIndex
{
get { return _page; }
set
{
_page = value;
OnPropertyChanged("PageIndex");
}
}
private int _pageTotal = 0;
public int PageTotal
{
get { return _pageTotal; }
set
{
_pageTotal = value;
OnPropertyChanged("PageTotal");
}
}
private int _pageSize = 50;
public int PageSize
{
get { return _pageSize; }
set
{
_pageSize = value;
OnPropertyChanged("PageSize");
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void OnPropertyChanged(string strPropertyInfo)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(strPropertyInfo));
}
}
private readonly MainWindow2 _mainWindow;
public RelayCommand OnPageChangeCmd { get; set; }
public PageControlModel(MainWindow2 mainWindow)
{
_mainWindow = mainWindow;
PageSize = 10;
OnPageChangeCmd = new RelayCommand(OnPageChange);
}
private void OnPageChange()
{
_mainWindow.LoadData();
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LiteChannel.Models
{
public class BaseJpWarehouse
{
public string id { get; set; }
public int? sort { get; set; }
public string name { get; set; }
public string location { get; set; }
public string locationDetail { get; set; }
public string orgizationId { get; set; }
public string phone { get; set; }
public DateTime createTime { get; set; }
public DateTime updateTime { get; set; }
public string updateUser { get; set; }
/// <summary>
/// 是否锁库,0:未锁库,1:锁库中
/// </summary>
public bool? isLocked { get; set; }
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LiteChannel.Models
{
public class equ_info
{
public string id { get; set; }
public string code { get; set; }
public string name { get; set; }
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LiteChannel.Models
{
public class inventory_info
{
public int detailCount { get; set; }
public string equipmentDetailId { get; set; }
public string equipmentDetailName { get; set; }
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LiteChannel.Models
{
public class order_equ
{
public string equCode { get; set; }
public int equRem { get; set; }
public int equCount { get; set; }
public int equUsed { get; set; }
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LiteChannel.Models
{
public class order_info
{
public string id { get; set; }
public string warehouseId { get; set; }
public string orderCode { get; set; }
public string orderCodeLast6 => orderCode.Substring(16);
public string orgId { get; set; }
public string createTime { get; set; }
public bool? isWork { get; set; }
public string orderType { get; set; }
public int orderQuantity { get; set; }
public string equNames { get; set; }
public string borrowPolice { get; set; }
public string receiveWarehouseId { get; set; }
public string receiveWarehouseName { get; set; }
}
public class order_detail
{
public string id { get; set; }
public string equId { get; set; }
public string equName { get; set; }
public string equCode { get; set; }
public int equCount { get; set; }
public int equUsed { get; set; }
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LiteChannel.Models
{
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;
namespace LiteChannel.Models
{
public class respone<T>
{
public int code { get; set; }
public string msg { get; set; }
public T data { get; set; }
}
public class respone
{
public int code { get; set; }
public string msg { get; set; }
}
public class PagedList<T>
{
public int totalElements { get; set; }
public List<T> content { get; set; }
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LiteChannel.Models
{
public class respone_upload
{
public int code { get; set; }
public string msg { get; set; }
public int timestamp { get; set; }
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LiteChannel.Models
{
public class response_BoxMarkModel
{
public string id { get; set; }
public string createTime { get; set; }
public string epc { get; set; }
public string oneBoxNum { get; set; }
public string warehouseId { get; set; }
public string warehouseName { get; set; }
public string orgizationId { get; set; }
public string equipmentInfoId { 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 string sizeEpcType { get; set; }
public string supplierId { get; set; }
public string supplierCode { get; set; }
public string supplierName { 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 LiteChannel.Models
{
public class rfid_res
{
public string epc { get; set; }
public string name { get; set; }
public int currentState { get; set; }
public int safeLevel { get; set; }
}
}
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LiteChannel.Models
{
public class scan_info : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
public int equRem { get; set; }
public string equCode { get; set; }
public string equName { get; set; }
private int _scan_qty = 0;
public int scanQty
{
get { return _scan_qty; }
set
{
_scan_qty = value;
PropertyChanged?.Invoke(this, new PropertyChangedEventArgs("scanQty"));
}
}
public int equCount { 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 LiteChannel.Models
{
public class soft_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 LiteChannel.Models
{
public class store_info
{
public string id { get; set; }
public string name { get; set; }
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LiteChannel.Models
{
public class sync_police
{
public string orgId { get; set; }
public string id { get; set; }
public string name { get; set; }
public string policeCode { get; set; }
public string photo { get; set; }
public DateTime udateTime { get; set; }
public DateTime createTime { get; set; }
public List<FingerInfo> fingerList { get; set; }
}
public class FingerInfo
{
public int fingerNum { get; set; }
public string fingerInfo { get; set; }
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LiteChannel.Models
{
public class upload_info
{
public string orgId { get; set; }
public string warehouseId { get; set; }
/// <summary>
/// "当前出入库状态",//0出库,1入库
/// </summary>
public string currentState { get; set; }
public string policeId { get; set; } = string.Empty;
public string picUrl { get; set; }
public List<rfid_info> RFIDList { get; set; }
}
public class rfid_info
{
public string RFID { get; set; }
}
}
<pu:WindowX x:Class="LiteChannel.OrderInfoWindows"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:pu="clr-namespace:Panuon.UI.Silver;assembly=Panuon.UI.Silver"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:LiteChannel"
mc:Ignorable="d" Icon="1.ico"
Height="720" Width="1024" ResizeMode="NoResize" WindowState="Maximized"
FontSize="24" Title="单据明细" Loaded="OnWindow_Loaded" WindowStartupLocation="CenterScreen">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="*"/>
<RowDefinition Height="50"/>
</Grid.RowDefinitions>
<DataGrid Grid.Row="0" FontSize="24" ColumnHeaderHeight="60" RowHeight="60" pu:DataGridHelper.ColumnHorizontalContentAlignment="Center" x:Name="dg_detail" HorizontalAlignment="Stretch" BorderThickness="0,0,0,0" VerticalAlignment="Stretch" pu:DataGridHelper.SelectedBackground="#44B5B5B5" pu:DataGridHelper.HoverBackground="#22B5B5B5" CanUserAddRows="False" >
<DataGrid.Columns>
<DataGridTextColumn IsReadOnly="True" Header="装备名称" Binding="{Binding equName}" Width="*" ></DataGridTextColumn>
<DataGridTextColumn IsReadOnly="True" Header="申请数量" Binding="{Binding equCount}" Width="150"></DataGridTextColumn>
<DataGridTextColumn IsReadOnly="True" Header="已出库数量" Binding="{Binding equUsed}" Width="150"></DataGridTextColumn>
</DataGrid.Columns>
</DataGrid>
<Button x:Name="bt_CloseOrder" Visibility="Collapsed" Grid.Row="1" Click="OnCloseOrder_Click" pu:ButtonHelper.Icon="&#xf2d3;" Margin="0,0,0,0" Content="中止单据" FontFamily="{StaticResource FontAwesome}" FontSize="18" Background="#C8FF0000" pu:ButtonHelper.HoverBrush="#FF0000" ></Button>
</Grid>
</pu:WindowX>
using LiteChannel.Commons;
using Panuon.UI.Silver;
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.Markup;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
namespace LiteChannel
{
/// <summary>
/// OrderInfoWindows.xaml 的交互逻辑
/// </summary>
public partial class OrderInfoWindows : WindowX, IComponentConnector
{
private string id = string.Empty;
private string type = string.Empty;
public event Action OnApplySuc;
public OrderInfoWindows(string id, string type)
{
InitializeComponent();
this.id = id;
this.type = type;
this.Title = type + "明细";
dg_detail.AutoGenerateColumns = false;
if (type == "借用" || type == "库存调拨" || type == "销毁")
{
bt_CloseOrder.Visibility = Visibility.Visible;
}
}
private void OnWindow_Loaded(object sender, RoutedEventArgs e)
{
dg_detail.ItemsSource = HttpHelper.GetOrderDetails(id, type);
}
private void OnCloseOrder_Click(object sender, RoutedEventArgs e)
{
if (MessageBox.Show("是否关闭此单据?此操作不可撤销", "警告", MessageBoxButton.YesNo, MessageBoxImage.Warning) == MessageBoxResult.Yes)
{
var orderType = "";
if (type == "借用")
{
orderType = "Borrow";
}
if (type == "库存调拨")
{
orderType = "Transfer";
}
if (type == "销毁")
{
orderType = "Destruction";
}
if (HttpHelper.CloseOrder(id, orderType))
{
MessageBox.Show("关闭成功");
OnApplySuc?.Invoke();
this.Close();
}
else
{
MessageBox.Show("关闭失败");
}
}
}
}
}
<?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
<pu:WindowX x:Class="LiteChannel.QuickCreateOrderWindow"
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:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:LiteChannel"
mc:Ignorable="d" Icon="1.ico"
Height="720" Width="1024" ResizeMode="NoResize" WindowState="Maximized"
Title="快捷创建单据" FontSize="24" WindowStartupLocation="CenterScreen"
Loaded="OnWindow_Loaded" Closing="OnWindow_Closing">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="*"></RowDefinition>
<RowDefinition Height="0"></RowDefinition>
<RowDefinition Height="50"></RowDefinition>
</Grid.RowDefinitions>
<DataGrid FontSize="24" ColumnHeaderHeight="60" RowHeight="60" Grid.Row="0" Grid.ColumnSpan="2" x:Name="dg_epc" HorizontalAlignment="Stretch" BorderThickness="0,0,0,1" VerticalAlignment="Stretch" pu:DataGridHelper.SelectedBackground="#44B5B5B5" pu:DataGridHelper.HoverBackground="#22B5B5B5" CanUserAddRows="False" >
<DataGrid.Columns>
<DataGridTextColumn IsReadOnly="True" Header="装备名称" Binding="{Binding equName}" Width="*"></DataGridTextColumn>
<DataGridTextColumn IsReadOnly="True" Header="装备数量" Binding="{Binding equCount,UpdateSourceTrigger=PropertyChanged,Mode=TwoWay}" Width="150"></DataGridTextColumn>
<DataGridTemplateColumn Header="操作" Width="150" IsReadOnly="True">
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal" VerticalAlignment="Center" HorizontalAlignment="Center">
<Button Content="编辑" FontSize="24" pu:ButtonHelper.CornerRadius="5" Click="EditItem_Click" Padding="4" Margin="0,5,2,5" >
</Button>
<Button Content="删除" FontSize="24" pu:ButtonHelper.CornerRadius="5" Click="DeleteItem_Click" Padding="4" Margin="2,5,0,5" >
</Button>
</StackPanel>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
<ComboBox Name="cbo_type" FontSize="24" Grid.Row="2" Grid.Column="0" pu:ComboBoxHelper.Watermark="单据类型" Height="40" Width="100" Margin="5,0,5,0" HorizontalAlignment="Left" SelectionChanged="cbo_type_SelectionChanged">
<ComboBoxItem FontSize="24">借用</ComboBoxItem>
<ComboBoxItem FontSize="24">领用</ComboBoxItem>
</ComboBox>
<ComboBox Grid.Row="2" Grid.Column="0" x:Name="cbo_police" FontSize="24"
Width="200" Height="40" Margin="110,0,5,0"
HorizontalAlignment="Left" VerticalAlignment="Center"
pu:ComboBoxHelper.HoverBackground="#1EB5B5B5"
pu:ComboBoxHelper.SelectedBackground="#32B5B5B5"
pu:ComboBoxHelper.Watermark="请选择警员" PreviewMouseDown="cbo_police_MouseDown"></ComboBox>
<CheckBox x:Name="cb_bindCabinet" Grid.Row="2" Grid.Column="0" Width="150" Margin="315,0,5,0" HorizontalAlignment="Left" FontSize="24">放入单警柜</CheckBox>
<Button pu:ButtonHelper.CornerRadius="4" Grid.Row="2" Grid.ColumnSpan="2" HorizontalAlignment="Right" Background="Red" pu:ButtonHelper.HoverBrush="Red" Width="120" Height="35" Margin="0,0,270,0" Click="AddInv_Click" FontSize="24">添加装备</Button>
<Button pu:ButtonHelper.CornerRadius="4" Grid.Row="2" Grid.ColumnSpan="2" HorizontalAlignment="Right" Width="120" Height="35" Margin="0,0,140,0" Click="OnSave_Click" FontSize="24">创建单据</Button>
<Button pu:ButtonHelper.CornerRadius="4" Grid.Row="2" Grid.ColumnSpan="2" HorizontalAlignment="Right" Background="#C8FF7F00" Click="OnExit_Click" pu:ButtonHelper.HoverBrush="#FF7F00" Width="120" Height="35" Margin="0,0,10,0" FontSize="24">返回</Button>
</Grid>
</pu:WindowX>
using JmpRfidLp;
using LiteChannel.Commons;
using LiteChannel.Models;
using Panuon.UI.Silver;
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.Markup;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Windows.Threading;
using Panuon.UI.Silver.Core;
namespace LiteChannel
{
/// <summary>
/// StoreWindow.xaml 的交互逻辑
/// </summary>
public partial class QuickCreateOrderWindow : WindowX, IComponentConnector
{
private ObservableCollection<scan_info> RefreshSourcesList = new ObservableCollection<scan_info>();
private List<sync_police> PoliceList { get; set; }
private sync_police police = null;
public QuickCreateOrderWindow()
{
InitializeComponent();
dg_epc.AutoGenerateColumns = false;
}
private void OnWindow_Loaded(object sender, RoutedEventArgs e)
{
PoliceList = HttpHelper.GetPoliceInfo();
cbo_police.ItemsSource = PoliceList;
cbo_police.DisplayMemberPath = "name";
cbo_police.SelectedValuePath = "id";
cbo_police.SelectedIndex = -1;
cbo_type.SelectedIndex = 0;
cb_bindCabinet.Visibility = Visibility.Hidden;
dg_epc.ItemsSource = RefreshSourcesList;
}
private void OnExit_Click(object sender, RoutedEventArgs e)
{
this.Close();
}
private void OnWindow_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
}
private void OnSave_Click(object sender, RoutedEventArgs e)
{
//上报数据
if (police == null)
{
MessageBox.Show("未选择警员");
return;
}
if (RefreshSourcesList.Count == 0)
{
MessageBox.Show("未选择装备");
return;
}
if (cbo_type.SelectedIndex == 0)
{
//借用
if (HttpHelper.CreateBorrowJYOrder(police.id, RefreshSourcesList.ToList(), out string msg))
{
MessageBox.Show("借用单创建成功");
this.Close();
}
else
{
MessageBox.Show(msg);
return;
}
}
else
{
//领用
if (HttpHelper.CreateBorrowLYOrder(police.id, RefreshSourcesList.ToList(), cb_bindCabinet.IsChecked == true, out string msg))
{
MessageBox.Show("领用单创建成功");
this.Close();
}
else
{
MessageBox.Show(msg);
return;
}
}
}
private void AddInv_Click(object sender, RoutedEventArgs e)
{
var from = new AddInvWindow(RefreshSourcesList);
from.Owner = this;
from.ShowDialog();
RefreshSourcesList = new ObservableCollection<scan_info>(RefreshSourcesList);
dg_epc.ItemsSource = RefreshSourcesList;
}
private void EditItem_Click(object sender, RoutedEventArgs e)
{
if (dg_epc.SelectedItem != null)
{
var item = dg_epc.SelectedItem as scan_info;
var from = new AddInvWindow(RefreshSourcesList, new inventory_info
{
detailCount = item.equCount,
equipmentDetailId = item.equCode,
equipmentDetailName = item.equName
});
from.Owner = this;
from.ShowDialog();
RefreshSourcesList = new ObservableCollection<scan_info>(RefreshSourcesList);
dg_epc.ItemsSource = RefreshSourcesList;
}
}
private void DeleteItem_Click(object sender, RoutedEventArgs e)
{
if (dg_epc.SelectedItem != null)
{
var item = dg_epc.SelectedItem as scan_info;
RefreshSourcesList.Remove(item);
RefreshSourcesList = new ObservableCollection<scan_info>(RefreshSourcesList);
dg_epc.ItemsSource = RefreshSourcesList;
}
}
private void cbo_police_MouseDown(object sender, MouseButtonEventArgs e)
{
cbo_police.IsDropDownOpen = false;
var select = new SelectPoliceWindow(PoliceList);
select.ShowDialog();
police = select.police;
if (police != null)
{
cbo_police.SelectedItem = police;
}
}
private void cbo_type_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (cbo_type.SelectedIndex == 1)
{
cb_bindCabinet.Visibility = Visibility.Visible;
}
else
{
cb_bindCabinet.Visibility = Visibility.Hidden;
}
}
}
}
<pu:WindowX x:Class="LiteChannel.SelectInvWindow"
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:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:LiteChannel"
mc:Ignorable="d" Icon="1.ico"
Title="选择装备" Height="350" Width="600" WindowState="Normal" FontSize="24"
WindowStartupLocation="CenterScreen"
ResizeMode="NoResize" Loaded="OnWindow_Loaded" >
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="0"></RowDefinition>
<RowDefinition Height="50"></RowDefinition>
<RowDefinition Height="*"></RowDefinition>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Grid Grid.Row="1" Margin="0,0,0,0" >
<Grid.ColumnDefinitions>
<ColumnDefinition Width="10"/>
<ColumnDefinition Width="50"/>
<ColumnDefinition Width="430"/>
<ColumnDefinition Width="20"/>
<ColumnDefinition Width="100"/>
</Grid.ColumnDefinitions>
<StackPanel Grid.Column="1" Orientation="Horizontal" Grid.ColumnSpan="2">
<TextBlock Text="装备名称:" FontSize="24" HorizontalAlignment="Center" VerticalAlignment="Center"/>
<TextBox Margin="0,1,0,0" x:Name="txt_vendor" FontSize="24" Focusable="True" Text="{Binding VendorName,UpdateSourceTrigger=PropertyChanged}" VerticalAlignment="Center" Width="360" Background="White" />
</StackPanel>
<StackPanel Grid.Column="4" Orientation="Horizontal">
<Button Content="查询" FontSize="24" Click="OnQueryClick" VerticalAlignment="Center" Margin="0,1,0,0" Width="70" HorizontalAlignment="Left" />
</StackPanel>
</Grid>
<DataGrid EnableRowVirtualization="False" x:Name="g_vender" Margin="3 5 3 20" Grid.Row="2" 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="FontSize" Value="24"/>
<Setter Property="Height" Value="30"/>
</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="24" Binding="{Binding equipmentDetailName}" ElementStyle="{StaticResource TextCenterStyle}"/>
<DataGridTextColumn Header="在库数量" IsReadOnly="True" Width="100" FontSize="24" Binding="{Binding detailCount}" ElementStyle="{StaticResource TextCenterStyle}"/>
<DataGridTemplateColumn Header="操作" Width="100" >
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal" VerticalAlignment="Center" HorizontalAlignment="Center">
<Button Content="选择" Click="OnSelectItemClick" Width="70" Height="35" FontSize="24" Margin="5,0,5,0" pu:ButtonHelper.CornerRadius="4" >
</Button>
</StackPanel>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
</Grid>
</pu:WindowX>
using LiteChannel.Commons;
using JmpRfidLp;
using LiteChannel.Commons;
using LiteChannel.Models;
using Panuon.UI.Silver;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.ComponentModel;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
......@@ -22,59 +20,44 @@ using System.Windows.Markup;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using GalaSoft.MvvmLight.CommandWpf;
using System.ComponentModel;
using System.Windows.Threading;
using Panuon.UI.Silver.Core;
namespace LiteChannel
{
/// <summary>
/// Window1.xaml 的交互逻辑
/// StoreWindow.xaml 的交互逻辑
/// </summary>
public partial class OutWindow : WindowX, IComponentConnector
public partial class SelectInvWindow : WindowX, IComponentConnector
{
public OutWindow()
private List<inventory_info> InventoryList { get; set; }
public inventory_info inventory = null;
public SelectInvWindow(List<inventory_info> inventoryList)
{
InitializeComponent();
InventoryList = inventoryList;
}
private void MainWindowLoaded(object sender, RoutedEventArgs e)
private void OnWindow_Loaded(object sender, RoutedEventArgs e)
{
g_vender.ItemsSource = InventoryList;
}
private void OnOutStoreNoOrder_Click(object sender, RoutedEventArgs e)
private void OnQueryClick(object sender, RoutedEventArgs e)
{
var from = new StoreOutWindow("", "NoOrder", null);
from.Owner = this;
from.ShowDialog();
}
private void OnOutStoreJY_Click(object sender, RoutedEventArgs e)
if (string.IsNullOrEmpty(txt_vendor.Text))
{
var from = new MainWindow2("借用");
from.Owner = this;
from.ShowDialog();
g_vender.ItemsSource = InventoryList;
}
private void OnOutStoreLY_Click(object sender, RoutedEventArgs e)
else
{
var from = new MainWindow2("领用");
from.Owner = this;
from.ShowDialog();
g_vender.ItemsSource = InventoryList?.Where(t => t.equipmentDetailName.Contains(txt_vendor.Text));
}
private void OnOutStoreDB_Click(object sender, RoutedEventArgs e)
{
var from = new MainWindow2("调拨");
from.Owner = this;
from.ShowDialog();
}
private void OnOutStoreKK_Click(object sender, RoutedEventArgs e)
{
var from = new MainWindow2("跨库");
from.Owner = this;
from.ShowDialog();
}
private void OnClose_Click(object sender, RoutedEventArgs e)
private void OnSelectItemClick(object sender, RoutedEventArgs e)
{
inventory = g_vender.SelectedValue as inventory_info;
this.Close();
}
}
......
<pu:WindowX x:Class="LiteChannel.SelectPoliceWindow"
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:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:LiteChannel"
mc:Ignorable="d" Icon="1.ico"
Title="选择警员" Height="350" Width="600" WindowState="Normal" FontSize="24"
WindowStartupLocation="CenterScreen"
ResizeMode="NoResize" Loaded="OnWindow_Loaded" >
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="0"></RowDefinition>
<RowDefinition Height="50"></RowDefinition>
<RowDefinition Height="*"></RowDefinition>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Grid Grid.Row="1" Margin="0,0,0,0" >
<Grid.ColumnDefinitions>
<ColumnDefinition Width="10"/>
<ColumnDefinition Width="50"/>
<ColumnDefinition Width="430"/>
<ColumnDefinition Width="20"/>
<ColumnDefinition Width="100"/>
</Grid.ColumnDefinitions>
<StackPanel Grid.Column="1" Orientation="Horizontal" Grid.ColumnSpan="2">
<TextBlock Text="姓名:" FontSize="24" HorizontalAlignment="Center" VerticalAlignment="Center"/>
<TextBox Margin="0,1,0,0" x:Name="txt_vendor" FontSize="24" Focusable="True" Text="{Binding VendorName,UpdateSourceTrigger=PropertyChanged}" VerticalAlignment="Center" Width="360" Background="White" />
</StackPanel>
<StackPanel Grid.Column="4" Orientation="Horizontal">
<Button Content="查询" FontSize="24" Click="OnQueryClick" VerticalAlignment="Center" Margin="0,1,0,0" Width="70" HorizontalAlignment="Left" />
</StackPanel>
</Grid>
<DataGrid EnableRowVirtualization="False" x:Name="g_vender" Margin="3 5 3 20" Grid.Row="2" 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="FontSize" Value="24"/>
<Setter Property="Height" Value="30"/>
</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="24" Binding="{Binding name}" ElementStyle="{StaticResource TextCenterStyle}"/>
<DataGridTextColumn Header="警号" IsReadOnly="True" Width="150" FontSize="24" Binding="{Binding policeCode}" ElementStyle="{StaticResource TextCenterStyle}"/>
<DataGridTemplateColumn Header="操作" Width="100" >
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<StackPanel Orientation="Horizontal" VerticalAlignment="Center" HorizontalAlignment="Center">
<Button Content="选择" Click="OnSelectItemClick" Width="70" Height="35" FontSize="24" Margin="5,0,5,0" pu:ButtonHelper.CornerRadius="4" >
</Button>
</StackPanel>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
</Grid>
</pu:WindowX>
using LiteChannel.Models;
using Panuon.UI.Silver;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using System.Windows.Markup;
namespace LiteChannel
{
/// <summary>
/// StoreWindow.xaml 的交互逻辑
/// </summary>
public partial class SelectPoliceWindow : WindowX, IComponentConnector
{
private List<sync_police> PoliceList { get; set; }
public sync_police police = null;
public SelectPoliceWindow(List<sync_police> policeList)
{
InitializeComponent();
PoliceList = policeList;
}
private void OnWindow_Loaded(object sender, RoutedEventArgs e)
{
g_vender.ItemsSource = PoliceList;
}
private void OnQueryClick(object sender, RoutedEventArgs e)
{
if (string.IsNullOrEmpty(txt_vendor.Text))
{
g_vender.ItemsSource = PoliceList;
}
else
{
g_vender.ItemsSource = PoliceList?.Where(t => t.name.Contains(txt_vendor.Text));
}
}
private void OnSelectItemClick(object sender, RoutedEventArgs e)
{
police = g_vender.SelectedValue as sync_police;
this.Close();
}
}
}
<pu:WindowX x:Class="LiteChannel.Setting"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:pu="clr-namespace:Panuon.UI.Silver;assembly=Panuon.UI.Silver"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:LiteChannel"
mc:Ignorable="d"
Title="系统配置" Height="500" Loaded="OnWindow_Loaded" Width="800" Icon="1.ico" ResizeMode="NoResize" WindowStartupLocation="CenterScreen">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="40"/>
<RowDefinition Height="40"/>
<RowDefinition Height="40"/>
<RowDefinition Height="40"/>
<RowDefinition Height="40"/>
<RowDefinition Height="40"/>
<RowDefinition Height="40"/>
<RowDefinition Height="40"/>
<RowDefinition Height="40"/>
<RowDefinition Height="40"/>
<RowDefinition Height="10"/>
<RowDefinition Height="40"/>
<RowDefinition Height="40"/>
</Grid.RowDefinitions>
<Grid.ColumnDefinitions>
<ColumnDefinition Width="10"/>
<ColumnDefinition Width="100"/>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="100"/>
<ColumnDefinition Width="*"/>
<ColumnDefinition Width="10"/>
</Grid.ColumnDefinitions>
<TextBlock Grid.Row="0" Grid.Column="1" Text="软件版本:" HorizontalAlignment="Right" VerticalAlignment="Center"/>
<TextBox Grid.Row="0" Grid.Column="2" Name="txt_ver" Width="auto" Height="25" HorizontalAlignment="Stretch" VerticalAlignment="Center"/>
<TextBlock Grid.Row="0" Grid.Column="3" Text="软件编码:" HorizontalAlignment="Right" VerticalAlignment="Center"/>
<TextBox Grid.Row="0" Grid.Column="4" Name="txt_code" Width="auto" Height="25" HorizontalAlignment="Stretch" VerticalAlignment="Center"/>
<TextBlock Grid.Row="1" Grid.Column="1" Text="接口域名:" HorizontalAlignment="Right" VerticalAlignment="Center"/>
<TextBox Grid.Row="1" Grid.Column="2" x:Name="txt_domain" Width="auto" Height="25" HorizontalAlignment="Stretch" VerticalAlignment="Center"/>
<TextBlock Grid.Row="1" Grid.Column="3" Text="登录接口:" HorizontalAlignment="Right" VerticalAlignment="Center"/>
<TextBox Grid.Row="1" Grid.Column="4" x:Name="txt_login" Width="auto" Height="25" HorizontalAlignment="Stretch" VerticalAlignment="Center"/>
<TextBlock Grid.Row="2" Grid.Column="1" Text="程序标题:" HorizontalAlignment="Right" VerticalAlignment="Center"/>
<TextBox Grid.Row="2" Grid.Column="2" x:Name="txt_title" Width="auto" Height="25" HorizontalAlignment="Stretch" VerticalAlignment="Center"/>
<TextBlock Grid.Row="3" Grid.Column="1" Text="门禁地址:" HorizontalAlignment="Right" VerticalAlignment="Center"/>
<TextBox Grid.Row="3" Grid.Column="2" x:Name="txt_ip" Width="auto" Height="25" HorizontalAlignment="Stretch" VerticalAlignment="Center"/>
<TextBlock Grid.Row="3" Grid.Column="3" Text="门禁端口:" HorizontalAlignment="Right" VerticalAlignment="Center"/>
<TextBox Grid.Row="3" Grid.Column="4" x:Name="txt_port" Width="auto" Height="25" HorizontalAlignment="Stretch" VerticalAlignment="Center"/>
<TextBlock Grid.Row="4" Grid.Column="1" Text="门禁用户:" HorizontalAlignment="Right" VerticalAlignment="Center"/>
<TextBox Grid.Row="4" Grid.Column="2" x:Name="txt_user" Width="auto" Height="25" HorizontalAlignment="Stretch" VerticalAlignment="Center"/>
<TextBlock Grid.Row="4" Grid.Column="3" Text="门禁密码:" HorizontalAlignment="Right" VerticalAlignment="Center"/>
<TextBox Grid.Row="4" Grid.Column="4" x:Name="txt_pwd" Width="auto" Height="25" HorizontalAlignment="Stretch" VerticalAlignment="Center"/>
<TextBlock Grid.Row="5" Grid.Column="1" Text="门禁状态:" HorizontalAlignment="Right" VerticalAlignment="Center"/>
<ComboBox Grid.Row="5" Grid.Column="2" x:Name="cbo_state" Width="auto" Height="25"
HorizontalAlignment="Stretch" VerticalAlignment="Center"
pu:ComboBoxHelper.HoverBackground="#1EB5B5B5"
pu:ComboBoxHelper.SelectedBackground="#32B5B5B5"
pu:ComboBoxHelper.IsSearchTextBoxVisible="False">
<ComboBoxItem>启用</ComboBoxItem>
<ComboBoxItem>禁用</ComboBoxItem>
</ComboBox>
<TextBlock Grid.Row="6" Grid.Column="1" Text="启用智能货架:" HorizontalAlignment="Right" VerticalAlignment="Center"/>
<ComboBox Grid.Row="6" Grid.Column="2" x:Name="cbo_shelf" Width="auto" Height="25"
HorizontalAlignment="Stretch" VerticalAlignment="Center"
pu:ComboBoxHelper.HoverBackground="#1EB5B5B5"
pu:ComboBoxHelper.SelectedBackground="#32B5B5B5"
pu:ComboBoxHelper.IsSearchTextBoxVisible="False">
<ComboBoxItem>启用</ComboBoxItem>
<ComboBoxItem>禁用</ComboBoxItem>
</ComboBox>
<TextBlock Grid.Row="6" Grid.Column="3" Text="智能货架地址:" HorizontalAlignment="Right" VerticalAlignment="Center"/>
<TextBox Grid.Row="6" Grid.Column="4" x:Name="txt_shelf" Width="auto" Height="25" HorizontalAlignment="Stretch" VerticalAlignment="Center"/>
<TextBlock Grid.Row="7" Grid.Column="1" Text="AppKey:" HorizontalAlignment="Right" VerticalAlignment="Center"/>
<TextBox Grid.Row="7" Grid.Column="2" x:Name="txt_appkey" Width="auto" Height="25" HorizontalAlignment="Stretch" VerticalAlignment="Center"/>
<TextBlock Grid.Row="7" Grid.Column="3" Text="SecretKey:" HorizontalAlignment="Right" VerticalAlignment="Center"/>
<TextBox Grid.Row="7" Grid.Column="4" x:Name="txt_secretkey" Width="auto" Height="25" HorizontalAlignment="Stretch" VerticalAlignment="Center"/>
<TextBlock Grid.Row="8" Grid.Column="1" Text="自动更新:" HorizontalAlignment="Right" VerticalAlignment="Center"/>
<CheckBox Grid.Row="8" Grid.Column="2" x:Name="cb_autoUpdate" Width="auto" Height="25" HorizontalAlignment="Left" VerticalAlignment="Center" Margin="8,8,0,8" Click="cb_autoUpdate_Click">启用自动更新,检查时间:</CheckBox>
<ComboBox Grid.Row="8" Grid.Column="2" x:Name="cbb_autoUpdate" Width="auto" Height="25" HorizontalAlignment="Stretch" VerticalAlignment="Center" Margin="188,0,0,0"
pu:ComboBoxHelper.HoverBackground="#1EB5B5B5"
pu:ComboBoxHelper.SelectedBackground="#32B5B5B5"
pu:ComboBoxHelper.IsSearchTextBoxVisible="False">
<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="9" Grid.Column="1" Text="读写器类型:" HorizontalAlignment="Right" VerticalAlignment="Center"/>
<ComboBox Grid.Row="9" Grid.Column="2" x:Name="cbo_readerType" Width="auto" Height="25"
HorizontalAlignment="Stretch" VerticalAlignment="Center"
pu:ComboBoxHelper.HoverBackground="#1EB5B5B5"
pu:ComboBoxHelper.SelectedBackground="#32B5B5B5"
pu:ComboBoxHelper.IsSearchTextBoxVisible="False" SelectionChanged="cbo_readerType_SelectionChanged">
<ComboBoxItem>钧普</ComboBoxItem>
<ComboBoxItem>索力得</ComboBoxItem>
</ComboBox>
<TextBlock Grid.Row="9" Grid.Column="3" x:Name="tb_com" Text="串口编号:" HorizontalAlignment="Right" VerticalAlignment="Center"/>
<ComboBox Grid.Row="9" Grid.Column="4" x:Name="cbo_com" Width="auto" Height="25" HorizontalAlignment="Stretch" VerticalAlignment="Center"/>
<Button Grid.Row="11" Grid.ColumnSpan="6" Click="OnSave_Click" HorizontalAlignment="Right" Width="90" Margin="0,0,110,0">保存配置</Button>
<!--<Button Grid.Row="14" Grid.ColumnSpan="6" Click="OnRefresh_Click" HorizontalAlignment="Right" Width="90" Margin="0,0,110,0">刷新仓库</Button>-->
<Button Grid.Row="11" Grid.ColumnSpan="6" Click="OnCancel_Click" HorizontalAlignment="Right" Background="#C8FF7F00" pu:ButtonHelper.HoverBrush="#FF7F00" Width="90" Margin="0,0,10,0">关闭</Button>
</Grid>
</pu:WindowX>
using LiteChannel.Commons;
using LiteChannel.Models;
using Panuon.UI.Silver;
using RJCP.IO.Ports;
using System;
using System.Collections.Generic;
using System.IO.Ports;
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.Markup;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
namespace LiteChannel
{
/// <summary>
/// Setting.xaml 的交互逻辑
/// </summary>
public partial class Setting : WindowX, IComponentConnector
{
private bool IsLoaded = false;
private List<store_info> StoreList { get; set; }
public Setting()
{
InitializeComponent();
}
private void OnSave_Click(object sender, RoutedEventArgs e)
{
//int.TryParse(txt_ver.Text, out int ver);
LiteCaChe.SysConfig.UserLogin = txt_login.Text;
LiteCaChe.SysConfig.AppCode = txt_code.Text;
LiteCaChe.SysConfig.DomainUrl = txt_domain.Text;
//LiteCaChe.SysConfig.AppTitle = txt_title.Text;
//LiteCaChe.SysConfig.AppVersion = ver;
//LiteCaChe.SysConfig.WarehouseID = cbo_warehouse.SelectedValue?.ToString() ?? "";
LiteCaChe.SysConfig.FaceAddress = txt_ip.Text;
LiteCaChe.SysConfig.FacePort = txt_port.Text;
LiteCaChe.SysConfig.FaceUser = txt_user.Text;
LiteCaChe.SysConfig.FacePwd = txt_pwd.Text;
LiteCaChe.SysConfig.IsUseFace = cbo_state.Text == "启用" ? true : false;
LiteCaChe.SysConfig.AppKey = txt_appkey.Text;
LiteCaChe.SysConfig.SecretKey = txt_secretkey.Text;
LiteCaChe.SysConfig.IsEnabledShelf = cbo_shelf.Text == "启用";
LiteCaChe.SysConfig.ShelfAddress = txt_shelf.Text;
LiteCaChe.SysConfig.IsAutoUpdate = cb_autoUpdate.IsChecked == true;
LiteCaChe.SysConfig.AutoUpdateTime = cbb_autoUpdate.SelectedIndex;
LiteCaChe.SysConfig.ReaderType = cbo_readerType.SelectedIndex;
if (LiteCaChe.SysConfig.ReaderType == 0)
{
LiteCaChe.SysConfig.ComMouth = cbo_com.Text;
}
LiteCaChe.SaveSystemStep(LiteCaChe.SysConfig);
MessageBox.Show("配置保存成功!", "提示", MessageBoxButton.OK, MessageBoxImage.Information);
this.Close();
}
private void OnCancel_Click(object sender, RoutedEventArgs e)
{
this.Close();
}
//private void OnRefresh_Click(object sender, RoutedEventArgs e)
//{
// StoreList = HttpHelper.GetStoreInfos();
// cbo_warehouse.ItemsSource = StoreList;
//}
private void OnWindow_Loaded(object sender, RoutedEventArgs e)
{
cbo_com.ItemsSource = SerialPortStream.GetPortNames();
//StoreList = HttpHelper.GetStoreInfos();
//cbo_warehouse.ItemsSource = StoreList;
//cbo_warehouse.DisplayMemberPath = "name";
//cbo_warehouse.SelectedValuePath = "id";
txt_login.Text = LiteCaChe.SysConfig.UserLogin;
txt_code.Text = LiteCaChe.SysConfig.AppCode;
txt_domain.Text = LiteCaChe.SysConfig.DomainUrl;
txt_title.Text = LiteCaChe.SysConfig.AppTitle;
txt_ver.Text = LiteCaChe.SysConfig.AppVersion.ToString();
//cbo_warehouse.SelectedValue = LiteCaChe.SysConfig.WarehouseID;
txt_ip.Text = LiteCaChe.SysConfig.FaceAddress;
txt_port.Text = LiteCaChe.SysConfig.FacePort;
txt_user.Text = LiteCaChe.SysConfig.FaceUser;
txt_pwd.Text = LiteCaChe.SysConfig.FacePwd;
cbo_state.SelectedIndex = LiteCaChe.SysConfig.IsUseFace ? 0 : 1;
txt_appkey.Text = LiteCaChe.SysConfig.AppKey;
txt_secretkey.Text = LiteCaChe.SysConfig.SecretKey;
cbo_shelf.SelectedIndex = LiteCaChe.SysConfig.IsEnabledShelf ? 0 : 1;
txt_shelf.Text = LiteCaChe.SysConfig.ShelfAddress;
cb_autoUpdate.IsChecked = LiteCaChe.SysConfig.IsAutoUpdate;
if (cb_autoUpdate.IsChecked == true)
{
cbb_autoUpdate.IsEnabled = true;
}
else
{
cbb_autoUpdate.IsEnabled = false;
}
cbb_autoUpdate.SelectedIndex = LiteCaChe.SysConfig.AutoUpdateTime;
IsLoaded = true;
cbo_readerType.SelectedIndex = LiteCaChe.SysConfig.ReaderType;
if (LiteCaChe.SysConfig.ReaderType == 0)
{
tb_com.Visibility = Visibility.Visible;
cbo_com.Visibility = Visibility.Visible;
cbo_com.Text = LiteCaChe.SysConfig.ComMouth;
}
else
{
tb_com.Visibility = Visibility.Hidden;
cbo_com.Visibility = Visibility.Hidden;
}
}
//private void cbo_warehouse_SearchTextChanged(object sender, Panuon.UI.Silver.Core.SearchTextChangedEventArgs e)
//{
// if (!IsLoaded)
// return;
// cbo_warehouse.ItemsSource = StoreList.Where(t => t.name.Contains(e.Text));
//}
private void OnSldCornerRadius_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)
{
if (!IsLoaded)
return;
}
private void cb_autoUpdate_Click(object sender, RoutedEventArgs e)
{
if (cb_autoUpdate.IsChecked == true)
{
cbb_autoUpdate.IsEnabled = true;
}
else
{
cbb_autoUpdate.IsEnabled = false;
}
}
private void cbo_readerType_SelectionChanged(object sender, SelectionChangedEventArgs e)
{
if (cbo_readerType.SelectedIndex == 0)
{
tb_com.Visibility = Visibility.Visible;
cbo_com.Visibility = Visibility.Visible;
cbo_com.Text = LiteCaChe.SysConfig.ComMouth;
}
else
{
tb_com.Visibility = Visibility.Hidden;
cbo_com.Visibility = Visibility.Hidden;
}
}
}
}
<pu:WindowX x:Class="LiteChannel.StoreInWindow"
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:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:LiteChannel"
mc:Ignorable="d" Icon="1.ico"
Height="720" Width="1024" ResizeMode="NoResize" WindowState="Maximized"
Title="盘点入库" FontSize="24" WindowStartupLocation="CenterScreen"
Loaded="OnWindow_Loaded" Closing="OnWindow_Closing">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="*"></RowDefinition>
<RowDefinition Height="0"></RowDefinition>
<RowDefinition Height="50"></RowDefinition>
</Grid.RowDefinitions>
<DataGrid FontSize="24" ColumnHeaderHeight="60" RowHeight="60" Grid.Row="0" Grid.ColumnSpan="2" x:Name="dg_epc" HorizontalAlignment="Stretch" BorderThickness="0,0,0,1" VerticalAlignment="Stretch" pu:DataGridHelper.SelectedBackground="#44B5B5B5" pu:DataGridHelper.HoverBackground="#22B5B5B5" CanUserAddRows="False" >
<DataGrid.Columns>
<DataGridTextColumn IsReadOnly="True" Header="装备名称" Binding="{Binding equName}" Width="*"></DataGridTextColumn>
<DataGridTextColumn IsReadOnly="True" Header="识别数量" Binding="{Binding scanQty,UpdateSourceTrigger=PropertyChanged,Mode=TwoWay}" Width="150"></DataGridTextColumn>
</DataGrid.Columns>
</DataGrid>
<!--<ComboBox Name="cbo_type" Grid.Row="1" Grid.Column="1" pu:ComboBoxHelper.Watermark="请选择入库类型..." Height="40" Margin="5,0,5,0">
<ComboBoxItem>采购</ComboBoxItem>
<ComboBoxItem>借用</ComboBoxItem>
<ComboBoxItem>跨库借用</ComboBoxItem>
<ComboBoxItem>库存调拨</ComboBoxItem>
<ComboBoxItem>维修</ComboBoxItem>
<ComboBoxItem>跨库归还</ComboBoxItem>
</ComboBox>-->
<TextBlock Grid.Row="2" Grid.ColumnSpan="2" Margin="0,0,220,0" Foreground="Red" Name="txt_stat" HorizontalAlignment="Left" VerticalAlignment="Center" FontSize="24">状态:读写器启动失败</TextBlock>
<Button pu:ButtonHelper.CornerRadius="4" Grid.Row="2" Grid.ColumnSpan="2" IsEnabled="false" Name="btn_inv" HorizontalAlignment="Right" Click="OnInv_Click" Width="120" Height="35" Margin="0,0,273,0" FontSize="24">开始读取</Button>
<Button pu:ButtonHelper.CornerRadius="4" Grid.Row="2" Grid.ColumnSpan="2" HorizontalAlignment="Right" Width="120" Height="35" Margin="0,0,140,0" Click="OnSave_Click" FontSize="24">提交入库</Button>
<Button pu:ButtonHelper.CornerRadius="4" Grid.Row="2" Grid.ColumnSpan="2" HorizontalAlignment="Right" Background="#C8FF7F00" Click="OnExit_Click" pu:ButtonHelper.HoverBrush="#FF7F00" Width="120" Height="35" Margin="0,0,10,0" FontSize="24">返回</Button>
</Grid>
</pu:WindowX>
using JmpRfidLp;
using LiteChannel.Commons;
using LiteChannel.Models;
using Panuon.UI.Silver;
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.Markup;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Windows.Threading;
using Panuon.UI.Silver.Core;
namespace LiteChannel
{
/// <summary>
/// StoreWindow.xaml 的交互逻辑
/// </summary>
public partial class StoreInWindow : WindowX, IComponentConnector
{
private IReaderHelper reader;
private List<scan_info> SourcesList = new List<scan_info>();
private List<scan_info> BoxMarkList = new List<scan_info>();
private Queue<string> _epcQueue = new Queue<string>();
private CancellationTokenSource tokenSource = new CancellationTokenSource();
private ObservableCollection<scan_info> RefreshSourcesList = new ObservableCollection<scan_info>();
private Dictionary<ulong, string> dic_equ = new Dictionary<ulong, string>();
private List<order_equ> orderWzdm = new List<order_equ>();
public event Action OnApplySuc;
public StoreInWindow()
{
InitializeComponent();
dg_epc.AutoGenerateColumns = false;
}
private void OnWindow_Loaded(object sender, RoutedEventArgs e)
{
ConnectReader();
EpcHandleTask(tokenSource.Token);
}
private bool ConnectReader()
{
try
{ //启动读写器
switch (LiteCaChe.SysConfig.ReaderType)
{
case 0:
{
reader = new JmpRfidLpReaderHelper(LiteCaChe.SysConfig.ComMouth);
break;
}
case 1:
{
reader = new USBRFIDReaderHelper();
break;
}
}
reader.OnInventory += OnRadioInventory;
var state = reader.Open();
if (state)
{
var version = reader.GetFWVerion();
if (string.IsNullOrEmpty(version))
{
txt_stat.Text = "状态:读写器版本读取失败";
txt_stat.Foreground = new SolidColorBrush(Colors.Red);
return false;
}
reader.InventoryStop();
reader.SetPALevel(1);
reader.SetTxPower(0, true, 24);
txt_stat.Text = "状态:读写器连接成功";
txt_stat.Foreground = new SolidColorBrush(Colors.Green);
btn_inv.IsEnabled = true;
return true;
}
else
{
txt_stat.Text = "状态:读写器连接失败";
txt_stat.Foreground = new SolidColorBrush(Colors.Red);
return false;
}
}
catch (Exception ex)
{
reader = null;
txt_stat.Text = "状态:读写器连接失败";
txt_stat.Foreground = new SolidColorBrush(Colors.Red);
return false;
}
}
private void OnRadioInventory(TagInfoData args)
{
if (!BoxMarkList.Any(t => t.epcList.Contains(args.EPC)) &&
args.EPC.Length == 24 && args.EPC.Substring(0, 4) == "5842")
{
//有效标签
lock (_epcQueue)
{
if (!_epcQueue.Contains(args.EPC))
{
_epcQueue.Enqueue(args.EPC);
return;
}
}
}
if (!SourcesList.Any(t => t.epcList.Contains(args.EPC)) &&
!BoxMarkList.Any(t => t.epcList.Contains(args.EPC)) &&
args.EPC.Length == 64)
{
var buffer = EpcConvert.ToHexByte(args.EPC);
var epc_info = EpcConvert.EpcAnlysing(buffer);
if (epc_info != null)
{
var equ_info = LiteCaChe.EquInfos?.FirstOrDefault(t => t.code == epc_info.Wzdm.ToString("X"));
if (equ_info != null)
{
//有效标签
lock (_epcQueue)
{
if (!_epcQueue.Contains(args.EPC))
{
_epcQueue.Enqueue(args.EPC);
}
}
}
}
}
}
private void EpcHandleTask(CancellationToken token)
{
Task.Run(() =>
{
var epcList = new List<string>();
while (true)
{
if (token.IsCancellationRequested)
{
break;
}
lock (_epcQueue)
{
if (_epcQueue.Count != 0)
{
epcList = _epcQueue.ToList();
_epcQueue.Clear();
}
else
{
Thread.Sleep(500);
continue;
}
}
foreach (var epc in epcList)
{
//再次检查是否被阻塞阶段添加标签
if (!SourcesList.Any(t => t.epcList.Contains(epc))
&& !BoxMarkList.Any(t => t.epcList.Contains(epc)))
{
var tempEpc = epc;
if (tempEpc.Length == 24)
{
//旧版箱标epc
var boxMarkInfo = new scan_info()
{
epcList = new List<string>() { tempEpc },
equCode = "",
equName = "",
};
lock (BoxMarkList)
{
BoxMarkList.Add(boxMarkInfo);
}
IPendingHandler handler = null;
Dispatcher.BeginInvoke(DispatcherPriority.Background,
new Action(() =>
{
handler = PendingBox.Show("EPC转换中...", "", false, Application.Current.MainWindow, new PendingBoxConfigurations()
{
LoadingForeground = "#5DBBEC".ToColor().ToBrush(),
MaxWidth = 250,
MinHeight = 110,
MinWidth = 250,
MaxHeight = 110,
ButtonBrush = "#5DBBEC".ToColor().ToBrush(),
});
}));
var xbData = HttpHelper.GetEpcListByBoxMarkEpc(new List<string>() { tempEpc });
Dispatcher.BeginInvoke(DispatcherPriority.Background,
new Action(() =>
{
handler?.Close();
}));
if (xbData == null || xbData.Count == 0)
{
//无效epc,过滤
continue;
}
tempEpc = xbData.First().epc;
}
var buffer = EpcConvert.ToHexByte(tempEpc);
var epc_info = EpcConvert.EpcAnlysing(buffer);
if (epc_info != null)
{
var equ_info = LiteCaChe.EquInfos?.FirstOrDefault(t => t.code == epc_info.Wzdm.ToString("X"));
if (equ_info != null)
{
if (epc_info.TagType == 0x01)
{
//读取到箱标提示
IPendingHandler handler2 = null;
Dispatcher.BeginInvoke(DispatcherPriority.Background,
new Action(() =>
{
handler2 = PendingBox.Show("读取到箱标,箱标解析中...", "", false,
Application.Current.MainWindow, new PendingBoxConfigurations()
{
LoadingForeground = "#5DBBEC".ToColor().ToBrush(),
MaxWidth = 350,
MinHeight = 110,
MinWidth = 350,
MaxHeight = 110,
ButtonBrush = "#5DBBEC".ToColor().ToBrush(),
});
}));
//箱标
var boxMarkInfo = new scan_info()
{
epcList = new List<string>() { tempEpc },
equCode = epc_info.Wzdm.ToString("X"),
equName = equ_info.name,
};
lock (BoxMarkList)
{
BoxMarkList.Add(boxMarkInfo);
}
var xbData = HttpHelper.GetEpcListByBoxMarkEpc(boxMarkInfo.epcList);
if (xbData == null || xbData.Count == 0)
{
//无效epc,过滤
Dispatcher.BeginInvoke(DispatcherPriority.Background,
new Action(() =>
{
handler2.Close();
}));
continue;
}
foreach (var innerEpc in xbData.First().epcList)
{
var tmp_info = SourcesList.FirstOrDefault(t => t.equCode == epc_info.Wzdm.ToString("X"));
if (tmp_info == null)
{
tmp_info = new scan_info()
{
epcList = new List<string>() { innerEpc },
equCode = epc_info.Wzdm.ToString("X"),
equName = equ_info.name,
scanQty = 1
};
lock (SourcesList)
{
SourcesList.Add(tmp_info);
}
}
else
{
tmp_info.scanQty += 1;
tmp_info.epcList.Add(innerEpc);
}
}
Dispatcher.BeginInvoke(DispatcherPriority.Background,
new Action<List<scan_info>>((x) =>
{
RefreshSourcesList = new ObservableCollection<scan_info>(x);
dg_epc.ItemsSource = RefreshSourcesList;
handler2.Close();
}), SourcesList);
}
else
{
var tmp_info = SourcesList.FirstOrDefault(t => t.equCode == epc_info.Wzdm.ToString("X"));
if (tmp_info == null)
{
tmp_info = new scan_info()
{
epcList = new List<string>() { tempEpc },
equCode = epc_info.Wzdm.ToString("X"),
equName = equ_info.name,
scanQty = 1
};
SourcesList.Add(tmp_info);
Dispatcher.BeginInvoke(DispatcherPriority.Background,
new Action<List<scan_info>>((x) =>
{
RefreshSourcesList = new ObservableCollection<scan_info>(x);
dg_epc.ItemsSource = RefreshSourcesList;
}), SourcesList);
}
else
{
tmp_info.scanQty += 1;
tmp_info.epcList.Add(tempEpc);
}
}
}
}
}
}
epcList.Clear();
}
}, token);
}
private void OnInv_Click(object sender, RoutedEventArgs e)
{
if (btn_inv.Content.ToString() == "开始读取")
{
reader?.InventoryStart();
btn_inv.Content = "停止读取";
}
else
{
reader?.InventoryStop();
btn_inv.Content = "开始读取";
}
}
private void OnExit_Click(object sender, RoutedEventArgs e)
{
this.Close();
}
private void OnWindow_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
tokenSource.Cancel();
if (reader?.IsOpen() ?? false)
{
reader?.InventoryStop();
reader?.Close();
}
}
private void OnSave_Click(object sender, RoutedEventArgs e)
{
if (SourcesList != null && SourcesList.Count > 0)
{
List<rfid_info> epcList = new List<rfid_info>();
SourcesList.SelectMany(t => t.epcList).ToList()
.ForEach(s => epcList.Add(new rfid_info()
{
RFID = s
}));
if (epcList.Count > 0)
{
//if (string.IsNullOrEmpty(cbo_type.Text))
//{
// MessageBox.Show(this, "入库类型未选择,请选择后重试!", "出库提示", MessageBoxButton.OK, MessageBoxImage.Information);
//}
//else
{
if (btn_inv.Content.ToString() == "停止读取")
{
OnInv_Click(default, default);
}
var _res = HttpHelper.RfidInStore("", epcList);
MessageBox.Show(this, _res.Item2, "出库提示", MessageBoxButton.OK, MessageBoxImage.Information);
if (_res.Item1)
{
OnApplySuc?.Invoke();
this.Close();
}
}
}
}
}
}
}
<pu:WindowX x:Class="LiteChannel.StoreOutWindow"
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:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:local="clr-namespace:LiteChannel"
mc:Ignorable="d" Icon="1.ico"
Height="720" Width="1024" ResizeMode="NoResize" WindowState="Maximized"
Title="盘点出库" FontSize="24" WindowStartupLocation="CenterScreen"
Loaded="OnWindow_Loaded" Closing="OnWindow_Closing">
<Grid>
<Grid.RowDefinitions>
<RowDefinition Height="*"></RowDefinition>
<RowDefinition Height="50"></RowDefinition>
</Grid.RowDefinitions>
<DataGrid Grid.Row="0" FontSize="24" ColumnHeaderHeight="60" RowHeight="60" x:Name="dg_epc" HorizontalAlignment="Stretch" BorderThickness="0,0,0,1" VerticalAlignment="Stretch" pu:DataGridHelper.SelectedBackground="#44B5B5B5" pu:DataGridHelper.HoverBackground="#22B5B5B5" CanUserAddRows="False" >
<DataGrid.Columns>
<DataGridTextColumn IsReadOnly="True" Header="装备名称" Binding="{Binding equName}" Width="*"></DataGridTextColumn>
<DataGridTextColumn IsReadOnly="True" Header="申领数量" Binding="{Binding equCount}" Width="150" x:Name="equCountGridTextColumn"></DataGridTextColumn>
<DataGridTextColumn IsReadOnly="True" Header="剩余数量" Binding="{Binding equRem}" Width="150" x:Name="equRemGridTextColumn"></DataGridTextColumn>
<DataGridTextColumn IsReadOnly="True" Header="识别数量" Binding="{Binding scanQty,UpdateSourceTrigger=PropertyChanged,Mode=TwoWay}" Width="150"></DataGridTextColumn>
</DataGrid.Columns>
</DataGrid>
<TextBlock Grid.Row="1" Margin="0,0,220,0" Foreground="Red" Name="txt_stat" HorizontalAlignment="Left" VerticalAlignment="Center" FontSize="24">状态:读写器启动失败</TextBlock>
<Button pu:ButtonHelper.CornerRadius="4" Grid.Row="1" IsEnabled="false" Name="btn_inv" HorizontalAlignment="Right" Click="OnInv_Click" Width="120" Height="35" Margin="0,0,270,0" FontSize="24">开始读取</Button>
<Button pu:ButtonHelper.CornerRadius="4" Grid.Row="1" HorizontalAlignment="Right" Width="120" Height="35" Margin="0,0,140,0" Click="OnSave_Click" FontSize="24">提交出库</Button>
<Button pu:ButtonHelper.CornerRadius="4" Grid.Row="1" HorizontalAlignment="Right" Background="#C8FF7F00" Click="OnExit_Click" pu:ButtonHelper.HoverBrush="#FF7F00" Width="120" Height="35" Margin="0,0,10,0" FontSize="24">返回</Button>
</Grid>
</pu:WindowX>
using JmpRfidLp;
using LiteChannel.Commons;
using LiteChannel.Models;
using Panuon.UI.Silver;
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.Markup;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Windows.Threading;
using Panuon.UI.Silver.Core;
namespace LiteChannel
{
/// <summary>
/// StoreWindow.xaml 的交互逻辑
/// </summary>
public partial class StoreOutWindow : WindowX, IComponentConnector
{
private IReaderHelper reader;
private List<scan_info> SourcesList = new List<scan_info>();
private List<scan_info> BoxMarkList = new List<scan_info>();
private Queue<string> _epcQueue = new Queue<string>();
private CancellationTokenSource tokenSource = new CancellationTokenSource();
private ObservableCollection<scan_info> RefreshSourcesList = new ObservableCollection<scan_info>();
private Dictionary<ulong, string> dic_equ = new Dictionary<ulong, string>();
private List<order_equ> orderWzdm = new List<order_equ>();
private string type, id, order_code;
private order_info _orderInfo;
public event Action OnApplySuc;
private readonly bool isNoOrder;
private readonly bool isHaveBoxMark;
public StoreOutWindow(string id, string type, order_info orderInfo)
{
InitializeComponent();
if (type == "NoOrder")
{
isNoOrder = true;
dg_epc.AutoGenerateColumns = false;
equCountGridTextColumn.Visibility = Visibility.Hidden;
equRemGridTextColumn.Visibility = Visibility.Hidden;
}
else
{
this.id = id;
this.order_code = orderInfo.orderCode;
this.type = type;
dg_epc.AutoGenerateColumns = false;
_orderInfo = orderInfo;
}
}
private void OnWindow_Loaded(object sender, RoutedEventArgs e)
{
if (isNoOrder)
{
ConnectReader();
EpcHandleTask(tokenSource.Token);
return;
}
var detail_info = HttpHelper.GetOrderDetails(id, type);
if (detail_info == null)
{
txt_stat.Text = "状态:单据明细获取失败";
txt_stat.Foreground = new SolidColorBrush(Colors.Red);
}
else
{
detail_info.ForEach(s =>
{
orderWzdm.Add(new order_equ()
{
equCode = s.equCode,
equUsed = s.equUsed,
equRem = s.equCount - s.equUsed,
equCount = s.equCount
});
SourcesList.Add(new scan_info()
{
epcList = new List<string>(),
equCode = s.equCode,
equName = s.equName,
scanQty = 0,
equCount = s.equCount,
equRem = s.equCount - s.equUsed
});
});
Dispatcher.BeginInvoke(DispatcherPriority.Background,
new Action<List<scan_info>>((x) =>
{
RefreshSourcesList = new ObservableCollection<scan_info>(x);
dg_epc.ItemsSource = RefreshSourcesList;
}), SourcesList);
ConnectReader();
EpcHandleTask(tokenSource.Token);
}
}
private bool ConnectReader()
{
try
{ //启动读写器
switch (LiteCaChe.SysConfig.ReaderType)
{
case 0:
{
reader = new JmpRfidLpReaderHelper(LiteCaChe.SysConfig.ComMouth);
break;
}
case 1:
{
reader = new USBRFIDReaderHelper();
break;
}
}
reader.OnInventory += OnRadioInventory;
var state = reader.Open();
if (state)
{
var version = reader.GetFWVerion();
if (string.IsNullOrEmpty(version))
{
txt_stat.Text = "状态:读写器版本读取失败";
txt_stat.Foreground = new SolidColorBrush(Colors.Red);
return false;
}
reader.InventoryStop();
reader.SetPALevel(1);
reader.SetTxPower(0, true, 24);
txt_stat.Text = "状态:读写器连接成功";
txt_stat.Foreground = new SolidColorBrush(Colors.Green);
btn_inv.IsEnabled = true;
return true;
}
else
{
txt_stat.Text = "状态:读写器连接失败";
txt_stat.Foreground = new SolidColorBrush(Colors.Red);
return false;
}
}
catch (Exception ex)
{
reader = null;
txt_stat.Text = "状态:读写器连接失败";
txt_stat.Foreground = new SolidColorBrush(Colors.Red);
return false;
}
}
private void OnRadioInventory(TagInfoData args)
{
if (!BoxMarkList.Any(t => t.epcList.Contains(args.EPC)) &&
args.EPC.Length == 24 && args.EPC.Substring(0, 4) == "5842")
{
//有效标签
lock (_epcQueue)
{
if (!_epcQueue.Contains(args.EPC))
{
_epcQueue.Enqueue(args.EPC);
return;
}
}
}
if (!SourcesList.Any(t => t.epcList.Contains(args.EPC)) &&
!BoxMarkList.Any(t => t.epcList.Contains(args.EPC)) &&
args.EPC.Length == 64)
{
var buffer = EpcConvert.ToHexByte(args.EPC);
var epc_info = EpcConvert.EpcAnlysing(buffer);
if (epc_info != null)
{
var equ_info = LiteCaChe.EquInfos?.FirstOrDefault(t => t.code == epc_info.Wzdm.ToString("X"));
if (equ_info != null)
{
//有效标签
lock (_epcQueue)
{
if (!_epcQueue.Contains(args.EPC))
{
_epcQueue.Enqueue(args.EPC);
}
}
}
}
}
}
private void EpcHandleTask(CancellationToken token)
{
Task.Run(() =>
{
var epcList = new List<string>();
while (true)
{
if (token.IsCancellationRequested)
{
break;
}
lock (_epcQueue)
{
if (_epcQueue.Count != 0)
{
epcList = _epcQueue.ToList();
_epcQueue.Clear();
}
else
{
Thread.Sleep(500);
continue;
}
}
foreach (var epc in epcList)
{
//再次检查是否被阻塞阶段添加标签
if (!SourcesList.Any(t => t.epcList.Contains(epc))
&& !BoxMarkList.Any(t => t.epcList.Contains(epc)))
{
var tempEpc = epc;
if (tempEpc.Length == 24)
{
//旧版箱标epc
var boxMarkInfo = new scan_info()
{
epcList = new List<string>() { tempEpc },
equCode = "",
equName = "",
};
lock (BoxMarkList)
{
BoxMarkList.Add(boxMarkInfo);
}
IPendingHandler handler = null;
Dispatcher.BeginInvoke(DispatcherPriority.Background,
new Action(() =>
{
handler = PendingBox.Show("EPC转换中...", "", false, Application.Current.MainWindow, new PendingBoxConfigurations()
{
LoadingForeground = "#5DBBEC".ToColor().ToBrush(),
MaxWidth = 250,
MinHeight = 110,
MinWidth = 250,
MaxHeight = 110,
ButtonBrush = "#5DBBEC".ToColor().ToBrush(),
});
}));
var xbData = HttpHelper.GetEpcListByBoxMarkEpc(new List<string>() { tempEpc });
Dispatcher.BeginInvoke(DispatcherPriority.Background,
new Action(() =>
{
handler?.Close();
}));
if (xbData == null || xbData.Count == 0)
{
//无效epc,过滤
continue;
}
tempEpc = xbData.First().epc;
}
var buffer = EpcConvert.ToHexByte(tempEpc);
var epc_info = EpcConvert.EpcAnlysing(buffer);
if (epc_info != null)
{
var equ_info = LiteCaChe.EquInfos?.FirstOrDefault(t => t.code == epc_info.Wzdm.ToString("X"));
if (equ_info != null)
{
var equCount = -1;
var equRem = -1;
if (!isNoOrder)
{
var tmp_wzdm = orderWzdm.FirstOrDefault(t => t.equCode.Contains(epc_info.Wzdm.ToString("X")));
if (tmp_wzdm != null)
{
equCount = tmp_wzdm.equCount;
equRem = tmp_wzdm.equRem;
}
else
{
//不是本单据物资,过滤
continue;
}
}
if (epc_info.TagType == 0x01)
{
//读取到箱标提示
IPendingHandler handler2 = null;
Dispatcher.BeginInvoke(DispatcherPriority.Background,
new Action(() =>
{
handler2 = PendingBox.Show("读取到箱标,箱标解析中...", "", false, Application.Current.MainWindow, new PendingBoxConfigurations()
{
LoadingForeground = "#5DBBEC".ToColor().ToBrush(),
MaxWidth = 350,
MinHeight = 110,
MinWidth = 350,
MaxHeight = 110,
ButtonBrush = "#5DBBEC".ToColor().ToBrush(),
});
}));
//箱标
var boxMarkInfo = new scan_info()
{
epcList = new List<string>() { tempEpc },
equCode = epc_info.Wzdm.ToString("X"),
equName = equ_info.name,
};
lock (BoxMarkList)
{
BoxMarkList.Add(boxMarkInfo);
}
var xbData = HttpHelper.GetEpcListByBoxMarkEpc(boxMarkInfo.epcList);
if (xbData == null || xbData.Count == 0)
{
//无效epc,过滤
Dispatcher.BeginInvoke(DispatcherPriority.Background,
new Action(() =>
{
handler2.Close();
}));
continue;
}
foreach (var innerEpc in xbData.First().epcList)
{
var tmp_info = SourcesList.FirstOrDefault(t => t.equCode == epc_info.Wzdm.ToString("X"));
if (tmp_info == null)
{
tmp_info = new scan_info()
{
epcList = new List<string>() { innerEpc },
equCode = epc_info.Wzdm.ToString("X"),
equName = equ_info.name,
scanQty = 1,
equCount = equCount,
equRem = equRem
};
lock (SourcesList)
{
SourcesList.Add(tmp_info);
}
}
else
{
tmp_info.scanQty += 1;
tmp_info.epcList.Add(innerEpc);
}
}
Dispatcher.BeginInvoke(DispatcherPriority.Background,
new Action<List<scan_info>>((x) =>
{
RefreshSourcesList = new ObservableCollection<scan_info>(x);
dg_epc.ItemsSource = RefreshSourcesList;
handler2.Close();
}), SourcesList);
}
else
{
var tmp_info = SourcesList.FirstOrDefault(t => t.equCode == epc_info.Wzdm.ToString("X"));
if (tmp_info == null)
{
tmp_info = new scan_info()
{
epcList = new List<string>() { tempEpc },
equCode = epc_info.Wzdm.ToString("X"),
equName = equ_info.name,
scanQty = 1,
equCount = equCount,
equRem = equRem
};
SourcesList.Add(tmp_info);
Dispatcher.BeginInvoke(DispatcherPriority.Background,
new Action<List<scan_info>>((x) =>
{
RefreshSourcesList = new ObservableCollection<scan_info>(x);
dg_epc.ItemsSource = RefreshSourcesList;
}), SourcesList);
}
else
{
tmp_info.scanQty += 1;
tmp_info.epcList.Add(tempEpc);
}
}
}
}
}
}
epcList.Clear();
}
}, token);
}
//private void OnRadioInventory(TagInfo args)
//{
// if (!SourcesList.Any(t => t.epcList.Contains(args.EPC)) && args.EPC.Length == 64)
// {
// var buffer = EpcConvert.ToHexByte(args.EPC);
// var epc_info = EpcConvert.EpcAnlysing(buffer);
// if (epc_info != null)
// {
// if (isNoOrder)
// {
// var equ_info = LiteCaChe.EquInfos.FirstOrDefault(t => t.code == epc_info.Wzdm.ToString("X"));
// if (equ_info != null)
// {
// var tmp_info = SourcesList.FirstOrDefault(t => t.equCode == epc_info.Wzdm.ToString("X"));
// if (tmp_info == null)
// {
// tmp_info = new scan_info()
// {
// epcList = new List<string>() { args.EPC },
// equCode = epc_info.Wzdm.ToString("X"),
// equName = equ_info.name,
// scanQty = 1,
// equCount = -1,
// equRem = -1
// };
// SourcesList.Add(tmp_info);
// Dispatcher.BeginInvoke(DispatcherPriority.Background,
// new Action<List<scan_info>>((x) =>
// {
// RefreshSourcesList = new ObservableCollection<scan_info>(x);
// dg_epc.ItemsSource = RefreshSourcesList;
// }), SourcesList);
// }
// else
// {
// tmp_info.scanQty += 1;
// tmp_info.epcList.Add(args.EPC);
// }
// //this.Dispatcher.Invoke(() =>
// //{
// // dg_epc.ItemsSource = default;
// // dg_epc.ItemsSource = SourcesList;
// //});
// }
// }
// else
// {
// var tmp_wzdm = orderWzdm.FirstOrDefault(t => t.equCode.Contains(epc_info.Wzdm.ToString("X")));
// if (tmp_wzdm != null)
// {
// var equ_info = LiteCaChe.EquInfos.FirstOrDefault(t => t.code == epc_info.Wzdm.ToString("X"));
// if (equ_info != null)
// {
// var tmp_info = SourcesList.FirstOrDefault(t => t.equCode == epc_info.Wzdm.ToString("X"));
// if (tmp_info == null)
// {
// tmp_info = new scan_info()
// {
// epcList = new List<string>() { args.EPC },
// equCode = epc_info.Wzdm.ToString("X"),
// equName = equ_info.name,
// scanQty = 1,
// equCount = tmp_wzdm.equCount,
// equRem = tmp_wzdm.equRem
// };
// SourcesList.Add(tmp_info);
// Dispatcher.BeginInvoke(DispatcherPriority.Background,
// new Action<List<scan_info>>((x) =>
// {
// RefreshSourcesList = new ObservableCollection<scan_info>(x);
// dg_epc.ItemsSource = RefreshSourcesList;
// }), SourcesList);
// }
// else
// {
// tmp_info.scanQty += 1;
// tmp_info.epcList.Add(args.EPC);
// }
// //this.Dispatcher.Invoke(() =>
// //{
// // dg_epc.ItemsSource = default;
// // dg_epc.ItemsSource = SourcesList;
// //});
// }
// }
// }
// }
// }
//}
private void OnInv_Click(object sender, RoutedEventArgs e)
{
if (btn_inv.Content.ToString() == "开始读取")
{
reader?.InventoryStart();
btn_inv.Content = "停止读取";
}
else
{
reader.InventoryStop();
btn_inv.Content = "开始读取";
}
}
private void OnExit_Click(object sender, RoutedEventArgs e)
{
this.Close();
}
private void OnSave_Click(object sender, RoutedEventArgs e)
{
if (SourcesList != null && SourcesList.Count > 0)
{
List<rfid_info> epcList = new List<rfid_info>();
SourcesList.SelectMany(t => t.epcList).ToList()
.ForEach(s => epcList.Add(new rfid_info()
{
RFID = s
}));
if (epcList.Count > 0)
{
if (btn_inv.Content.ToString() == "停止读取")
{
OnInv_Click(default, default);
}
if (isNoOrder)
{
//存在箱标,阻止提交
if (isHaveBoxMark)
{
MessageBox.Show(this, "箱标不允许无单据出库", "出库提示", MessageBoxButton.OK,
MessageBoxImage.Information);
return;
}
//关闭全部单据 传入空的单据信息
if (!HttpHelper.OpenOrderWork(new order_info() { id = "空的单据信息", orderType = "借用" }))
{
MessageBox.Show(this, "单据关闭失败,请重试", "出库提示", MessageBoxButton.OK,
MessageBoxImage.Information);
return;
}
var _res = HttpHelper.RfidOutStore("", "", epcList);
MessageBox.Show(this, _res.Item2, "出库提示", MessageBoxButton.OK, MessageBoxImage.Information);
if (_res.Item1)
{
OnApplySuc?.Invoke();
this.Close();
}
}
else
{
//判断扫描数量是否超出单据数量
var orderDetailList = HttpHelper.GetOrderDetails(id, type);
if (orderDetailList?.Count == 0)
{
Log.WorkLog("单据详情获取失败。");
return;
}
foreach (var item in orderDetailList)
{
var sources = SourcesList.FirstOrDefault(x => x.equName == item.equName);
item.equUsed += sources == null ? 0 : sources.scanQty;
if (item.equUsed > item.equCount)
{
Log.WorkLog("扫描数量超出单据限制:装备名:" + item.equName);
MessageBox.Show(this, "扫描数量超出单据限制:装备名:" + item.equName, "出库提示", MessageBoxButton.OK,
MessageBoxImage.Information);
return;
}
}
//存在箱标并且单据不是调拨,阻止提交
if (isHaveBoxMark && _orderInfo.orderType != "库存调拨")
{
MessageBox.Show(this, "箱标不允许非调拨单据出库", "出库提示", MessageBoxButton.OK,
MessageBoxImage.Information);
return;
}
//开启单据
if (!HttpHelper.OpenOrderWork(_orderInfo))
{
MessageBox.Show(this, "单据开启失败,请重试", "出库提示", MessageBoxButton.OK,
MessageBoxImage.Information);
return;
}
var _res = HttpHelper.RfidOutStore(order_code, type, epcList);
MessageBox.Show(this, _res.Item2, "出库提示", MessageBoxButton.OK, MessageBoxImage.Information);
if (_res.Item1)
{
OnApplySuc?.Invoke();
this.Close();
}
}
}
}
}
private void OnWindow_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
if (reader?.IsOpen() ?? false)
{
reader?.InventoryStop();
reader?.Close();
}
}
}
}
#缺省不输出日志到控制台
#FATAL、ERROR、WARN、INFO、DEBUG 优先级顺序 如果子模块和根模块都匹配,那么都会输出
log4j.rootLogger=DEBUG, default
#log4j.rootLogger=DEBUG
##hlog.async=false
##hlog.secret.show=true
##hlog.secret.encrypt=false
#log4j.logger用于控制日志采集级别及采集内容,Threshold用于控制日志输出级别
#应用于控制台
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=[%d][%t][%-5p]- %m%n
log4j.logger.NPQ=TRACE, NPQ
log4j.appender.NPQ=org.apache.log4j.RollingFileAppender
log4j.appender.NPQ.File=./NPQLog/NPQ.log
log4j.appender.NPQ.MaxFileSize=80MB
log4j.appender.NPQ.MaxBackupIndex=12
log4j.appender.NPQ.Append=false
log4j.appender.NPQ.Threshold=TRACE
log4j.appender.NPQ.layout=org.apache.log4j.PatternLayout
log4j.appender.NPQ.layout.ConversionPattern=[%d][%t][%-5p]- %m%n
log4j.additivity.NPQ = false
#最后一位修改为true 既可以控制台输出又可以文件输出
#log4j.logger用于控制日志采集级别及采集内容,Threshold用于控制日志输出级别
#应用于控制台
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{HH:mm:ss,SSS} [%t] %-5p - %m%n
#应用于文件回滚
log4j.appender.default=org.apache.log4j.RollingFileAppender
log4j.appender.default.File=./log/DefaultClient.log
log4j.appender.default.MaxBackupIndex=12
log4j.appender.default.MaxFileSize=20MB
log4j.appender.default.Append=true
log4j.appender.default.Threshol= TRACE
log4j.appender.default.layout=org.apache.log4j.PatternLayout
log4j.appender.default.layout.ConversionPattern=%d [%t] %-5p %.16c - %m%n
#设置VMS
log4j.logger.Crash=TRACE, Crash
#每天产生一个日志文件
log4j.appender.Crash=org.apache.log4j.DailyRollingFileAppender
log4j.appender.Crash.File=./log/CrashClient.log
log4j.appender.Crash.DatePattern='.'yyyy-MM-dd
log4j.appender.Crash.Append=true
log4j.appender.Crash.Threshold=TRACE
log4j.appender.Crash.layout=org.apache.log4j.PatternLayout
log4j.appender.Crash.layout.ConversionPattern=%d [%t] %-5p %.16c - %m%n
##hlog.async=false
##hlog.secret.show=false
##hlog.secret.encrypt=true
<UserControl x:Class="LiteChannel.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"
mc:Ignorable="d"
d:DesignHeight="65" Background="white" Loaded="DataPageControl_Loaded">
<UserControl.Resources>
<ResourceDictionary>
<ResourceDictionary.MergedDictionaries>
<ResourceDictionary Source="pack://application:,,,/MaterialDesignThemes.Wpf;component/Themes/MaterialDesignTheme.Defaults.xaml"/>
<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>
</ResourceDictionary>
</UserControl.Resources>
<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 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 LiteChannel.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;
}
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace LiteChannel
{
public class VOrderInfo
{
public string Id { get; set; }
public string WarehouseId { get; set; }
public string OrderCode { get; set; }
public string OrgId { get; set; }
public DateTime CreateTime { get; set; }
public bool? IsWork { get; set; }
public string OrderType { get; set; }
}
}
Markdown 格式
0%
您添加了 0 到此讨论。请谨慎行事。
请先完成此评论的编辑!
注册 或者 后发表评论