diff --git a/.gitignore b/.gitignore index 90d59640d4b907885def52f27278768b2ef1e579..268fe78193d3002c22d7838d9c68f94e0f4bf18c 100644 --- a/.gitignore +++ b/.gitignore @@ -108,7 +108,6 @@ csx AppPackages/ # Others -sql/ *.Cache ClientBin/ [Ss]tyle[Cc]op.* @@ -151,48 +150,10 @@ $RECYCLE.BIN/ .DS_Store .vs *.cache -/Build/netcoreapp2.1/GB28181.Service.dll -/Build/netcoreapp2.1/GB28181.Service.dll -/Build/netcoreapp2.1/SIPSorcery.28181.dll -/Build/netcoreapp2.1/SIPSorcery.28181.dll -/Build/netcoreapp2.1/SIPSorcery.28181.pdb -/GB28181.Service/obj/Debug/netcoreapp2.1/GB28181.Service.csprojAssemblyReference.cache -/GrpcAgent/bin/Debug/netcoreapp2.1/SIPSorcery.28181.dll -/GrpcAgent/bin/Debug/netcoreapp2.1/SIPSorcery.28181.pdb -/GrpcAgent/obj/Debug/netcoreapp2.1/GrpcAgent.csprojAssemblyReference.cache -/SIPSorcery.28181/bin/Debug/netcoreapp2.1/SIPSorcery.28181.dll -/SIPSorcery.28181/bin/Debug/netcoreapp2.1/SIPSorcery.28181.pdb -/SIPSorcery.28181/obj/Debug/netcoreapp2.1/SIPSorcery.28181.dll -/SIPSorcery.28181/obj/Debug/netcoreapp2.1/SIPSorcery.28181.pdb -/Test.GB28181.Service/bin/Debug/netcoreapp2.1/SIPSorcery.28181.dll -/Test.GB28181.Service/bin/Debug/netcoreapp2.1/SIPSorcery.28181.pdb -/Test.GB28181.Service/obj/Debug/netcoreapp2.1/Test.GB28181.Service.csprojAssemblyReference.cache -/Build/netcoreapp2.1/GB28181.Service.dll -/Build/netcoreapp2.1/GB28181.Service.pdb -/GB28181.Service/obj/Debug/netcoreapp2.1/GB28181.Service.dll -/GB28181.Service/obj/Debug/netcoreapp2.1/GB28181.Service.pdb -/Logger4Net/obj/Debug/netcoreapp2.1/Logger4Net.csproj.FileListAbsolute.txt -/Logger4Net/obj/Debug/netcoreapp2.1/Logger4Net.csprojAssemblyReference.cache -/NATS.Client/obj/Debug/netcoreapp2.1/NATS.Client.csproj.FileListAbsolute.txt -/NATS.Client/obj/Debug/netcoreapp2.1/NATS.Client.csprojAssemblyReference.cache -/Proto.Grpc/obj/Debug/netcoreapp2.1/GrpcProtocol.csproj.FileListAbsolute.txt -/Proto.Grpc/obj/Debug/netcoreapp2.1/GrpcProtocol.csprojAssemblyReference.cache -/SIPSorcery.28181/obj/Debug/netcoreapp2.1/SIPSorcery.28181.csprojAssemblyReference.cache -/Test.GB28181.Service/bin/Debug/netcoreapp2.1/GB28181.Service.dll -/Test.GB28181.Service/bin/Debug/netcoreapp2.1/GB28181.Service.pdb -/Build/netcoreapp2.1/GB28181.Service.dll -/Build/netcoreapp2.1/GB28181.Service.pdb -/GB28181.Service/obj/Debug/netcoreapp2.1/GB28181.Service.dll -/GB28181.Service/obj/Debug/netcoreapp2.1/GB28181.Service.pdb -/Logger4Net/obj/Debug/netcoreapp2.1/Logger4Net.csproj.FileListAbsolute.txt -/Logger4Net/obj/Debug/netcoreapp2.1/Logger4Net.csprojAssemblyReference.cache -/NATS.Client/obj/Debug/netcoreapp2.1/NATS.Client.csproj.FileListAbsolute.txt -/NATS.Client/obj/Debug/netcoreapp2.1/NATS.Client.csprojAssemblyReference.cache -/Proto.Grpc/obj/Debug/netcoreapp2.1/GrpcProtocol.csproj.FileListAbsolute.txt -/Proto.Grpc/obj/Debug/netcoreapp2.1/GrpcProtocol.csprojAssemblyReference.cache -/SIPSorcery.28181/obj/Debug/netcoreapp2.1/SIPSorcery.28181.csprojAssemblyReference.cache -/Test.GB28181.Service/bin/Debug/netcoreapp2.1/GB28181.Service.dll -/Test.GB28181.Service/bin/Debug/netcoreapp2.1/GB28181.Service.pdb -/SIPSorcery.28181/obj/Debug/netcoreapp2.1/SIPSorcery.28181.csproj.FileListAbsolute.txt obj/ bin/ +/.vs/ +/packages +packages.config +obj/ +*.orig diff --git a/CHANGELOG.md b/CHANGELOG.md index 34f2fc0fe72b19267cbb4f8963e45347d3899f3e..211467cf063d43b5f2cdd3fa82d36d636744e525 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,12 +1,3 @@ -## release v6.0.0.1 -* realtime video and playback video successfully finished +# Important Change -## release v6.0.0.1 -* Registered device to DMS -* Get GBserver config info from devicemanagementservice -* Real video request and play -* Keepalive of real video request - -## release v6.0.0.0 - -* add md log file +## a lot of change ,as a basic codes \ No newline at end of file diff --git a/CallStack1.dgml b/CallStack1.dgml new file mode 100644 index 0000000000000000000000000000000000000000..7654bf88f0b45a7c3ec78e54f62f2068798324da --- /dev/null +++ b/CallStack1.dgml @@ -0,0 +1,689 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + \ No newline at end of file diff --git a/Common.GLib.WinControls/Common.GLib.WinControls.csproj b/Common.GLib.WinControls/Common.GLib.WinControls.csproj new file mode 100644 index 0000000000000000000000000000000000000000..0b89b8f59dd290f1197ce31f568ce53ffe4f99e7 --- /dev/null +++ b/Common.GLib.WinControls/Common.GLib.WinControls.csproj @@ -0,0 +1,11 @@ + + + + Library + netcoreapp3.1 + Common.GLib.WinControls + Common.GLib.WinControls + true + + + diff --git a/Common.GLib.WinControls/GLib.Controls.Form/AXDataGridView.cs b/Common.GLib.WinControls/GLib.Controls.Form/AXDataGridView.cs new file mode 100644 index 0000000000000000000000000000000000000000..3a0259ff86ecfd9ba6268a1225cf8a34a1156fa1 --- /dev/null +++ b/Common.GLib.WinControls/GLib.Controls.Form/AXDataGridView.cs @@ -0,0 +1,136 @@ +using System; +using System.ComponentModel; +using System.Drawing; +using System.Windows.Forms; + +namespace GLib.Controls.Form +{ + public class AXDataGridView : DataGridView + { + private int _index = 0; + + private bool _isScorll = true; + + private int _move = 30; + + private IContainer components = null; + + private Timer timer1; + + [Browsable(true)] + [DefaultValue(true)] + public new bool ReadOnly + { + get + { + return base.ReadOnly; + } + set + { + base.ReadOnly = value; + } + } + + public AXDataGridView() + { + InitializeComponent(); + Init(); + } + + private void Init() + { + base.AllowUserToAddRows = false; + base.AllowUserToDeleteRows = false; + base.BorderStyle = BorderStyle.None; + base.BackgroundColor = SystemColors.Window; + base.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.DisableResizing; + base.EnableHeadersVisualStyles = false; + base.RowHeadersVisible = false; + base.RowTemplate.Height = 20; + base.SelectionMode = DataGridViewSelectionMode.FullRowSelect; + base.AutoGenerateColumns = false; + base.AllowUserToResizeRows = false; + SetStyle(ControlStyles.AllPaintingInWmPaint | ControlStyles.DoubleBuffer | ControlStyles.OptimizedDoubleBuffer, value: true); + UpdateStyles(); + } + + private void AXDataGridView_MouseWheel(object sender, MouseEventArgs e) + { + _move = 0; + } + + private void AXDataGridView_RowsAdded(object sender, DataGridViewRowsAddedEventArgs e) + { + if (_isScorll && base.FirstDisplayedScrollingRowIndex != -1) + { + _index++; + base.FirstDisplayedScrollingRowIndex = ((base.Rows.Count > 0) ? (base.Rows.Count - 1) : 0); + } + } + + private void AXDataGridView_RowsRemoved(object sender, DataGridViewRowsRemovedEventArgs e) + { + _index--; + if (_isScorll && base.FirstDisplayedScrollingRowIndex != -1) + { + base.FirstDisplayedScrollingRowIndex = base.Rows.Count - 2; + } + } + + private void AXDataGridView_Scroll(object sender, ScrollEventArgs e) + { + if (_index > e.NewValue) + { + _move = 0; + _isScorll = false; + } + else + { + _isScorll = true; + } + if (_isScorll) + { + _index = e.NewValue; + } + } + + private void AXDataGridView_MouseClick(object sender, MouseEventArgs e) + { + _isScorll = false; + } + + private void AXDataGridView_MouseMove(object sender, MouseEventArgs e) + { + _move = 0; + } + + private void timer1_Tick(object sender, EventArgs e) + { + } + + protected override void Dispose(bool disposing) + { + if (disposing && components != null) + { + timer1.Enabled = false; + timer1.Dispose(); + components.Dispose(); + } + base.Dispose(disposing); + } + + private void InitializeComponent() + { + components = new System.ComponentModel.Container(); + timer1 = new System.Windows.Forms.Timer(components); + ((System.ComponentModel.ISupportInitialize)this).BeginInit(); + SuspendLayout(); + timer1.Enabled = true; + timer1.Interval = 1000; + timer1.Tick += new System.EventHandler(timer1_Tick); + base.RowTemplate.Height = 23; + ((System.ComponentModel.ISupportInitialize)this).EndInit(); + ResumeLayout(false); + } + } +} diff --git a/Common.GLib.WinControls/GLib.Controls.Web/BulletedList.cs b/Common.GLib.WinControls/GLib.Controls.Web/BulletedList.cs new file mode 100644 index 0000000000000000000000000000000000000000..fe4798f002962598f25dd5264952073160c70b83 --- /dev/null +++ b/Common.GLib.WinControls/GLib.Controls.Web/BulletedList.cs @@ -0,0 +1,13 @@ +//using System.Web.UI.WebControls; + +namespace GLib.Controls.Web +{ + //public class BulletedList : System.Web.UI.WebControls.BulletedList + //{ + // public BulletedList() + // { + // DataValueField = ControlsConfig.Controls_DataValueField; + // DataTextField = ControlsConfig.Controls_DataTextField; + // } + //} +} diff --git a/Common.GLib.WinControls/GLib.Controls.Web/Button.cs b/Common.GLib.WinControls/GLib.Controls.Web/Button.cs new file mode 100644 index 0000000000000000000000000000000000000000..2395a44f5f4aa02aa61162a06eea22b38ff83d12 --- /dev/null +++ b/Common.GLib.WinControls/GLib.Controls.Web/Button.cs @@ -0,0 +1,8 @@ +//using System.Web.UI.WebControls; + +//namespace GLib.Controls.Web +//{ +// public class Button : System.Web.UI.WebControls.Button +// { +// } +//} diff --git a/Common.GLib.WinControls/GLib.Controls.Web/CheckBox.cs b/Common.GLib.WinControls/GLib.Controls.Web/CheckBox.cs new file mode 100644 index 0000000000000000000000000000000000000000..8f36f8175ac13a7d6eedbcc01efe6f8b9880f752 --- /dev/null +++ b/Common.GLib.WinControls/GLib.Controls.Web/CheckBox.cs @@ -0,0 +1,8 @@ +//using System.Web.UI.WebControls; + +//namespace GLib.Controls.Web +//{ +// public class CheckBox : System.Web.UI.WebControls.CheckBox +// { +// } +//} diff --git a/Common.GLib.WinControls/GLib.Controls.Web/CheckBoxList.cs b/Common.GLib.WinControls/GLib.Controls.Web/CheckBoxList.cs new file mode 100644 index 0000000000000000000000000000000000000000..be793b8acafde6a2596e5f7f7418be92c27cb3b2 --- /dev/null +++ b/Common.GLib.WinControls/GLib.Controls.Web/CheckBoxList.cs @@ -0,0 +1,13 @@ +//using System.Web.UI.WebControls; + +//namespace GLib.Controls.Web +//{ +// public class CheckBoxList : System.Web.UI.WebControls.CheckBoxList +// { +// public CheckBoxList() +// { +// DataValueField = ControlsConfig.Controls_DataValueField; +// DataTextField = ControlsConfig.Controls_DataTextField; +// } +// } +//} diff --git a/Common.GLib.WinControls/GLib.Controls.Web/ControlsConfig.cs b/Common.GLib.WinControls/GLib.Controls.Web/ControlsConfig.cs new file mode 100644 index 0000000000000000000000000000000000000000..944360397a383fab58233590db89f4d9d630d394 --- /dev/null +++ b/Common.GLib.WinControls/GLib.Controls.Web/ControlsConfig.cs @@ -0,0 +1,9 @@ +namespace GLib.Controls.Web +{ + internal class ControlsConfig + { + public static string Controls_DataValueField => "Key"; + + public static string Controls_DataTextField => "Value"; + } +} diff --git a/Common.GLib.WinControls/GLib.Controls.Web/DropDownList.cs b/Common.GLib.WinControls/GLib.Controls.Web/DropDownList.cs new file mode 100644 index 0000000000000000000000000000000000000000..ade7f336a34240af87e8e39de0bc609ca8b8f87d --- /dev/null +++ b/Common.GLib.WinControls/GLib.Controls.Web/DropDownList.cs @@ -0,0 +1,13 @@ +//using System.Web.UI.WebControls; + +//namespace GLib.Controls.Web +//{ +// public class DropDownList : System.Web.UI.WebControls.DropDownList +// { +// public DropDownList() +// { +// DataValueField = ControlsConfig.Controls_DataValueField; +// DataTextField = ControlsConfig.Controls_DataTextField; +// } +// } +//} diff --git a/Common.GLib.WinControls/GLib.Controls.Web/GridView.cs b/Common.GLib.WinControls/GLib.Controls.Web/GridView.cs new file mode 100644 index 0000000000000000000000000000000000000000..4dd4297b30f1357858e8fea16ea56e3c99f884da --- /dev/null +++ b/Common.GLib.WinControls/GLib.Controls.Web/GridView.cs @@ -0,0 +1,8 @@ +//using System.Web.UI.WebControls; + +//namespace GLib.Controls.Web +//{ +// public class GridView : System.Web.UI.WebControls.GridView +// { +// } +//} diff --git a/Common.GLib.WinControls/GLib.Controls.Web/HiddenField.cs b/Common.GLib.WinControls/GLib.Controls.Web/HiddenField.cs new file mode 100644 index 0000000000000000000000000000000000000000..9745e50906403b603df7d78928ff4543123a9df3 --- /dev/null +++ b/Common.GLib.WinControls/GLib.Controls.Web/HiddenField.cs @@ -0,0 +1,8 @@ +//using System.Web.UI.WebControls; + +namespace GLib.Controls.Web +{ + //public class HiddenField : System.Web.UI.WebControls.HiddenField + //{ + //} +} diff --git a/Common.GLib.WinControls/GLib.Controls.Web/HyperLink.cs b/Common.GLib.WinControls/GLib.Controls.Web/HyperLink.cs new file mode 100644 index 0000000000000000000000000000000000000000..d5f1a6d07750dc1a99ba7984f8abe7bfba657efd --- /dev/null +++ b/Common.GLib.WinControls/GLib.Controls.Web/HyperLink.cs @@ -0,0 +1,8 @@ +//using System.Web.UI.WebControls; + +//namespace GLib.Controls.Web +//{ +// public class HyperLink : System.Web.UI.WebControls.HyperLink +// { +// } +//} diff --git a/Common.GLib.WinControls/GLib.Controls.Web/Image.cs b/Common.GLib.WinControls/GLib.Controls.Web/Image.cs new file mode 100644 index 0000000000000000000000000000000000000000..c5dc76b49e89cc822bd18f579062d633cc53c34a --- /dev/null +++ b/Common.GLib.WinControls/GLib.Controls.Web/Image.cs @@ -0,0 +1,8 @@ +//using System.Web.UI.WebControls; + +//namespace GLib.Controls.Web +//{ +// public class Image : System.Web.UI.WebControls.Image +// { +// } +//} diff --git a/Common.GLib.WinControls/GLib.Controls.Web/ImageButton.cs b/Common.GLib.WinControls/GLib.Controls.Web/ImageButton.cs new file mode 100644 index 0000000000000000000000000000000000000000..bf9ec45e065c9f3680da7af4ea8c0074c3d4a004 --- /dev/null +++ b/Common.GLib.WinControls/GLib.Controls.Web/ImageButton.cs @@ -0,0 +1,8 @@ +//using System.Web.UI.WebControls; + +namespace GLib.Controls.Web +{ + //public class ImageButton : System.Web.UI.WebControls.ImageButton + //{ + //} +} diff --git a/Common.GLib.WinControls/GLib.Controls.Web/ImageMap.cs b/Common.GLib.WinControls/GLib.Controls.Web/ImageMap.cs new file mode 100644 index 0000000000000000000000000000000000000000..0c89a3bd4b7ebf74421c59d503bae64ee722705b --- /dev/null +++ b/Common.GLib.WinControls/GLib.Controls.Web/ImageMap.cs @@ -0,0 +1,8 @@ +//using System.Web.UI.WebControls; + +//namespace GLib.Controls.Web +//{ +// public class ImageMap : System.Web.UI.WebControls.ImageMap +// { +// } +//} diff --git a/Common.GLib.WinControls/GLib.Controls.Web/Label.cs b/Common.GLib.WinControls/GLib.Controls.Web/Label.cs new file mode 100644 index 0000000000000000000000000000000000000000..55a45c3d254e1f9aa1082cbfc039ec78fed5a6e6 --- /dev/null +++ b/Common.GLib.WinControls/GLib.Controls.Web/Label.cs @@ -0,0 +1,8 @@ +//using System.Web.UI.WebControls; + +//namespace GLib.Controls.Web +//{ +// public class Label : System.Web.UI.WebControls.Label +// { +// } +//} diff --git a/Common.GLib.WinControls/GLib.Controls.Web/LinkButton.cs b/Common.GLib.WinControls/GLib.Controls.Web/LinkButton.cs new file mode 100644 index 0000000000000000000000000000000000000000..ac0a81b4b6c5260cdd5743218aac9f8badff7212 --- /dev/null +++ b/Common.GLib.WinControls/GLib.Controls.Web/LinkButton.cs @@ -0,0 +1,8 @@ +//using System.Web.UI.WebControls; + +//namespace GLib.Controls.Web +//{ +// public class LinkButton : System.Web.UI.WebControls.LinkButton +// { +// } +//} diff --git a/Common.GLib.WinControls/GLib.Controls.Web/ListBox.cs b/Common.GLib.WinControls/GLib.Controls.Web/ListBox.cs new file mode 100644 index 0000000000000000000000000000000000000000..667b4559a314dc40120734520e8b82434325095e --- /dev/null +++ b/Common.GLib.WinControls/GLib.Controls.Web/ListBox.cs @@ -0,0 +1,13 @@ +//using System.Web.UI.WebControls; + +//namespace GLib.Controls.Web +//{ +// public class ListBox : System.Web.UI.WebControls.ListBox +// { +// public ListBox() +// { +// DataValueField = ControlsConfig.Controls_DataValueField; +// DataTextField = ControlsConfig.Controls_DataTextField; +// } +// } +//} diff --git a/Common.GLib.WinControls/GLib.Controls.Web/ListView.cs b/Common.GLib.WinControls/GLib.Controls.Web/ListView.cs new file mode 100644 index 0000000000000000000000000000000000000000..e2cf2766b25ab40cb738422ea879e52711ad692f --- /dev/null +++ b/Common.GLib.WinControls/GLib.Controls.Web/ListView.cs @@ -0,0 +1,8 @@ +//using System.Web.UI.WebControls; + +//namespace GLib.Controls.Web +//{ +// public class ListView : System.Web.UI.WebControls.ListView +// { +// } +//} diff --git a/Common.GLib.WinControls/GLib.Controls.Web/Literal.cs b/Common.GLib.WinControls/GLib.Controls.Web/Literal.cs new file mode 100644 index 0000000000000000000000000000000000000000..af74d54f7c3f4c5f55661797b14759f15f4abe4a --- /dev/null +++ b/Common.GLib.WinControls/GLib.Controls.Web/Literal.cs @@ -0,0 +1,8 @@ +//using System.Web.UI.WebControls; + +//namespace GLib.Controls.Web +//{ +// public class Literal : System.Web.UI.WebControls.Literal +// { +// } +//} diff --git a/Common.GLib.WinControls/GLib.Controls.Web/Panel.cs b/Common.GLib.WinControls/GLib.Controls.Web/Panel.cs new file mode 100644 index 0000000000000000000000000000000000000000..bc77e509fe38f91d8d732df5d617008ec4c043c5 --- /dev/null +++ b/Common.GLib.WinControls/GLib.Controls.Web/Panel.cs @@ -0,0 +1,8 @@ +//using System.Web.UI.WebControls; + +//namespace GLib.Controls.Web +//{ +// public class Panel : System.Web.UI.WebControls.Panel +// { +// } +//} diff --git a/Common.GLib.WinControls/GLib.Controls.Web/PlaceHolder.cs b/Common.GLib.WinControls/GLib.Controls.Web/PlaceHolder.cs new file mode 100644 index 0000000000000000000000000000000000000000..97515f62ebb10cebc1594f8b8b2f0fbe9a26d2b9 --- /dev/null +++ b/Common.GLib.WinControls/GLib.Controls.Web/PlaceHolder.cs @@ -0,0 +1,8 @@ +//using System.Web.UI.WebControls; + +//namespace GLib.Controls.Web +//{ +// public class PlaceHolder : System.Web.UI.WebControls.PlaceHolder +// { +// } +//} diff --git a/Common.GLib.WinControls/GLib.Controls.Web/RadioButton.cs b/Common.GLib.WinControls/GLib.Controls.Web/RadioButton.cs new file mode 100644 index 0000000000000000000000000000000000000000..baf418e271c4b829fd8453a6a2c660fbb567eb80 --- /dev/null +++ b/Common.GLib.WinControls/GLib.Controls.Web/RadioButton.cs @@ -0,0 +1,8 @@ +//using System.Web.UI.WebControls; + +//namespace GLib.Controls.Web +//{ +// public class RadioButton : System.Web.UI.WebControls.RadioButton +// { +// } +//} diff --git a/Common.GLib.WinControls/GLib.Controls.Web/RadioButtonList.cs b/Common.GLib.WinControls/GLib.Controls.Web/RadioButtonList.cs new file mode 100644 index 0000000000000000000000000000000000000000..f661398f4296316363d0ba6ce343673c7f1d3e50 --- /dev/null +++ b/Common.GLib.WinControls/GLib.Controls.Web/RadioButtonList.cs @@ -0,0 +1,13 @@ +//using System.Web.UI.WebControls; + +//namespace GLib.Controls.Web +//{ +// public class RadioButtonList : System.Web.UI.WebControls.RadioButtonList +// { +// public RadioButtonList() +// { +// DataValueField = ControlsConfig.Controls_DataValueField; +// DataTextField = ControlsConfig.Controls_DataTextField; +// } +// } +//} diff --git a/Common.GLib.WinControls/GLib.Controls.Web/TextBox.cs b/Common.GLib.WinControls/GLib.Controls.Web/TextBox.cs new file mode 100644 index 0000000000000000000000000000000000000000..84a193c9a0cc85e6f8fb6c1aa48f9a2e157161f0 --- /dev/null +++ b/Common.GLib.WinControls/GLib.Controls.Web/TextBox.cs @@ -0,0 +1,8 @@ +//using System.Web.UI.WebControls; + +//namespace GLib.Controls.Web +//{ +// public class TextBox : System.Web.UI.WebControls.TextBox +// { +// } +//} diff --git a/Common.GLib.WinControls/GLib/DebugEx.cs b/Common.GLib.WinControls/GLib/DebugEx.cs new file mode 100644 index 0000000000000000000000000000000000000000..02df780fb0e5731860f7e7a9f0cd36af600ddaab --- /dev/null +++ b/Common.GLib.WinControls/GLib/DebugEx.cs @@ -0,0 +1,131 @@ +using System; +using System.IO; +using System.Reflection; +using System.Text; +using System.Threading; +using System.Windows.Forms; + +namespace GLib +{ + public static class DebugEx + { + private static string _appName = ""; + + private static Action _unhandledExceptionCallBack = null; + + private static bool _alertExceptionMsg = false; + + public static string LogPath = Application.StartupPath + "\\log\\"; + + public static string Version = Assembly.GetExecutingAssembly().GetName().Version.ToString(); + + public static event Action EvtTrace; + + public static void Trace(string flag, string msg) + { + string text = $"{flag}___{msg}"; + Console.WriteLine(text); + if (EvtTrace != null) + { + EvtTrace(text); + } + } + + public static void RegisterUnHandldException() + { + RegisterUnHandldException(Application.ProductName, null, alertExceptionMsg: true); + } + + public static void RegisterUnHandldException(string appName, Action unhandledExceptionCallBack, bool alertExceptionMsg = false) + { + _appName = appName; + _alertExceptionMsg = alertExceptionMsg; + _unhandledExceptionCallBack = unhandledExceptionCallBack; + Application.ThreadException += Application_ThreadException; + AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException; + } + + private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e) + { + OnFatalException(e.ExceptionObject as Exception); + if (e.IsTerminating && _unhandledExceptionCallBack != null) + { + _unhandledExceptionCallBack(e); + } + } + + private static void Application_ThreadException(object sender, ThreadExceptionEventArgs e) + { + OnFatalException(e.Exception); + } + + public static void OnFatalException(Exception ex, bool isEnd = false) + { + StringBuilder stringBuilder = new StringBuilder(); + string text = ""; + string version = Version; + text = $"{_appName} {version} {DateTime.Now}"; + if (isEnd) + { + text = string.Format("=================致命错误==================\r\n{0} {1}", _appName, ""); + } + stringBuilder.AppendLine(text); + stringBuilder.AppendLine(GetErrorString(ex)); + WriteLog(stringBuilder.ToString()); + string text2 = $"{text}出现一个未处理的异常\r\n请将程序安装目录下的日志反馈给软件提供商。\r\n详细信息:{ex.Message + ex.StackTrace}\r\n发生时间:{DateTime.Now}"; + if (!_alertExceptionMsg) + { + } + } + + public static string GetLog(Exception ex, bool isEnd = false) + { + StringBuilder stringBuilder = new StringBuilder(); + string text = ""; + string arg = Assembly.GetExecutingAssembly().GetName().Version.ToString(); + text = $"{_appName} {arg} {DateTime.Now}"; + if (isEnd) + { + text = string.Format("=================致命错误==================\r\n{0} {1}", _appName, ""); + } + stringBuilder.AppendLine(text); + stringBuilder.AppendLine(GetErrorString(ex)); + return stringBuilder.ToString(); + } + + public static void WriteLog(string msg) + { + string text = LogPath.ToSystemPath(); + if (!Directory.Exists(text)) + { + Directory.CreateDirectory(text); + } + string path = string.Format("{0}\\Log_{1}.txt", text, DateTime.Now.ToString("yyyy-MM-dd")).ToSystemPath(); + File.AppendAllText(path, msg + "\r\n", Encoding.UTF8); + } + + private static string GetErrorString(Exception ex, string pleft = "") + { + StringBuilder stringBuilder = new StringBuilder(); + stringBuilder.AppendLine(pleft + ex.Message); + stringBuilder.AppendLine(pleft + ex.GetType().Name); + stringBuilder.AppendLine(pleft + ex.StackTrace); + if (ex.InnerException != null) + { + stringBuilder.AppendLine("---------------------------------------------->"); + stringBuilder.AppendLine(GetErrorString(ex.InnerException, pleft + " ")); + } + return stringBuilder.ToString(); + } + + public static string ToSystemPath(this string path) + { + if (Environment.OSVersion.Platform == PlatformID.Unix) + { + return path.Replace("\\", "/"); + } + return path.Replace("/", "\\"); + } + } + +} diff --git a/Common.GLib.WinControls/RegistryHelper.cs b/Common.GLib.WinControls/RegistryHelper.cs new file mode 100644 index 0000000000000000000000000000000000000000..54aa27b7b766c7a331f15d806d77e1d4b0b24575 --- /dev/null +++ b/Common.GLib.WinControls/RegistryHelper.cs @@ -0,0 +1,81 @@ +using Microsoft.Win32; +using System; +using System.Diagnostics; +using System.Windows.Forms; + +public class RegistryHelper +{ + public static bool ConfigAutoStart(bool isAutoStart, string[] args) + { + try + { + string processName = Process.GetCurrentProcess().ProcessName; + RegistryKey registryKey = null; + using (registryKey = OpenKeyForWrite("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run")) + { + if (registryKey == null) + { + return false; + } + string text = $"\"{Application.ExecutablePath}\""; + for (int i = 0; i < args.Length; i++) + { + text = ((i != 2) ? (text + " " + args[i]) : (text + " " + $"\"{args[i]}\"")); + } + if (isAutoStart) + { + registryKey.SetValue(processName, text); + } + else + { + registryKey.DeleteValue(processName, throwOnMissingValue: false); + } + registryKey.Close(); + return true; + } + } + catch (Exception) + { + return false; + } + } + + public static RegistryKey OpenKeyForWrite(string subKey) + { + return OpenKeyForWrite(Registry.LocalMachine, subKey); + } + + public static RegistryKey OpenKeyForWrite(RegistryKey key, string subKey) + { + RegistryKey registryKey = null; + registryKey = key.OpenSubKey(subKey, writable: true); + if (registryKey == null) + { + registryKey = key.CreateSubKey(subKey); + } + return registryKey; + } + + public static void WriteAutoLoginWindowRegistryKey(bool isAutoLogin, string defaultUserName, string defaultPassword) + { + try + { + RegistryKey registryKey = Registry.LocalMachine.OpenSubKey("SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Winlogon", writable: true); + if (isAutoLogin) + { + registryKey.SetValue("AutoAdminLogon", "1"); + registryKey.SetValue("DefaultUserName", defaultUserName); + registryKey.SetValue("DefaultPassword", defaultPassword); + } + else + { + registryKey.SetValue("AutoAdminLogon", "0"); + registryKey.SetValue("DefaultPassword", string.Empty); + } + registryKey.Close(); + } + catch (Exception) + { + } + } +} diff --git a/Common.GLib.WinControls/Watchdog.cs b/Common.GLib.WinControls/Watchdog.cs new file mode 100644 index 0000000000000000000000000000000000000000..b0a9479b060cee8fa316c88f8655b8de1bc46386 --- /dev/null +++ b/Common.GLib.WinControls/Watchdog.cs @@ -0,0 +1,236 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.IO; +using System.Linq; +using System.Runtime.InteropServices; +using System.Text; +using System.Threading; +using System.Windows.Forms; + +public static class Watchdog +{ + private static void Application_ThreadException(object sender, ThreadExceptionEventArgs e) + { + OnFatalException(e.Exception); + } + + private static int CheckActive(string appName) + { + int num = 0; + Process[] processes = Process.GetProcesses(); + foreach (Process process in processes) + { + if (process.ProcessName == appName) + { + num++; + } + } + return num; + } + + private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e) + { + OnFatalException(e.ExceptionObject as Exception); + } + + [DllImport("user32.dll", CharSet = CharSet.Unicode)] + public static extern IntPtr FindWindow(string lpClassName, string lpWindowName); + + [DllImport("User32.dll", CharSet = CharSet.Unicode)] + public static extern IntPtr FindWindowEx(IntPtr hwndParent, IntPtr hwndChildAfter, string strClassName, string strWindowName); + + [DllImport("user32.dll")] + private static extern int GetWindowThreadProcessId(IntPtr hWnd, out int ProcessId); + + private static void HideConsoleWindow() + { + Console.Title = Application.ProductName; + IntPtr intPtr = FindWindow("ConsoleWindowClass", Application.ProductName); + if (intPtr != IntPtr.Zero) + { + ShowWindow(intPtr, 0u); + } + } + + private static void KillDApp(string appName) + { + List list = Enumerable.ToList(Enumerable.Select(new string[6] + { + "WerFault.exe", + "dwwin.exe", + "dw20.exe", + "WerFault", + "dwwin", + "dw20" + }, (string p) => p.ToUpper())); + Process[] processes = Process.GetProcesses(); + Process[] array = processes; + foreach (Process process in array) + { + try + { + if (list.Contains(process.ProcessName.ToUpper().Replace(" *32", ""))) + { + Log($"异常进程:{process.ProcessName}"); + process.Kill(); + } + } + catch (Exception) + { + } + } + try + { + IntPtr intPtr = FindWindowEx(IntPtr.Zero, IntPtr.Zero, null, $"{appName}.exe - 应用程序错误"); + if (intPtr != IntPtr.Zero) + { + int ProcessId = 0; + GetWindowThreadProcessId(intPtr, out ProcessId); + if (ProcessId != 0) + { + Process.GetProcessById(ProcessId).Kill(); + Log($"异常窗口 {appName}.exe - 应用程序错误"); + } + } + intPtr = FindWindowEx(IntPtr.Zero, IntPtr.Zero, null, "Microsoft Visual C++ Runtime Library"); + if (intPtr != IntPtr.Zero) + { + int ProcessId2 = 0; + GetWindowThreadProcessId(intPtr, out ProcessId2); + if (ProcessId2 != 0) + { + Process.GetProcessById(ProcessId2).Kill(); + Log($"异常窗口 {appName}.exe - Microsoft Visual C++ Runtime Library"); + } + } + } + catch (Exception) + { + } + } + + private static void KillOtherDog() + { + Process currentProcess = Process.GetCurrentProcess(); + Process[] processes = Process.GetProcesses(); + foreach (Process process in processes) + { + if (process.ProcessName.ToUpper() == currentProcess.ProcessName.ToUpper()) + { + try + { + if (currentProcess.Id != process.Id) + { + process.Kill(); + } + } + catch (Exception) + { + } + } + } + } + + private static void Log(string msg) + { + msg = $"{DateTime.Now} {msg}"; + Console.WriteLine(msg); + string text = Application.StartupPath + "\\Watchdog"; + if (!Directory.Exists(text)) + { + Directory.CreateDirectory(text); + } + File.AppendAllText(string.Format("{0}\\{1}.txt", text, DateTime.Now.ToString("yyyy_MM")), msg + "\r\n"); + } + + private static void Main(string[] args) + { + try + { + RegisterUnHandldException(); + HideConsoleWindow(); + string text = args[0]; + string text2 = args[1]; + string text3 = args[2]; + int num = int.Parse(args[3]); + string text4 = args[4]; + string text5 = args[5]; + string text6 = (args.Length > 6) ? args[6] : null; + string text7 = (args.Length > 7) ? args[7] : null; + Console.WriteLine(string.Format("{0} {1} {2} {3} {4} {5} {6}", text, text2, text3, num, text4, text5, text6, text7)); + if (!(text == "0")) + { + RegistryHelper.ConfigAutoStart(text4 == "1", args); + KillOtherDog(); + DateTime now = DateTime.Now; + while (true) + { + bool flag = true; + KillDApp(text2); + if (CheckActive(text2) > 0) + { + now = DateTime.Now; + } + if (now.AddSeconds(num) < DateTime.Now) + { + StartApp(text2, text3); + now = DateTime.Now; + } + Thread.Sleep(1000); + } + } + RegistryHelper.ConfigAutoStart(isAutoStart: false, args); + KillOtherDog(); + } + catch (Exception ex) + { + Console.WriteLine(ex.ToString()); + Console.Read(); + } + } + + private static void OnFatalException(Exception ex) + { + StringBuilder stringBuilder = new StringBuilder(); + string value = string.Format("{0} {1}", "Watchdog", ""); + stringBuilder.AppendLine(value); + stringBuilder.AppendLine(ex.Message); + stringBuilder.AppendLine(ex.GetType().Name); + stringBuilder.AppendLine(ex.StackTrace); + Log(stringBuilder.ToString()); + } + + private static void RegisterUnHandldException() + { + Application.ThreadException += Application_ThreadException; + AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException; + } + + [DllImport("user32.dll")] + public static extern bool ShowWindow(IntPtr hWnd, uint nCmdShow); + + private static void StartApp(string appName, string exe) + { + try + { + int num = CheckActive(appName); + Log($"尝试启动 {appName} 路径:{exe}"); + Directory.SetCurrentDirectory(new FileInfo(exe).Directory.ToString()); + Process.Start(exe); + if (CheckActive(appName) > num) + { + Log($"启动成功 {appName} 路径:{exe}"); + } + else + { + Log($"启动失败 {appName} 路径:{exe}"); + } + Thread.Sleep(3000); + } + catch (Exception arg) + { + Log($"启动异常 {appName} 路径:{exe} \r\n异常信息 {arg}"); + } + } +} diff --git a/Common.GLib/AXLib.Utility/Action.cs b/Common.GLib/AXLib.Utility/Action.cs new file mode 100644 index 0000000000000000000000000000000000000000..dcf7b14dff928c20b1993a76dae2981b938aeffb --- /dev/null +++ b/Common.GLib/AXLib.Utility/Action.cs @@ -0,0 +1,22 @@ +using System; + +namespace AXLib.Utility +{ + public class Action : IAction + { + private System.Action _action = null; + + public Action(System.Action action) + { + _action = action; + } + + public void invoke(T t) + { + if (_action != null) + { + _action(t); + } + } + } +} diff --git a/Common.GLib/AXLib.Utility/Callback.cs b/Common.GLib/AXLib.Utility/Callback.cs new file mode 100644 index 0000000000000000000000000000000000000000..ed764c70b76d571bb34a88c3aa3ab87bd50dacb7 --- /dev/null +++ b/Common.GLib/AXLib.Utility/Callback.cs @@ -0,0 +1,22 @@ +using System; + +namespace AXLib.Utility +{ + public class Callback : ICallback + { + private Action _action = null; + + public Callback(Action action) + { + _action = action; + } + + public void invoke() + { + if (_action != null) + { + _action(); + } + } + } +} diff --git a/Common.GLib/AXLib.Utility/IAction.cs b/Common.GLib/AXLib.Utility/IAction.cs new file mode 100644 index 0000000000000000000000000000000000000000..7762efa40d755ec19f5fa16a988d0950e0405c98 --- /dev/null +++ b/Common.GLib/AXLib.Utility/IAction.cs @@ -0,0 +1,7 @@ +namespace AXLib.Utility +{ + public interface IAction + { + void invoke(T t); + } +} diff --git a/Common.GLib/AXLib.Utility/ICallback.cs b/Common.GLib/AXLib.Utility/ICallback.cs new file mode 100644 index 0000000000000000000000000000000000000000..d036c8acc7f83f5de3c84d3a788f1be6c7df06ba --- /dev/null +++ b/Common.GLib/AXLib.Utility/ICallback.cs @@ -0,0 +1,7 @@ +namespace AXLib.Utility +{ + public interface ICallback + { + void invoke(); + } +} diff --git a/Common.GLib/Common.GLib.csproj b/Common.GLib/Common.GLib.csproj new file mode 100644 index 0000000000000000000000000000000000000000..7882e1c80875fa07bbdceae1b974fdc2d25dd6a6 --- /dev/null +++ b/Common.GLib/Common.GLib.csproj @@ -0,0 +1,22 @@ + + + Library + 8.0 + false + GLib + Common.GLib + netstandard2.0 + true + + + + TRACE;DEBUG;NETCOREAPP3_1 + + + + + + + + + \ No newline at end of file diff --git a/Common.GLib/GLib.AXLib.Utility/ALog.cs b/Common.GLib/GLib.AXLib.Utility/ALog.cs new file mode 100644 index 0000000000000000000000000000000000000000..453c94a2a55efc1a94d55a9aa00c24b943d873ac --- /dev/null +++ b/Common.GLib/GLib.AXLib.Utility/ALog.cs @@ -0,0 +1,109 @@ +using System; + +namespace GLib.AXLib.Utility +{ + public class ALog + { + public bool Enabled; + + public bool EnabledT; + + public bool EnabledI; + + public bool EnabledD; + + public bool EnabledE; + + public string Tag; + + private ALog(string tag) + { + Tag = tag; + Enabled = (EnabledT = (EnabledI = (EnabledD = (EnabledE = true)))); + } + + public static ALog Create(string tag) + { + return new ALog(tag); + } + + public static ALog Create(Type type) + { + return new ALog(type.Name); + } + + private void Print(string str) + { + Console.WriteLine(str); + } + + private void Print(Exception e) + { + Console.WriteLine(e.ToString()); + } + + public void I(string format, params string[] args) + { + if (Enabled && EnabledI) + { + Print(string.Format(format, args)); + } + } + + public void I(Exception e) + { + if (Enabled && EnabledI) + { + Print(e); + } + } + + public void T(string format, params string[] args) + { + if (Enabled && EnabledT) + { + Print(string.Format(format, args)); + } + } + + public void T(Exception e) + { + if (Enabled && EnabledT) + { + Print(e); + } + } + + public void D(string format, params string[] args) + { + if (Enabled && EnabledD) + { + Print(string.Format(format, args)); + } + } + + public void D(Exception e) + { + if (Enabled && EnabledD) + { + Print(e); + } + } + + public void E(string format, params string[] args) + { + if (Enabled && EnabledE) + { + Print(string.Format(format, args)); + } + } + + public void E(Exception e) + { + if (Enabled && EnabledE) + { + Print(e); + } + } + } +} diff --git a/Common.GLib/GLib.AXLib.Utility/Loop.cs b/Common.GLib/GLib.AXLib.Utility/Loop.cs new file mode 100644 index 0000000000000000000000000000000000000000..39f0040c7a34e00cdb5c0768dc6c753cc5619949 --- /dev/null +++ b/Common.GLib/GLib.AXLib.Utility/Loop.cs @@ -0,0 +1,53 @@ +using System; + +namespace GLib.AXLib.Utility +{ + public class Loop + { + private int _interval = 0; + + private Action _callback = null; + + private Action _error = null; + + private bool _isRuning = false; + + public Guid Key + { + get; + private set; + } + + public int Interval => _interval; + + public Loop(int interval, Action callback) + : this(interval, callback, null) + { + } + + public Loop(int interval, Action callback, Action error) + { + _interval = interval; + _callback = callback; + _error = error; + } + + public void Start() + { + if (!_isRuning) + { + _isRuning = true; + Key = ThreadEx.NewTimer(_interval, _callback, _error); + } + } + + public void Stop() + { + if (_isRuning) + { + _isRuning = false; + ThreadEx.FreeTimer(Key); + } + } + } +} diff --git a/Common.GLib/GLib.AXLib.Utility/ObjectPool.cs b/Common.GLib/GLib.AXLib.Utility/ObjectPool.cs new file mode 100644 index 0000000000000000000000000000000000000000..fc9f8771e16bae0c3c8f488a6b0bf1e5776e5d34 --- /dev/null +++ b/Common.GLib/GLib.AXLib.Utility/ObjectPool.cs @@ -0,0 +1,154 @@ +using GLib.GeneralModel; +using System; +using System.Collections.Generic; + +namespace GLib.AXLib.Utility +{ + public class ObjectPool + { + public class Item + { + private int _refCount = 0; + + private object _lockObj = new object(); + + private ObjectPool _control = null; + + public T Object + { + get; + private set; + } + + public Item(ObjectPool control, T @object) + { + Object = @object; + _control = control; + } + + public void AddRef() + { + lock (_lockObj) + { + _refCount++; + if (_refCount > 1) + { + throw new Exception(); + } + } + } + + public void DelRef() + { + lock (_lockObj) + { + _refCount--; + if (_refCount < 0) + { + throw new Exception(); + } + if (_refCount == 0) + { + _control.ReleaseItem(this); + } + } + } + } + + private int _min = 0; + + private int _max = 0; + + private int _count = 0; + + private AQueue _qIdle = new AQueue(); + + private List _listUsed = new List(); + + private Func _getObjectItemCallback = null; + + public ObjectPool(int count, Func getObjectItemCallback) + : this(count, count, getObjectItemCallback) + { + } + + public ObjectPool(int min, int max, Func getObjectItemCallback) + { + _min = min; + _max = max; + _getObjectItemCallback = getObjectItemCallback; + Init(); + } + + public ObjectPool(T[] arr) + { + _min = arr.Length; + _max = arr.Length; + lock (_qIdle) + { + foreach (T @object in arr) + { + Item item = new Item(this, @object); + _qIdle.Enqueue(item); + _count++; + } + } + } + + private void Init() + { + for (int i = 0; i < _min; i++) + { + AddItem(); + } + } + + private void AddItem() + { + lock (_qIdle) + { + Item item = new Item(this, _getObjectItemCallback()); + _qIdle.Enqueue(item); + _count++; + } + } + + public Item AllowItem() + { + lock (_qIdle) + { + if (_qIdle.Count > 0) + { + Item item = _qIdle.Dequeue(); + item.AddRef(); + lock (_listUsed) + { + if (!_listUsed.Contains(item)) + { + _listUsed.Add(item); + } + } + return item; + } + if (_count < _max) + { + AddItem(); + return AllowItem(); + } + return null; + } + } + + public void ReleaseItem(Item item) + { + lock (_qIdle) + { + lock (_listUsed) + { + _listUsed.Remove(item); + } + _qIdle.Enqueue(item); + } + } + } +} diff --git a/Common.GLib/GLib.AXLib.Utility/RuntimeExceptionEx.cs b/Common.GLib/GLib.AXLib.Utility/RuntimeExceptionEx.cs new file mode 100644 index 0000000000000000000000000000000000000000..dd05e448406d97c3f4e9a84b4e7dc9534c115b23 --- /dev/null +++ b/Common.GLib/GLib.AXLib.Utility/RuntimeExceptionEx.cs @@ -0,0 +1,62 @@ +using System; + +namespace GLib.AXLib.Utility +{ + public class RuntimeExceptionEx : Exception + { + private bool _setMsged = false; + + public new string Message = null; + + public bool CanCancel = false; + + public string StackTraceString = ""; + + public RuntimeExceptionEx(string msg) + : base(msg) + { + SetStackTraceString(); + } + + public RuntimeExceptionEx(Exception e) + : base(e.Message, e) + { + SetStackTraceString(); + } + + public RuntimeExceptionEx(string msg, Exception e) + : base(msg, e) + { + } + + private void SetStackTraceString() + { + StackTraceString = ToString(); + } + + public static string GetStackTraceString(Exception e) + { + return GetStackTraceString(e, ""); + } + + public static string GetStackTraceString(Exception e, string span) + { + return e?.ToString(); + } + + public static void PrintException(Exception e) + { + Console.WriteLine("PrintException", GetStackTraceString(e)); + } + + public static RuntimeExceptionEx Create(Exception e) + { + return new RuntimeExceptionEx(e); + } + + public static RuntimeExceptionEx Create(string msg) + { + return new RuntimeExceptionEx(msg); + } + } +} diff --git a/Common.GLib/GLib.AXLib.Utility/ThreadEx.cs b/Common.GLib/GLib.AXLib.Utility/ThreadEx.cs new file mode 100644 index 0000000000000000000000000000000000000000..e5595ae6112ba56c626e0a7dd92cb3f47a2b7a41 --- /dev/null +++ b/Common.GLib/GLib.AXLib.Utility/ThreadEx.cs @@ -0,0 +1,554 @@ +using GLib.GeneralModel; +using System; +using System.Collections.Generic; +using System.Threading; + +namespace GLib.AXLib.Utility +{ + public class ThreadEx + { + private class TimerExecuter + { + private bool _isworking = false; + + private Semaphore _semaphore = new Semaphore(0, 1); + + private TimerInfo _timerInfo; + + private Thread _loopThread = null; + + private Action _completed; + + private bool _rerun = false; + + private object _syncObj = new object(); + + public bool IsRuning + { + get; + private set; + } + + public long CompleteTime + { + get; + private set; + } + + public Thread Thread => _loopThread; + + public TimerExecuter(Action completed) + { + _completed = completed; + } + + public void Run(TimerInfo info) + { + if (!_isworking) + { + throw new Exception("status error"); + } + if (IsRuning) + { + throw new Exception("status error"); + } + _timerInfo = info; + _timerInfo.TimerThread = this; + if (!_DEBUG) + { + _semaphore.Release(1); + } + } + + public void ReRun(TimerInfo info) + { + if (!_isworking) + { + throw new Exception("status error"); + } + if (IsRuning) + { + throw new Exception("status error"); + } + _rerun = true; + _timerInfo = info; + _timerInfo.TimerThread = this; + } + + public void Start() + { + if (!_isworking) + { + _isworking = true; + _loopThread = ThreadCall(Loop); + } + } + + public void Stop() + { + if (_isworking) + { + _isworking = false; + ThreadStop(_loopThread); + } + } + + public void Reset() + { + if (_isworking) + { + _loopThread.Abort(); + _loopThread.Join(10); + _semaphore.Close(); + _semaphore = new Semaphore(0, 1); + if (_timerInfo != null && _timerInfo.TimerThread != null) + { + _timerInfo.TimerThread = null; + } + _timerInfo = null; + IsRuning = false; + _loopThread = ThreadCall(Loop); + ThreadReset(this); + } + } + + private void Loop() + { + Loop(null); + } + + private void Loop(object obj) + { + while (_isworking) + { + if (_DEBUG) + { + if (_timerInfo == null) + { + Thread.Sleep(5); + continue; + } + } + else if (!_rerun) + { + _semaphore.WaitOne(); + } + _rerun = false; + IsRuning = true; + Call(); + IsRuning = false; + OnCompleted(); + CompleteTime = TickCount; + } + } + + private void Call() + { + TimerInfo timerInfo = _timerInfo; + object syncObject = default(object); + try + { + bool lockTaken = false; + try + { + Monitor.Enter(syncObject = timerInfo.SyncObject, ref lockTaken); + timerInfo.IsRuning = true; + timerInfo.IsReady = false; + } + finally + { + if (lockTaken) + { + Monitor.Exit(syncObject); + } + } + timerInfo.LastBeginTime = TickCount; + timerInfo.Callback(); + timerInfo.LastEndTime = TickCount; + _timerInfo = null; + } + catch (Exception ex) + { + if (!(timerInfo?.IsFree ?? true)) + { + timerInfo.IsError = true; + timerInfo.Error = ex; + timerInfo.LastEndTime = TickCount; + OnError(ex); + } + _timerInfo = null; + } + finally + { + if (!(timerInfo?.IsFree ?? true)) + { + bool lockTaken2 = false; + try + { + Monitor.Enter(syncObject = timerInfo.SyncObject, ref lockTaken2); + timerInfo.IsRuning = false; + timerInfo.TimerThread = null; + } + finally + { + if (lockTaken2) + { + Monitor.Exit(syncObject); + } + } + } + } + } + + private void OnCompleted() + { + _completed(this); + } + + private void OnError(Exception e) + { + if (_timerInfo.ErrorHandle != null) + { + _timerInfo.ErrorHandle.BeginInvoke(e, null, null); + } + FreeTimer(_timerInfo.Key); + } + } + + private class TimerInfo + { + public Guid Key; + + public long LastBeginTime; + + public long LastEndTime; + + public string Name; + + public Action Callback; + + public int Interval; + + public bool IsReady; + + public bool IsRuning; + + public bool IsError; + + public bool IsFree; + + public Exception Error; + + public Action ErrorHandle; + + public object SyncObject = new object(); + + public TimerExecuter TimerThread; + } + + private static bool _DEBUG = false; + + private static int _maxThread = 400; + + private static bool _runing = false; + + private static Dictionary _dicTimers = new Dictionary(); + + private static AQueue _queueTimers = new AQueue(); + + private static AQueue _queueIdleThreads = new AQueue(); + + private static AQueue _queueCompleteThreads = new AQueue(); + + private static List _timerThreads = new List(); + + private static long _lastSystemTick = 0L; + + private static long _TickStart = 0L; + + private static long _TickCount = 0L; + + public static long TickCount + { + get + { + if (_TickCount == 0) + { + _TickCount = DateTime.Now.Ticks / 10000; + } + if (_lastSystemTick == Environment.TickCount) + { + return _TickCount; + } + _lastSystemTick = Environment.TickCount; + _TickCount = DateTime.Now.Ticks / 10000 - _TickStart; + return _TickCount; + } + } + + public static Thread Call(Action action, string name) + { + Thread thread = new Thread(action.Invoke); + if (name != null) + { + thread.Name = name; + } + thread.Start(); + return thread; + } + + public static Thread ThreadCall(Action action) + { + return ThreadCall(action, null); + } + + public static Thread ThreadCall(Action action, string name) + { + return Call(action, name); + } + + public static Loop LoopCall(int interval, Action callback, Action error) + { + Loop loop = new Loop(interval, callback, error); + loop.Start(); + return loop; + } + + public static void PoolCall(Action handle, object value = null) + { + ThreadPool.QueueUserWorkItem(handle.Invoke, value); + } + + public static void ThreadStop(Thread thread) + { + Stop(thread); + } + + public static void ThreadStop(Thread thread, object lockObj, int time) + { + bool flag = false; + try + { + flag = Monitor.TryEnter(lockObj, time); + } + finally + { + if (flag) + { + Monitor.Exit(lockObj); + } + } + Stop(thread); + } + + public static void LoopStop(Loop loop) + { + loop.Stop(); + } + + public static void Stop(Thread thread) + { + try + { + thread.Abort(); + } + catch + { + } + } + + public static void Sleep(int ms = 10) + { + Thread.Sleep(ms); + } + + public static Guid NewTimer(int interval, Action callback, Action errorHandle) + { + return NewTimer(interval, callback, null, errorHandle); + } + + public static Guid NewTimer(int interval, Action callback, string name, Action errorHandle) + { + TimerInfo timerInfo = new TimerInfo(); + timerInfo.Interval = interval; + timerInfo.Key = Guid.NewGuid(); + timerInfo.Callback = callback; + timerInfo.ErrorHandle = errorHandle; + timerInfo.IsError = false; + timerInfo.IsReady = false; + timerInfo.IsRuning = false; + timerInfo.Name = name; + TimerInfo timerInfo2 = timerInfo; + NewTimer(timerInfo2); + return timerInfo2.Key; + } + + private static void NewTimer(TimerInfo info) + { + lock (_dicTimers) + { + _dicTimers[info.Key] = info; + if (!_runing) + { + _runing = true; + ThreadCall(Thread1); + ThreadCall(Thread2); + } + } + } + + public static void FreeTimer(Guid key, bool _stopThread = false) + { + TimerInfo timerInfo = null; + lock (_dicTimers) + { + if (_dicTimers.ContainsKey(key)) + { + timerInfo = _dicTimers[key]; + timerInfo.IsFree = true; + _dicTimers.Remove(key); + } + } + if (timerInfo != null && _stopThread) + { + lock (timerInfo.SyncObject) + { + if (timerInfo.TimerThread != null) + { + timerInfo.TimerThread.Reset(); + } + } + } + } + + private static void Thread1() + { + while (true) + { + bool flag = true; + long tickCount = TickCount; + lock (_dicTimers) + { + foreach (TimerInfo value in _dicTimers.Values) + { + lock (value.SyncObject) + { + if (!value.IsReady && !value.IsRuning && tickCount - value.LastEndTime > value.Interval) + { + value.IsReady = true; + _queueTimers.Enqueue(value); + } + } + } + } + long tickCount2 = TickCount; + if (tickCount2 - tickCount < 5) + { + Thread.Sleep(5); + } + } + } + + private static void Thread2() + { + int num = 200; + while (true) + { + bool flag = true; + long tickCount = TickCount; + while (_queueTimers.Count > 0) + { + TimerInfo timerInfo = null; + lock (_queueTimers) + { + if (_queueTimers.Count > 0) + { + TimerInfo timerInfo2 = _queueTimers.Dequeue(); + if (timerInfo2 != null && _dicTimers.ContainsKey(timerInfo2.Key)) + { + timerInfo = timerInfo2; + } + } + } + if (timerInfo == null) + { + continue; + } + TimerExecuter timerExecuter = null; + while (true) + { + flag = true; + timerExecuter = GetIdleThread(); + if (timerExecuter != null) + { + break; + } + Thread.Sleep(1); + } + if (timerInfo == null) + { + throw new Exception("item null"); + } + timerExecuter.Run(timerInfo); + } + long tickCount2 = TickCount; + if (tickCount2 - tickCount < 5) + { + Thread.Sleep(5); + } + } + } + + private static void ThreadCompleted(TimerExecuter executer) + { + _ = _DEBUG; + bool flag = 1 == 0; + lock (_queueCompleteThreads) + { + _queueCompleteThreads.Enqueue(executer); + } + } + + private static void ThreadReset(TimerExecuter executer) + { + lock (_queueCompleteThreads) + { + if (!_queueCompleteThreads.Contains(executer)) + { + _queueCompleteThreads.Enqueue(executer); + } + } + } + + private static TimerExecuter GetIdleThread() + { + if (_queueIdleThreads.Count > 0) + { + return _queueIdleThreads.Dequeue(); + } + while (_queueCompleteThreads.Count > 0) + { + TimerExecuter timerExecuter = _queueCompleteThreads.Peek(); + timerExecuter = _queueCompleteThreads.Dequeue(); + _queueIdleThreads.Enqueue(timerExecuter); + } + if (_queueIdleThreads.Count > 0) + { + return _queueIdleThreads.Dequeue(); + } + if (_timerThreads.Count <= _maxThread) + { + return CreateThread(); + } + return null; + } + + private static TimerExecuter CreateThread() + { + TimerExecuter timerExecuter = new TimerExecuter(ThreadCompleted); + _timerThreads.Add(timerExecuter); + timerExecuter.Start(); + return timerExecuter; + } + } +} diff --git a/Common.GLib/GLib.AXLib.Utility/WaitResult.cs b/Common.GLib/GLib.AXLib.Utility/WaitResult.cs new file mode 100644 index 0000000000000000000000000000000000000000..be4c442a31cbbbc1d6542c4632977dbdfc136159 --- /dev/null +++ b/Common.GLib/GLib.AXLib.Utility/WaitResult.cs @@ -0,0 +1,68 @@ +using System; +using System.Threading; + +namespace GLib.AXLib.Utility +{ + public class WaitResult + { + private bool _isFinish = false; + + private Thread _waitThread = null; + + private object _lockObject = new object(); + + private Semaphore _sp = new Semaphore(0, 1); + + public T Result; + + public void Wait() + { + _waitThread = Thread.CurrentThread; + try + { + lock (_lockObject) + { + _sp.WaitOne(); + } + } + catch (Exception ex) + { + throw ex; + } + } + + public void Wait(long timeout) + { + _waitThread = Thread.CurrentThread; + try + { + lock (_lockObject) + { + _sp.WaitOne((int)timeout); + } + } + catch (Exception ex) + { + throw ex; + } + } + + public void Finish(T result) + { + Result = result; + _isFinish = true; + if (_waitThread != null) + { + lock (_lockObject) + { + _sp.Release(); + } + } + } + + public bool GetIsFinish() + { + return _isFinish; + } + } +} diff --git a/Common.GLib/GLib.Assist/XmlHelper.cs b/Common.GLib/GLib.Assist/XmlHelper.cs new file mode 100644 index 0000000000000000000000000000000000000000..664ecd21080ce3e9eb5d5753d41143eb558ce409 --- /dev/null +++ b/Common.GLib/GLib.Assist/XmlHelper.cs @@ -0,0 +1,178 @@ +using System; +using System.Collections.Generic; +using System.Xml; +using System.Xml.Linq; +using System.Xml.XPath; + +namespace GLib.Assist +{ + public static class XmlHelper + { + public static string GetXPath(string xeName, string xeAttribute, string xeValue, XmlRange range) + { + string result = null; + switch (range) + { + case XmlRange.All: + result = ((xeAttribute == null || xeValue == null || !(xeAttribute.Trim() != "") || !(xeValue.Trim() != "")) ? ("//" + xeName) : $"//{xeName}[@{xeAttribute}=\"{xeValue}\"]"); + break; + case XmlRange.Root: + result = ((xeAttribute == null || xeValue == null || !(xeAttribute.Trim() != "") || !(xeValue.Trim() != "")) ? ("/" + xeName) : $"/{xeName}[@{xeAttribute}=\"{xeValue}\"]"); + break; + case XmlRange.ThisNode: + result = ((xeAttribute == null || xeValue == null || !(xeAttribute.Trim() != "") || !(xeValue.Trim() != "")) ? (xeName ?? "") : $"{xeName}[@{xeAttribute}=\"{xeValue}\"]"); + break; + } + return result; + } + + public static XmlElement GetFirstXmlElement(string strXML, string xPath) + { + bool flag = false; + XmlDocument xmlDocument = new XmlDocument(); + try + { + xmlDocument.LoadXml(strXML); + flag = true; + } + catch (Exception) + { + throw new ArgumentException("Xml字符串格式错误", "strXML"); + } + if (flag) + { + return GetFirstXmlElement(xmlDocument, xPath); + } + return null; + } + + public static XmlElement GetFirstXmlElement(XmlElement xElement, string name, XmlRange range) + { + XmlDocument xmlDocument = new XmlDocument(); + xmlDocument.LoadXml(xElement.OuterXml); + return GetFirstXmlElement(xmlDocument, name, range); + } + + public static XmlElement GetFirstXmlElement(XmlElement xElement, string xPath) + { + XmlDocument xmlDocument = new XmlDocument(); + xmlDocument.LoadXml(xElement.OuterXml); + return GetFirstXmlElement(xmlDocument, xPath); + } + + public static XmlElement GetFirstXmlElement(XmlDocument xDoc, string name, XmlRange range) + { + string xPath = GetXPath(name, null, null, range); + return GetFirstXmlElement(xDoc, xPath); + } + + public static XmlElement GetFirstXmlElement(XmlDocument xDoc, string xPath) + { + XmlNode xmlNode = xDoc.DocumentElement.SelectSingleNode(xPath); + return (XmlElement)xmlNode; + } + + public static XmlElement GetFirstXmlElement(XmlDocument xDoc, string name, string attribute, string value, XmlRange range) + { + string xPath = GetXPath(name, attribute, value, range); + return GetFirstXmlElement(xDoc, xPath); + } + + public static XmlElement GetFirstXmlElement(XmlDocument xDoc, string name, string attribute, string value) + { + string xPath = GetXPath(name, attribute, value, XmlRange.ThisNode); + return GetFirstXmlElement(xDoc, xPath); + } + + public static XmlNodeList GetXmlNodeList(XmlDocument xDoc, string name, XmlRange range) + { + string xPath = GetXPath(name, null, null, range); + return GetXmlNodeList(xDoc, xPath); + } + + public static XmlNodeList GetXmlNodeList(XmlDocument xDoc, string name, string attribute, string value) + { + string xPath = GetXPath(name, attribute, value, XmlRange.ThisNode); + return GetXmlNodeList(xDoc, xPath); + } + + public static XmlNodeList GetXmlNodeList(XmlDocument xDoc, string name, string attribute, string value, XmlRange range) + { + string xPath = GetXPath(name, attribute, value, range); + return GetXmlNodeList(xDoc, xPath); + } + + public static XmlNodeList GetXmlNodeList(XmlDocument xDoc, string xPath) + { + return xDoc.DocumentElement.SelectNodes(xPath); + } + + public static XElement GetFirstXElement(XElement xElement, string name, XmlRange range) + { + string xPath = GetXPath(name, null, null, range); + return GetFirstXElement(xElement, xPath); + } + + public static XElement GetFirstXElement(XElement xElement, string xPath) + { + return xElement.XPathSelectElement(xPath); + } + + public static XElement GetFirstXElement(XElement xElement, string name, string attribute, string value, XmlRange range) + { + string xPath = GetXPath(name, null, null, range); + return GetFirstXElement(xElement, xPath); + } + + public static IEnumerable GetXElement(XElement xElement, string name, XmlRange range) + { + string xPath = GetXPath(name, null, null, range); + return GetXElement(xElement, xPath); + } + + public static IEnumerable GetXElement(XElement xElement, string xPath) + { + return xElement.XPathSelectElements(xPath); + } + + public static IEnumerable GetXElement(XElement xElement, string name, string attribute, string value, XmlRange range) + { + string xPath = GetXPath(name, null, null, range); + return GetXElement(xElement, xPath); + } + + public static XElement GetFirstXElement(XDocument xDoc, string name, XmlRange range) + { + string xPath = GetXPath(name, null, null, range); + return xDoc.Root.XPathSelectElement(xPath); + } + + public static XElement GetFirstXElement(XDocument xDoc, string xPath) + { + return xDoc.Root.XPathSelectElement(xPath); + } + + public static XElement GetFirstXElement(XDocument xDoc, string name, string attribute, string value, XmlRange range) + { + string xPath = GetXPath(name, null, null, range); + return xDoc.Root.XPathSelectElement(xPath); + } + + public static IEnumerable GetXElement(XDocument xDoc, string name, XmlRange range) + { + string xPath = GetXPath(name, null, null, range); + return xDoc.Root.XPathSelectElements(xPath); + } + + public static IEnumerable GetXElement(XDocument xDoc, string xPath) + { + return xDoc.Root.XPathSelectElements(xPath); + } + + public static IEnumerable GetXElement(XDocument xDoc, string name, string attribute, string value, XmlRange range) + { + string xPath = GetXPath(name, null, null, range); + return xDoc.Root.XPathSelectElements(xPath); + } + } +} diff --git a/Common.GLib/GLib.Assist/XmlRange.cs b/Common.GLib/GLib.Assist/XmlRange.cs new file mode 100644 index 0000000000000000000000000000000000000000..10626703dc18e6a9dd2d45d1cc9793794251027f --- /dev/null +++ b/Common.GLib/GLib.Assist/XmlRange.cs @@ -0,0 +1,9 @@ +namespace GLib.Assist +{ + public enum XmlRange + { + All = 0, + Root = 1, + ThisNode = 2 + } +} diff --git a/Common.GLib/GLib.Data.Core/DataBaseType.cs b/Common.GLib/GLib.Data.Core/DataBaseType.cs new file mode 100644 index 0000000000000000000000000000000000000000..d655b15a7558cee81ad7fcf14f172b0a6b17c703 --- /dev/null +++ b/Common.GLib/GLib.Data.Core/DataBaseType.cs @@ -0,0 +1,10 @@ +namespace GLib.Data.Core +{ + public enum DataBaseType + { + SqlServer = 1, + Access = 2, + MySql = 3, + Oracle = 4 + } +} diff --git a/Common.GLib/GLib.Data.Core/IRepository.cs b/Common.GLib/GLib.Data.Core/IRepository.cs new file mode 100644 index 0000000000000000000000000000000000000000..790840194e1f506f3df8a12a49a9aa8188fcdf81 --- /dev/null +++ b/Common.GLib/GLib.Data.Core/IRepository.cs @@ -0,0 +1,66 @@ +using GLib.Data.Entity; +using System; + +namespace GLib.Data.Core +{ + public interface IRepository : IDisposable + { + bool Exists(TL model); + + bool Exists(int id); + + bool Exists(long id); + + bool Exists(string selector); + + bool Exists(string selector, params DBParam[] values); + + int Sum(string selector, string column); + + int Sum(string selector, string column, params DBParam[] values); + + int InsertModel(TL model); + + int[] InsertModelList(TL[] modelList); + + TL GetModel(int id); + + TL GetModel(long id); + + TL GetModel(TL model); + + TL GetModel(string selector, params DBParam[] values); + + TL GetModel(string selector, string colList, params DBParam[] values); + + TL[] GetModelList(); + + TL[] GetModelList(TL model); + + TL[] GetModelList(string selector, params DBParam[] values); + + TL[] GetModelList(string selector, string ordering, params DBParam[] values); + + TL[] GetModelList(string selector, string ordering, string colList, params DBParam[] values); + + TL[] GetModelList(string selector, string ordering, string colList, int pageIndex, int pageSize, params DBParam[] values); + + int GetModelListCount(string selector, params DBParam[] values); + + bool UpdateModel(TL model); + + bool UpdateModel(TL model, string colList); + + bool UpdateModel(TL model, string selector, params DBParam[] values); + + bool UpdateModel(TL model, string colList, string selector, params DBParam[] values); + + bool DeleteModel(int id); + + bool DeleteModel(long id); + + bool DeleteModel(TL model); + + bool Delete(string selector, params DBParam[] values); + } +} diff --git a/Common.GLib/GLib.Data.Core/ISqlCreator.cs b/Common.GLib/GLib.Data.Core/ISqlCreator.cs new file mode 100644 index 0000000000000000000000000000000000000000..edac4d4a1befeabf608dd79ddc7a7879150c9c03 --- /dev/null +++ b/Common.GLib/GLib.Data.Core/ISqlCreator.cs @@ -0,0 +1,30 @@ +using GLib.Data.Entity; +using System; + +namespace GLib.Data.Core +{ + public interface ISqlCreator : IDisposable where TL : ILogicEntity, new() + { + string CreateMaxSql(string selector, string col); + + string CreateCountSql(string selector, string col); + + string CreateSumSql(string selector, string col); + + string CreateInsertSql(TL model, out DBParam[] outparam); + + string CreateUpdateSql(TL model, string colList, string selector, out DBParam[] outparam, params DBParam[] values); + + string CreateDeleteSql(TL model, out DBParam[] outparam); + + string CreateDeleteSql(string selector); + + string CreateModelSql(TL model, out DBParam[] outparam); + + string CreateModelSql(string selector, string colList); + + string CreatePageSql(TL model, out DBParam[] outparam); + + string CreatePageSql(string selector, int pageIndex, int pageSize, string ordering, string colList, params DBParam[] values); + } +} diff --git a/Common.GLib/GLib.Data.Core/Repository.cs b/Common.GLib/GLib.Data.Core/Repository.cs new file mode 100644 index 0000000000000000000000000000000000000000..49342e2d0de58d9af4e761b3748a51283a8f6277 --- /dev/null +++ b/Common.GLib/GLib.Data.Core/Repository.cs @@ -0,0 +1,594 @@ +using GLib.Data.Entity; +using GLib.Logging; +using System; +using System.Collections.Generic; +using System.Data; +using System.Reflection; + +namespace GLib.Data.Core +{ + public class Repository : IRepository, IDisposable where TL : ILogicEntity, new() + { + private ISqlCreator creator = null; + + private string _dbname = ""; + + private string _PrimaryKey = ""; + + private TL _model = default(TL); + + private int _PageSize = 100; + + private TL Model + { + get + { + if (_model == null) + { + _model = new TL(); + } + return _model; + } + } + + public string DbName + { + get + { + if (string.IsNullOrEmpty(_dbname)) + { + if (Model == null) + { + throw new ArgumentNullException("model is null!"); + } + _dbname = Model.DbName; + } + return _dbname; + } + set + { + _dbname = value; + } + } + + public string PrimaryKey + { + get + { + if (_PrimaryKey == "") + { + if (Model == null) + { + throw new ArgumentNullException("model is null !"); + } + _PrimaryKey = Model.PrimaryKey; + } + return _PrimaryKey; + } + set + { + _PrimaryKey = value; + } + } + + public int MaxID + { + get + { + string strCommand = creator.CreateMaxSql(string.Empty, PrimaryKey); + object obj = SqlHelper.ExecuteScalar(DbName, strCommand, CommandType.Text, null); + if (obj == null) + { + return 0; + } + if (obj.ToString().Trim() == "") + { + return 0; + } + return int.Parse(obj.ToString()); + } + } + + public int PageSize + { + get + { + return _PageSize; + } + set + { + _PageSize = value; + } + } + + public Repository() + { + creator = SqlCreatorFactory.GetSqlCreator(); + } + + protected Repository(string dbName) + : this() + { + _dbname = dbName; + creator = SqlCreatorFactory.GetSqlCreator(); + } + + public virtual bool Exists(TL model) + { + throw new ArgumentNullException("Exists is not implement!"); + } + + public virtual bool Exists(int id) + { + return Exists($"{PrimaryKey}=@0", new DBParam + { + ParamName = PrimaryKey, + ParamDbType = DbType.Int32, + ParamValue = id + }); + } + + public virtual bool Exists(long id) + { + return Exists($"{PrimaryKey}=@0", new DBParam + { + ParamName = PrimaryKey, + ParamDbType = DbType.Int64, + ParamValue = id + }); + } + + public virtual bool Exists(string selector) + { + return Exists(selector, (DBParam[])null); + } + + public virtual bool Exists(string selector, params DBParam[] values) + { + string strCommand = creator.CreateCountSql(selector, string.Empty); + object obj = SqlHelper.ExecuteScalar(DbName, strCommand, CommandType.Text, values); + if (object.Equals(obj, null) || object.Equals(obj, DBNull.Value)) + { + return false; + } + if (Convert.ToInt32(obj) == 0) + { + return false; + } + return true; + } + + public virtual int Sum(string selector, string column) + { + return Sum(selector, column, (DBParam[])null); + } + + public virtual int Sum(string selector, string column, params DBParam[] values) + { + string strCommand = creator.CreateSumSql(selector, column); + object obj = SqlHelper.ExecuteScalar(DbName, strCommand, CommandType.Text, values); + if (object.Equals(obj, null) || object.Equals(obj, DBNull.Value)) + { + return 0; + } + return Convert.ToInt32(obj); + } + + public virtual int InsertModel(TL model) + { + _model = model; + try + { + DBParam[] outparam = null; + string strCommand = creator.CreateInsertSql(model, out outparam); + if (model.IsAutoID) + { + object obj = SqlHelper.ExecuteScalar(DbName, strCommand, CommandType.Text, outparam); + if (SqlHelper.GetDBType() == DataBaseType.Access) + { + return MaxID; + } + if (obj == null || obj == DBNull.Value) + { + return 0; + } + return Convert.ToInt32(obj); + } + return SqlHelper.ExecuteNonQuery(DbName, strCommand, CommandType.Text, outparam); + } + catch (Exception ex) + { + Log log = new Log(); + log.Write(new LogMessage + { + Content = "GLib.Data.Core.Repository. InsertModel(TL model):\r\n " + ex.Message, + Type = MessageType.Error + }); + return 0; + } + } + + public virtual int[] InsertModelList(TL[] modelList) + { + List list = new List(); + foreach (TL model in modelList) + { + int item; + if ((item = InsertModel(model)) > 0) + { + list.Add(item); + } + } + return list.ToArray(); + } + + public virtual TL GetModel(int id) + { + return GetModel($"{PrimaryKey}={id}", string.Empty, (DBParam[])null); + } + + public virtual TL GetModel(long id) + { + return GetModel($"{PrimaryKey}={id}", string.Empty, (DBParam[])null); + } + + public virtual TL GetModel(TL model) + { + try + { + DBParam[] outparam = null; + string strCommand = creator.CreateModelSql(model, out outparam); + model = default(TL); + using (IDataReader dataReader = SqlHelper.ExecuteDataReader(DbName, strCommand, CommandType.Text, outparam)) + { + if (dataReader.Read()) + { + model = GetModel(dataReader); + } + dataReader.Close(); + } + return model; + } + catch (Exception ex) + { + Log log = new Log(); + log.Write(new LogMessage + { + Content = "GLib.Data.Core.Repository. GetModel(String selector, String colList, params DBParam[] values):\r\n " + ex.Message, + Type = MessageType.Error + }); + return default(TL); + } + } + + public virtual TL GetModel(string selector, params DBParam[] values) + { + return GetModel(selector, string.Empty, values); + } + + public virtual TL GetModel(string selector, string colList, params DBParam[] values) + { + try + { + string strCommand = creator.CreateModelSql(selector, colList); + TL result = default(TL); + using (IDataReader dataReader = SqlHelper.ExecuteDataReader(DbName, strCommand, CommandType.Text, values)) + { + if (dataReader.Read()) + { + result = GetModel(dataReader); + } + dataReader.Close(); + } + return result; + } + catch (Exception ex) + { + Log log = new Log(); + log.Write(new LogMessage + { + Content = "GLib.Data.Core.Repository. GetModel(String selector, String colList, params DBParam[] values):\r\n " + ex.Message, + Type = MessageType.Error + }); + return default(TL); + } + } + + public virtual TL GetModel(IDataReader dr) + { + TL val = new TL(); + PropertyInfo[] properties = EntityTypeCache.GetEntityInfo(typeof(TL)).Properties; + PropertyInfo[] array = properties; + foreach (PropertyInfo propertyInfo in array) + { + object[] customAttributes = propertyInfo.GetCustomAttributes(typeof(EntityAttribute), inherit: true); + EntityAttribute entityAttribute = null; + if (customAttributes.Length > 0) + { + entityAttribute = (EntityAttribute)customAttributes[0]; + } + if (entityAttribute != null && entityAttribute.CustomMember) + { + continue; + } + int ordinal; + try + { + ordinal = dr.GetOrdinal(propertyInfo.Name); + } + catch (IndexOutOfRangeException) + { + continue; + } + object value; + if (dr.IsDBNull(ordinal) && EntityHelper.GetDbType(propertyInfo.PropertyType) == DbType.String) + { + value = string.Empty; + } + else + { + if (dr.IsDBNull(ordinal)) + { + continue; + } + value = dr.GetValue(ordinal); + } + propertyInfo.SetValue(val, value, null); + } + return val; + } + + public virtual TL[] GetModelList() + { + return GetModelList(string.Empty, string.Empty, string.Empty, 0, PageSize, (DBParam[])null); + } + + public virtual TL[] GetModelList(TL model) + { + try + { + DBParam[] outparam = null; + string strCommand = creator.CreatePageSql(model, out outparam); + TL[] array = null; + using (IDataReader dr = SqlHelper.ExecuteDataReader(DbName, strCommand, CommandType.Text, outparam)) + { + array = GetModelList(dr); + } + if (array == null) + { + array = new TL[0]; + } + return array; + } + catch (Exception ex) + { + Log log = new Log(); + log.Write(new LogMessage + { + Content = "GLib.Data.Core.Repository.GetModelList(TL model)" + ex.Message, + Type = MessageType.Error + }); + return null; + } + } + + public virtual TL[] GetModelList(string selector, params DBParam[] values) + { + return GetModelList(selector, string.Empty, values); + } + + public virtual TL[] GetModelList(string selector, string ordering, params DBParam[] values) + { + return GetModelList(selector, ordering, string.Empty, values); + } + + public virtual TL[] GetModelList(string selector, string ordering, string colList, params DBParam[] values) + { + return GetModelList(selector, ordering, colList, 0, PageSize, values); + } + + public virtual TL[] GetModelList(string selector, string ordering, string colList, int pageIndex, int pageSize, params DBParam[] values) + { + if (pageIndex <= 0) + { + pageIndex = 1; + } + if (pageSize <= 0) + { + pageSize = PageSize; + } + try + { + string strCommand = creator.CreatePageSql(selector, pageIndex, pageSize, ordering, colList, values); + TL[] array = null; + using (IDataReader dr = SqlHelper.ExecuteDataReader(DbName, strCommand, CommandType.Text, values)) + { + array = GetModelList(dr); + } + if (array == null) + { + array = new TL[0]; + } + return array; + } + catch (Exception ex) + { + Log log = new Log(); + log.Write(new LogMessage + { + Content = "GLib.Data.Core.Repository. GetModelList(String selector, String ordering, String colList, Int32 pageIndex, Int32 pageSize, params DBParam[] values):\r\n " + ex.Message, + Type = MessageType.Error + }); + return null; + } + } + + public virtual PageList GetPageList(string selector, string ordering, string colList, int pageIndex, int pageSize, params DBParam[] values) + { + if (pageIndex <= 0) + { + pageIndex = 1; + } + if (pageSize <= 0) + { + pageSize = PageSize; + } + PageList pageList = new PageList(pageIndex, pageSize, 0); + string str = creator.CreatePageSql(selector, pageIndex, pageSize, ordering, colList, values); + string str2 = creator.CreateCountSql(selector, string.Empty); + try + { + List list = new List(); + using (IDataReader dataReader = SqlHelper.ExecuteDataReader(DbName, str + " " + str2, CommandType.Text, values)) + { + while (dataReader.Read()) + { + list.Add(GetModel(dataReader)); + } + if (!dataReader.IsClosed) + { + dataReader.Close(); + } + } + pageList.TotalCount = GetModelListCount(selector, values); + pageList.AddRange(list); + return pageList; + } + catch (Exception ex) + { + Log log = new Log(); + log.Write(new LogMessage + { + Content = "GLib.Data.Core.Repository.GetPageList(String selector, String ordering, String colList, int pageIndex, int pageSize, params DBParam[] values):\r\n " + ex.Message, + Type = MessageType.Error + }); + return pageList; + } + } + + public virtual TL[] GetModelList(IDataReader dr) + { + List list = new List(); + if (dr != null) + { + while (dr.Read()) + { + list.Add(GetModel(dr)); + } + dr?.Close(); + } + return list.ToArray(); + } + + public virtual int GetModelListCount(string selector, params DBParam[] values) + { + int num = 0; + try + { + string strCommand = creator.CreateCountSql(selector, string.Empty); + return int.Parse(SqlHelper.ExecuteScalar(DbName, strCommand, CommandType.Text, values).ToString()); + } + catch (Exception ex) + { + Log log = new Log(); + log.Write(new LogMessage + { + Content = "GLib.Data.Core.Repository. GetModelListCount(String selector, params DBParam[] values):\r\n " + ex.Message, + Type = MessageType.Error + }); + return 0; + } + } + + public virtual bool UpdateModel(TL model) + { + return UpdateModel(model, string.Empty, string.Empty, (DBParam[])null); + } + + public virtual bool UpdateModel(TL model, string colList) + { + return UpdateModel(model, colList, string.Empty, (DBParam[])null); + } + + public virtual bool UpdateModel(TL model, string selector, params DBParam[] values) + { + return UpdateModel(model, string.Empty, selector, values); + } + + public virtual bool UpdateModel(TL model, string colList, string selector, params DBParam[] values) + { + _model = model; + try + { + DBParam[] outparam = null; + string strCommand = creator.CreateUpdateSql(model, colList, selector, out outparam, values); + return SqlHelper.ExecuteNonQuery(DbName, strCommand, CommandType.Text, outparam) > 0; + } + catch (Exception ex) + { + Log log = new Log(); + log.Write(new LogMessage + { + Content = "GLib.Data.Core.Repository. UpdateModel(TL model, string colList, string selector, params DBParam[] values):\r\n " + ex.Message, + Type = MessageType.Error + }); + return false; + } + } + + public virtual bool DeleteModel(int id) + { + return Delete($"{PrimaryKey}={id}", (DBParam[])null); + } + + public virtual bool DeleteModel(long id) + { + return Delete($"{PrimaryKey}={id}", (DBParam[])null); + } + + public virtual bool DeleteModel(TL model) + { + _model = model; + try + { + DBParam[] outparam = null; + string strCommand = creator.CreateDeleteSql(model, out outparam); + return SqlHelper.ExecuteNonQuery(DbName, strCommand, CommandType.Text, outparam) > 0; + } + catch (Exception ex) + { + Log log = new Log(); + log.Write(new LogMessage + { + Content = "GLib.Data.Core.Repository.Delete(TL model):\r\n " + ex.Message, + Type = MessageType.Error + }); + return false; + } + } + + public virtual bool Delete(string selector, params DBParam[] values) + { + try + { + string strCommand = creator.CreateDeleteSql(selector); + return SqlHelper.ExecuteNonQuery(DbName, strCommand, CommandType.Text, values) > 0; + } + catch (Exception ex) + { + Log log = new Log(); + log.Write(new LogMessage + { + Content = "GLib.Data.Core.Repository.Delete(String selector, params DBParam[] values):\r\n " + ex.Message, + Type = MessageType.Error + }); + return false; + } + } + + public void Dispose() + { + GC.SuppressFinalize(true); + } + } +} diff --git a/Common.GLib/GLib.Data.Core/SqLiteCreator.cs b/Common.GLib/GLib.Data.Core/SqLiteCreator.cs new file mode 100644 index 0000000000000000000000000000000000000000..d3f818849d7d6d162d0aff2af73b510968173f93 --- /dev/null +++ b/Common.GLib/GLib.Data.Core/SqLiteCreator.cs @@ -0,0 +1,419 @@ +using GLib.Data.Entity; +using System; +using System.Collections.Generic; +using System.Reflection; +using System.Text; + +namespace GLib.Data.Core +{ + public class SqLiteCreator : ISqlCreator, IDisposable where TL : ILogicEntity, new() + { + private string _PrimaryKey = ""; + + private string _TableName = ""; + + private TL _model = default(TL); + + private int _PageSize = 100; + + private TL Model + { + get + { + if (_model == null) + { + _model = new TL(); + } + return _model; + } + } + + public string PrimaryKey + { + get + { + if (_PrimaryKey == "") + { + if (Model == null) + { + throw new ArgumentNullException("model is null !"); + } + _PrimaryKey = Model.PrimaryKey; + } + return _PrimaryKey; + } + set + { + _PrimaryKey = value; + } + } + + public virtual string TableName + { + get + { + if (_TableName == "") + { + bool flag = false; + PropertyInfo[] properties = EntityTypeCache.GetEntityInfo(typeof(TL)).Properties; + for (int i = 0; i < properties.Length; i++) + { + if (properties[i].Name.Trim().ToLower() == "TableName".ToLower()) + { + object value = properties[i].GetValue(Model, null); + if (value != null && !string.IsNullOrEmpty(value.ToString())) + { + _TableName = value.ToString(); + flag = true; + break; + } + } + } + if (!flag) + { + _TableName = "[" + typeof(TL).Name + "]"; + } + } + return _TableName; + } + set + { + _TableName = value; + } + } + + public int PageSize + { + get + { + return _PageSize; + } + set + { + _PageSize = value; + } + } + + public string CreateMaxSql(string selector, string col) + { + col = (string.IsNullOrEmpty(col) ? PrimaryKey : col); + StringBuilder stringBuilder = new StringBuilder(); + stringBuilder.Append($"select max({GetSQLFildList(col)}) from {TableName}"); + if (!string.IsNullOrEmpty(selector)) + { + stringBuilder.Append(" where " + selector); + } + return stringBuilder.ToString(); + } + + public string CreateCountSql(string selector, string col) + { + col = (string.IsNullOrEmpty(col) ? "1" : col); + StringBuilder stringBuilder = new StringBuilder(); + stringBuilder.Append($"select count({col}) as TotalCount from {TableName} "); + if (!string.IsNullOrEmpty(selector)) + { + stringBuilder.Append(" where " + selector); + } + return stringBuilder.ToString(); + } + + public string CreateSumSql(string selector, string col) + { + StringBuilder stringBuilder = new StringBuilder(); + stringBuilder.Append($"select sum({GetSQLFildList(col)}) from {TableName} "); + if (!string.IsNullOrEmpty(selector)) + { + stringBuilder.Append(" where " + selector); + } + return stringBuilder.ToString(); + } + + public string CreateInsertSql(TL model, out DBParam[] outparam) + { + StringBuilder stringBuilder = new StringBuilder(); + StringBuilder stringBuilder2 = new StringBuilder(); + stringBuilder.Append($"insert into {TableName}("); + PropertyInfo[] properties = EntityTypeCache.GetEntityInfo(typeof(TL)).Properties; + List list = new List(); + for (int i = 0; i < properties.Length; i++) + { + object[] customAttributes = properties[i].GetCustomAttributes(typeof(EntityAttribute), inherit: true); + EntityAttribute entityAttribute = null; + if (customAttributes.Length > 0) + { + entityAttribute = (EntityAttribute)customAttributes[0]; + } + if (!model.IsAutoID || !(model.PrimaryKey == properties[i].Name) || entityAttribute == null || !entityAttribute.IsDbGenerated) + { + if (properties[i].Name == PrimaryKey && entityAttribute != null && !entityAttribute.IsDbGenerated) + { + stringBuilder.Append("[" + properties[i].Name + "],"); + stringBuilder2.Append("@" + properties[i].Name + ","); + list.Add(new DBParam + { + ParamName = properties[i].Name, + ParamDbType = EntityHelper.GetDbType(properties[i].PropertyType), + ParamValue = EntityHelper.GetTypeDefaultValue(properties[i].GetValue(model, null), EntityHelper.GetDbType(properties[i].PropertyType)) + }); + } + else if (properties[i].Name != PrimaryKey && (entityAttribute == null || (!entityAttribute.IsDbGenerated && !entityAttribute.CustomMember))) + { + stringBuilder.Append("[" + properties[i].Name + "],"); + stringBuilder2.Append("@" + properties[i].Name + ","); + list.Add(new DBParam + { + ParamName = properties[i].Name, + ParamDbType = EntityHelper.GetDbType(properties[i].PropertyType), + ParamValue = EntityHelper.GetTypeDefaultValue(properties[i].GetValue(model, null), EntityHelper.GetDbType(properties[i].PropertyType)) + }); + } + } + } + stringBuilder = stringBuilder.Replace(",", ")", stringBuilder.Length - 1, 1); + stringBuilder2 = stringBuilder2.Replace(",", ")", stringBuilder2.Length - 1, 1); + stringBuilder.Append(" values ("); + stringBuilder.Append(stringBuilder2.ToString() + ";"); + if (model.IsAutoID) + { + stringBuilder.Append($" select ident_current('{TableName}') "); + } + outparam = list.ToArray(); + return stringBuilder.ToString(); + } + + public string CreateUpdateSql(TL model, string colList, string selector, out DBParam[] outparam, params DBParam[] values) + { + StringBuilder stringBuilder = new StringBuilder(); + stringBuilder.Append("update " + TableName + " set "); + PropertyInfo[] properties = EntityTypeCache.GetEntityInfo(typeof(TL)).Properties; + PropertyInfo propertyInfo = null; + List list = new List(); + for (int i = 0; i < properties.Length; i++) + { + object[] customAttributes = properties[i].GetCustomAttributes(typeof(EntityAttribute), inherit: true); + EntityAttribute entityAttribute = null; + if (customAttributes.Length > 0) + { + entityAttribute = (EntityAttribute)customAttributes[0]; + } + if (properties[i].Name == PrimaryKey) + { + propertyInfo = properties[i]; + } + else if (properties[i].Name != PrimaryKey && !(entityAttribute?.CustomMember ?? false) && (string.IsNullOrEmpty(colList) || colList.IndexOf(properties[i].Name.Trim()) >= 0) && !EntityHelper.IsTypeMinValue(properties[i].GetValue(model, null), EntityHelper.GetDbType(properties[i].PropertyType))) + { + stringBuilder.Append("[" + properties[i].Name + "]=@" + properties[i].Name + ","); + list.Add(new DBParam + { + ParamDbType = EntityHelper.GetDbType(properties[i].PropertyType), + ParamName = properties[i].Name, + ParamValue = properties[i].GetValue(model, null) + }); + } + } + stringBuilder = stringBuilder.Replace(",", " ", stringBuilder.Length - 1, 1); + if (!string.IsNullOrEmpty(selector)) + { + stringBuilder.Append(" where 1=1 and " + selector); + if (values != null) + { + for (int i = 0; i < values.Length; i++) + { + list.Insert(i, values[i]); + } + } + } + else + { + stringBuilder.Append(" where [" + PrimaryKey + "]=@" + PrimaryKey); + list.Add(new DBParam + { + ParamDbType = EntityHelper.GetDbType(propertyInfo.PropertyType), + ParamName = propertyInfo.Name, + ParamValue = propertyInfo.GetValue(model, null) + }); + } + outparam = list.ToArray(); + return stringBuilder.ToString(); + } + + public string CreateDeleteSql(TL model, out DBParam[] outparam) + { + StringBuilder stringBuilder = new StringBuilder(); + PropertyInfo[] properties = EntityTypeCache.GetEntityInfo(typeof(TL)).Properties; + PropertyInfo propertyInfo = null; + List list = new List(); + for (int i = 0; i < properties.Length; i++) + { + object[] customAttributes = properties[i].GetCustomAttributes(typeof(EntityAttribute), inherit: true); + EntityAttribute entityAttribute = null; + if (customAttributes.Length > 0) + { + entityAttribute = (EntityAttribute)customAttributes[0]; + } + if (properties[i].Name == PrimaryKey) + { + propertyInfo = properties[i]; + } + } + stringBuilder.Append(" " + PrimaryKey + "=@" + PrimaryKey); + list.Add(new DBParam + { + ParamDbType = EntityHelper.GetDbType(propertyInfo.PropertyType), + ParamName = propertyInfo.Name, + ParamValue = propertyInfo.GetValue(model, null) + }); + outparam = list.ToArray(); + return CreateDeleteSql(stringBuilder.ToString()); + } + + public string CreateDeleteSql(string selector) + { + StringBuilder stringBuilder = new StringBuilder(); + stringBuilder.Append("delete from " + TableName); + if (!string.IsNullOrEmpty(selector)) + { + stringBuilder.Append(" where " + selector); + } + return stringBuilder.ToString(); + } + + public string CreateModelSql(TL model, out DBParam[] outparam) + { + PropertyInfo[] properties = EntityTypeCache.GetEntityInfo(typeof(TL)).Properties; + List list = new List(); + for (int i = 0; i < properties.Length; i++) + { + if (properties[i].Name == PrimaryKey) + { + list.Add(new DBParam + { + ParamName = properties[i].Name, + ParamDbType = EntityHelper.GetDbType(properties[i].PropertyType), + ParamValue = properties[i].GetValue(model, null) + }); + break; + } + } + outparam = list.ToArray(); + return CreateModelSql(string.Format("{0}=@{0}", PrimaryKey), string.Empty); + } + + public string CreateModelSql(string selector, string colList) + { + StringBuilder stringBuilder = new StringBuilder(); + if (string.IsNullOrEmpty(colList)) + { + stringBuilder.Append(string.Format("select top 1 {0} from {1}", "*", TableName)); + } + else + { + stringBuilder.Append(string.Format("select top 1 {0} from {1}", colList.Replace("new", ""), TableName)); + } + if (!string.IsNullOrEmpty(selector)) + { + stringBuilder.Append(" where " + selector); + } + return stringBuilder.ToString(); + } + + public string CreatePageSql(TL model, out DBParam[] outparam) + { + PropertyInfo[] properties = EntityTypeCache.GetEntityInfo(typeof(TL)).Properties; + List list = new List(); + for (int i = 0; i < properties.Length; i++) + { + if (properties[i].Name == PrimaryKey) + { + list.Add(new DBParam + { + ParamName = properties[i].Name, + ParamDbType = EntityHelper.GetDbType(properties[i].PropertyType), + ParamValue = properties[i].GetValue(model, null) + }); + break; + } + } + outparam = list.ToArray(); + return CreatePageSql(string.Format("{0}=@{0}", PrimaryKey), 0, PageSize, string.Empty, string.Empty, outparam); + } + + public string CreatePageSql(string selector, int pageIndex, int pageSize, string ordering, string colList, params DBParam[] values) + { + pageIndex = ((pageIndex <= 0) ? 1 : pageIndex); + if (pageSize == 0) + { + pageSize = PageSize; + } + string text = ""; + if (string.IsNullOrEmpty(colList) || colList == "*") + { + PropertyInfo[] properties = EntityTypeCache.GetEntityInfo(typeof(TL)).Properties; + PropertyInfo[] array = properties; + foreach (PropertyInfo propertyInfo in array) + { + object[] customAttributes = propertyInfo.GetCustomAttributes(typeof(EntityAttribute), inherit: true); + EntityAttribute entityAttribute = null; + if (customAttributes.Length > 0) + { + entityAttribute = (EntityAttribute)customAttributes[0]; + } + if (!(entityAttribute?.CustomMember ?? false)) + { + text = text + "[" + propertyInfo.Name + "],"; + } + } + text = text.Substring(0, text.Length - 1); + } + else + { + text = GetSQLFildList(colList); + } + StringBuilder stringBuilder = new StringBuilder(); + string arg; + if (string.IsNullOrEmpty(ordering)) + { + arg = ((!string.IsNullOrEmpty(PrimaryKey)) ? $" order by {PrimaryKey} desc" : string.Format(" order by {0} desc", "newid()")); + } + else + { + ordering = ordering.Replace("descending", "desc").Replace("ascending", "asc"); + arg = $" order by {ordering}"; + } + if (string.IsNullOrEmpty(selector)) + { + stringBuilder.Append($"select {text} from {TableName} "); + stringBuilder.Append($" {arg} limit {(pageIndex - 1) * pageSize},{pageSize};"); + } + else + { + stringBuilder.Append($"select {text} from {TableName} "); + stringBuilder.Append($" where {SqlHelper.ParseSelector(selector, values)}"); + stringBuilder.Append($" {arg} limit {(pageIndex - 1) * pageSize},{pageSize};"); + } + return stringBuilder.ToString(); + } + + public void Dispose() + { + GC.SuppressFinalize(this); + } + + private string GetSQLFildList(string fldList) + { + if (string.IsNullOrEmpty(fldList)) + { + return "*"; + } + if (fldList.Trim() == "*") + { + return "*"; + } + fldList = "[" + fldList + "]"; + fldList = fldList.Replace(',', ','); + fldList = fldList.Replace(",", "],["); + return fldList; + } + } +} diff --git a/Common.GLib/GLib.Data.Core/SqlCreator.cs b/Common.GLib/GLib.Data.Core/SqlCreator.cs new file mode 100644 index 0000000000000000000000000000000000000000..ca0a76eb555c5e7b1dc94e6df7d20ff5cd629359 --- /dev/null +++ b/Common.GLib/GLib.Data.Core/SqlCreator.cs @@ -0,0 +1,419 @@ +using GLib.Data.Entity; +using System; +using System.Collections.Generic; +using System.Reflection; +using System.Text; + +namespace GLib.Data.Core +{ + public class SqlCreator : ISqlCreator, IDisposable where TL : ILogicEntity, new() + { + private string _PrimaryKey = ""; + + private string _TableName = ""; + + private TL _model = default(TL); + + private int _PageSize = 100; + + private TL Model + { + get + { + if (_model == null) + { + _model = new TL(); + } + return _model; + } + } + + public string PrimaryKey + { + get + { + if (_PrimaryKey == "") + { + if (Model == null) + { + throw new ArgumentNullException("model is null !"); + } + _PrimaryKey = Model.PrimaryKey; + } + return _PrimaryKey; + } + set + { + _PrimaryKey = value; + } + } + + public virtual string TableName + { + get + { + if (_TableName == "") + { + bool flag = false; + PropertyInfo[] properties = EntityTypeCache.GetEntityInfo(typeof(TL)).Properties; + for (int i = 0; i < properties.Length; i++) + { + if (properties[i].Name.Trim().ToLower() == "TableName".ToLower()) + { + object value = properties[i].GetValue(Model, null); + if (value != null && !string.IsNullOrEmpty(value.ToString())) + { + _TableName = value.ToString(); + flag = true; + break; + } + } + } + if (!flag) + { + _TableName = "[" + typeof(TL).Name + "]"; + } + } + return _TableName; + } + set + { + _TableName = value; + } + } + + public int PageSize + { + get + { + return _PageSize; + } + set + { + _PageSize = value; + } + } + + public string CreateMaxSql(string selector, string col) + { + col = (string.IsNullOrEmpty(col) ? PrimaryKey : col); + StringBuilder stringBuilder = new StringBuilder(); + stringBuilder.Append($"select max({GetSQLFildList(col)}) from {TableName}"); + if (!string.IsNullOrEmpty(selector)) + { + stringBuilder.Append(" where " + selector); + } + return stringBuilder.ToString(); + } + + public string CreateCountSql(string selector, string col) + { + col = (string.IsNullOrEmpty(col) ? "1" : col); + StringBuilder stringBuilder = new StringBuilder(); + stringBuilder.Append($"select count({col}) as TotalCount from {TableName} "); + if (!string.IsNullOrEmpty(selector)) + { + stringBuilder.Append(" where " + selector); + } + return stringBuilder.ToString(); + } + + public string CreateSumSql(string selector, string col) + { + StringBuilder stringBuilder = new StringBuilder(); + stringBuilder.Append($"select sum({GetSQLFildList(col)}) from {TableName} "); + if (!string.IsNullOrEmpty(selector)) + { + stringBuilder.Append(" where " + selector); + } + return stringBuilder.ToString(); + } + + public string CreateInsertSql(TL model, out DBParam[] outparam) + { + StringBuilder stringBuilder = new StringBuilder(); + StringBuilder stringBuilder2 = new StringBuilder(); + stringBuilder.Append($"insert into {TableName}("); + PropertyInfo[] properties = EntityTypeCache.GetEntityInfo(typeof(TL)).Properties; + List list = new List(); + for (int i = 0; i < properties.Length; i++) + { + object[] customAttributes = properties[i].GetCustomAttributes(typeof(EntityAttribute), inherit: true); + EntityAttribute entityAttribute = null; + if (customAttributes.Length > 0) + { + entityAttribute = (EntityAttribute)customAttributes[0]; + } + if (!model.IsAutoID || !(model.PrimaryKey == properties[i].Name) || entityAttribute == null || !entityAttribute.IsDbGenerated) + { + if (properties[i].Name == PrimaryKey && entityAttribute != null && !entityAttribute.IsDbGenerated) + { + stringBuilder.Append("[" + properties[i].Name + "],"); + stringBuilder2.Append("@" + properties[i].Name + ","); + list.Add(new DBParam + { + ParamName = properties[i].Name, + ParamDbType = EntityHelper.GetDbType(properties[i].PropertyType), + ParamValue = EntityHelper.GetTypeDefaultValue(properties[i].GetValue(model, null), EntityHelper.GetDbType(properties[i].PropertyType)) + }); + } + else if (properties[i].Name != PrimaryKey && (entityAttribute == null || (!entityAttribute.IsDbGenerated && !entityAttribute.CustomMember))) + { + stringBuilder.Append("[" + properties[i].Name + "],"); + stringBuilder2.Append("@" + properties[i].Name + ","); + list.Add(new DBParam + { + ParamName = properties[i].Name, + ParamDbType = EntityHelper.GetDbType(properties[i].PropertyType), + ParamValue = EntityHelper.GetTypeDefaultValue(properties[i].GetValue(model, null), EntityHelper.GetDbType(properties[i].PropertyType)) + }); + } + } + } + stringBuilder = stringBuilder.Replace(",", ")", stringBuilder.Length - 1, 1); + stringBuilder2 = stringBuilder2.Replace(",", ")", stringBuilder2.Length - 1, 1); + stringBuilder.Append(" values ("); + stringBuilder.Append(stringBuilder2.ToString() + ";"); + if (model.IsAutoID) + { + stringBuilder.Append($" select ident_current('{TableName}') "); + } + outparam = list.ToArray(); + return stringBuilder.ToString(); + } + + public string CreateUpdateSql(TL model, string colList, string selector, out DBParam[] outparam, params DBParam[] values) + { + StringBuilder stringBuilder = new StringBuilder(); + stringBuilder.Append("update " + TableName + " set "); + PropertyInfo[] properties = EntityTypeCache.GetEntityInfo(typeof(TL)).Properties; + PropertyInfo propertyInfo = null; + List list = new List(); + for (int i = 0; i < properties.Length; i++) + { + object[] customAttributes = properties[i].GetCustomAttributes(typeof(EntityAttribute), inherit: true); + EntityAttribute entityAttribute = null; + if (customAttributes.Length > 0) + { + entityAttribute = (EntityAttribute)customAttributes[0]; + } + if (properties[i].Name == PrimaryKey) + { + propertyInfo = properties[i]; + } + else if (properties[i].Name != PrimaryKey && !(entityAttribute?.CustomMember ?? false) && (string.IsNullOrEmpty(colList) || colList.IndexOf(properties[i].Name.Trim()) >= 0) && !EntityHelper.IsTypeMinValue(properties[i].GetValue(model, null), EntityHelper.GetDbType(properties[i].PropertyType))) + { + stringBuilder.Append("[" + properties[i].Name + "]=@" + properties[i].Name + ","); + list.Add(new DBParam + { + ParamDbType = EntityHelper.GetDbType(properties[i].PropertyType), + ParamName = properties[i].Name, + ParamValue = properties[i].GetValue(model, null) + }); + } + } + stringBuilder = stringBuilder.Replace(",", " ", stringBuilder.Length - 1, 1); + if (!string.IsNullOrEmpty(selector)) + { + stringBuilder.Append(" where 1=1 and " + selector); + if (values != null) + { + for (int i = 0; i < values.Length; i++) + { + list.Insert(i, values[i]); + } + } + } + else + { + stringBuilder.Append(" where [" + PrimaryKey + "]=@" + PrimaryKey); + list.Add(new DBParam + { + ParamDbType = EntityHelper.GetDbType(propertyInfo.PropertyType), + ParamName = propertyInfo.Name, + ParamValue = propertyInfo.GetValue(model, null) + }); + } + outparam = list.ToArray(); + return stringBuilder.ToString(); + } + + public string CreateDeleteSql(TL model, out DBParam[] outparam) + { + StringBuilder stringBuilder = new StringBuilder(); + PropertyInfo[] properties = EntityTypeCache.GetEntityInfo(typeof(TL)).Properties; + PropertyInfo propertyInfo = null; + List list = new List(); + for (int i = 0; i < properties.Length; i++) + { + object[] customAttributes = properties[i].GetCustomAttributes(typeof(EntityAttribute), inherit: true); + EntityAttribute entityAttribute = null; + if (customAttributes.Length > 0) + { + entityAttribute = (EntityAttribute)customAttributes[0]; + } + if (properties[i].Name == PrimaryKey) + { + propertyInfo = properties[i]; + } + } + stringBuilder.Append(" " + PrimaryKey + "=@" + PrimaryKey); + list.Add(new DBParam + { + ParamDbType = EntityHelper.GetDbType(propertyInfo.PropertyType), + ParamName = propertyInfo.Name, + ParamValue = propertyInfo.GetValue(model, null) + }); + outparam = list.ToArray(); + return CreateDeleteSql(stringBuilder.ToString()); + } + + public string CreateDeleteSql(string selector) + { + StringBuilder stringBuilder = new StringBuilder(); + stringBuilder.Append("delete from " + TableName); + if (!string.IsNullOrEmpty(selector)) + { + stringBuilder.Append(" where " + selector); + } + return stringBuilder.ToString(); + } + + public string CreateModelSql(TL model, out DBParam[] outparam) + { + PropertyInfo[] properties = EntityTypeCache.GetEntityInfo(typeof(TL)).Properties; + List list = new List(); + for (int i = 0; i < properties.Length; i++) + { + if (properties[i].Name == PrimaryKey) + { + list.Add(new DBParam + { + ParamName = properties[i].Name, + ParamDbType = EntityHelper.GetDbType(properties[i].PropertyType), + ParamValue = properties[i].GetValue(model, null) + }); + break; + } + } + outparam = list.ToArray(); + return CreateModelSql(string.Format("{0}=@{0}", PrimaryKey), string.Empty); + } + + public string CreateModelSql(string selector, string colList) + { + StringBuilder stringBuilder = new StringBuilder(); + if (string.IsNullOrEmpty(colList)) + { + stringBuilder.Append(string.Format("select top 1 {0} from {1}", "*", TableName)); + } + else + { + stringBuilder.Append(string.Format("select top 1 {0} from {1}", colList.Replace("new", ""), TableName)); + } + if (!string.IsNullOrEmpty(selector)) + { + stringBuilder.Append(" where " + selector); + } + return stringBuilder.ToString(); + } + + public string CreatePageSql(TL model, out DBParam[] outparam) + { + PropertyInfo[] properties = EntityTypeCache.GetEntityInfo(typeof(TL)).Properties; + List list = new List(); + for (int i = 0; i < properties.Length; i++) + { + if (properties[i].Name == PrimaryKey) + { + list.Add(new DBParam + { + ParamName = properties[i].Name, + ParamDbType = EntityHelper.GetDbType(properties[i].PropertyType), + ParamValue = properties[i].GetValue(model, null) + }); + break; + } + } + outparam = list.ToArray(); + return CreatePageSql(string.Format("{0}=@{0}", PrimaryKey), 0, PageSize, string.Empty, string.Empty, outparam); + } + + public string CreatePageSql(string selector, int pageIndex, int pageSize, string ordering, string colList, params DBParam[] values) + { + pageIndex = ((pageIndex <= 0) ? 1 : pageIndex); + if (pageSize == 0) + { + pageSize = PageSize; + } + string text = ""; + if (string.IsNullOrEmpty(colList) || colList == "*") + { + PropertyInfo[] properties = EntityTypeCache.GetEntityInfo(typeof(TL)).Properties; + PropertyInfo[] array = properties; + foreach (PropertyInfo propertyInfo in array) + { + object[] customAttributes = propertyInfo.GetCustomAttributes(typeof(EntityAttribute), inherit: true); + EntityAttribute entityAttribute = null; + if (customAttributes.Length > 0) + { + entityAttribute = (EntityAttribute)customAttributes[0]; + } + if (!(entityAttribute?.CustomMember ?? false)) + { + text = text + "[" + propertyInfo.Name + "],"; + } + } + text = text.Substring(0, text.Length - 1); + } + else + { + text = GetSQLFildList(colList); + } + StringBuilder stringBuilder = new StringBuilder(); + string text2; + if (string.IsNullOrEmpty(ordering)) + { + text2 = ((!string.IsNullOrEmpty(PrimaryKey)) ? $" order by {PrimaryKey} desc" : string.Format(" order by {0} desc", "newid()")); + } + else + { + ordering = ordering.Replace("descending", "desc").Replace("ascending", "asc"); + text2 = $" order by {ordering}"; + } + if (string.IsNullOrEmpty(selector)) + { + stringBuilder.Append($"select {text} from(select {text}, row_number() over({text2}) as row from {TableName}"); + stringBuilder.Append($") a where row between {(pageIndex - 1) * pageSize + 1} and {pageIndex * pageSize}"); + } + else + { + stringBuilder.Append($"select {text} from(select {text}, row_number() over({text2}) as row from {TableName}"); + stringBuilder.Append($" where {SqlHelper.ParseSelector(selector, values)}"); + stringBuilder.Append($") a where row between {(pageIndex - 1) * pageSize + 1} and {pageIndex * pageSize}"); + } + return stringBuilder.ToString(); + } + + public void Dispose() + { + GC.SuppressFinalize(this); + } + + private string GetSQLFildList(string fldList) + { + if (string.IsNullOrEmpty(fldList)) + { + return "*"; + } + if (fldList.Trim() == "*") + { + return "*"; + } + fldList = "[" + fldList + "]"; + fldList = fldList.Replace(',', ','); + fldList = fldList.Replace(",", "],["); + return fldList; + } + } +} diff --git a/Common.GLib/GLib.Data.Core/SqlCreatorFactory.cs b/Common.GLib/GLib.Data.Core/SqlCreatorFactory.cs new file mode 100644 index 0000000000000000000000000000000000000000..5b6b89e0c18849809b29cf924f81f9158ba82575 --- /dev/null +++ b/Common.GLib/GLib.Data.Core/SqlCreatorFactory.cs @@ -0,0 +1,17 @@ +using GLib.Data.Entity; + +namespace GLib.Data.Core +{ + public class SqlCreatorFactory + { + public static ISqlCreator GetSqlCreator() where TL : ILogicEntity, new() + { + DataBaseType dBType = SqlHelper.GetDBType(); + if (dBType == DataBaseType.SqlServer) + { + return new SqlCreator(); + } + return new SqlCreator(); + } + } +} diff --git a/Common.GLib/GLib.Data.Core/SqlHelper.cs b/Common.GLib/GLib.Data.Core/SqlHelper.cs new file mode 100644 index 0000000000000000000000000000000000000000..016e65f42f653d038e6302a0a9ede72f3e4835a1 --- /dev/null +++ b/Common.GLib/GLib.Data.Core/SqlHelper.cs @@ -0,0 +1,259 @@ +using GLib.Data.Entity; +using GLib.Logging; +using MySql.Data.MySqlClient; +using System; +using System.Configuration; +using System.Data; +using System.Data.Common; +using System.Data.OleDb; +using System.Data.OracleClient; +using System.Data.SqlClient; + +namespace GLib.Data.Core +{ + public class SqlHelper + { + public static string GetConnectionString(string dbName) + { + if (string.IsNullOrEmpty(dbName)) + { + throw new ArgumentNullException("ConnectionString is null"); + } + return ConfigurationManager.ConnectionStrings[dbName].ConnectionString; + } + + public static DataBaseType GetDBType() + { + switch (ConfigurationManager.AppSettings["DBType"]) + { + case "SqlServer": + return DataBaseType.SqlServer; + case "Access": + return DataBaseType.Access; + case "MySql": + return DataBaseType.MySql; + case "Oracle": + return DataBaseType.Oracle; + default: + return DataBaseType.SqlServer; + } + } + + public static DbProviderFactory GetDBFactory(DataBaseType dbType) + { + switch (dbType) + { + case DataBaseType.SqlServer: + return SqlClientFactory.Instance; + case DataBaseType.Access: + return OleDbFactory.Instance; + case DataBaseType.MySql: + return (DbProviderFactory)(object)MySqlClientFactory.Instance; + //case DataBaseType.Oracle: + // return OracleClientFactory.Instance; + default: + return SqlClientFactory.Instance; + } + } + + public static string ParseSelector(string selector, params DBParam[] values) + { + string text = selector; + if (values != null) + { + for (int i = 0; i < values.Length; i++) + { + if (string.IsNullOrEmpty(values[i].ParamName)) + { + text = text.Replace($"@{i}", $"@param{i}"); + values[i].ParamName = $"param{i}"; + } + else + { + text = text.Replace($"@{i}", "@" + values[i].ParamName); + } + } + } + return text.Replace("==", " = ").Replace("&&", " and ").Replace("||", " or "); + } + + public static DbCommand GetCommand(string dbName, string strCommand) + { + return GetCommand(dbName, strCommand, 30); + } + + public static DbCommand GetCommand(string dbName, string strCommand, int timeOut) + { + DbProviderFactory dBFactory = GetDBFactory(GetDBType()); + DbCommand dbCommand = dBFactory.CreateCommand(); + string text = GetConnectionString(dbName); + if (GetDBType() == DataBaseType.MySql) + { + strCommand = strCommand.Replace("[", "").Replace("]", ""); + } + if (GetDBType() == DataBaseType.Access) + { + text = text.Replace("@Path", AppDomain.CurrentDomain.BaseDirectory); + } + dbCommand.CommandText = strCommand; + DbConnection dbConnection = dBFactory.CreateConnection(); + dbConnection.ConnectionString = text; + dbConnection.Open(); + dbCommand.Connection = dbConnection; + dbCommand.CommandTimeout = timeOut; + return dbCommand; + } + + public static IDataReader ExecuteDataReader(string dbName, string strCommand, CommandType commandType, DBParam[] listParam) + { + return ExecuteDataReader(dbName, strCommand, commandType, listParam, 30); + } + + public static IDataReader ExecuteDataReader(string dbName, string strCommand, CommandType commandType, DBParam[] listParam, int timeOut) + { + strCommand = ParseSelector(strCommand, listParam); + DbCommand command = GetCommand(dbName, strCommand, timeOut); + command.CommandType = commandType; + if (listParam != null) + { + DbParameterCollection parameters = command.Parameters; + foreach (DBParam dBParam in listParam) + { + DbParameter dbParameter = command.CreateParameter(); + dbParameter.ParameterName = dBParam.ParamName; + dbParameter.DbType = dBParam.ParamDbType; + dbParameter.Value = dBParam.ParamValue; + if (!parameters.Contains(dbParameter)) + { + parameters.Add(dbParameter); + } + } + } + try + { + IDataReader result = command.ExecuteReader(CommandBehavior.CloseConnection); + command.Parameters.Clear(); + return result; + } + catch (Exception ex) + { + if (command.Connection.State == ConnectionState.Open) + { + command.Connection.Close(); + command.Connection.Dispose(); + } + Log log = new Log(); + log.Write(new LogMessage + { + Content = "GLib.Data.Core.SqlHelper.ExecuteDataReader:\r\n" + ex.Message, + Type = MessageType.Error + }); + return null; + } + } + + public static int ExecuteNonQuery(string dbName, string strCommand, CommandType commandType, DBParam[] listParam) + { + strCommand = ParseSelector(strCommand, listParam); + int result = -1; + using (DbCommand dbCommand = GetCommand(dbName, strCommand)) + { + dbCommand.CommandType = commandType; + if (listParam != null) + { + DbParameterCollection parameters = dbCommand.Parameters; + foreach (DBParam dBParam in listParam) + { + DbParameter dbParameter = dbCommand.CreateParameter(); + dbParameter.ParameterName = dBParam.ParamName; + dbParameter.DbType = dBParam.ParamDbType; + dbParameter.Value = dBParam.ParamValue; + if (!parameters.Contains(dbParameter)) + { + parameters.Add(dbParameter); + } + } + } + result = dbCommand.ExecuteNonQuery(); + dbCommand.Connection.Close(); + dbCommand.Dispose(); + } + return result; + } + + public static object ExecuteScalar(string dbName, string strCommand, CommandType commandType, DBParam[] listParam) + { + strCommand = ParseSelector(strCommand, listParam); + object result = null; + using (DbCommand dbCommand = GetCommand(dbName, strCommand)) + { + dbCommand.CommandType = commandType; + if (listParam != null) + { + DbParameterCollection parameters = dbCommand.Parameters; + foreach (DBParam dBParam in listParam) + { + DbParameter dbParameter = dbCommand.CreateParameter(); + dbParameter.ParameterName = dBParam.ParamName; + dbParameter.DbType = dBParam.ParamDbType; + dbParameter.Value = dBParam.ParamValue; + if (!parameters.Contains(dbParameter)) + { + parameters.Add(dbParameter); + } + } + } + result = dbCommand.ExecuteScalar(); + dbCommand.Connection.Close(); + dbCommand.Dispose(); + } + return result; + } + + public static DataTable ExecuteTable(string dbName, string strCommand, CommandType commandType, DBParam[] listParam) + { + string text = GetConnectionString(dbName); + if (GetDBType() == DataBaseType.MySql) + { + strCommand = strCommand.Replace("[", "").Replace("]", ""); + } + if (GetDBType() == DataBaseType.Access) + { + text = text.Replace("@Path", AppDomain.CurrentDomain.BaseDirectory); + } + DataTable dataTable = new DataTable(); + DbProviderFactory dBFactory = GetDBFactory(GetDBType()); + using (DbCommand dbCommand = dBFactory.CreateCommand()) + { + DbConnection dbConnection = dBFactory.CreateConnection(); + dbConnection.ConnectionString = text; + dbConnection.Open(); + dbCommand.Connection = dbConnection; + dbCommand.CommandTimeout = 30; + dbCommand.CommandType = commandType; + dbCommand.CommandText = ParseSelector(strCommand, listParam); + if (listParam != null) + { + DbParameterCollection parameters = dbCommand.Parameters; + foreach (DBParam dBParam in listParam) + { + DbParameter dbParameter = dbCommand.CreateParameter(); + dbParameter.ParameterName = dBParam.ParamName; + dbParameter.DbType = dBParam.ParamDbType; + dbParameter.Value = dBParam.ParamValue; + if (!parameters.Contains(dbParameter)) + { + parameters.Add(dbParameter); + } + } + } + DbDataAdapter dbDataAdapter = dBFactory.CreateDataAdapter(); + dbDataAdapter.SelectCommand = dbCommand; + dbDataAdapter.Fill(dataTable); + dbCommand.Connection.Close(); + dbCommand.Dispose(); + } + return dataTable; + } + } +} diff --git a/Common.GLib/GLib.Data.Entity/DBParam.cs b/Common.GLib/GLib.Data.Entity/DBParam.cs new file mode 100644 index 0000000000000000000000000000000000000000..2f205ca2393db18f799563e3ba7e9b414dc9b5f9 --- /dev/null +++ b/Common.GLib/GLib.Data.Entity/DBParam.cs @@ -0,0 +1,49 @@ +using System.Data; + +namespace GLib.Data.Entity +{ + public class DBParam + { + private string _ParamName = ""; + + private DbType _ParamDbType = DbType.String; + + private object _ParamValue = null; + + public string ParamName + { + get + { + return _ParamName; + } + set + { + _ParamName = value; + } + } + + public DbType ParamDbType + { + get + { + return _ParamDbType; + } + set + { + _ParamDbType = value; + } + } + + public object ParamValue + { + get + { + return _ParamValue; + } + set + { + _ParamValue = value; + } + } + } +} diff --git a/Common.GLib/GLib.Data.Entity/EntityAttribute.cs b/Common.GLib/GLib.Data.Entity/EntityAttribute.cs new file mode 100644 index 0000000000000000000000000000000000000000..0d8b855462ca3e9b3f9b184d254e7e6b18b7782f --- /dev/null +++ b/Common.GLib/GLib.Data.Entity/EntityAttribute.cs @@ -0,0 +1,36 @@ +using System; + +namespace GLib.Data.Entity +{ + [AttributeUsage(AttributeTargets.All, AllowMultiple = true, Inherited = true)] + public class EntityAttribute : Attribute + { + private bool _customMember; + + private bool _IsDbGenerated; + + public bool CustomMember + { + get + { + return _customMember; + } + set + { + _customMember = value; + } + } + + public bool IsDbGenerated + { + get + { + return _IsDbGenerated; + } + set + { + _IsDbGenerated = value; + } + } + } +} diff --git a/Common.GLib/GLib.Data.Entity/EntityHelper.cs b/Common.GLib/GLib.Data.Entity/EntityHelper.cs new file mode 100644 index 0000000000000000000000000000000000000000..5d74b8f7e3d646102de1478819fac8d199cb141a --- /dev/null +++ b/Common.GLib/GLib.Data.Entity/EntityHelper.cs @@ -0,0 +1,170 @@ +using System; +using System.Data; + +namespace GLib.Data.Entity +{ + public static class EntityHelper + { + public static DbType GetDbType(Type sysType) + { + DbType result = DbType.String; + switch (sysType.Name) + { + case "String": + result = DbType.String; + break; + case "Byte": + result = DbType.Byte; + break; + case "Byte[]": + result = DbType.Binary; + break; + case "Int16": + result = DbType.Int16; + break; + case "Int32": + result = DbType.Int32; + break; + case "Int64": + result = DbType.Int64; + break; + case "DateTime": + result = DbType.DateTime; + break; + case "Decimal": + result = DbType.Decimal; + break; + case "Double": + result = DbType.Double; + break; + case "Single": + result = DbType.Single; + break; + case "Boolean": + result = DbType.Boolean; + break; + case "Guid": + result = DbType.Guid; + break; + } + return result; + } + + public static bool IsTypeMinValue(object obValue, DbType dbType) + { + bool result = false; + switch (dbType) + { + case DbType.String: + if (obValue == null) + { + result = true; + } + break; + case DbType.Int16: + if (Convert.ToInt16(obValue) == short.MinValue) + { + result = true; + } + break; + case DbType.Int32: + if (Convert.ToInt32(obValue) == int.MinValue) + { + result = true; + } + break; + case DbType.Int64: + if (Convert.ToInt64(obValue) == long.MinValue) + { + result = true; + } + break; + case DbType.Decimal: + if (Convert.ToDecimal(obValue) == decimal.MinValue) + { + result = true; + } + break; + case DbType.Double: + if (Convert.ToDouble(obValue) == double.MinValue) + { + result = true; + } + break; + case DbType.Single: + if (Convert.ToSingle(obValue) == float.MinValue) + { + result = true; + } + break; + case DbType.DateTime: + if (Convert.ToDateTime(obValue) == new DateTime(1900, 1, 1)) + { + result = true; + } + break; + } + return result; + } + + public static object GetTypeDefaultValue(object obValue, DbType dbType) + { + object result = obValue; + switch (dbType) + { + case DbType.String: + if (obValue == null || Convert.ToString(obValue) == string.Empty) + { + result = string.Empty; + } + break; + case DbType.Int16: + if (Convert.ToInt16(obValue) == short.MinValue) + { + result = 0; + } + break; + case DbType.Int32: + if (Convert.ToInt32(obValue) == int.MinValue) + { + result = 0; + } + break; + case DbType.Int64: + if (Convert.ToInt64(obValue) == long.MinValue) + { + result = 0; + } + break; + case DbType.Byte: + if (Convert.ToByte(obValue) == 0) + { + result = 0; + } + break; + case DbType.Decimal: + if (Convert.ToDecimal(obValue) == decimal.MinValue) + { + result = 0; + } + break; + case DbType.Double: + if (Convert.ToDouble(obValue) == double.MinValue) + { + result = 0; + } + break; + case DbType.Single: + if (Convert.ToSingle(obValue) == float.MinValue) + { + result = 0; + } + break; + default: + result = obValue; + break; + } + return result; + } + } +} diff --git a/Common.GLib/GLib.Data.Entity/EntityInfo.cs b/Common.GLib/GLib.Data.Entity/EntityInfo.cs new file mode 100644 index 0000000000000000000000000000000000000000..30b309d8e270035675929def4b2f617f74ba36a4 --- /dev/null +++ b/Common.GLib/GLib.Data.Entity/EntityInfo.cs @@ -0,0 +1,103 @@ +using System.Collections.Generic; +using System.Reflection; + +namespace GLib.Data.Entity +{ + public class EntityInfo + { + private EntityAttribute[] columns; + + private IDictionary dicColumns = new Dictionary(); + + private FieldInfo[] fields; + + private IDictionary dicFields = new Dictionary(); + + private PropertyInfo[] properties; + + private IDictionary dicProperties = new Dictionary(); + + public EntityAttribute[] Columns + { + get + { + return columns; + } + set + { + columns = value; + } + } + + public FieldInfo[] Fields + { + get + { + return fields; + } + set + { + fields = value; + } + } + + public PropertyInfo[] Properties + { + get + { + return properties; + } + set + { + properties = value; + } + } + + public IDictionary DicColumns + { + get + { + return dicColumns; + } + set + { + dicColumns = value; + } + } + + public IDictionary DicFields + { + get + { + return dicFields; + } + set + { + dicFields = value; + } + } + + public IDictionary DicProperties + { + get + { + return dicProperties; + } + set + { + dicProperties = value; + } + } + + public EntityInfo() + { + } + + public EntityInfo(EntityAttribute[] columns, FieldInfo[] fields, PropertyInfo[] properties) + { + this.columns = columns; + this.fields = fields; + this.properties = properties; + } + } +} diff --git a/Common.GLib/GLib.Data.Entity/EntityTypeCache.cs b/Common.GLib/GLib.Data.Entity/EntityTypeCache.cs new file mode 100644 index 0000000000000000000000000000000000000000..ba21cdc94dc35e0cc180180854a3b871c0edca78 --- /dev/null +++ b/Common.GLib/GLib.Data.Entity/EntityTypeCache.cs @@ -0,0 +1,54 @@ +using System; +using System.Collections.Generic; +using System.Reflection; + +namespace GLib.Data.Entity +{ + public static class EntityTypeCache + { + private static IDictionary cache; + + static EntityTypeCache() + { + cache = null; + cache = new Dictionary(); + } + + public static void InsertEntityInfo(Type type, EntityInfo entityInfo) + { + if (!cache.ContainsKey(type)) + { + cache.Add(type, entityInfo); + } + } + + public static void InsertEntityInfo(ILogicEntity entity, EntityInfo entityInfo) + { + Type type = entity.GetType(); + InsertEntityInfo(type, entityInfo); + } + + public static EntityInfo GetEntityInfo(Type type) + { + if (cache.ContainsKey(type)) + { + return cache[type]; + } + EntityInfo entityInfo = new EntityInfo(null, null, type.GetProperties(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public)); + InsertEntityInfo(type, entityInfo); + return entityInfo; + } + + public static EntityInfo GetEntityInfo(ILogicEntity entity) + { + Type type = entity.GetType(); + return GetEntityInfo(type); + } + + public static EntityInfo GetEntityInfo() where T : ILogicEntity + { + Type typeFromHandle = typeof(T); + return GetEntityInfo(typeFromHandle); + } + } +} diff --git a/Common.GLib/GLib.Data.Entity/ILogicEntity.cs b/Common.GLib/GLib.Data.Entity/ILogicEntity.cs new file mode 100644 index 0000000000000000000000000000000000000000..bfdec8f6b8ac4b07def743bc9fb0f58e93c6c8f5 --- /dev/null +++ b/Common.GLib/GLib.Data.Entity/ILogicEntity.cs @@ -0,0 +1,26 @@ +namespace GLib.Data.Entity +{ + public interface ILogicEntity + { + [Entity(CustomMember = true)] + string PrimaryKey + { + get; + set; + } + + [Entity(CustomMember = true)] + bool IsAutoID + { + get; + set; + } + + [Entity(CustomMember = true)] + string DbName + { + get; + set; + } + } +} diff --git a/Common.GLib/GLib.Data/DBT_SqlHelper.cs b/Common.GLib/GLib.Data/DBT_SqlHelper.cs new file mode 100644 index 0000000000000000000000000000000000000000..18cb7e396864d0933ebd92c16fd5d164d98be7b0 --- /dev/null +++ b/Common.GLib/GLib.Data/DBT_SqlHelper.cs @@ -0,0 +1,254 @@ +using System; +using System.Configuration; +using System.Data; +using System.Data.SqlClient; +using System.IO; +using System.Text; + +namespace GLib.Data +{ + public abstract class DBT_SqlHelper + { + public static string connectionString = string.Concat(ConfigurationSettings.AppSettings["con"]); + + public static int ExecteNonQuery(string connectionString, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters) + { + SqlCommand sqlCommand = new SqlCommand(); + using (SqlConnection conn = new SqlConnection(connectionString)) + { + PrepareCommand(sqlCommand, conn, null, cmdType, cmdText, commandParameters); + int result = sqlCommand.ExecuteNonQuery(); + sqlCommand.Parameters.Clear(); + return result; + } + } + + public static int ExecteNonQueryProducts(string cmdText, params SqlParameter[] commandParameters) + { + return ExecteNonQuery(connectionString, CommandType.StoredProcedure, cmdText, commandParameters); + } + + public static int ExecteNonQueryText(string cmdText, params SqlParameter[] commandParameters) + { + return ExecteNonQuery(connectionString, CommandType.Text, cmdText, commandParameters); + } + + private static void PrepareCommand(SqlCommand cmd, SqlConnection conn, SqlTransaction trans, CommandType cmdType, string cmdText, SqlParameter[] cmdParms) + { + if (conn.State != ConnectionState.Open) + { + conn.Open(); + } + cmd.Connection = conn; + cmd.CommandText = cmdText; + if (trans != null) + { + cmd.Transaction = trans; + } + cmd.CommandType = cmdType; + if (cmdParms != null) + { + foreach (SqlParameter value in cmdParms) + { + cmd.Parameters.Add(value); + } + } + } + + public static void CreateDatabase(string dbName, string dbFileName, string dbSize, string dbMaxSize, string dbFileGrowth, string logName, string logFileName, string logSize, string logMaxSize, string logFileGrowth, bool isDeletedb) + { + StringBuilder stringBuilder = new StringBuilder(); + stringBuilder.Append("USE master "); + stringBuilder.Append(" GO"); + if (isDeletedb) + { + stringBuilder.Append("IF EXISTS(SELECT * FROM sysdatabases WHERE name ='@dbName')begin DROP DATABASE @dbName end"); + } + stringBuilder.Append("CREATE DATABASE @dbName ON PRIMARY ("); + stringBuilder.Append("NAME='@ dbName_data',"); + stringBuilder.Append("FILENAME='@dbFileName', "); + stringBuilder.Append("SIZE=@dbSize, "); + stringBuilder.Append("MAXSIZE= @dbMaxSize,"); + stringBuilder.Append("FILEGROWTH=@dbFileGrowth)"); + stringBuilder.Append("LOG ON ("); + stringBuilder.Append("NAME='@logName_log',"); + stringBuilder.Append("FILENAME='@logFileName',"); + stringBuilder.Append("SIZE=@logSize,"); + stringBuilder.Append("MAXSIZE=@logMaxSize,"); + stringBuilder.Append("FILEGROWTH=@logFileGrowth ) GO"); + SqlParameter[] array = new SqlParameter[10] + { + new SqlParameter("@dbName", dbName), + new SqlParameter("@dbFileName", dbFileName), + new SqlParameter("@dbSize", dbSize), + new SqlParameter("@dbMaxSize", dbMaxSize), + new SqlParameter("@dbFileGrowth", dbFileGrowth), + new SqlParameter("@logName", logName), + new SqlParameter("@logFileName", logFileName), + new SqlParameter("@logSize", logSize), + new SqlParameter("@logMaxSize", logMaxSize), + new SqlParameter("@logFileGrowth", logFileGrowth) + }; + ExecteNonQueryText(stringBuilder.ToString().Trim(), (SqlParameter[])null); + } + + public static void DropDatabase(string dbName) + { + StringBuilder stringBuilder = new StringBuilder(); + stringBuilder.AppendLine("USE master "); + stringBuilder.AppendLine("DROP DATABASE " + dbName); + SqlParameter[] array = new SqlParameter[1] + { + new SqlParameter("@dbName", dbName) + }; + ExecteNonQueryText(stringBuilder.ToString().Trim()); + } + + public static void BackupDatabase(string dbName, string dbFileName) + { + StringBuilder stringBuilder = new StringBuilder(); + stringBuilder.Append("USE master "); + stringBuilder.Append(" GO "); + stringBuilder.Append("BACKUP DATABASE @dbName TO DISK ='@dbFileName'"); + SqlParameter[] commandParameters = new SqlParameter[2] + { + new SqlParameter("@dbName", dbName), + new SqlParameter("@dbFileName", dbFileName) + }; + ExecteNonQueryText(stringBuilder.ToString().Trim(), commandParameters); + } + + public static void RestoreDatabase(string dbName, string dbFileName) + { + StringBuilder stringBuilder = new StringBuilder(); + stringBuilder.Append("USE master "); + stringBuilder.Append(" GO "); + stringBuilder.Append("restore database @dbName from disk='@dbFileName' WITH REPLACE,RECOVERY"); + SqlParameter[] array = new SqlParameter[2] + { + new SqlParameter("@dbName", dbName), + new SqlParameter("@dbFileName", dbFileName) + }; + ExecteNonQueryText(stringBuilder.ToString().Trim(), (SqlParameter[])null); + } + + public static void OnlineDatabase(string newDbName, string dbFileName, string logFileName) + { + StringBuilder stringBuilder = new StringBuilder(); + stringBuilder.Append("USE master "); + stringBuilder.Append(" GO "); + stringBuilder.Append("EXEC sp_attach_db @ newDbName,'@dbFileName','@logFileName'"); + SqlParameter[] commandParameters = new SqlParameter[2] + { + new SqlParameter("@dbFileName", dbFileName), + new SqlParameter("@logFileName", logFileName) + }; + ExecteNonQueryText(stringBuilder.ToString().Trim(), commandParameters); + } + + public static void OfflineDatabase(string dbName) + { + StringBuilder stringBuilder = new StringBuilder(); + stringBuilder.Append("USE master "); + stringBuilder.Append(" GO "); + stringBuilder.Append(" exec sp_detach_db '@dbName' "); + SqlParameter[] array = new SqlParameter[1] + { + new SqlParameter("@dbName", dbName) + }; + ExecteNonQueryText(stringBuilder.ToString().Trim(), (SqlParameter[])null); + } + + public static void ResetPassword(string newPassword, string userName) + { + StringBuilder stringBuilder = new StringBuilder(); + stringBuilder.Append("USE master "); + stringBuilder.Append(" GO "); + stringBuilder.Append("EXEC sp_password null,'@newPassword','@userName'"); + SqlParameter[] array = new SqlParameter[2] + { + new SqlParameter("@newPassword", newPassword), + new SqlParameter("@userName", userName) + }; + ExecteNonQueryText(stringBuilder.ToString().Trim(), (SqlParameter[])null); + } + + public static void CreateDbUser(string dbName, string userName, string passWord) + { + StringBuilder stringBuilder = new StringBuilder(); + stringBuilder.Append("USE " + dbName); + stringBuilder.Append(" GO "); + stringBuilder.Append("EXEC sp_addlogin N'@userName','@passWord'"); + stringBuilder.Append("EXEC sp_grantdbaccess N'@userName'"); + SqlParameter[] array = new SqlParameter[3] + { + new SqlParameter("@dbName", userName), + new SqlParameter("@userName", userName), + new SqlParameter("@passWord", passWord) + }; + ExecteNonQueryText(stringBuilder.ToString().Trim(), (SqlParameter[])null); + } + + public static void AddRoleToDbUser(string dbName, string userName) + { + StringBuilder stringBuilder = new StringBuilder(); + stringBuilder.Append("USE " + dbName); + stringBuilder.Append("GO "); + stringBuilder.Append("EXEC sp_addrolemember N'@dbName', N'@userName'"); + SqlParameter[] array = new SqlParameter[2] + { + new SqlParameter("@dbName", userName), + new SqlParameter("@userName", userName) + }; + ExecteNonQueryText(stringBuilder.ToString().Trim(), (SqlParameter[])null); + } + + public static void ExecuteSQLFile(string sqlFileName) + { + SqlConnection sqlConnection = null; + try + { + sqlConnection = new SqlConnection(connectionString); + SqlCommand sqlCommand = sqlConnection.CreateCommand(); + sqlConnection.Open(); + using (FileStream fileStream = new FileStream(sqlFileName, FileMode.Open, FileAccess.ReadWrite)) + { + StreamReader streamReader = new StreamReader(fileStream, Encoding.Default); + StringBuilder stringBuilder = new StringBuilder(); + string text = ""; + while ((text = streamReader.ReadLine()) != null) + { + if (text.Trim().ToUpper() != "GO") + { + stringBuilder.AppendLine(text); + } + else + { + sqlCommand.CommandText = stringBuilder.ToString(); + sqlCommand.ExecuteNonQuery(); + stringBuilder.Remove(0, stringBuilder.Length); + } + } + fileStream.Dispose(); + } + } + catch (Exception ex) + { + Console.WriteLine(ex.Message); + } + finally + { + if (sqlConnection != null && sqlConnection.State != 0) + { + sqlConnection.Close(); + } + } + } + + public static void Test() + { + connectionString = "server=.;uid=sa;password=123456;database=master"; + DropDatabase("db"); + } + } +} diff --git a/Common.GLib/GLib.Data/PageList.cs b/Common.GLib/GLib.Data/PageList.cs new file mode 100644 index 0000000000000000000000000000000000000000..e4b20db94b9827d251727cc1399425d468d72837 --- /dev/null +++ b/Common.GLib/GLib.Data/PageList.cs @@ -0,0 +1,32 @@ +using System.Collections.Generic; + +namespace GLib.Data +{ + public class PageList : List + { + public int PageIndex + { + get; + set; + } + + public int PageSize + { + get; + set; + } + + public int TotalCount + { + get; + set; + } + + public PageList(int pageIndex, int pageSize, int totalCount) + { + PageIndex = pageIndex; + PageSize = pageSize; + TotalCount = totalCount; + } + } +} diff --git a/Common.GLib/GLib.Extension/ComHelper.cs b/Common.GLib/GLib.Extension/ComHelper.cs new file mode 100644 index 0000000000000000000000000000000000000000..e43be2463153b94611a8b9f24ba8761ceefef9a8 --- /dev/null +++ b/Common.GLib/GLib.Extension/ComHelper.cs @@ -0,0 +1,669 @@ +using System; +using System.Data; +using System.IO; +using System.Net; +using System.Security.Cryptography; +using System.Text; +using System.Text.RegularExpressions; +//using System.Web.Caching; +//using System.Web.UI; +//using System.Web.UI.WebControls; + +namespace GLib.Extension +{ + public class ComHelper + { + private static byte[] Keys = new byte[8] + { + 16, + 48, + 80, + 115, + 151, + 171, + 205, + 239 + }; + + public static string AddSucces => "添加成功"; + + public static string AddSame => "已经存在!"; + + public static string AddError => "添加出错,请重试!"; + + public static string DeleteSucces => "删除成功"; + + public static string DeleteSame => "已经存在!"; + + public static string DeleteError => "删除出错,请重试!"; + + public static string UpdateSucces => "修改成功"; + + public static string UpdateSame => "已经存在!"; + + public static string UpdateError => "修改出错,请重试!"; + + public static string StrConvert(string strInput) + { + if (strInput != null && strInput != "") + { + string[,] array = new string[13, 2] + { + { + "'", + "’" + }, + { + "%20", + " " + }, + { + "%24", + " " + }, + { + "%27", + " " + }, + { + "%3a", + " " + }, + { + "%3b", + " " + }, + { + "%3c", + " " + }, + { + ";", + ";" + }, + { + ":", + ":" + }, + { + "%", + "%" + }, + { + "--", + "--" + }, + { + "*", + "*" + }, + { + "\\", + "、、" + } + }; + for (int i = 0; i < array.Length / 2; i++) + { + strInput = strInput.Replace(array[i, 0], array[i, 1]); + } + } + return strInput; + } + + public static string EncryptDES(string encryptString, string encryptKey) + { + try + { + byte[] bytes = Encoding.UTF8.GetBytes(encryptKey.Substring(0, 8)); + byte[] keys = Keys; + byte[] bytes2 = Encoding.UTF8.GetBytes(encryptString); + DESCryptoServiceProvider dESCryptoServiceProvider = new DESCryptoServiceProvider(); + MemoryStream memoryStream = new MemoryStream(); + CryptoStream cryptoStream = new CryptoStream(memoryStream, dESCryptoServiceProvider.CreateEncryptor(bytes, keys), CryptoStreamMode.Write); + cryptoStream.Write(bytes2, 0, bytes2.Length); + cryptoStream.FlushFinalBlock(); + return Convert.ToBase64String(memoryStream.ToArray()); + } + catch + { + return encryptString; + } + } + + public static string DecryptDES(string decryptString, string decryptKey) + { + try + { + byte[] bytes = Encoding.UTF8.GetBytes(decryptKey); + byte[] keys = Keys; + byte[] array = Convert.FromBase64String(decryptString); + DESCryptoServiceProvider dESCryptoServiceProvider = new DESCryptoServiceProvider(); + MemoryStream memoryStream = new MemoryStream(); + CryptoStream cryptoStream = new CryptoStream(memoryStream, dESCryptoServiceProvider.CreateDecryptor(bytes, keys), CryptoStreamMode.Write); + cryptoStream.Write(array, 0, array.Length); + cryptoStream.FlushFinalBlock(); + return Encoding.UTF8.GetString(memoryStream.ToArray()); + } + catch + { + return decryptString; + } + } + +/* + public static void RunScript(Page p, string sScript) + { + ClientScriptManager clientScript = p.ClientScript; + string script = ""; + clientScript.RegisterStartupScript(p.GetType(), "alertMessage", script); + } + + public static void Alert(Page p, string message) + { + ClientScriptManager clientScript = p.ClientScript; + string script = ""; + clientScript.RegisterClientScriptBlock(p.GetType(), "alertMessage", script); + } + + public static void Alert(Page p, string message, string derectPage) + { + ClientScriptManager clientScript = p.ClientScript; + string script = ""; + clientScript.RegisterClientScriptBlock(p.GetType(), "alertMessage", script); + } + + public static void Confirm(Page p, string message, string derectPage) + { + ClientScriptManager clientScript = p.ClientScript; + string script = ""; + clientScript.RegisterClientScriptBlock(p.GetType(), "alertMessage", script); + } + + public static void Confirm(string message, string url) + { + ClientScriptManager clientScript = ((Page)HttpContext.Current.Handler).ClientScript; + string script = ""; + clientScript.RegisterClientScriptBlock(((Page)HttpContext.Current.Handler).GetType(), "alertMessage", script); + } + + public static void Go(string url) + { + ClientScriptManager clientScript = ((Page)HttpContext.Current.Handler).ClientScript; + string script = ""; + clientScript.RegisterClientScriptBlock(((Page)HttpContext.Current.Handler).GetType(), "go", script); + } + + public static void GoParent(string url) + { + ClientScriptManager clientScript = ((Page)HttpContext.Current.Handler).ClientScript; + string script = ""; + clientScript.RegisterClientScriptBlock(((Page)HttpContext.Current.Handler).GetType(), "go", script); + } + + public static void GoParent(Page p, string url) + { + ClientScriptManager clientScript = p.ClientScript; + string script = ""; + clientScript.RegisterClientScriptBlock(p.GetType(), "go", script); + } + + public static void Back(Page p, int nFlag) + { + ClientScriptManager clientScript = p.ClientScript; + string script = ""; + clientScript.RegisterClientScriptBlock(p.GetType(), "back", script); + } +*/ + public static bool HasData(DataSet ds) + { + bool result = false; + if (ds != null) + { + int count = ds.Tables.Count; + if (count > 0) + { + int count2 = ds.Tables[0].Rows.Count; + if (count2 > 0) + { + result = true; + } + } + } + return result; + } + + /* + public static List GetCheckedAllControls(string checkedBoxId, GridView gv) + { + List list = new List(); + for (int i = 0; i < gv.Rows.Count; i++) + { + CheckBox checkBox = (CheckBox)gv.Rows[i].FindControl(checkedBoxId); + if (checkBox != null && checkBox.Checked) + { + list.Add(checkBox); + } + } + return list; + } + + public static List GetGetCheckedAllControlsAll(string checkedBoxId, Repeater gv) + { + List list = new List(); + for (int i = 0; i < gv.Items.Count; i++) + { + CheckBox checkBox = (CheckBox)gv.Items[i].FindControl(checkedBoxId); + if (checkBox != null) + { + list.Add(checkBox); + } + } + return list; + } + + public static List GetCheckedAllControls(string checkedBoxId, Repeater gv) + { + List list = new List(); + for (int i = 0; i < gv.Items.Count; i++) + { + CheckBox checkBox = (CheckBox)gv.Items[i].FindControl(checkedBoxId); + if (checkBox != null && checkBox.Checked) + { + list.Add(checkBox); + } + } + return list; + } + + public static void GetTreeViewCheckNodeAllList(TreeView treeview, List getList) + { + foreach (TreeNode node in treeview.Nodes) + { + getList.Add(node); + if (node.ChildNodes.Count > 0) + { + GetTreeViewNodeAll(node, getList); + } + } + } + + private static void GetTreeViewNodeAll(TreeNode ParentNode, List getList) + { + foreach (TreeNode childNode in ParentNode.ChildNodes) + { + getList.Add(childNode); + if (childNode.ChildNodes.Count > 0) + { + GetTreeViewNodeAll(childNode, getList); + } + } + } + + public static void GetTreeViewCheckNodeList(TreeView treeview, List getList) + { + foreach (TreeNode node in treeview.Nodes) + { + if (node.Checked) + { + getList.Add(node); + } + if (node.ChildNodes.Count > 0) + { + GetTreeViewNode(node, getList); + } + } + } + + private static void GetTreeViewNode(TreeNode ParentNode, List getList) + { + foreach (TreeNode childNode in ParentNode.ChildNodes) + { + if (childNode.Checked) + { + getList.Add(childNode); + } + if (childNode.ChildNodes.Count > 0) + { + GetTreeViewNode(childNode, getList); + } + } + } + + public static void UpdateMessage(ObjectDataSourceStatusEventArgs e, Label lblMessage) + { + if (e.Exception != null) + { + e.ExceptionHandled = true; + return; + } + int num = (int)e.ReturnValue; + if (num > 0) + { + lblMessage.Text = "编辑成功!"; + } + else if (num == 0) + { + lblMessage.Text = "请重试!"; + } + } + + public static void UpdateAlertMessage(ObjectDataSourceStatusEventArgs e, Page page) + { + if (e.Exception != null) + { + e.ExceptionHandled = true; + return; + } + int num = (int)e.ReturnValue; + if (num > 0) + { + Alert(page, "编辑成功!"); + } + else if (num == 0) + { + Alert(page, "请重试!"); + } + } + + public static void DeleteMessage(ObjectDataSourceStatusEventArgs e, Label lblMessage) + { + if (e.Exception != null) + { + e.ExceptionHandled = true; + return; + } + int num = (int)e.ReturnValue; + if (num > 0) + { + lblMessage.Text = "删除成功!"; + } + else if (num == 0) + { + lblMessage.Text = "请重试!"; + } + } + + public static List GetListControl(ListControl control) + { + List list = new List(); + for (int i = 0; i < control.Items.Count; i++) + { + if (control.Items[i].Selected) + { + list.Add(control.Items[i]); + } + } + return list; + } + + public static DataSet GetXMLDataSet(string key, string xml) + { + object obj = HttpContext.Current.Cache[key]; + if (obj == null) + { + DataSet dataSet = new DataSet(); + dataSet.ReadXml(xml); + HttpContext.Current.Cache.Insert(key, dataSet, new CacheDependency(xml)); + return dataSet; + } + return (DataSet)obj; + } + + */ + public static string Post(string Web, string postData) + { + string text = ""; + postData = postData.Replace(" ", "%20"); + try + { + HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(Web); + Stream stream = new MemoryStream(); + StreamWriter streamWriter = new StreamWriter(stream, Encoding.Default); + streamWriter.Write(postData); + streamWriter.Flush(); + long length = stream.Length; + streamWriter.Close(); + httpWebRequest.ContentType = "application/x-www-form-urlencoded"; + httpWebRequest.ContentLength = length; + httpWebRequest.Method = "POST"; + Stream requestStream = httpWebRequest.GetRequestStream(); + streamWriter = new StreamWriter(requestStream, Encoding.Default); + streamWriter.Write(postData); + streamWriter.Close(); + HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse(); + Stream responseStream = httpWebResponse.GetResponseStream(); + Encoding @default = Encoding.Default; + StreamReader streamReader = new StreamReader(responseStream, @default); + text = streamReader.ReadToEnd(); + streamReader.Close(); + httpWebResponse.Close(); + return text; + } + catch (Exception ex) + { + throw ex; + } + } + + private static string UrlEncode(string url, Encoding enc) + { + byte[] bytes = enc.GetBytes(url); + StringBuilder stringBuilder = new StringBuilder(); + for (int i = 0; i < bytes.Length; i++) + { + if (bytes[i] < 128) + { + stringBuilder.Append((char)bytes[i]); + continue; + } + stringBuilder.Append("%" + bytes[i++].ToString("x").PadLeft(2, '0')); + stringBuilder.Append("%" + bytes[i].ToString("x").PadLeft(2, '0')); + } + return stringBuilder.ToString(); + } + + public static string Get(string url, Encoding enc) + { + string requestUriString = UrlEncode(url, enc); + HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(requestUriString); + HttpWebResponse httpWebResponse = (HttpWebResponse)httpWebRequest.GetResponse(); + Stream responseStream = httpWebResponse.GetResponseStream(); + StreamReader streamReader = new StreamReader(responseStream, enc); + string result = streamReader.ReadToEnd(); + streamReader.Close(); + httpWebResponse.Close(); + return result; + } + + public static string Get(string url) + { + Encoding encoding = Encoding.GetEncoding("gb2312"); + return Get(UrlEncode(url, encoding), encoding); + } +/* + public static string RenderUserControl(string UserControlName) + { + StringBuilder stringBuilder = new StringBuilder(); + StringWriter writer = new StringWriter(stringBuilder); + HtmlTextWriter writer2 = new HtmlTextWriter(writer); + UserControl userControl = new UserControl(); + Control control = userControl.LoadControl(UserControlName); + control.RenderControl(writer2); + return stringBuilder.ToString(); + } + + public static void SetListControl(ListControl control, object oItemValue, int flag) + { + string b = string.Concat(oItemValue); + if (flag >= 0) + { + for (int i = 0; i < control.Items.Count; i++) + { + if (control.Items[i].Value == b) + { + control.Items[i].Selected = true; + } + else + { + control.Items[i].Selected = false; + } + } + return; + } + for (int i = 0; i < control.Items.Count; i++) + { + if (control.Items[i].Text == b) + { + control.Items[i].Selected = true; + } + else + { + control.Items[i].Selected = false; + } + } + } + + public static void SetListControlFuzz(ListControl control, object oItemValue) + { + string text = $"\uff3e{string.Concat(oItemValue)}\uff3e"; + int num = 0; + while (true) + { + if (num < control.Items.Count) + { + if ($"\uff3e{control.Items[num].Value}\uff3e".IndexOf(text.ToString()) == 0) + { + break; + } + control.Items[num].Selected = false; + num++; + continue; + } + return; + } + control.Items[num].Selected = true; + } +*/ + public static bool IsInt(string str) + { + Regex regex = new Regex("^[-]?\\d+$"); + return regex.IsMatch(str); + } + + public static bool IsNumeric(string str) + { + str.Trim(); + Regex regex = new Regex("^[-]?\\d+[.]?\\d*$"); + return regex.IsMatch(str); + } + + public static bool IsDateTime(string strValue) + { + if (null == strValue) + { + return false; + } + strValue = strValue.Trim(); + string pattern = "[1-2]{1}[0-9]{3}((-|\\/){1}(([0]?[1-9]{1})|(1[0-2]{1}))((-|\\/){1}((([0]?[1-9]{1})|([1-2]{1}[0-9]{1})|(3[0-1]{1})))( (([0-1]{1}[0-9]{1})|2[0-3]{1}):([0-5]{1}[0-9]{1}):([0-5]{1}[0-9]{1})(\\.[0-9]{3})?)?)?)?$"; + if (Regex.IsMatch(strValue, pattern)) + { + int num = -1; + int num2 = -1; + int num3 = -1; + if (-1 != (num = strValue.IndexOf("-"))) + { + num2 = strValue.IndexOf("-", num + 1); + num3 = strValue.IndexOf(":"); + } + else + { + num = strValue.IndexOf("/"); + num2 = strValue.IndexOf("/", num + 1); + num3 = strValue.IndexOf(":"); + } + if (-1 == num2) + { + return true; + } + if (-1 == num3) + { + num3 = strValue.Length + 3; + } + int num4 = Convert.ToInt32(strValue.Substring(0, num)); + int num5 = Convert.ToInt32(strValue.Substring(num + 1, num2 - num - 1)); + int num6 = Convert.ToInt32(strValue.Substring(num2 + 1, num3 - num2 - 4)); + if ((num5 < 8 && 1 == num5 % 2) || (num5 > 8 && 0 == num5 % 2)) + { + if (num6 < 32) + { + return true; + } + } + else if (num5 != 2) + { + if (num6 < 31) + { + return true; + } + } + else if (num4 % 400 == 0 || (num4 % 4 == 0 && 0 < num4 % 100)) + { + if (num6 < 30) + { + return true; + } + } + else if (num6 < 29) + { + return true; + } + } + return false; + } + + public static string DisplayBoolean(int boolFlag) + { + string result = string.Empty; + switch (boolFlag) + { + case 0: + result = "是"; + break; + case 1: + result = "否"; + break; + } + return result; + } + + public static string GetExtendName(string fileName) + { + string text = ""; + int num = fileName.LastIndexOf('.') + 1; + text = fileName.Substring(num, fileName.Length - num); + return text.ToLower(); + } +/* + public static void DownloadFileByFilePath(Page WebForm, string FileNameWhenUserDownload, string FilePath) + { + WebForm.Response.ContentType = "application/x-zip-compressed"; + WebForm.Response.AddHeader("Content-Disposition", "attachment;filename=" + FileNameWhenUserDownload); + WebForm.Response.TransmitFile(FilePath); + } + + public static string GetClientIP() + { + string text = HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"]; + if (text == null || text == string.Empty) + { + text = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"]; + } + if (text == null || text == string.Empty) + { + text = HttpContext.Current.Request.UserHostAddress; + } + return text; + } +*/ + } +} diff --git a/Common.GLib/GLib.Extension/FunctionEx.cs b/Common.GLib/GLib.Extension/FunctionEx.cs new file mode 100644 index 0000000000000000000000000000000000000000..56e067e141cdd6fc59a208b19b6b3ac867234d39 --- /dev/null +++ b/Common.GLib/GLib.Extension/FunctionEx.cs @@ -0,0 +1,1136 @@ +using System; +using System.Collections.Generic; +using System.Runtime.InteropServices; + +namespace GLib.Extension +{ + public static class FunctionEx + { + private static byte[] ArrayCRCHigh = new byte[256] + { + 0, + 193, + 129, + 64, + 1, + 192, + 128, + 65, + 1, + 192, + 128, + 65, + 0, + 193, + 129, + 64, + 1, + 192, + 128, + 65, + 0, + 193, + 129, + 64, + 0, + 193, + 129, + 64, + 1, + 192, + 128, + 65, + 1, + 192, + 128, + 65, + 0, + 193, + 129, + 64, + 0, + 193, + 129, + 64, + 1, + 192, + 128, + 65, + 0, + 193, + 129, + 64, + 1, + 192, + 128, + 65, + 1, + 192, + 128, + 65, + 0, + 193, + 129, + 64, + 1, + 192, + 128, + 65, + 0, + 193, + 129, + 64, + 0, + 193, + 129, + 64, + 1, + 192, + 128, + 65, + 0, + 193, + 129, + 64, + 1, + 192, + 128, + 65, + 1, + 192, + 128, + 65, + 0, + 193, + 129, + 64, + 0, + 193, + 129, + 64, + 1, + 192, + 128, + 65, + 1, + 192, + 128, + 65, + 0, + 193, + 129, + 64, + 1, + 192, + 128, + 65, + 0, + 193, + 129, + 64, + 0, + 193, + 129, + 64, + 1, + 192, + 128, + 65, + 1, + 192, + 128, + 65, + 0, + 193, + 129, + 64, + 0, + 193, + 129, + 64, + 1, + 192, + 128, + 65, + 0, + 193, + 129, + 64, + 1, + 192, + 128, + 65, + 1, + 192, + 128, + 65, + 0, + 193, + 129, + 64, + 0, + 193, + 129, + 64, + 1, + 192, + 128, + 65, + 1, + 192, + 128, + 65, + 0, + 193, + 129, + 64, + 1, + 192, + 128, + 65, + 0, + 193, + 129, + 64, + 0, + 193, + 129, + 64, + 1, + 192, + 128, + 65, + 0, + 193, + 129, + 64, + 1, + 192, + 128, + 65, + 1, + 192, + 128, + 65, + 0, + 193, + 129, + 64, + 1, + 192, + 128, + 65, + 0, + 193, + 129, + 64, + 0, + 193, + 129, + 64, + 1, + 192, + 128, + 65, + 1, + 192, + 128, + 65, + 0, + 193, + 129, + 64, + 0, + 193, + 129, + 64, + 1, + 192, + 128, + 65, + 0, + 193, + 129, + 64, + 1, + 192, + 128, + 65, + 1, + 192, + 128, + 65, + 0, + 193, + 129, + 64 + }; + + private static byte[] checkCRCLow = new byte[256] + { + 0, + 192, + 193, + 1, + 195, + 3, + 2, + 194, + 198, + 6, + 7, + 199, + 5, + 197, + 196, + 4, + 204, + 12, + 13, + 205, + 15, + 207, + 206, + 14, + 10, + 202, + 203, + 11, + 201, + 9, + 8, + 200, + 216, + 24, + 25, + 217, + 27, + 219, + 218, + 26, + 30, + 222, + 223, + 31, + 221, + 29, + 28, + 220, + 20, + 212, + 213, + 21, + 215, + 23, + 22, + 214, + 210, + 18, + 19, + 211, + 17, + 209, + 208, + 16, + 240, + 48, + 49, + 241, + 51, + 243, + 242, + 50, + 54, + 246, + 247, + 55, + 245, + 53, + 52, + 244, + 60, + 252, + 253, + 61, + 255, + 63, + 62, + 254, + 250, + 58, + 59, + 251, + 57, + 249, + 248, + 56, + 40, + 232, + 233, + 41, + 235, + 43, + 42, + 234, + 238, + 46, + 47, + 239, + 45, + 237, + 236, + 44, + 228, + 36, + 37, + 229, + 39, + 231, + 230, + 38, + 34, + 226, + 227, + 35, + 225, + 33, + 32, + 224, + 160, + 96, + 97, + 161, + 99, + 163, + 162, + 98, + 102, + 166, + 167, + 103, + 165, + 101, + 100, + 164, + 108, + 172, + 173, + 109, + 175, + 111, + 110, + 174, + 170, + 106, + 107, + 171, + 105, + 169, + 168, + 104, + 120, + 184, + 185, + 121, + 187, + 123, + 122, + 186, + 190, + 126, + 127, + 191, + 125, + 189, + 188, + 124, + 180, + 116, + 117, + 181, + 119, + 183, + 182, + 118, + 114, + 178, + 179, + 115, + 177, + 113, + 112, + 176, + 80, + 144, + 145, + 81, + 147, + 83, + 82, + 146, + 150, + 86, + 87, + 151, + 85, + 149, + 148, + 84, + 156, + 92, + 93, + 157, + 95, + 159, + 158, + 94, + 90, + 154, + 155, + 91, + 153, + 89, + 88, + 152, + 136, + 72, + 73, + 137, + 75, + 139, + 138, + 74, + 78, + 142, + 143, + 79, + 141, + 77, + 76, + 140, + 68, + 132, + 133, + 69, + 135, + 71, + 70, + 134, + 130, + 66, + 67, + 131, + 65, + 129, + 128, + 64 + }; + + public static string EmptyString(this string value) + { + return value.EmptyString(null); + } + + public static string EmptyString(this string value, string def) + { + if (value != null) + { + if (value.Trim() == "") + { + return def; + } + return value; + } + return def; + } + + public static decimal EmptyDecimal(this string value, decimal def = 0m) + { + if (value.EmptyString() == null) + { + return def; + } + return value.Convert(); + } + + public static int? EmptyInt(this string value) + { + if (value.EmptyString() == null) + { + return null; + } + return value.Convert(); + } + + public static int EmptyInt(this string value, int def = 0) + { + if (value.EmptyString() == null) + { + return def; + } + return value.Convert(); + } + + public static long? EmptyLong(this string value) + { + if (value.EmptyString() == null) + { + return null; + } + return value.Convert(); + } + + public static long EmptyLong(this string value, long def = 0L) + { + if (value.EmptyString() == null) + { + return def; + } + return value.Convert(); + } + + public static string EmptyString(this int? value, string def = "") + { + return value.HasValue ? string.Concat(value) : def; + } + + public static string EmptyString(this decimal? value, string def = "") + { + if (value.HasValue) + { + if (value.Value == 0m) + { + return "0"; + } + return value.Value.ToString("G0"); + } + return def; + } + + public static string EmptyString(this long? value, string def = "") + { + return value.HasValue ? string.Concat(value) : def; + } + + public static string EmptyString(this DateTime? value, string def = "") + { + return value.HasValue ? value.ToDateTime() : def; + } + + public static string EmptyString(this object value, string def = "") + { + if (value != null && (value is decimal || value is decimal)) + { + if (value is decimal?) + { + return ((decimal?)value).EmptyString(); + } + return EmptyString((decimal)value); + } + return string.Concat(value).EmptyString(def); + } + + public static DateTime? EmptyDateTime(this string value) + { + if (value.EmptyString() == null) + { + return null; + } + return value.Convert(); + } + + public static DateTime EmptyDateTime(this string value, DateTime def) + { + if (value.EmptyString() == null) + { + return def; + } + return value.Convert(); + } + + public static T NullType(T? value) where T : struct + { + return NullType(value, default(T)); + } + + public static T NullType(T? value, T def) where T : struct + { + if (value.HasValue) + { + return value.Value; + } + return def; + } + + public static int NullInt(this int? value) + { + return NullType(value, 0); + } + + public static int NullInt(this int? value, int def) + { + return NullType(value, def); + } + + public static int NullInt(this object value, int def = 0) + { + if (value is int) + { + return (int)value; + } + if (value is int?) + { + if (((int?)value).HasValue) + { + return ((int?)value).Value; + } + return def; + } + if (value is string) + { + return ((string)value).EmptyInt(def); + } + return def; + } + + public static decimal NullDecimal(this decimal? value) + { + return NullType(value, 0m); + } + + public static decimal NullDecimal(this decimal? value, decimal def) + { + return NullType(value, def); + } + + public static decimal NullDecimal(this object value, long def = 0L) + { + if (value is decimal) + { + return (decimal)value; + } + if (value is decimal?) + { + if (((decimal?)value).HasValue) + { + return ((decimal?)value).Value; + } + return def; + } + if (value is string) + { + return ((string)value).EmptyDecimal(def); + } + return def; + } + + public static long NullLong(this long? value) + { + return NullType(value, 0L); + } + + public static long NullLong(this long? value, long def) + { + return NullType(value, def); + } + + public static long NullLong(this object value, long def = 0L) + { + if (value is long) + { + return (long)value; + } + if (value is long?) + { + if (((long?)value).HasValue) + { + return ((long?)value).Value; + } + return def; + } + if (value is string) + { + return ((string)value).EmptyLong(def); + } + return def; + } + + public static bool NullBool(this bool? value) + { + return value.NullBool(def: false); + } + + public static bool NullBool(this bool? value, bool def = false) + { + if (value.HasValue) + { + return value.Value; + } + return def; + } + + public static bool NullBool(this object value, bool def = false) + { + if (value is bool) + { + return (bool)value; + } + if (value is bool?) + { + if (((bool?)value).HasValue) + { + return ((bool?)value).Value; + } + return def; + } + return def; + } + + public static T Convert(this object value) + { + return value.Convert(showError: true); + } + + public static T Convert(this object value, bool showError) + { + Exception ex = null; + T outValue = default(T); + if (!value.Convert(out outValue, out ex) && showError) + { + throw ex; + } + return outValue; + } + + public static bool Convert(this object value, out T outValue) + { + Exception ex = null; + return value.Convert(out outValue, out ex); + } + + public static T Convert(this object value, string message) + { + T val = default(T); + try + { + return value.Convert(); + } + catch + { + throw new ArgumentException(message); + } + } + + private static bool Convert(this object value, out T outValue, out Exception ex) + { + bool result = false; + ex = null; + try + { + Type typeFromHandle = typeof(T); + if (value is T) + { + outValue = (T)value; + } + else if (typeFromHandle.IsEnum) + { + outValue = (T)Enum.Parse(typeof(T), value.ToString(), ignoreCase: true); + } + else + { + outValue = (T)System.Convert.ChangeType(value, typeof(T)); + } + result = true; + } + catch (Exception ex2) + { + Exception ex3 = ex = ex2; + outValue = default(T); + } + return result; + } + + public static T Convert(this string value) + { + return ((object)value).Convert(); + } + + public static T[] Convert(this Array Collection) + { + List list = new List(); + foreach (object item in Collection) + { + list.Add(item.Convert()); + } + return list.ToArray(); + } + + public static T Convert(this IEnumerable items) where T : ICollection, new() + { + T result = new T(); + foreach (U item in items) + { + result.Add(item); + } + return result; + } + + public static T BytesToStruct(byte[] bytes, int startIndex, int length) + { + if (bytes == null) + { + return default(T); + } + if (bytes.Length <= 0) + { + return default(T); + } + IntPtr intPtr = Marshal.AllocHGlobal(length); + try + { + Marshal.Copy(bytes, startIndex, intPtr, length); + return (T)Marshal.PtrToStructure(intPtr, typeof(T)); + } + catch (Exception ex) + { + throw new Exception("Error in BytesToStruct ! " + ex.Message); + } + finally + { + Marshal.FreeHGlobal(intPtr); + } + } + + public static T BytesToStruct(byte[] bytes) + { + return BytesToStruct(bytes, 0, bytes.Length); + } + + public static byte[] StructToBytes(object structObj, int size) + { + IntPtr intPtr = Marshal.AllocHGlobal(size); + try + { + Marshal.StructureToPtr(structObj, intPtr, fDeleteOld: false); + byte[] array = new byte[size]; + Marshal.Copy(intPtr, array, 0, size); + return array; + } + catch (Exception ex) + { + throw new Exception("Error in StructToBytes ! " + ex.Message); + } + finally + { + Marshal.FreeHGlobal(intPtr); + } + } + + public static byte[] StructToBytes(object structObj) + { + int size = Marshal.SizeOf(structObj); + return StructToBytes(structObj, size); + } + + public static IntPtr StructToIntPtr(object structObj) + { + byte[] buff = StructToBytes(structObj); + return BytesToIntPtr(buff); + } + + public static T IntPtrToStruct(IntPtr intptr) + { + int index = 0; + int length = Marshal.SizeOf(typeof(T)); + return IntPtrToStruct(intptr, index, length); + } + + public static T IntPtrToStruct(IntPtr intptr, int index, int length) + { + byte[] array = new byte[length]; + Marshal.Copy(intptr, array, index, length); + return BytesToStruct(array, 0, array.Length); + } + + public static IntPtr BytesToIntPtr(byte[] buff) + { + IntPtr intPtr = Marshal.AllocHGlobal(buff.Length); + Marshal.Copy(buff, 0, intPtr, buff.Length); + return intPtr; + } + + public static byte[] IntPtrToBytes(IntPtr intptr, int index, int length) + { + byte[] array = new byte[length]; + Marshal.Copy(intptr, array, index, length); + return array; + } + + public static void IntPtrSetValue(IntPtr intptr, object structObj) + { + IntPtrSetValue(intptr, StructToBytes(structObj)); + } + + public static void IntPtrSetValue(IntPtr intptr, byte[] bytes) + { + Marshal.Copy(bytes, 0, intptr, bytes.Length); + } + + public static long GetHashNum(this Guid guid) + { + return guid.ToString().Replace("-", "").GetHashNum(); + } + + public static long GetHashNum(this string szStr) + { + long num = 5381L; + foreach (int num2 in szStr) + { + num = (((num << 5) + num) ^ num2); + } + return num; + } + + public static long GenerateUniqueCode() + { + return Guid.NewGuid().ToString().Replace("-", "") + .GetHashNum(); + } + + public static string ToDateTime(this DateTime? time) + { + return (!time.HasValue) ? "" : time.Value.ToString("yyyy-MM-dd"); + } + + public static string ToDisplayTime(this DateTime? time) + { + return (!time.HasValue) ? "" : time.Value.ToString("yyyy年MM月dd日"); + } + + public static string ToDisplayTime(this DateTime time) + { + return time.ToString("yyyy年MM月dd日"); + } + + public static string ToDateTime(this DateTime time) + { + return time.ToString("yyyy-MM-dd"); + } + + public static string ToDecimalString(this decimal? d) + { + string result = ""; + if (d.HasValue) + { + result = d.ToString(); + } + return result; + } + + public static string ToIntString(this int? n) + { + string result = ""; + if (n.HasValue) + { + result = n.ToString(); + } + return result; + } + + public static string ToSString(this string ss) + { + string result = ""; + if (!string.IsNullOrEmpty(ss)) + { + result = ss; + } + return result; + } + + public static string ToDateTime(this object time) + { + if (time is DateTime) + { + return ((DateTime)time).ToString("yyyy-MM-dd"); + } + if (time is DateTime? && ((DateTime?)time).HasValue) + { + return ((DateTime?)time).Value.ToString("yyyy-MM-dd"); + } + return null; + } + + public static bool IsNotNull(this string s) + { + return !string.IsNullOrEmpty(s); + } + + public static bool IsNullOrEmpty(this string s) + { + return string.IsNullOrEmpty(s); + } + + public static byte[] ToByteArray(short[] src) + { + int num = src.Length * 2; + IntPtr intPtr = Marshal.AllocHGlobal(num); + Marshal.Copy(src, 0, intPtr, src.Length); + byte[] array = new byte[num]; + Marshal.Copy(intPtr, array, 0, num); + Marshal.FreeHGlobal(intPtr); + return array; + } + + public static byte[] ToByteArray(int[] src) + { + int num = src.Length * 4; + IntPtr intPtr = Marshal.AllocHGlobal(num); + Marshal.Copy(src, 0, intPtr, src.Length); + byte[] array = new byte[num]; + Marshal.Copy(intPtr, array, 0, num); + Marshal.FreeHGlobal(intPtr); + return array; + } + + public static short[] ToShortArray(byte[] src) + { + int num = (src.Length % 2 == 0) ? (src.Length / 2) : (src.Length / 2 + 1); + IntPtr intPtr = Marshal.AllocHGlobal(src.Length); + Marshal.Copy(src, 0, intPtr, src.Length); + short[] array = new short[num]; + Marshal.Copy(intPtr, array, 0, array.Length); + Marshal.FreeHGlobal(intPtr); + return array; + } + + public static int[] ToIntArray(byte[] src) + { + int num = (src.Length % 4 == 0) ? (src.Length / 4) : (src.Length / 4 + 1); + IntPtr intPtr = Marshal.AllocHGlobal(src.Length); + Marshal.Copy(src, 0, intPtr, src.Length); + int[] array = new int[num]; + Marshal.Copy(intPtr, array, 0, array.Length); + Marshal.FreeHGlobal(intPtr); + return array; + } + + public static short CRC16(this byte[] data) + { + return CRC16(data, data.Length); + } + + public static short CRC16(byte[] data, int arrayLength) + { + byte b = byte.MaxValue; + byte b2 = byte.MaxValue; + int num = 0; + while (arrayLength-- > 0) + { + byte b3 = (byte)(b ^ data[num++]); + b = (byte)(b2 ^ ArrayCRCHigh[b3]); + b2 = checkCRCLow[b3]; + } + return (short)((b << 8) | b2); + } + } +} diff --git a/Common.GLib/GLib.Extension/ReflectionEx.cs b/Common.GLib/GLib.Extension/ReflectionEx.cs new file mode 100644 index 0000000000000000000000000000000000000000..48088670570129032ce7a5006987ddf9c2d89de1 --- /dev/null +++ b/Common.GLib/GLib.Extension/ReflectionEx.cs @@ -0,0 +1,174 @@ +using System; +using System.Linq; +using System.Reflection; + +namespace GLib.Extension +{ + public static class ReflectionEx + { + public static void EvaluationByFields(object o1, object o2) + { + EvaluationByFields(o1, o2, null); + } + + public static void EvaluationByFields(object o1, object o2, Type attType) + { + if (o1 == null || o2 == null) + { + throw new Exception(); + } + Type type = o1.GetType(); + Type type2 = o2.GetType(); + FieldInfo[] array = type.GetFields(); + if (attType != null) + { + array = type.GetAttributeFields(attType).ToArray(); + } + FieldInfo[] array2 = type2.GetFields(); + if (attType != null) + { + array2 = type2.GetAttributeFields(attType).ToArray(); + } + FieldInfo[] array3 = array; + foreach (FieldInfo f1 in array3) + { + FieldInfo[] source = array2; + Func predicate = (FieldInfo p) => p.Name == f1.Name; + FieldInfo fieldInfo = source.FirstOrDefault(predicate); + if (fieldInfo != null) + { + f1.SetValue(o1, fieldInfo.GetValue(o2)); + } + } + } + + public static void RefSetFieldsByFields(object dts, object src) + { + RefSetFieldsByFields(dts, src, null); + } + + public static void RefSetFieldsByFields(object dts, object src, Type attType) + { + if (dts == null || src == null) + { + throw new Exception(); + } + Type type = dts.GetType(); + Type type2 = src.GetType(); + FieldInfo[] array = type.GetFields(); + if (attType != null) + { + array = type.GetAttributeFields(attType).ToArray(); + } + FieldInfo[] array2 = type2.GetFields(); + if (attType != null) + { + array2 = type2.GetAttributeFields(attType).ToArray(); + } + FieldInfo[] array3 = array; + foreach (FieldInfo f1 in array3) + { + FieldInfo[] source = array2; + Func predicate = (FieldInfo p) => p.Name == f1.Name; + FieldInfo fieldInfo = source.FirstOrDefault(predicate); + if (fieldInfo != null) + { + f1.SetValue(dts, fieldInfo.GetValue(src)); + } + } + } + + public static void RefSetPropertiesByProperties(object o1, object o2, Type attType) + { + if (o1 == null || o2 == null) + { + throw new Exception(); + } + Type type = o1.GetType(); + Type type2 = o2.GetType(); + PropertyInfo[] array = type.GetProperties(); + if (attType != null) + { + array = type.GetAttributeProperties(attType).ToArray(); + } + PropertyInfo[] array2 = type2.GetProperties(); + if (attType != null) + { + array2 = type2.GetAttributeProperties(attType).ToArray(); + } + PropertyInfo[] array3 = array; + foreach (PropertyInfo f1 in array3) + { + PropertyInfo[] source = array2; + Func predicate = (PropertyInfo p) => p.Name == f1.Name; + PropertyInfo propertyInfo = source.FirstOrDefault(predicate); + if (propertyInfo != null) + { + f1.SetValue(o1, propertyInfo.GetValue(o2, null), null); + } + } + } + + public static void RefSetFieldsByProperties(object o1, object o2, Type attType) + { + if (o1 == null || o2 == null) + { + throw new Exception(); + } + Type type = o1.GetType(); + Type type2 = o2.GetType(); + FieldInfo[] array = type.GetFields(); + if (attType != null) + { + array = type.GetAttributeFields(attType).ToArray(); + } + PropertyInfo[] array2 = type2.GetProperties(); + if (attType != null) + { + array2 = type2.GetAttributeProperties(attType).ToArray(); + } + FieldInfo[] array3 = array; + foreach (FieldInfo f1 in array3) + { + PropertyInfo[] source = array2; + Func predicate = (PropertyInfo p) => p.Name == f1.Name; + PropertyInfo propertyInfo = source.FirstOrDefault(predicate); + if (propertyInfo != null) + { + f1.SetValue(o1, propertyInfo.GetValue(o2, null)); + } + } + } + + public static void RefSetPropertiesByFields(object o1, object o2, Type attType) + { + if (o1 == null || o2 == null) + { + throw new Exception(); + } + Type type = o1.GetType(); + Type type2 = o2.GetType(); + PropertyInfo[] array = type.GetProperties(); + if (attType != null) + { + array = type.GetAttributeProperties(attType).ToArray(); + } + FieldInfo[] array2 = type2.GetFields(); + if (attType != null) + { + array2 = type.GetAttributeFields(attType).ToArray(); + } + PropertyInfo[] array3 = array; + foreach (PropertyInfo f1 in array3) + { + FieldInfo[] source = array2; + Func predicate = (FieldInfo p) => p.Name == f1.Name; + FieldInfo fieldInfo = source.FirstOrDefault(predicate); + if (fieldInfo != null) + { + f1.SetValue(o1, fieldInfo.GetValue(o2), null); + } + } + } + } +} diff --git a/Common.GLib/GLib.Extension/Singleton.cs b/Common.GLib/GLib.Extension/Singleton.cs new file mode 100644 index 0000000000000000000000000000000000000000..b5483438e0a2679fc6e42f8245c2d5872c33ae64 --- /dev/null +++ b/Common.GLib/GLib.Extension/Singleton.cs @@ -0,0 +1,27 @@ +namespace GLib.Extension +{ + public class Singleton where T : new() + { + private static T instance__ = default(T); + + private static object syncRoot__ = new object(); + + public static T Instance + { + get + { + if (instance__ == null) + { + lock (syncRoot__) + { + if (instance__ == null) + { + instance__ = new T(); + } + } + } + return instance__; + } + } + } +} diff --git a/Common.GLib/GLib.Extension/StringEx.cs b/Common.GLib/GLib.Extension/StringEx.cs new file mode 100644 index 0000000000000000000000000000000000000000..828abd7d04e825a9507eecfafef01a462c903d60 --- /dev/null +++ b/Common.GLib/GLib.Extension/StringEx.cs @@ -0,0 +1,263 @@ +using Newtonsoft.Json; +using Newtonsoft.Json.Converters; +using System; +using System.Collections; +using System.Collections.Generic; +using System.Linq; +using System.Text; + +namespace GLib.Extension +{ + public static class StringEx + { + public static string _Format(this string str, string format) + { + return string.Format(format, str); + } + + public static string CutString(this string inputString, int len) + { + ASCIIEncoding aSCIIEncoding = new ASCIIEncoding(); + int num = 0; + string text = ""; + byte[] bytes = aSCIIEncoding.GetBytes(inputString); + for (int i = 0; i < bytes.Length; i++) + { + num = ((bytes[i] != 63) ? (num + 1) : (num + 2)); + try + { + text += inputString.Substring(i, 1); + } + catch + { + break; + } + if (num > len) + { + break; + } + } + byte[] bytes2 = Encoding.Default.GetBytes(inputString); + if (bytes2.Length > len) + { + text += "..."; + } + return text; + } + + public static string CutString(this object inputString, int len) + { + return string.Concat(inputString).CutString(len); + } + + public static string ConstituteString(this IEnumerable items, string splitKey) + { + string text = ""; + foreach (object item in items) + { + if (item != null) + { + text = string.Concat(text, (text == "") ? "" : splitKey, string.Concat(item)); + } + } + return text; + } + + public static string ConstituteString(this IEnumerable items) + { + return items.ConstituteString(","); + } + + public static bool EqIgnoreCase(this string source, string value) + { + if (source == value) + { + return true; + } + return source?.Equals(value, StringComparison.OrdinalIgnoreCase) ?? false; + } + + public static T[] Split(this string source, string splitKey = ",") + { + if (string.IsNullOrEmpty(source)) + { + return new T[0]; + } + return Enumerable.ToArray(Enumerable.Select(source.Split(new string[1] + { + splitKey + }, StringSplitOptions.RemoveEmptyEntries), (string p) => p.Convert())); + } + + public static string UrlFilter(this string url, string filter) + { + return new Uri(url).UrlFilter(filter); + } + + public static string UrlFilter(this Uri url, string filter) + { + string text = ""; + string[] array = url.Query.Replace("?", "").Split("&"); + string[] array2 = array; + foreach (string text2 in array2) + { + string[] array3 = text2.Split("="); + string source = ""; + string text3 = ""; + if (array3.Length > 0) + { + source = array3[0]; + } + if (array3.Length > 1) + { + text3 = array3[1]; + } + if (!source.EqIgnoreCase(filter)) + { + text = text + ((text == "") ? "" : "&") + text2; + } + } + if (text == "") + { + text = "1=1"; + } + string result = url.AbsoluteUri + "?" + text; + if (url.Query != "") + { + result = url.AbsoluteUri.Replace(url.Query, "") + "?" + text; + } + return result; + } + + public static string To16Str(this byte b) + { + return Convert.ToString(b, 16).PadLeft(2, '0'); + } + + public static byte To16Byte(this string s) + { + return Convert.ToByte(s, 16); + } + + public static string To16Strs(this byte[] bs) + { + return bs.To16Strs(0, bs.Length); + } + + public static string To16Strs(this byte[] bs, int offset, int len) + { + StringBuilder stringBuilder = new StringBuilder(); + foreach (byte item in Enumerable.Take(Enumerable.Skip(bs, offset), len)) + { + stringBuilder.Append(item.To16Str() + " "); + } + return stringBuilder.ToString(); + } + + public static byte[] To16Bytes(this string s) + { + List list = new List(); + string[] array = s.Split(new string[1] + { + " " + }, StringSplitOptions.RemoveEmptyEntries); + string[] array2 = array; + foreach (string s2 in array2) + { + list.Add(s2.To16Byte()); + } + return list.ToArray(); + } + + public static string ToSystemPath(this string path) + { + if (Environment.OSVersion.Platform == PlatformID.Unix) + { + return path.Replace("\\", "/"); + } + return path.Replace("/", "\\"); + } + + public static string JsonConvert(this object o) + { + IsoDateTimeConverter isoDateTimeConverter = new IsoDateTimeConverter(); + isoDateTimeConverter.DateTimeFormat = "yyyy-MM-dd HH:mm:ss.fff"; + return Newtonsoft.Json.JsonConvert.SerializeObject(o, Formatting.Indented, isoDateTimeConverter); + } + + public static string JsonConvert(this object o, bool isIndented) + { + return Newtonsoft.Json.JsonConvert.SerializeObject(o, isIndented ? Formatting.Indented : Formatting.None); + } + + public static T JsonConvert(this string str) + { + return Newtonsoft.Json.JsonConvert.DeserializeObject(str); + } + + public static object JsonConvert(this string str, Type type) + { + return Newtonsoft.Json.JsonConvert.DeserializeObject(str, type); + } + + public static T JsonConvert(this string str, T obj) + { + return Newtonsoft.Json.JsonConvert.DeserializeAnonymousType(str, obj); + } + + public static string StringToBase64String(this string value) + { + byte[] bytes = new UnicodeEncoding().GetBytes(value); + int num = (int)Math.Ceiling((double)bytes.Length / 3.0) * 4; + char[] array = new char[num]; + Convert.ToBase64CharArray(bytes, 0, bytes.Length, array, 0); + return new string(array); + } + + public static string Base64StringToString(this string base64) + { + char[] array = base64.ToCharArray(); + byte[] bytes = Convert.FromBase64CharArray(array, 0, array.Length); + return new UnicodeEncoding().GetString(bytes); + } + + public static string ToBase64(this byte[] binBuffer) + { + return binBuffer.ToBase64(0, binBuffer.Length); + } + + public static string ToBase64(this byte[] binBuffer, int offset, int count) + { + int num = (int)Math.Ceiling((double)count / 3.0) * 4; + char[] array = new char[num]; + Convert.ToBase64CharArray(binBuffer, offset, count, array, 0); + return new string(array); + } + + public static byte[] Base64ToBytes(this string base64) + { + char[] array = base64.ToCharArray(); + return Convert.FromBase64CharArray(array, 0, array.Length); + } + + public static byte[] ToUTF8Bytes(this string value) + { + return Encoding.UTF8.GetBytes(value); + } + + public static string ToUTF8String(this byte[] bytes) + { + return Encoding.UTF8.GetString(bytes); + } + + public static string ToUTF8String(this byte[] bytes, int offset, int count) + { + return Encoding.UTF8.GetString(bytes, offset, count); + } + + public static string EmptyString(string str1, string str2) + { + return str1.EmptyString(str2); + } + } +} diff --git a/Common.GLib/GLib.Extension/TypeEx.cs b/Common.GLib/GLib.Extension/TypeEx.cs new file mode 100644 index 0000000000000000000000000000000000000000..b8096f896088b04a911c80ba7cb5372448790f33 --- /dev/null +++ b/Common.GLib/GLib.Extension/TypeEx.cs @@ -0,0 +1,57 @@ +using System; +using System.Collections.Generic; +using System.Reflection; + +namespace GLib.Extension +{ + public static class TypeEx + { + public static List GetAttributeProperties(this Type type, Type attType) + { + PropertyInfo[] properties = type.GetProperties(); + List list = new List(); + PropertyInfo[] array = properties; + foreach (PropertyInfo propertyInfo in array) + { + object[] customAttributes = propertyInfo.GetCustomAttributes(attType, inherit: true); + if (customAttributes.Length > 0) + { + list.Add(propertyInfo); + } + } + return list; + } + + public static List GetAttributeFields(this Type type, Type attType) + { + FieldInfo[] fields = type.GetFields(); + List list = new List(); + FieldInfo[] array = fields; + foreach (FieldInfo fieldInfo in array) + { + object[] customAttributes = fieldInfo.GetCustomAttributes(attType, inherit: true); + if (customAttributes.Length > 0) + { + list.Add(fieldInfo); + } + } + return list; + } + + public static List GetAttributeMembers(this Type type, Type attType) + { + MemberInfo[] members = type.GetMembers(); + List list = new List(); + MemberInfo[] array = members; + foreach (MemberInfo memberInfo in array) + { + object[] customAttributes = memberInfo.GetCustomAttributes(attType, inherit: true); + if (customAttributes.Length > 0) + { + list.Add(memberInfo); + } + } + return list; + } + } +} diff --git a/Common.GLib/GLib.GeneralModel/AQueue.cs b/Common.GLib/GLib.GeneralModel/AQueue.cs new file mode 100644 index 0000000000000000000000000000000000000000..6eb61a1322ef3f0a29d05728badb8cd96404b8ee --- /dev/null +++ b/Common.GLib/GLib.GeneralModel/AQueue.cs @@ -0,0 +1,75 @@ +using System.Collections.Generic; + +namespace GLib.GeneralModel +{ + public class AQueue : Queue + { + private object _lock = new object(); + + public new int Count + { + get + { + lock (_lock) + { + return base.Count; + } + } + } + + public AQueue() + { + } + + public AQueue(IEnumerable collection) + : base(collection) + { + } + + public AQueue(int capacity) + : base(capacity) + { + } + + public new T Dequeue() + { + lock (_lock) + { + return base.Dequeue(); + } + } + + public new void Enqueue(T item) + { + lock (_lock) + { + base.Enqueue(item); + } + } + + public new T Peek() + { + lock (_lock) + { + if (base.Count == 0) + { + return default(T); + } + return base.Peek(); + } + } + + public new T[] ToArray() + { + lock (_lock) + { + return base.ToArray(); + } + } + + public object GetLock() + { + return _lock; + } + } +} diff --git a/Common.GLib/GLib.GeneralModel/EventArgsEx.cs b/Common.GLib/GLib.GeneralModel/EventArgsEx.cs new file mode 100644 index 0000000000000000000000000000000000000000..9972a577c8e8e34e1b05e63722149b073ae8c478 --- /dev/null +++ b/Common.GLib/GLib.GeneralModel/EventArgsEx.cs @@ -0,0 +1,18 @@ +using System; + +namespace GLib.GeneralModel +{ + public class EventArgsEx : EventArgs + { + public T Arg + { + get; + private set; + } + + public EventArgsEx(T arg) + { + Arg = arg; + } + } +} diff --git a/Common.GLib/GLib.GeneralModel/KeyValue.cs b/Common.GLib/GLib.GeneralModel/KeyValue.cs new file mode 100644 index 0000000000000000000000000000000000000000..faa87fc7fdb85f244cba9227d8c386ef1de49cdf --- /dev/null +++ b/Common.GLib/GLib.GeneralModel/KeyValue.cs @@ -0,0 +1,43 @@ +using System; + +namespace GLib.GeneralModel +{ + [Serializable] + public class KeyValue + { + public TKey Key + { + get; + set; + } + + public UValue Value + { + get; + set; + } + + public KeyValue() + { + } + + public KeyValue(TKey key, UValue value) + { + Key = key; + Value = value; + } + + public override string ToString() + { + if (Value != null) + { + return Value.ToString(); + } + if (Key != null) + { + return Key.ToString(); + } + return base.ToString(); + } + } +} diff --git a/Common.GLib/GLib.GeneralModel/KeyValueList.cs b/Common.GLib/GLib.GeneralModel/KeyValueList.cs new file mode 100644 index 0000000000000000000000000000000000000000..ba7b6da448677050be24f856d0feba4d1e42eb5a --- /dev/null +++ b/Common.GLib/GLib.GeneralModel/KeyValueList.cs @@ -0,0 +1,44 @@ +using System; +using System.Collections.Generic; +using System.Linq; + +namespace GLib.GeneralModel +{ + [Serializable] + public class KeyValueList : List> + { + public UValue this[TKey key] + { + get + { + KeyValue keyValue = Enumerable.FirstOrDefault(this, (KeyValue p) => p.Key.Equals(key)); + if (keyValue != null) + { + return keyValue.Value; + } + return default(UValue); + } + set + { + KeyValue keyValue = Enumerable.FirstOrDefault(this, (KeyValue p) => p.Key.Equals(key)); + if (keyValue != null) + { + keyValue.Value = value; + } + else + { + Add(new KeyValue(key, value)); + } + } + } + + public KeyValueList() + { + } + + public KeyValueList(IEnumerable> collection) + : base(collection) + { + } + } +} diff --git a/Common.GLib/GLib.GeneralModel/ListEx.cs b/Common.GLib/GLib.GeneralModel/ListEx.cs new file mode 100644 index 0000000000000000000000000000000000000000..0638c937bf66b7c592adced18cd6ca568bdc461a --- /dev/null +++ b/Common.GLib/GLib.GeneralModel/ListEx.cs @@ -0,0 +1,16 @@ +using System.Collections.Generic; + +namespace GLib.GeneralModel +{ + public class ListEx : List + { + public ListEx() + { + } + + public ListEx(IEnumerable collection) + : base(collection) + { + } + } +} diff --git a/Common.GLib/GLib.GeneralModel/TreeNode.cs b/Common.GLib/GLib.GeneralModel/TreeNode.cs new file mode 100644 index 0000000000000000000000000000000000000000..24837e9a2b12597558b35fe51197738639fc8db6 --- /dev/null +++ b/Common.GLib/GLib.GeneralModel/TreeNode.cs @@ -0,0 +1,101 @@ +using System; +using System.Collections.Generic; +using System.Linq; + +namespace GLib.GeneralModel +{ + public class TreeNode + { + public TKey Key + { + get; + set; + } + + public UValue Value + { + get; + set; + } + + public TKey ParentKey + { + get; + set; + } + + public TreeNode Parent + { + get; + set; + } + + public List> Childs + { + get; + set; + } + + public virtual TreeNode this[TKey key] => GetValue(key); + + public TreeNode(TKey key, UValue value, TKey parentKey) + { + Key = key; + Value = value; + ParentKey = parentKey; + Childs = new List>(); + } + + public TreeNode(List> list) + { + Init(list, default(TKey)); + } + + public TreeNode(List> list, TKey rootKey) + { + Init(list, rootKey); + } + + protected void Init(List> list, TKey rootKey) + { + TreeNode treeNode = Enumerable.FirstOrDefault(list, (TreeNode p) => p.Key.Equals(rootKey)); + if (treeNode == null) + { + throw new ApplicationException("parent no find"); + } + Key = treeNode.Key; + Value = treeNode.Value; + ParentKey = treeNode.ParentKey; + IEnumerable> enumerable = Enumerable.Where(list, (TreeNode p) => p.ParentKey.Equals(rootKey)); + Childs = new List>(); + foreach (TreeNode item2 in enumerable) + { + TreeNode treeNode2 = new TreeNode(list, item2.Key); + treeNode2.Parent = this; + TreeNode item = treeNode2; + Childs.Add(item); + } + } + + public virtual TreeNode GetValue(TKey key) + { + TreeNode treeNode = null; + if (Key.Equals(key)) + { + treeNode = this; + } + else + { + foreach (TreeNode child in Childs) + { + treeNode = child.GetValue(key); + if (treeNode != null) + { + break; + } + } + } + return treeNode; + } + } +} diff --git a/Common.GLib/GLib.GeneralModel/TreeRoot.cs b/Common.GLib/GLib.GeneralModel/TreeRoot.cs new file mode 100644 index 0000000000000000000000000000000000000000..a3ce2d208227cfdede1f3b598c6d6112688b7412 --- /dev/null +++ b/Common.GLib/GLib.GeneralModel/TreeRoot.cs @@ -0,0 +1,63 @@ +using System.Collections.Generic; +using System.Linq; + +namespace GLib.GeneralModel +{ + public class TreeRoot : TreeNode + { + public List> SourceList + { + get; + set; + } + + public override TreeNode this[TKey key] => GetValue(key); + + public TreeRoot(TKey defKey, UValue value, List> list) + : base(default(TKey), default(UValue), default(TKey)) + { + init(defKey, value, list); + } + + public TreeRoot(List> list) + : base(default(TKey), default(UValue), default(TKey)) + { + init(default(TKey), default(UValue), list); + } + + private void init(TKey defKey, UValue value, List> list) + { + SourceList = list; + IEnumerable> enumerable = Enumerable.Where(list, (TreeNode p) => p.ParentKey.Equals(defKey)); + base.Childs = new List>(); + foreach (TreeNode item2 in enumerable) + { + TreeNode treeNode = new TreeNode(list, item2.Key); + treeNode.Parent = this; + TreeNode item = treeNode; + base.Childs.Add(item); + } + } + + public override TreeNode GetValue(TKey key) + { + TreeNode treeNode = null; + if (base.Key != null && base.Key.Equals(key)) + { + treeNode = this; + } + else + { + foreach (TreeNode child in base.Childs) + { + treeNode = child.GetValue(key); + if (treeNode != null) + { + break; + } + } + } + return treeNode; + } + } +} diff --git a/Common.GLib/GLib.IO/BitStream.cs b/Common.GLib/GLib.IO/BitStream.cs new file mode 100644 index 0000000000000000000000000000000000000000..69ab31b0229fc96da405d8906ee2d5d802fa945a --- /dev/null +++ b/Common.GLib/GLib.IO/BitStream.cs @@ -0,0 +1,2615 @@ +using System; +using System.Globalization; +using System.IO; +using System.Net.Sockets; +using System.Resources; +using System.Security.Cryptography; +using System.Text; + +namespace GLib.IO +{ + public class BitStream : Stream + { + private sealed class BitStreamResources + { + private static ResourceManager _resman; + + private static object _oResManLock; + + private static bool _blnLoadingResource; + + private static void InitialiseResourceManager() + { + if (_resman == null) + { + lock (typeof(BitStreamResources)) + { + if (_resman == null) + { + _oResManLock = new object(); + _resman = new ResourceManager("BKSystem.IO.BitStream", typeof(BitStream).Assembly); + } + } + } + } + + public static string GetString(string name) + { + if (_resman == null) + { + InitialiseResourceManager(); + } + string @string; + lock (_oResManLock) + { + if (_blnLoadingResource) + { + return "The resource manager was unable to load the resource: " + name; + } + _blnLoadingResource = true; + @string = _resman.GetString(name, null); + _blnLoadingResource = false; + } + return @string; + } + } + + private const int SizeOfByte = 8; + + private const int SizeOfChar = 128; + + private const int SizeOfUInt16 = 16; + + private const int SizeOfUInt32 = 32; + + private const int SizeOfSingle = 32; + + private const int SizeOfUInt64 = 64; + + private const int SizeOfDouble = 64; + + private const uint BitBuffer_SizeOfElement = 32u; + + private const int BitBuffer_SizeOfElement_Shift = 5; + + private const uint BitBuffer_SizeOfElement_Mod = 31u; + + private static uint[] BitMaskHelperLUT = new uint[33] + { + 0u, + 1u, + 3u, + 7u, + 15u, + 31u, + 63u, + 127u, + 255u, + 511u, + 1023u, + 2047u, + 4095u, + 8191u, + 16383u, + 32767u, + 65535u, + 131071u, + 262143u, + 524287u, + 1048575u, + 2097151u, + 4194303u, + 8388607u, + 16777215u, + 33554431u, + 67108863u, + 134217727u, + 268435455u, + 536870911u, + 1073741823u, + 2147483647u, + 4294967295u + }; + + private bool _blnIsOpen = true; + + private uint[] _auiBitBuffer; + + private uint _uiBitBuffer_Length; + + private uint _uiBitBuffer_Index; + + private uint _uiBitBuffer_BitIndex; + + private static IFormatProvider _ifp = CultureInfo.InvariantCulture; + + public override long Length + { + get + { + if (!_blnIsOpen) + { + throw new ObjectDisposedException(BitStreamResources.GetString("ObjectDisposed_BitStreamClosed")); + } + return _uiBitBuffer_Length; + } + } + + public virtual long Length8 + { + get + { + if (!_blnIsOpen) + { + throw new ObjectDisposedException(BitStreamResources.GetString("ObjectDisposed_BitStreamClosed")); + } + return (_uiBitBuffer_Length >> 3) + (((_uiBitBuffer_Length & 7) != 0) ? 1 : 0); + } + } + + public virtual long Length16 + { + get + { + if (!_blnIsOpen) + { + throw new ObjectDisposedException(BitStreamResources.GetString("ObjectDisposed_BitStreamClosed")); + } + return (_uiBitBuffer_Length >> 4) + (((_uiBitBuffer_Length & 0xF) != 0) ? 1 : 0); + } + } + + public virtual long Length32 + { + get + { + if (!_blnIsOpen) + { + throw new ObjectDisposedException(BitStreamResources.GetString("ObjectDisposed_BitStreamClosed")); + } + return (_uiBitBuffer_Length >> 5) + (((_uiBitBuffer_Length & 0x1F) != 0) ? 1 : 0); + } + } + + public virtual long Length64 + { + get + { + if (!_blnIsOpen) + { + throw new ObjectDisposedException(BitStreamResources.GetString("ObjectDisposed_BitStreamClosed")); + } + return (_uiBitBuffer_Length >> 6) + (((_uiBitBuffer_Length & 0x3F) != 0) ? 1 : 0); + } + } + + public virtual long Capacity + { + get + { + if (!_blnIsOpen) + { + throw new ObjectDisposedException(BitStreamResources.GetString("ObjectDisposed_BitStreamClosed")); + } + return (long)_auiBitBuffer.Length << 5; + } + } + + public override long Position + { + get + { + if (!_blnIsOpen) + { + throw new ObjectDisposedException(BitStreamResources.GetString("ObjectDisposed_BitStreamClosed")); + } + uint num = (_uiBitBuffer_Index << 5) + _uiBitBuffer_BitIndex; + return num; + } + set + { + if (!_blnIsOpen) + { + throw new ObjectDisposedException(BitStreamResources.GetString("ObjectDisposed_BitStreamClosed")); + } + if (value < 0) + { + throw new ArgumentOutOfRangeException("value", BitStreamResources.GetString("ArgumentOutOfRange_NegativePosition")); + } + uint num = (uint)value; + if (_uiBitBuffer_Length < num + 1) + { + throw new ArgumentOutOfRangeException("value", BitStreamResources.GetString("ArgumentOutOfRange_InvalidPosition")); + } + _uiBitBuffer_Index = num >> 5; + if ((num & 0x1F) != 0) + { + _uiBitBuffer_BitIndex = (num & 0x1F); + } + else + { + _uiBitBuffer_BitIndex = 0u; + } + } + } + + public override bool CanRead => _blnIsOpen; + + public override bool CanSeek => false; + + public override bool CanWrite => _blnIsOpen; + + public static bool CanSetLength => false; + + public static bool CanFlush => false; + + public BitStream() + { + _auiBitBuffer = new uint[1]; + } + + public BitStream(long capacity) + { + if (capacity <= 0) + { + throw new ArgumentOutOfRangeException(BitStreamResources.GetString("ArgumentOutOfRange_NegativeOrZeroCapacity")); + } + _auiBitBuffer = new uint[(capacity >> 5) + (((capacity & 0x1F) > 0) ? 1 : 0)]; + } + + public BitStream(byte[] bits) + : this() + { + if (bits == null) + { + throw new ArgumentNullException("bits", BitStreamResources.GetString("ArgumentNull_BitBuffer")); + } + Write(bits, 0, bits.Length); + } + + public BitStream(Stream bits) + : this() + { + if (bits == null) + { + throw new ArgumentNullException("bits", BitStreamResources.GetString("ArgumentNull_BitBuffer")); + } + byte[] buffer = new byte[bits.Length]; + long position = bits.Position; + bits.Position = 0L; + bits.Read(buffer, 0, (int)bits.Length); + bits.Position = position; + Write(buffer, 0, (int)bits.Length); + } + + private void Write(ref uint bits, ref uint bitIndex, ref uint count) + { + uint num = (_uiBitBuffer_Index << 5) + _uiBitBuffer_BitIndex; + uint num2 = _uiBitBuffer_Length >> 5; + uint num3 = bitIndex + count; + int num4 = (int)bitIndex; + uint num5 = BitMaskHelperLUT[count] << num4; + bits &= num5; + uint num6 = 32 - _uiBitBuffer_BitIndex; + num4 = (int)(num6 - num3); + uint num7 = 0u; + num7 = ((num4 >= 0) ? (bits << num4) : (bits >> Math.Abs(num4))); + if (_uiBitBuffer_Length >= num + 1) + { + int num8 = (int)(num6 - count); + uint num9 = 0u; + num9 = (uint)((num8 >= 0) ? (-1 ^ (int)(BitMaskHelperLUT[count] << num8)) : (-1 ^ (int)(BitMaskHelperLUT[count] >> Math.Abs(num8)))); + _auiBitBuffer[_uiBitBuffer_Index] &= num9; + if (num2 == _uiBitBuffer_Index) + { + uint num10 = 0u; + num10 = ((num6 < count) ? (num + num6) : (num + count)); + if (num10 > _uiBitBuffer_Length) + { + uint bits2 = num10 - _uiBitBuffer_Length; + UpdateLengthForWrite(bits2); + } + } + } + else if (num6 >= count) + { + UpdateLengthForWrite(count); + } + else + { + UpdateLengthForWrite(num6); + } + _auiBitBuffer[_uiBitBuffer_Index] |= num7; + if (num6 >= count) + { + UpdateIndicesForWrite(count); + return; + } + UpdateIndicesForWrite(num6); + uint count2 = count - num6; + uint bitIndex2 = bitIndex; + Write(ref bits, ref bitIndex2, ref count2); + } + + public virtual void Write(bool bit) + { + if (!_blnIsOpen) + { + throw new ObjectDisposedException(BitStreamResources.GetString("ObjectDisposed_BitStreamClosed")); + } + uint bits = bit ? 1u : 0u; + uint bitIndex = 0u; + uint count = 1u; + Write(ref bits, ref bitIndex, ref count); + } + + public virtual void Write(bool[] bits) + { + if (!_blnIsOpen) + { + throw new ObjectDisposedException(BitStreamResources.GetString("ObjectDisposed_BitStreamClosed")); + } + if (bits == null) + { + throw new ArgumentNullException("bits", BitStreamResources.GetString("ArgumentNull_BitBuffer")); + } + Write(bits, 0, bits.Length); + } + + public virtual void Write(bool[] bits, int offset, int count) + { + if (!_blnIsOpen) + { + throw new ObjectDisposedException(BitStreamResources.GetString("ObjectDisposed_BitStreamClosed")); + } + if (bits == null) + { + throw new ArgumentNullException("bits", BitStreamResources.GetString("ArgumentNull_BitBuffer")); + } + if (offset < 0) + { + throw new ArgumentOutOfRangeException("offset", BitStreamResources.GetString("ArgumentOutOfRange_NegativeParameter")); + } + if (count < 0) + { + throw new ArgumentOutOfRangeException("count", BitStreamResources.GetString("ArgumentOutOfRange_NegativeParameter")); + } + if (count > bits.Length - offset) + { + throw new ArgumentException(BitStreamResources.GetString("Argument_InvalidCountOrOffset")); + } + int num = offset + count; + for (int i = offset; i < num; i++) + { + Write(bits[i]); + } + } + + public virtual void Write(byte bits) + { + Write(bits, 0, 8); + } + + public virtual void Write(byte bits, int bitIndex, int count) + { + if (!_blnIsOpen) + { + throw new ObjectDisposedException(BitStreamResources.GetString("ObjectDisposed_BitStreamClosed")); + } + if (bitIndex < 0) + { + throw new ArgumentOutOfRangeException("bitIndex", BitStreamResources.GetString("ArgumentOutOfRange_NegativeParameter")); + } + if (count < 0) + { + throw new ArgumentOutOfRangeException("count", BitStreamResources.GetString("ArgumentOutOfRange_NegativeParameter")); + } + if (count > 8 - bitIndex) + { + throw new ArgumentException(BitStreamResources.GetString("Argument_InvalidCountOrBitIndex_Byte")); + } + uint bits2 = bits; + uint bitIndex2 = (uint)bitIndex; + uint count2 = (uint)count; + Write(ref bits2, ref bitIndex2, ref count2); + } + + public virtual void Write(byte[] bits) + { + if (!_blnIsOpen) + { + throw new ObjectDisposedException(BitStreamResources.GetString("ObjectDisposed_BitStreamClosed")); + } + if (bits == null) + { + throw new ArgumentNullException("bits", BitStreamResources.GetString("ArgumentNull_BitBuffer")); + } + Write(bits, 0, bits.Length); + } + + public override void Write(byte[] bits, int offset, int count) + { + if (!_blnIsOpen) + { + throw new ObjectDisposedException(BitStreamResources.GetString("ObjectDisposed_BitStreamClosed")); + } + if (bits == null) + { + throw new ArgumentNullException("bits", BitStreamResources.GetString("ArgumentNull_BitBuffer")); + } + if (offset < 0) + { + throw new ArgumentOutOfRangeException("offset", BitStreamResources.GetString("ArgumentOutOfRange_NegativeParameter")); + } + if (count < 0) + { + throw new ArgumentOutOfRangeException("count", BitStreamResources.GetString("ArgumentOutOfRange_NegativeParameter")); + } + if (count > bits.Length - offset) + { + throw new ArgumentException(BitStreamResources.GetString("Argument_InvalidCountOrOffset")); + } + int num = offset + count; + for (int i = offset; i < num; i++) + { + Write(bits[i]); + } + } + + [CLSCompliant(false)] + public virtual void Write(sbyte bits) + { + Write(bits, 0, 8); + } + + [CLSCompliant(false)] + public virtual void Write(sbyte bits, int bitIndex, int count) + { + byte bits2 = (byte)bits; + Write(bits2, bitIndex, count); + } + + [CLSCompliant(false)] + public virtual void Write(sbyte[] bits) + { + if (!_blnIsOpen) + { + throw new ObjectDisposedException(BitStreamResources.GetString("ObjectDisposed_BitStreamClosed")); + } + if (bits == null) + { + throw new ArgumentNullException("bits", BitStreamResources.GetString("ArgumentNull_BitBuffer")); + } + Write(bits, 0, bits.Length); + } + + [CLSCompliant(false)] + public virtual void Write(sbyte[] bits, int offset, int count) + { + if (!_blnIsOpen) + { + throw new ObjectDisposedException(BitStreamResources.GetString("ObjectDisposed_BitStreamClosed")); + } + if (bits == null) + { + throw new ArgumentNullException("bits", BitStreamResources.GetString("ArgumentNull_BitBuffer")); + } + if (offset < 0) + { + throw new ArgumentOutOfRangeException("offset", BitStreamResources.GetString("ArgumentOutOfRange_NegativeParameter")); + } + if (count < 0) + { + throw new ArgumentOutOfRangeException("count", BitStreamResources.GetString("ArgumentOutOfRange_NegativeParameter")); + } + if (count > bits.Length - offset) + { + throw new ArgumentException(BitStreamResources.GetString("Argument_InvalidCountOrOffset")); + } + byte[] array = new byte[count]; + Buffer.BlockCopy(bits, offset, array, 0, count); + Write(array, 0, count); + } + + public override void WriteByte(byte value) + { + Write(value); + } + + [CLSCompliant(false)] + public virtual void Write(char bits) + { + Write(bits, 0, 128); + } + + [CLSCompliant(false)] + public virtual void Write(char bits, int bitIndex, int count) + { + if (!_blnIsOpen) + { + throw new ObjectDisposedException(BitStreamResources.GetString("ObjectDisposed_BitStreamClosed")); + } + if (bitIndex < 0) + { + throw new ArgumentOutOfRangeException("bitIndex", BitStreamResources.GetString("ArgumentOutOfRange_NegativeParameter")); + } + if (count < 0) + { + throw new ArgumentOutOfRangeException("count", BitStreamResources.GetString("ArgumentOutOfRange_NegativeParameter")); + } + if (count > 128 - bitIndex) + { + throw new ArgumentException(BitStreamResources.GetString("Argument_InvalidCountOrBitIndex_Char")); + } + uint bits2 = bits; + uint bitIndex2 = (uint)bitIndex; + uint count2 = (uint)count; + Write(ref bits2, ref bitIndex2, ref count2); + } + + [CLSCompliant(false)] + public virtual void Write(char[] bits) + { + if (!_blnIsOpen) + { + throw new ObjectDisposedException(BitStreamResources.GetString("ObjectDisposed_BitStreamClosed")); + } + if (bits == null) + { + throw new ArgumentNullException("bits", BitStreamResources.GetString("ArgumentNull_BitBuffer")); + } + Write(bits, 0, bits.Length); + } + + [CLSCompliant(false)] + public virtual void Write(char[] bits, int offset, int count) + { + if (!_blnIsOpen) + { + throw new ObjectDisposedException(BitStreamResources.GetString("ObjectDisposed_BitStreamClosed")); + } + if (bits == null) + { + throw new ArgumentNullException("bits", BitStreamResources.GetString("ArgumentNull_BitBuffer")); + } + if (offset < 0) + { + throw new ArgumentOutOfRangeException("offset", BitStreamResources.GetString("ArgumentOutOfRange_NegativeParameter")); + } + if (count < 0) + { + throw new ArgumentOutOfRangeException("count", BitStreamResources.GetString("ArgumentOutOfRange_NegativeParameter")); + } + if (count > bits.Length - offset) + { + throw new ArgumentException(BitStreamResources.GetString("Argument_InvalidCountOrOffset")); + } + int num = offset + count; + for (int i = offset; i < num; i++) + { + Write(bits[i]); + } + } + + [CLSCompliant(false)] + public virtual void Write(ushort bits) + { + Write(bits, 0, 16); + } + + [CLSCompliant(false)] + public virtual void Write(ushort bits, int bitIndex, int count) + { + if (!_blnIsOpen) + { + throw new ObjectDisposedException(BitStreamResources.GetString("ObjectDisposed_BitStreamClosed")); + } + if (bitIndex < 0) + { + throw new ArgumentOutOfRangeException("bitIndex", BitStreamResources.GetString("ArgumentOutOfRange_NegativeParameter")); + } + if (count < 0) + { + throw new ArgumentOutOfRangeException("count", BitStreamResources.GetString("ArgumentOutOfRange_NegativeParameter")); + } + if (count > 16 - bitIndex) + { + throw new ArgumentException(BitStreamResources.GetString("Argument_InvalidCountOrBitIndex_UInt16")); + } + uint bits2 = bits; + uint bitIndex2 = (uint)bitIndex; + uint count2 = (uint)count; + Write(ref bits2, ref bitIndex2, ref count2); + } + + [CLSCompliant(false)] + public virtual void Write(ushort[] bits) + { + if (!_blnIsOpen) + { + throw new ObjectDisposedException(BitStreamResources.GetString("ObjectDisposed_BitStreamClosed")); + } + if (bits == null) + { + throw new ArgumentNullException("bits", BitStreamResources.GetString("ArgumentNull_BitBuffer")); + } + Write(bits, 0, bits.Length); + } + + [CLSCompliant(false)] + public virtual void Write(ushort[] bits, int offset, int count) + { + if (!_blnIsOpen) + { + throw new ObjectDisposedException(BitStreamResources.GetString("ObjectDisposed_BitStreamClosed")); + } + if (bits == null) + { + throw new ArgumentNullException("bits", BitStreamResources.GetString("ArgumentNull_BitBuffer")); + } + if (offset < 0) + { + throw new ArgumentOutOfRangeException("offset", BitStreamResources.GetString("ArgumentOutOfRange_NegativeParameter")); + } + if (count < 0) + { + throw new ArgumentOutOfRangeException("count", BitStreamResources.GetString("ArgumentOutOfRange_NegativeParameter")); + } + if (count > bits.Length - offset) + { + throw new ArgumentException(BitStreamResources.GetString("Argument_InvalidCountOrOffset")); + } + int num = offset + count; + for (int i = offset; i < num; i++) + { + Write(bits[i]); + } + } + + public virtual void Write(short bits) + { + Write(bits, 0, 16); + } + + public virtual void Write(short bits, int bitIndex, int count) + { + ushort bits2 = (ushort)bits; + Write(bits2, bitIndex, count); + } + + public virtual void Write(short[] bits) + { + if (!_blnIsOpen) + { + throw new ObjectDisposedException(BitStreamResources.GetString("ObjectDisposed_BitStreamClosed")); + } + if (bits == null) + { + throw new ArgumentNullException("bits", BitStreamResources.GetString("ArgumentNull_BitBuffer")); + } + Write(bits, 0, bits.Length); + } + + public virtual void Write(short[] bits, int offset, int count) + { + if (!_blnIsOpen) + { + throw new ObjectDisposedException(BitStreamResources.GetString("ObjectDisposed_BitStreamClosed")); + } + if (bits == null) + { + throw new ArgumentNullException("bits", BitStreamResources.GetString("ArgumentNull_BitBuffer")); + } + if (offset < 0) + { + throw new ArgumentOutOfRangeException("offset", BitStreamResources.GetString("ArgumentOutOfRange_NegativeParameter")); + } + if (count < 0) + { + throw new ArgumentOutOfRangeException("count", BitStreamResources.GetString("ArgumentOutOfRange_NegativeParameter")); + } + if (count > bits.Length - offset) + { + throw new ArgumentException(BitStreamResources.GetString("Argument_InvalidCountOrOffset")); + } + ushort[] array = new ushort[count]; + Buffer.BlockCopy(bits, offset << 1, array, 0, count << 1); + Write(array, 0, count); + } + + [CLSCompliant(false)] + public virtual void Write(uint bits) + { + Write(bits, 0, 32); + } + + [CLSCompliant(false)] + public virtual void Write(uint bits, int bitIndex, int count) + { + if (!_blnIsOpen) + { + throw new ObjectDisposedException(BitStreamResources.GetString("ObjectDisposed_BitStreamClosed")); + } + if (bitIndex < 0) + { + throw new ArgumentOutOfRangeException("bitIndex", BitStreamResources.GetString("ArgumentOutOfRange_NegativeParameter")); + } + if (count < 0) + { + throw new ArgumentOutOfRangeException("count", BitStreamResources.GetString("ArgumentOutOfRange_NegativeParameter")); + } + if (count > 32 - bitIndex) + { + throw new ArgumentException(BitStreamResources.GetString("Argument_InvalidCountOrBitIndex_UInt32")); + } + uint bitIndex2 = (uint)bitIndex; + uint count2 = (uint)count; + Write(ref bits, ref bitIndex2, ref count2); + } + + [CLSCompliant(false)] + public virtual void Write(uint[] bits) + { + if (!_blnIsOpen) + { + throw new ObjectDisposedException(BitStreamResources.GetString("ObjectDisposed_BitStreamClosed")); + } + if (bits == null) + { + throw new ArgumentNullException("bits", BitStreamResources.GetString("ArgumentNull_BitBuffer")); + } + Write(bits, 0, bits.Length); + } + + [CLSCompliant(false)] + public virtual void Write(uint[] bits, int offset, int count) + { + if (!_blnIsOpen) + { + throw new ObjectDisposedException(BitStreamResources.GetString("ObjectDisposed_BitStreamClosed")); + } + if (bits == null) + { + throw new ArgumentNullException("bits", BitStreamResources.GetString("ArgumentNull_BitBuffer")); + } + if (offset < 0) + { + throw new ArgumentOutOfRangeException("offset", BitStreamResources.GetString("ArgumentOutOfRange_NegativeParameter")); + } + if (count < 0) + { + throw new ArgumentOutOfRangeException("count", BitStreamResources.GetString("ArgumentOutOfRange_NegativeParameter")); + } + if (count > bits.Length - offset) + { + throw new ArgumentException(BitStreamResources.GetString("Argument_InvalidCountOrOffset")); + } + int num = offset + count; + for (int i = offset; i < num; i++) + { + Write(bits[i]); + } + } + + public virtual void Write(int bits) + { + Write(bits, 0, 32); + } + + public virtual void Write(int bits, int bitIndex, int count) + { + Write((uint)bits, bitIndex, count); + } + + public virtual void Write(int[] bits) + { + if (!_blnIsOpen) + { + throw new ObjectDisposedException(BitStreamResources.GetString("ObjectDisposed_BitStreamClosed")); + } + if (bits == null) + { + throw new ArgumentNullException("bits", BitStreamResources.GetString("ArgumentNull_BitBuffer")); + } + Write(bits, 0, bits.Length); + } + + public virtual void Write(int[] bits, int offset, int count) + { + if (!_blnIsOpen) + { + throw new ObjectDisposedException(BitStreamResources.GetString("ObjectDisposed_BitStreamClosed")); + } + if (bits == null) + { + throw new ArgumentNullException("bits", BitStreamResources.GetString("ArgumentNull_BitBuffer")); + } + if (offset < 0) + { + throw new ArgumentOutOfRangeException("offset", BitStreamResources.GetString("ArgumentOutOfRange_NegativeParameter")); + } + if (count < 0) + { + throw new ArgumentOutOfRangeException("count", BitStreamResources.GetString("ArgumentOutOfRange_NegativeParameter")); + } + if (count > bits.Length - offset) + { + throw new ArgumentException(BitStreamResources.GetString("Argument_InvalidCountOrOffset")); + } + uint[] array = new uint[count]; + Buffer.BlockCopy(bits, offset << 2, array, 0, count << 2); + Write(array, 0, count); + } + + public virtual void Write(float bits) + { + Write(bits, 0, 32); + } + + public virtual void Write(float bits, int bitIndex, int count) + { + byte[] bytes = BitConverter.GetBytes(bits); + uint bits2 = (uint)(bytes[0] | (bytes[1] << 8) | (bytes[2] << 16) | (bytes[3] << 24)); + Write(bits2, bitIndex, count); + } + + public virtual void Write(float[] bits) + { + if (!_blnIsOpen) + { + throw new ObjectDisposedException(BitStreamResources.GetString("ObjectDisposed_BitStreamClosed")); + } + if (bits == null) + { + throw new ArgumentNullException("bits", BitStreamResources.GetString("ArgumentNull_BitBuffer")); + } + Write(bits, 0, bits.Length); + } + + public virtual void Write(float[] bits, int offset, int count) + { + if (!_blnIsOpen) + { + throw new ObjectDisposedException(BitStreamResources.GetString("ObjectDisposed_BitStreamClosed")); + } + if (bits == null) + { + throw new ArgumentNullException("bits", BitStreamResources.GetString("ArgumentNull_BitBuffer")); + } + if (offset < 0) + { + throw new ArgumentOutOfRangeException("offset", BitStreamResources.GetString("ArgumentOutOfRange_NegativeParameter")); + } + if (count < 0) + { + throw new ArgumentOutOfRangeException("count", BitStreamResources.GetString("ArgumentOutOfRange_NegativeParameter")); + } + if (count > bits.Length - offset) + { + throw new ArgumentException(BitStreamResources.GetString("Argument_InvalidCountOrOffset")); + } + int num = offset + count; + for (int i = offset; i < num; i++) + { + Write(bits[i]); + } + } + + [CLSCompliant(false)] + public virtual void Write(ulong bits) + { + Write(bits, 0, 64); + } + + [CLSCompliant(false)] + public virtual void Write(ulong bits, int bitIndex, int count) + { + if (!_blnIsOpen) + { + throw new ObjectDisposedException(BitStreamResources.GetString("ObjectDisposed_BitStreamClosed")); + } + if (bitIndex < 0) + { + throw new ArgumentOutOfRangeException("bitIndex", BitStreamResources.GetString("ArgumentOutOfRange_NegativeParameter")); + } + if (count < 0) + { + throw new ArgumentOutOfRangeException("count", BitStreamResources.GetString("ArgumentOutOfRange_NegativeParameter")); + } + if (count > 64 - bitIndex) + { + throw new ArgumentException(BitStreamResources.GetString("Argument_InvalidCountOrBitIndex_UInt64")); + } + int num = (bitIndex >> 5 < 1) ? bitIndex : (-1); + int num2 = (bitIndex + count <= 32) ? (-1) : ((num < 0) ? (bitIndex - 32) : 0); + int num3 = (num > -1) ? ((num + count > 32) ? (32 - num) : count) : 0; + int num4 = (num2 > -1) ? ((num3 == 0) ? count : (count - num3)) : 0; + if (num3 > 0) + { + uint bits2 = (uint)bits; + uint bitIndex2 = (uint)num; + uint count2 = (uint)num3; + Write(ref bits2, ref bitIndex2, ref count2); + } + if (num4 > 0) + { + uint bits3 = (uint)(bits >> 32); + uint bitIndex3 = (uint)num2; + uint count3 = (uint)num4; + Write(ref bits3, ref bitIndex3, ref count3); + } + } + + [CLSCompliant(false)] + public virtual void Write(ulong[] bits) + { + if (!_blnIsOpen) + { + throw new ObjectDisposedException(BitStreamResources.GetString("ObjectDisposed_BitStreamClosed")); + } + if (bits == null) + { + throw new ArgumentNullException("bits", BitStreamResources.GetString("ArgumentNull_BitBuffer")); + } + Write(bits, 0, bits.Length); + } + + [CLSCompliant(false)] + public virtual void Write(ulong[] bits, int offset, int count) + { + if (!_blnIsOpen) + { + throw new ObjectDisposedException(BitStreamResources.GetString("ObjectDisposed_BitStreamClosed")); + } + if (bits == null) + { + throw new ArgumentNullException("bits", BitStreamResources.GetString("ArgumentNull_BitBuffer")); + } + if (offset < 0) + { + throw new ArgumentOutOfRangeException("offset", BitStreamResources.GetString("ArgumentOutOfRange_NegativeParameter")); + } + if (count < 0) + { + throw new ArgumentOutOfRangeException("count", BitStreamResources.GetString("ArgumentOutOfRange_NegativeParameter")); + } + if (count > bits.Length - offset) + { + throw new ArgumentException(BitStreamResources.GetString("Argument_InvalidCountOrOffset")); + } + int num = offset + count; + for (int i = offset; i < num; i++) + { + Write(bits[i]); + } + } + + public virtual void Write(long bits) + { + Write(bits, 0, 64); + } + + public virtual void Write(long bits, int bitIndex, int count) + { + Write((ulong)bits, bitIndex, count); + } + + public virtual void Write(long[] bits) + { + if (!_blnIsOpen) + { + throw new ObjectDisposedException(BitStreamResources.GetString("ObjectDisposed_BitStreamClosed")); + } + if (bits == null) + { + throw new ArgumentNullException("bits", BitStreamResources.GetString("ArgumentNull_BitBuffer")); + } + Write(bits, 0, bits.Length); + } + + public virtual void Write(long[] bits, int offset, int count) + { + if (!_blnIsOpen) + { + throw new ObjectDisposedException(BitStreamResources.GetString("ObjectDisposed_BitStreamClosed")); + } + if (bits == null) + { + throw new ArgumentNullException("bits", BitStreamResources.GetString("ArgumentNull_BitBuffer")); + } + if (offset < 0) + { + throw new ArgumentOutOfRangeException("offset", BitStreamResources.GetString("ArgumentOutOfRange_NegativeParameter")); + } + if (count < 0) + { + throw new ArgumentOutOfRangeException("count", BitStreamResources.GetString("ArgumentOutOfRange_NegativeParameter")); + } + if (count > bits.Length - offset) + { + throw new ArgumentException(BitStreamResources.GetString("Argument_InvalidCountOrOffset")); + } + ulong[] array = new ulong[count]; + Buffer.BlockCopy(bits, offset << 4, array, 0, count << 4); + Write(array, 0, count); + } + + public virtual void Write(double bits) + { + Write(bits, 0, 64); + } + + public virtual void Write(double bits, int bitIndex, int count) + { + byte[] bytes = BitConverter.GetBytes(bits); + ulong bits2 = bytes[0] | ((ulong)bytes[1] << 8) | ((ulong)bytes[2] << 16) | ((ulong)bytes[3] << 24) | ((ulong)bytes[4] << 32) | ((ulong)bytes[5] << 40) | ((ulong)bytes[6] << 48) | ((ulong)bytes[7] << 56); + Write(bits2, bitIndex, count); + } + + public virtual void Write(double[] bits) + { + if (!_blnIsOpen) + { + throw new ObjectDisposedException(BitStreamResources.GetString("ObjectDisposed_BitStreamClosed")); + } + if (bits == null) + { + throw new ArgumentNullException("bits", BitStreamResources.GetString("ArgumentNull_BitBuffer")); + } + Write(bits, 0, bits.Length); + } + + public virtual void Write(double[] bits, int offset, int count) + { + if (!_blnIsOpen) + { + throw new ObjectDisposedException(BitStreamResources.GetString("ObjectDisposed_BitStreamClosed")); + } + if (bits == null) + { + throw new ArgumentNullException("bits", BitStreamResources.GetString("ArgumentNull_BitBuffer")); + } + if (offset < 0) + { + throw new ArgumentOutOfRangeException("offset", BitStreamResources.GetString("ArgumentOutOfRange_NegativeParameter")); + } + if (count < 0) + { + throw new ArgumentOutOfRangeException("count", BitStreamResources.GetString("ArgumentOutOfRange_NegativeParameter")); + } + if (count > bits.Length - offset) + { + throw new ArgumentException(BitStreamResources.GetString("Argument_InvalidCountOrOffset")); + } + int num = offset + count; + for (int i = offset; i < num; i++) + { + Write(bits[i]); + } + } + + public virtual void WriteTo(Stream bits) + { + if (!_blnIsOpen) + { + throw new ObjectDisposedException(BitStreamResources.GetString("ObjectDisposed_BitStreamClosed")); + } + if (bits == null) + { + throw new ArgumentNullException("bits", BitStreamResources.GetString("ArgumentNull_Stream")); + } + byte[] array = ToByteArray(); + bits.Write(array, 0, array.Length); + } + + private uint Read(ref uint bits, ref uint bitIndex, ref uint count) + { + uint num = (_uiBitBuffer_Index << 5) + _uiBitBuffer_BitIndex; + uint num2 = count; + if (_uiBitBuffer_Length < num + num2) + { + num2 = _uiBitBuffer_Length - num; + } + uint num3 = _auiBitBuffer[_uiBitBuffer_Index]; + int num4 = (int)(32 - (_uiBitBuffer_BitIndex + num2)); + if (num4 < 0) + { + num4 = Math.Abs(num4); + uint num5 = BitMaskHelperLUT[num2] >> num4; + num3 &= num5; + num3 <<= num4; + uint count2 = (uint)num4; + uint bitIndex2 = 0u; + uint bits2 = 0u; + UpdateIndicesForRead(num2 - count2); + Read(ref bits2, ref bitIndex2, ref count2); + num3 |= bits2; + } + else + { + uint num5 = BitMaskHelperLUT[num2] << num4; + num3 &= num5; + num3 >>= num4; + UpdateIndicesForRead(num2); + } + bits = num3 << (int)bitIndex; + return num2; + } + + public virtual int Read(out bool bit) + { + if (!_blnIsOpen) + { + throw new ObjectDisposedException(BitStreamResources.GetString("ObjectDisposed_BitStreamClosed")); + } + uint bitIndex = 0u; + uint count = 1u; + uint bits = 0u; + uint result = Read(ref bits, ref bitIndex, ref count); + bit = Convert.ToBoolean(bits); + return (int)result; + } + + public virtual int Read(bool[] bits) + { + if (!_blnIsOpen) + { + throw new ObjectDisposedException(BitStreamResources.GetString("ObjectDisposed_BitStreamClosed")); + } + if (bits == null) + { + throw new ArgumentNullException("bits", BitStreamResources.GetString("ArgumentNull_BitBuffer")); + } + return Read(bits, 0, bits.Length); + } + + public virtual int Read(bool[] bits, int offset, int count) + { + if (!_blnIsOpen) + { + throw new ObjectDisposedException(BitStreamResources.GetString("ObjectDisposed_BitStreamClosed")); + } + if (bits == null) + { + throw new ArgumentNullException("bits", BitStreamResources.GetString("ArgumentNull_BitBuffer")); + } + if (offset < 0) + { + throw new ArgumentOutOfRangeException("offset", BitStreamResources.GetString("ArgumentOutOfRange_NegativeParameter")); + } + if (count < 0) + { + throw new ArgumentOutOfRangeException("count", BitStreamResources.GetString("ArgumentOutOfRange_NegativeParameter")); + } + if (count > bits.Length - offset) + { + throw new ArgumentException(BitStreamResources.GetString("Argument_InvalidCountOrOffset")); + } + int num = offset + count; + int num2 = 0; + for (int i = offset; i < num; i++) + { + num2 += Read(out bits[i]); + } + return num2; + } + + public virtual int Read(out byte bits) + { + return Read(out bits, 0, 8); + } + + public virtual int Read(out byte bits, int bitIndex, int count) + { + if (!_blnIsOpen) + { + throw new ObjectDisposedException(BitStreamResources.GetString("ObjectDisposed_BitStreamClosed")); + } + if (bitIndex < 0) + { + throw new ArgumentOutOfRangeException("bitIndex", BitStreamResources.GetString("ArgumentOutOfRange_NegativeParameter")); + } + if (count < 0) + { + throw new ArgumentOutOfRangeException("count", BitStreamResources.GetString("ArgumentOutOfRange_NegativeParameter")); + } + if (count > 8 - bitIndex) + { + throw new ArgumentException(BitStreamResources.GetString("Argument_InvalidCountOrBitIndex_Byte")); + } + uint bitIndex2 = (uint)bitIndex; + uint count2 = (uint)count; + uint bits2 = 0u; + uint result = Read(ref bits2, ref bitIndex2, ref count2); + bits = (byte)bits2; + return (int)result; + } + + public virtual int Read(byte[] bits) + { + if (!_blnIsOpen) + { + throw new ObjectDisposedException(BitStreamResources.GetString("ObjectDisposed_BitStreamClosed")); + } + if (bits == null) + { + throw new ArgumentNullException("bits", BitStreamResources.GetString("ArgumentNull_BitBuffer")); + } + return Read(bits, 0, bits.Length); + } + + public override int Read(byte[] bits, int offset, int count) + { + if (!_blnIsOpen) + { + throw new ObjectDisposedException(BitStreamResources.GetString("ObjectDisposed_BitStreamClosed")); + } + if (bits == null) + { + throw new ArgumentNullException("bits", BitStreamResources.GetString("ArgumentNull_BitBuffer")); + } + if (offset < 0) + { + throw new ArgumentOutOfRangeException("offset", BitStreamResources.GetString("ArgumentOutOfRange_NegativeParameter")); + } + if (count < 0) + { + throw new ArgumentOutOfRangeException("count", BitStreamResources.GetString("ArgumentOutOfRange_NegativeParameter")); + } + if (count > bits.Length - offset) + { + throw new ArgumentException(BitStreamResources.GetString("Argument_InvalidCountOrOffset")); + } + int num = offset + count; + int num2 = 0; + for (int i = offset; i < num; i++) + { + num2 += Read(out bits[i]); + } + return num2; + } + + [CLSCompliant(false)] + public virtual int Read(out sbyte bits) + { + return Read(out bits, 0, 8); + } + + [CLSCompliant(false)] + public virtual int Read(out sbyte bits, int bitIndex, int count) + { + byte bits2 = 0; + int result = Read(out bits2, bitIndex, count); + bits = (sbyte)bits2; + return result; + } + + [CLSCompliant(false)] + public virtual int Read(sbyte[] bits) + { + if (!_blnIsOpen) + { + throw new ObjectDisposedException(BitStreamResources.GetString("ObjectDisposed_BitStreamClosed")); + } + if (bits == null) + { + throw new ArgumentNullException("bits", BitStreamResources.GetString("ArgumentNull_BitBuffer")); + } + return Read(bits, 0, bits.Length); + } + + [CLSCompliant(false)] + public virtual int Read(sbyte[] bits, int offset, int count) + { + if (!_blnIsOpen) + { + throw new ObjectDisposedException(BitStreamResources.GetString("ObjectDisposed_BitStreamClosed")); + } + if (bits == null) + { + throw new ArgumentNullException("bits", BitStreamResources.GetString("ArgumentNull_BitBuffer")); + } + if (offset < 0) + { + throw new ArgumentOutOfRangeException("offset", BitStreamResources.GetString("ArgumentOutOfRange_NegativeParameter")); + } + if (count < 0) + { + throw new ArgumentOutOfRangeException("count", BitStreamResources.GetString("ArgumentOutOfRange_NegativeParameter")); + } + if (count > bits.Length - offset) + { + throw new ArgumentException(BitStreamResources.GetString("Argument_InvalidCountOrOffset")); + } + int num = offset + count; + int num2 = 0; + for (int i = offset; i < num; i++) + { + num2 += Read(out bits[i]); + } + return num2; + } + + public override int ReadByte() + { + if (Read(out byte bits) == 0) + { + return -1; + } + return bits; + } + + public virtual byte[] ToByteArray() + { + long position = Position; + Position = 0L; + byte[] array = new byte[Length8]; + Read(array, 0, (int)Length8); + if (Position != position) + { + Position = position; + } + return array; + } + + public virtual int Read(out char bits) + { + return Read(out bits, 0, 128); + } + + public virtual int Read(out char bits, int bitIndex, int count) + { + if (!_blnIsOpen) + { + throw new ObjectDisposedException(BitStreamResources.GetString("ObjectDisposed_BitStreamClosed")); + } + if (bitIndex < 0) + { + throw new ArgumentOutOfRangeException("bitIndex", BitStreamResources.GetString("ArgumentOutOfRange_NegativeParameter")); + } + if (count < 0) + { + throw new ArgumentOutOfRangeException("count", BitStreamResources.GetString("ArgumentOutOfRange_NegativeParameter")); + } + if (count > 128 - bitIndex) + { + throw new ArgumentException(BitStreamResources.GetString("Argument_InvalidCountOrBitIndex_Char")); + } + uint bitIndex2 = (uint)bitIndex; + uint count2 = (uint)count; + uint bits2 = 0u; + uint result = Read(ref bits2, ref bitIndex2, ref count2); + bits = (char)bits2; + return (int)result; + } + + public virtual int Read(char[] bits) + { + if (!_blnIsOpen) + { + throw new ObjectDisposedException(BitStreamResources.GetString("ObjectDisposed_BitStreamClosed")); + } + if (bits == null) + { + throw new ArgumentNullException("bits", BitStreamResources.GetString("ArgumentNull_BitBuffer")); + } + return Read(bits, 0, bits.Length); + } + + public virtual int Read(char[] bits, int offset, int count) + { + if (!_blnIsOpen) + { + throw new ObjectDisposedException(BitStreamResources.GetString("ObjectDisposed_BitStreamClosed")); + } + if (bits == null) + { + throw new ArgumentNullException("bits", BitStreamResources.GetString("ArgumentNull_BitBuffer")); + } + if (offset < 0) + { + throw new ArgumentOutOfRangeException("offset", BitStreamResources.GetString("ArgumentOutOfRange_NegativeParameter")); + } + if (count < 0) + { + throw new ArgumentOutOfRangeException("count", BitStreamResources.GetString("ArgumentOutOfRange_NegativeParameter")); + } + if (count > bits.Length - offset) + { + throw new ArgumentException(BitStreamResources.GetString("Argument_InvalidCountOrOffset")); + } + int num = offset + count; + int num2 = 0; + for (int i = offset; i < num; i++) + { + num2 += Read(out bits[i]); + } + return num2; + } + + [CLSCompliant(false)] + public virtual int Read(out ushort bits) + { + return Read(out bits, 0, 16); + } + + [CLSCompliant(false)] + public virtual int Read(out ushort bits, int bitIndex, int count) + { + if (!_blnIsOpen) + { + throw new ObjectDisposedException(BitStreamResources.GetString("ObjectDisposed_BitStreamClosed")); + } + if (bitIndex < 0) + { + throw new ArgumentOutOfRangeException("bitIndex", BitStreamResources.GetString("ArgumentOutOfRange_NegativeParameter")); + } + if (count < 0) + { + throw new ArgumentOutOfRangeException("count", BitStreamResources.GetString("ArgumentOutOfRange_NegativeParameter")); + } + if (count > 16 - bitIndex) + { + throw new ArgumentException(BitStreamResources.GetString("Argument_InvalidCountOrBitIndex_UInt16")); + } + uint bitIndex2 = (uint)bitIndex; + uint count2 = (uint)count; + uint bits2 = 0u; + uint result = Read(ref bits2, ref bitIndex2, ref count2); + bits = (ushort)bits2; + return (int)result; + } + + [CLSCompliant(false)] + public virtual int Read(ushort[] bits) + { + if (!_blnIsOpen) + { + throw new ObjectDisposedException(BitStreamResources.GetString("ObjectDisposed_BitStreamClosed")); + } + if (bits == null) + { + throw new ArgumentNullException("bits", BitStreamResources.GetString("ArgumentNull_BitBuffer")); + } + return Read(bits, 0, bits.Length); + } + + [CLSCompliant(false)] + public virtual int Read(ushort[] bits, int offset, int count) + { + if (!_blnIsOpen) + { + throw new ObjectDisposedException(BitStreamResources.GetString("ObjectDisposed_BitStreamClosed")); + } + if (bits == null) + { + throw new ArgumentNullException("bits", BitStreamResources.GetString("ArgumentNull_BitBuffer")); + } + if (offset < 0) + { + throw new ArgumentOutOfRangeException("offset", BitStreamResources.GetString("ArgumentOutOfRange_NegativeParameter")); + } + if (count < 0) + { + throw new ArgumentOutOfRangeException("count", BitStreamResources.GetString("ArgumentOutOfRange_NegativeParameter")); + } + if (count > bits.Length - offset) + { + throw new ArgumentException(BitStreamResources.GetString("Argument_InvalidCountOrOffset")); + } + int num = offset + count; + int num2 = 0; + for (int i = offset; i < num; i++) + { + num2 += Read(out bits[i]); + } + return num2; + } + + public virtual int Read(out short bits) + { + return Read(out bits, 0, 16); + } + + public virtual int Read(out short bits, int bitIndex, int count) + { + ushort bits2 = 0; + int result = Read(out bits2, bitIndex, count); + bits = (short)bits2; + return result; + } + + public virtual int Read(short[] bits) + { + if (!_blnIsOpen) + { + throw new ObjectDisposedException(BitStreamResources.GetString("ObjectDisposed_BitStreamClosed")); + } + if (bits == null) + { + throw new ArgumentNullException("bits", BitStreamResources.GetString("ArgumentNull_BitBuffer")); + } + return Read(bits, 0, bits.Length); + } + + public virtual int Read(short[] bits, int offset, int count) + { + if (!_blnIsOpen) + { + throw new ObjectDisposedException(BitStreamResources.GetString("ObjectDisposed_BitStreamClosed")); + } + if (bits == null) + { + throw new ArgumentNullException("bits", BitStreamResources.GetString("ArgumentNull_BitBuffer")); + } + if (offset < 0) + { + throw new ArgumentOutOfRangeException("offset", BitStreamResources.GetString("ArgumentOutOfRange_NegativeParameter")); + } + if (count < 0) + { + throw new ArgumentOutOfRangeException("count", BitStreamResources.GetString("ArgumentOutOfRange_NegativeParameter")); + } + if (count > bits.Length - offset) + { + throw new ArgumentException(BitStreamResources.GetString("Argument_InvalidCountOrOffset")); + } + int num = offset + count; + int num2 = 0; + for (int i = offset; i < num; i++) + { + num2 += Read(out bits[i]); + } + return num2; + } + + [CLSCompliant(false)] + public virtual int Read(out uint bits) + { + return Read(out bits, 0, 32); + } + + [CLSCompliant(false)] + public virtual int Read(out uint bits, int bitIndex, int count) + { + if (!_blnIsOpen) + { + throw new ObjectDisposedException(BitStreamResources.GetString("ObjectDisposed_BitStreamClosed")); + } + if (bitIndex < 0) + { + throw new ArgumentOutOfRangeException("bitIndex", BitStreamResources.GetString("ArgumentOutOfRange_NegativeParameter")); + } + if (count < 0) + { + throw new ArgumentOutOfRangeException("count", BitStreamResources.GetString("ArgumentOutOfRange_NegativeParameter")); + } + if (count > 32 - bitIndex) + { + throw new ArgumentException(BitStreamResources.GetString("Argument_InvalidCountOrBitIndex_UInt32")); + } + uint bitIndex2 = (uint)bitIndex; + uint count2 = (uint)count; + uint bits2 = 0u; + uint result = Read(ref bits2, ref bitIndex2, ref count2); + bits = bits2; + return (int)result; + } + + [CLSCompliant(false)] + public virtual int Read(uint[] bits) + { + if (!_blnIsOpen) + { + throw new ObjectDisposedException(BitStreamResources.GetString("ObjectDisposed_BitStreamClosed")); + } + if (bits == null) + { + throw new ArgumentNullException("bits", BitStreamResources.GetString("ArgumentNull_BitBuffer")); + } + return Read(bits, 0, bits.Length); + } + + [CLSCompliant(false)] + public virtual int Read(uint[] bits, int offset, int count) + { + if (!_blnIsOpen) + { + throw new ObjectDisposedException(BitStreamResources.GetString("ObjectDisposed_BitStreamClosed")); + } + if (bits == null) + { + throw new ArgumentNullException("bits", BitStreamResources.GetString("ArgumentNull_BitBuffer")); + } + if (offset < 0) + { + throw new ArgumentOutOfRangeException("offset", BitStreamResources.GetString("ArgumentOutOfRange_NegativeParameter")); + } + if (count < 0) + { + throw new ArgumentOutOfRangeException("count", BitStreamResources.GetString("ArgumentOutOfRange_NegativeParameter")); + } + if (count > bits.Length - offset) + { + throw new ArgumentException(BitStreamResources.GetString("Argument_InvalidCountOrOffset")); + } + int num = offset + count; + int num2 = 0; + for (int i = offset; i < num; i++) + { + num2 += Read(out bits[i]); + } + return num2; + } + + public virtual int Read(out int bits) + { + return Read(out bits, 0, 32); + } + + public virtual int Read(out int bits, int bitIndex, int count) + { + uint bits2 = 0u; + int result = Read(out bits2, bitIndex, count); + bits = (int)bits2; + return result; + } + + public virtual int Read(int[] bits) + { + if (!_blnIsOpen) + { + throw new ObjectDisposedException(BitStreamResources.GetString("ObjectDisposed_BitStreamClosed")); + } + if (bits == null) + { + throw new ArgumentNullException("bits", BitStreamResources.GetString("ArgumentNull_BitBuffer")); + } + return Read(bits, 0, bits.Length); + } + + public virtual int Read(int[] bits, int offset, int count) + { + if (!_blnIsOpen) + { + throw new ObjectDisposedException(BitStreamResources.GetString("ObjectDisposed_BitStreamClosed")); + } + if (bits == null) + { + throw new ArgumentNullException("bits", BitStreamResources.GetString("ArgumentNull_BitBuffer")); + } + if (offset < 0) + { + throw new ArgumentOutOfRangeException("offset", BitStreamResources.GetString("ArgumentOutOfRange_NegativeParameter")); + } + if (count < 0) + { + throw new ArgumentOutOfRangeException("count", BitStreamResources.GetString("ArgumentOutOfRange_NegativeParameter")); + } + if (count > bits.Length - offset) + { + throw new ArgumentException(BitStreamResources.GetString("Argument_InvalidCountOrOffset")); + } + int num = offset + count; + int num2 = 0; + for (int i = offset; i < num; i++) + { + num2 += Read(out bits[i]); + } + return num2; + } + + public virtual int Read(out float bits) + { + return Read(out bits, 0, 32); + } + + public virtual int Read(out float bits, int bitIndex, int count) + { + int bits2 = 0; + int result = Read(out bits2, bitIndex, count); + bits = BitConverter.ToSingle(BitConverter.GetBytes(bits2), 0); + return result; + } + + public virtual int Read(float[] bits) + { + if (!_blnIsOpen) + { + throw new ObjectDisposedException(BitStreamResources.GetString("ObjectDisposed_BitStreamClosed")); + } + if (bits == null) + { + throw new ArgumentNullException("bits", BitStreamResources.GetString("ArgumentNull_BitBuffer")); + } + return Read(bits, 0, bits.Length); + } + + public virtual int Read(float[] bits, int offset, int count) + { + if (!_blnIsOpen) + { + throw new ObjectDisposedException(BitStreamResources.GetString("ObjectDisposed_BitStreamClosed")); + } + if (bits == null) + { + throw new ArgumentNullException("bits", BitStreamResources.GetString("ArgumentNull_BitBuffer")); + } + if (offset < 0) + { + throw new ArgumentOutOfRangeException("offset", BitStreamResources.GetString("ArgumentOutOfRange_NegativeParameter")); + } + if (count < 0) + { + throw new ArgumentOutOfRangeException("count", BitStreamResources.GetString("ArgumentOutOfRange_NegativeParameter")); + } + if (count > bits.Length - offset) + { + throw new ArgumentException(BitStreamResources.GetString("Argument_InvalidCountOrOffset")); + } + int num = offset + count; + int num2 = 0; + for (int i = offset; i < num; i++) + { + num2 += Read(out bits[i]); + } + return num2; + } + + [CLSCompliant(false)] + public virtual int Read(out ulong bits) + { + return Read(out bits, 0, 64); + } + + [CLSCompliant(false)] + public virtual int Read(out ulong bits, int bitIndex, int count) + { + if (!_blnIsOpen) + { + throw new ObjectDisposedException(BitStreamResources.GetString("ObjectDisposed_BitStreamClosed")); + } + if (bitIndex < 0) + { + throw new ArgumentOutOfRangeException("bitIndex", BitStreamResources.GetString("ArgumentOutOfRange_NegativeParameter")); + } + if (count < 0) + { + throw new ArgumentOutOfRangeException("count", BitStreamResources.GetString("ArgumentOutOfRange_NegativeParameter")); + } + if (count > 64 - bitIndex) + { + throw new ArgumentException(BitStreamResources.GetString("Argument_InvalidCountOrBitIndex_UInt64")); + } + int num = (bitIndex >> 5 < 1) ? bitIndex : (-1); + int num2 = (bitIndex + count <= 32) ? (-1) : ((num < 0) ? (bitIndex - 32) : 0); + int num3 = (num > -1) ? ((num + count > 32) ? (32 - num) : count) : 0; + int num4 = (num2 > -1) ? ((num3 == 0) ? count : (count - num3)) : 0; + uint num5 = 0u; + uint bits2 = 0u; + uint bits3 = 0u; + if (num3 > 0) + { + uint bitIndex2 = (uint)num; + uint count2 = (uint)num3; + num5 = Read(ref bits2, ref bitIndex2, ref count2); + } + if (num4 > 0) + { + uint bitIndex3 = (uint)num2; + uint count3 = (uint)num4; + num5 += Read(ref bits3, ref bitIndex3, ref count3); + } + bits = (((ulong)bits3 << 32) | bits2); + return (int)num5; + } + + [CLSCompliant(false)] + public virtual int Read(ulong[] bits) + { + if (!_blnIsOpen) + { + throw new ObjectDisposedException(BitStreamResources.GetString("ObjectDisposed_BitStreamClosed")); + } + if (bits == null) + { + throw new ArgumentNullException("bits", BitStreamResources.GetString("ArgumentNull_BitBuffer")); + } + return Read(bits, 0, bits.Length); + } + + [CLSCompliant(false)] + public virtual int Read(ulong[] bits, int offset, int count) + { + if (!_blnIsOpen) + { + throw new ObjectDisposedException(BitStreamResources.GetString("ObjectDisposed_BitStreamClosed")); + } + if (bits == null) + { + throw new ArgumentNullException("bits", BitStreamResources.GetString("ArgumentNull_BitBuffer")); + } + if (offset < 0) + { + throw new ArgumentOutOfRangeException("offset", BitStreamResources.GetString("ArgumentOutOfRange_NegativeParameter")); + } + if (count < 0) + { + throw new ArgumentOutOfRangeException("count", BitStreamResources.GetString("ArgumentOutOfRange_NegativeParameter")); + } + if (count > bits.Length - offset) + { + throw new ArgumentException(BitStreamResources.GetString("Argument_InvalidCountOrOffset")); + } + int num = offset + count; + int num2 = 0; + for (int i = offset; i < num; i++) + { + num2 += Read(out bits[i]); + } + return num2; + } + + public virtual int Read(out long bits) + { + return Read(out bits, 0, 64); + } + + public virtual int Read(out long bits, int bitIndex, int count) + { + ulong bits2 = 0uL; + int result = Read(out bits2, bitIndex, count); + bits = (long)bits2; + return result; + } + + public virtual int Read(long[] bits) + { + if (!_blnIsOpen) + { + throw new ObjectDisposedException(BitStreamResources.GetString("ObjectDisposed_BitStreamClosed")); + } + if (bits == null) + { + throw new ArgumentNullException("bits", BitStreamResources.GetString("ArgumentNull_BitBuffer")); + } + return Read(bits, 0, bits.Length); + } + + public virtual int Read(long[] bits, int offset, int count) + { + if (!_blnIsOpen) + { + throw new ObjectDisposedException(BitStreamResources.GetString("ObjectDisposed_BitStreamClosed")); + } + if (bits == null) + { + throw new ArgumentNullException("bits", BitStreamResources.GetString("ArgumentNull_BitBuffer")); + } + if (offset < 0) + { + throw new ArgumentOutOfRangeException("offset", BitStreamResources.GetString("ArgumentOutOfRange_NegativeParameter")); + } + if (count < 0) + { + throw new ArgumentOutOfRangeException("count", BitStreamResources.GetString("ArgumentOutOfRange_NegativeParameter")); + } + if (count > bits.Length - offset) + { + throw new ArgumentException(BitStreamResources.GetString("Argument_InvalidCountOrOffset")); + } + int num = offset + count; + int num2 = 0; + for (int i = offset; i < num; i++) + { + num2 += Read(out bits[i]); + } + return num2; + } + + public virtual int Read(out double bits) + { + return Read(out bits, 0, 64); + } + + public virtual int Read(out double bits, int bitIndex, int count) + { + ulong bits2 = 0uL; + int result = Read(out bits2, bitIndex, count); + bits = BitConverter.ToDouble(BitConverter.GetBytes(bits2), 0); + return result; + } + + public virtual int Read(double[] bits) + { + if (!_blnIsOpen) + { + throw new ObjectDisposedException(BitStreamResources.GetString("ObjectDisposed_BitStreamClosed")); + } + if (bits == null) + { + throw new ArgumentNullException("bits", BitStreamResources.GetString("ArgumentNull_BitBuffer")); + } + return Read(bits, 0, bits.Length); + } + + public virtual int Read(double[] bits, int offset, int count) + { + if (!_blnIsOpen) + { + throw new ObjectDisposedException(BitStreamResources.GetString("ObjectDisposed_BitStreamClosed")); + } + if (bits == null) + { + throw new ArgumentNullException("bits", BitStreamResources.GetString("ArgumentNull_BitBuffer")); + } + if (offset < 0) + { + throw new ArgumentOutOfRangeException("offset", BitStreamResources.GetString("ArgumentOutOfRange_NegativeParameter")); + } + if (count < 0) + { + throw new ArgumentOutOfRangeException("count", BitStreamResources.GetString("ArgumentOutOfRange_NegativeParameter")); + } + if (count > bits.Length - offset) + { + throw new ArgumentException(BitStreamResources.GetString("Argument_InvalidCountOrOffset")); + } + int num = offset + count; + int num2 = 0; + for (int i = offset; i < num; i++) + { + num2 += Read(out bits[i]); + } + return num2; + } + + public virtual BitStream And(BitStream bits) + { + if (!_blnIsOpen) + { + throw new ObjectDisposedException(BitStreamResources.GetString("ObjectDisposed_BitStreamClosed")); + } + if (bits == null) + { + throw new ArgumentNullException("bits", BitStreamResources.GetString("ArgumentNull_BitStream")); + } + if (bits.Length != _uiBitBuffer_Length) + { + throw new ArgumentException(BitStreamResources.GetString("Argument_DifferentBitStreamLengths")); + } + BitStream bitStream = new BitStream(_uiBitBuffer_Length); + uint num = _uiBitBuffer_Length >> 5; + uint num2 = 0u; + for (num2 = 0u; num2 < num; num2++) + { + bitStream._auiBitBuffer[num2] = (_auiBitBuffer[num2] & bits._auiBitBuffer[num2]); + } + if ((_uiBitBuffer_Length & 0x1F) != 0) + { + uint num3 = (uint)(-1 << (int)(32 - (_uiBitBuffer_Length & 0x1F))); + bitStream._auiBitBuffer[num2] = (_auiBitBuffer[num2] & bits._auiBitBuffer[num2] & num3); + } + return bitStream; + } + + public virtual BitStream Or(BitStream bits) + { + if (!_blnIsOpen) + { + throw new ObjectDisposedException(BitStreamResources.GetString("ObjectDisposed_BitStreamClosed")); + } + if (bits == null) + { + throw new ArgumentNullException("bits", BitStreamResources.GetString("ArgumentNull_BitStream")); + } + if (bits.Length != _uiBitBuffer_Length) + { + throw new ArgumentException(BitStreamResources.GetString("Argument_DifferentBitStreamLengths")); + } + BitStream bitStream = new BitStream(_uiBitBuffer_Length); + uint num = _uiBitBuffer_Length >> 5; + uint num2 = 0u; + for (num2 = 0u; num2 < num; num2++) + { + bitStream._auiBitBuffer[num2] = (_auiBitBuffer[num2] | bits._auiBitBuffer[num2]); + } + if ((_uiBitBuffer_Length & 0x1F) != 0) + { + uint num3 = (uint)(-1 << (int)(32 - (_uiBitBuffer_Length & 0x1F))); + bitStream._auiBitBuffer[num2] = (_auiBitBuffer[num2] | (bits._auiBitBuffer[num2] & num3)); + } + return bitStream; + } + + public virtual BitStream Xor(BitStream bits) + { + if (!_blnIsOpen) + { + throw new ObjectDisposedException(BitStreamResources.GetString("ObjectDisposed_BitStreamClosed")); + } + if (bits == null) + { + throw new ArgumentNullException("bits", BitStreamResources.GetString("ArgumentNull_BitStream")); + } + if (bits.Length != _uiBitBuffer_Length) + { + throw new ArgumentException(BitStreamResources.GetString("Argument_DifferentBitStreamLengths")); + } + BitStream bitStream = new BitStream(_uiBitBuffer_Length); + uint num = _uiBitBuffer_Length >> 5; + uint num2 = 0u; + for (num2 = 0u; num2 < num; num2++) + { + bitStream._auiBitBuffer[num2] = (_auiBitBuffer[num2] ^ bits._auiBitBuffer[num2]); + } + if ((_uiBitBuffer_Length & 0x1F) != 0) + { + uint num3 = (uint)(-1 << (int)(32 - (_uiBitBuffer_Length & 0x1F))); + bitStream._auiBitBuffer[num2] = (_auiBitBuffer[num2] ^ (bits._auiBitBuffer[num2] & num3)); + } + return bitStream; + } + + public virtual BitStream Not() + { + if (!_blnIsOpen) + { + throw new ObjectDisposedException(BitStreamResources.GetString("ObjectDisposed_BitStreamClosed")); + } + BitStream bitStream = new BitStream(_uiBitBuffer_Length); + uint num = _uiBitBuffer_Length >> 5; + uint num2 = 0u; + for (num2 = 0u; num2 < num; num2++) + { + bitStream._auiBitBuffer[num2] = ~_auiBitBuffer[num2]; + } + if ((_uiBitBuffer_Length & 0x1F) != 0) + { + uint num3 = (uint)(-1 << (int)(32 - (_uiBitBuffer_Length & 0x1F))); + bitStream._auiBitBuffer[num2] = (~_auiBitBuffer[num2] & num3); + } + return bitStream; + } + + public virtual BitStream ShiftLeft(long count) + { + if (!_blnIsOpen) + { + throw new ObjectDisposedException(BitStreamResources.GetString("ObjectDisposed_BitStreamClosed")); + } + BitStream bitStream = Copy(); + uint num = (uint)count; + uint num2 = (uint)bitStream.Length; + if (num >= num2) + { + bitStream.Position = 0L; + for (uint num3 = 0u; num3 < num2; num3++) + { + bitStream.Write(bit: false); + } + } + else + { + bool bit = false; + for (uint num3 = 0u; num3 < num2 - num; num3++) + { + bitStream.Position = num + num3; + bitStream.Read(out bit); + bitStream.Position = num3; + bitStream.Write(bit); + } + for (uint num3 = num2 - num; num3 < num2; num3++) + { + bitStream.Write(bit: false); + } + } + bitStream.Position = 0L; + return bitStream; + } + + public virtual BitStream ShiftRight(long count) + { + if (!_blnIsOpen) + { + throw new ObjectDisposedException(BitStreamResources.GetString("ObjectDisposed_BitStreamClosed")); + } + BitStream bitStream = Copy(); + uint num = (uint)count; + uint num2 = (uint)bitStream.Length; + if (num >= num2) + { + bitStream.Position = 0L; + for (uint num3 = 0u; num3 < num2; num3++) + { + bitStream.Write(bit: false); + } + } + else + { + bool bit = false; + for (uint num3 = 0u; num3 < num2 - num; num3++) + { + bitStream.Position = num3; + bitStream.Read(out bit); + bitStream.Position = num3 + num; + bitStream.Write(bit); + } + bitStream.Position = 0L; + for (uint num3 = 0u; num3 < num; num3++) + { + bitStream.Write(bit: false); + } + } + bitStream.Position = 0L; + return bitStream; + } + + public override string ToString() + { + uint num = _uiBitBuffer_Length >> 5; + uint num2 = 0u; + int num3 = 0; + uint num4 = 1u; + StringBuilder stringBuilder = new StringBuilder((int)_uiBitBuffer_Length); + for (num2 = 0u; num2 < num; num2++) + { + stringBuilder.Append("[" + num2.ToString(_ifp) + "]:{"); + for (num3 = 31; num3 >= 0; num3--) + { + uint num5 = num4 << num3; + if ((_auiBitBuffer[num2] & num5) == num5) + { + stringBuilder.Append('1'); + } + else + { + stringBuilder.Append('0'); + } + } + stringBuilder.Append("}\r\n"); + } + if ((_uiBitBuffer_Length & 0x1F) != 0) + { + stringBuilder.Append("[" + num2.ToString(_ifp) + "]:{"); + int num6 = (int)(32 - (_uiBitBuffer_Length & 0x1F)); + for (num3 = 31; num3 >= num6; num3--) + { + uint num5 = num4 << num3; + if ((_auiBitBuffer[num2] & num5) == num5) + { + stringBuilder.Append('1'); + } + else + { + stringBuilder.Append('0'); + } + } + for (num3 = num6 - 1; num3 >= 0; num3--) + { + stringBuilder.Append('.'); + } + stringBuilder.Append("}\r\n"); + } + return stringBuilder.ToString(); + } + + public static string ToString(bool bit) + { + return "Boolean{" + (bit ? 1 : 0) + "}"; + } + + public static string ToString(byte bits) + { + StringBuilder stringBuilder = new StringBuilder(8); + uint num = 1u; + stringBuilder.Append("Byte{"); + for (int num2 = 7; num2 >= 0; num2--) + { + uint num3 = num << num2; + if ((bits & num3) == num3) + { + stringBuilder.Append('1'); + } + else + { + stringBuilder.Append('0'); + } + } + stringBuilder.Append("}"); + return stringBuilder.ToString(); + } + + [CLSCompliant(false)] + public static string ToString(sbyte bits) + { + byte b = (byte)bits; + StringBuilder stringBuilder = new StringBuilder(8); + uint num = 1u; + stringBuilder.Append("SByte{"); + for (int num2 = 7; num2 >= 0; num2--) + { + uint num3 = num << num2; + if ((b & num3) == num3) + { + stringBuilder.Append('1'); + } + else + { + stringBuilder.Append('0'); + } + } + stringBuilder.Append("}"); + return stringBuilder.ToString(); + } + + public static string ToString(char bits) + { + StringBuilder stringBuilder = new StringBuilder(16); + uint num = 1u; + stringBuilder.Append("Char{"); + for (int num2 = 15; num2 >= 0; num2--) + { + uint num3 = num << num2; + if ((bits & num3) == num3) + { + stringBuilder.Append('1'); + } + else + { + stringBuilder.Append('0'); + } + } + stringBuilder.Append("}"); + return stringBuilder.ToString(); + } + + [CLSCompliant(false)] + public static string ToString(ushort bits) + { + short num = (short)bits; + StringBuilder stringBuilder = new StringBuilder(16); + uint num2 = 1u; + stringBuilder.Append("UInt16{"); + for (int num3 = 15; num3 >= 0; num3--) + { + uint num4 = num2 << num3; + if ((num & num4) == num4) + { + stringBuilder.Append('1'); + } + else + { + stringBuilder.Append('0'); + } + } + stringBuilder.Append("}"); + return stringBuilder.ToString(); + } + + public static string ToString(short bits) + { + StringBuilder stringBuilder = new StringBuilder(16); + uint num = 1u; + stringBuilder.Append("Int16{"); + for (int num2 = 15; num2 >= 0; num2--) + { + uint num3 = num << num2; + if ((bits & num3) == num3) + { + stringBuilder.Append('1'); + } + else + { + stringBuilder.Append('0'); + } + } + stringBuilder.Append("}"); + return stringBuilder.ToString(); + } + + [CLSCompliant(false)] + public static string ToString(uint bits) + { + StringBuilder stringBuilder = new StringBuilder(32); + uint num = 1u; + stringBuilder.Append("UInt32{"); + for (int num2 = 31; num2 >= 0; num2--) + { + uint num3 = num << num2; + if ((bits & num3) == num3) + { + stringBuilder.Append('1'); + } + else + { + stringBuilder.Append('0'); + } + } + stringBuilder.Append("}"); + return stringBuilder.ToString(); + } + + public static string ToString(int bits) + { + StringBuilder stringBuilder = new StringBuilder(32); + uint num = 1u; + stringBuilder.Append("Int32{"); + for (int num2 = 31; num2 >= 0; num2--) + { + uint num3 = num << num2; + if ((bits & (int)num3) == (int)num3) + { + stringBuilder.Append('1'); + } + else + { + stringBuilder.Append('0'); + } + } + stringBuilder.Append("}"); + return stringBuilder.ToString(); + } + + [CLSCompliant(false)] + public static string ToString(ulong bits) + { + StringBuilder stringBuilder = new StringBuilder(64); + ulong num = 1uL; + stringBuilder.Append("UInt64{"); + for (int num2 = 63; num2 >= 0; num2--) + { + ulong num3 = num << num2; + if ((bits & num3) == num3) + { + stringBuilder.Append('1'); + } + else + { + stringBuilder.Append('0'); + } + } + stringBuilder.Append("}"); + return stringBuilder.ToString(); + } + + public static string ToString(long bits) + { + StringBuilder stringBuilder = new StringBuilder(64); + ulong num = 1uL; + stringBuilder.Append("Int64{"); + for (int num2 = 63; num2 >= 0; num2--) + { + ulong num3 = num << num2; + if ((bits & (long)num3) == (long)num3) + { + stringBuilder.Append('1'); + } + else + { + stringBuilder.Append('0'); + } + } + stringBuilder.Append("}"); + return stringBuilder.ToString(); + } + + public static string ToString(float bits) + { + byte[] bytes = BitConverter.GetBytes(bits); + uint num = (uint)(bytes[0] | (bytes[1] << 8) | (bytes[2] << 16) | (bytes[3] << 24)); + StringBuilder stringBuilder = new StringBuilder(32); + uint num2 = 1u; + stringBuilder.Append("Single{"); + for (int num3 = 31; num3 >= 0; num3--) + { + uint num4 = num2 << num3; + if ((num & num4) == num4) + { + stringBuilder.Append('1'); + } + else + { + stringBuilder.Append('0'); + } + } + stringBuilder.Append("}"); + return stringBuilder.ToString(); + } + + public static string ToString(double bits) + { + byte[] bytes = BitConverter.GetBytes(bits); + ulong num = bytes[0] | ((ulong)bytes[1] << 8) | ((ulong)bytes[2] << 16) | ((ulong)bytes[3] << 24) | ((ulong)bytes[4] << 32) | ((ulong)bytes[5] << 40) | ((ulong)bytes[6] << 48) | ((ulong)bytes[7] << 56); + StringBuilder stringBuilder = new StringBuilder(64); + ulong num2 = 1uL; + stringBuilder.Append("Double{"); + for (int num3 = 63; num3 >= 0; num3--) + { + ulong num4 = num2 << num3; + if ((num & num4) == num4) + { + stringBuilder.Append('1'); + } + else + { + stringBuilder.Append('0'); + } + } + stringBuilder.Append("}"); + return stringBuilder.ToString(); + } + + private void UpdateLengthForWrite(uint bits) + { + _uiBitBuffer_Length += bits; + } + + private void UpdateIndicesForWrite(uint bits) + { + _uiBitBuffer_BitIndex += bits; + if (_uiBitBuffer_BitIndex == 32) + { + _uiBitBuffer_Index++; + _uiBitBuffer_BitIndex = 0u; + if (_auiBitBuffer.Length == _uiBitBuffer_Length >> 5) + { + _auiBitBuffer = ReDimPreserve(_auiBitBuffer, (uint)(_auiBitBuffer.Length << 1)); + } + } + else if (_uiBitBuffer_BitIndex > 32) + { + throw new InvalidOperationException(BitStreamResources.GetString("InvalidOperation_BitIndexGreaterThan32")); + } + } + + private void UpdateIndicesForRead(uint bits) + { + _uiBitBuffer_BitIndex += bits; + if (_uiBitBuffer_BitIndex == 32) + { + _uiBitBuffer_Index++; + _uiBitBuffer_BitIndex = 0u; + } + else if (_uiBitBuffer_BitIndex > 32) + { + throw new InvalidOperationException(BitStreamResources.GetString("InvalidOperation_BitIndexGreaterThan32")); + } + } + + private static uint[] ReDimPreserve(uint[] buffer, uint newLength) + { + uint[] array = new uint[newLength]; + uint num = (uint)buffer.Length; + if (num < newLength) + { + Buffer.BlockCopy(buffer, 0, array, 0, (int)(num << 2)); + } + else + { + Buffer.BlockCopy(buffer, 0, array, 0, (int)(newLength << 2)); + } + buffer = null; + return array; + } + + public override void Close() + { + _blnIsOpen = false; + _uiBitBuffer_Index = 0u; + _uiBitBuffer_BitIndex = 0u; + } + + [CLSCompliant(false)] + public virtual uint[] GetBuffer() + { + return _auiBitBuffer; + } + + public virtual BitStream Copy() + { + BitStream bitStream = new BitStream(Length); + Buffer.BlockCopy(_auiBitBuffer, 0, bitStream._auiBitBuffer, 0, bitStream._auiBitBuffer.Length << 2); + bitStream._uiBitBuffer_Length = _uiBitBuffer_Length; + return bitStream; + } + + public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback callback, object state) + { + throw new NotSupportedException(BitStreamResources.GetString("NotSupported_AsyncOps")); + } + + public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback callback, object state) + { + throw new NotSupportedException(BitStreamResources.GetString("NotSupported_AsyncOps")); + } + + public override int EndRead(IAsyncResult asyncResult) + { + throw new NotSupportedException(BitStreamResources.GetString("NotSupported_AsyncOps")); + } + + public override void EndWrite(IAsyncResult asyncResult) + { + throw new NotSupportedException(BitStreamResources.GetString("NotSupported_AsyncOps")); + } + + public override long Seek(long offset, SeekOrigin origin) + { + throw new NotSupportedException(BitStreamResources.GetString("NotSupported_Seek")); + } + + public override void SetLength(long value) + { + throw new NotSupportedException(BitStreamResources.GetString("NotSupported_SetLength")); + } + + public override void Flush() + { + throw new NotSupportedException(BitStreamResources.GetString("NotSupported_Flush")); + } + + public static implicit operator BitStream(MemoryStream bits) + { + if (bits == null) + { + throw new ArgumentNullException("bits", BitStreamResources.GetString("ArgumentNull_MemoryStream")); + } + return new BitStream(bits); + } + + public static implicit operator MemoryStream(BitStream bits) + { + if (bits == null) + { + throw new ArgumentNullException("bits", BitStreamResources.GetString("ArgumentNull_BitStream")); + } + return new MemoryStream(bits.ToByteArray()); + } + + public static implicit operator BitStream(FileStream bits) + { + if (bits == null) + { + throw new ArgumentNullException("bits", BitStreamResources.GetString("ArgumentNull_FileStream")); + } + return new BitStream(bits); + } + + public static implicit operator BitStream(BufferedStream bits) + { + if (bits == null) + { + throw new ArgumentNullException("bits", BitStreamResources.GetString("ArgumentNull_BufferedStream")); + } + return new BitStream(bits); + } + + public static implicit operator BufferedStream(BitStream bits) + { + if (bits == null) + { + throw new ArgumentNullException("bits", BitStreamResources.GetString("ArgumentNull_BitStream")); + } + return new BufferedStream((MemoryStream)bits); + } + + public static implicit operator BitStream(NetworkStream bits) + { + if (bits == null) + { + throw new ArgumentNullException("bits", BitStreamResources.GetString("ArgumentNull_NetworkStream")); + } + return new BitStream(bits); + } + + public static implicit operator BitStream(CryptoStream bits) + { + if (bits == null) + { + throw new ArgumentNullException("bits", BitStreamResources.GetString("ArgumentNull_CryptoStream")); + } + return new BitStream(bits); + } + } +} diff --git a/Common.GLib/GLib.IO/BitStream.resx b/Common.GLib/GLib.IO/BitStream.resx new file mode 100644 index 0000000000000000000000000000000000000000..5e7aedb1d26f9584a0c4b7c9bb118d46dfe9b335 --- /dev/null +++ b/Common.GLib/GLib.IO/BitStream.resx @@ -0,0 +1,59 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +text/microsoft-resx1.3System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089Position must be greater than or equal to zero. + count + offset were out of bounds for the BitStream or count is greater than the number of elements from bitIndex to the end of the BitStream. + The BitStream cannot be null. + The BufferedStream cannot be null. + Capacity must be greater than zero. + count + bitIndex exceeds the length of the 128-bit value. + Parameter must be greater than or equal to zero. + The CryptoStream cannot be null. + The internal bit buffer's bit index cannot be greater than 32. + Cannot SetLength of a BitStream. + The NetworkStream cannot be null. + Asynchronous operations are not supported by the BitStream class. + Cannot Seek on a BitStream. Use Position property instead. + The inherited ReadByte method is not supported by the BitStream class. Use one of the overloaded Read methods instead. + Position must be less than or equal to the Bit Stream Length - 1. + count + bitIndex exceeds the length of the 16-bit value. + count + bitIndex exceeds the length of the 8-bit value. + The inherited WriteByte method is not supported by the BitStream class. Use one of the overloaded Write methods instead. + The FileStream cannot be null. + count + offset were out of bounds for the array or count is greater than the number of elements from offset to the end of the array. + The Stream cannot be null. + count + bitIndex exceeds the length of the 64-bit value. + count + bitIndex exceeds the length of the 32-bit value. + count + bitIndex exceeds the length of the 16-bit value. + The MemoryStream cannot be null. + Cannot Flush a BitStream. + Cannot access a closed BitStream. + BitStream lengths must be the same. + The bit buffer cannot be null. + \ No newline at end of file diff --git a/Common.GLib/GLib.IO/BitStreamReader.cs b/Common.GLib/GLib.IO/BitStreamReader.cs new file mode 100644 index 0000000000000000000000000000000000000000..cefd4eb165e772675d634e154a760971ace60d6b --- /dev/null +++ b/Common.GLib/GLib.IO/BitStreamReader.cs @@ -0,0 +1,110 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.IO; + +namespace GLib.IO +{ + public class BitStreamReader + { + private Stream _stream = null; + + private BinaryReader _reader = null; + + private int byte_point = -1; + + private BitArray bit_arr = null; + + public BitStreamReader(byte[] bytes) + : this(new MemoryStream(bytes)) + { + } + + public BitStreamReader(Stream stream) + { + _stream = stream; + _reader = new BinaryReader(_stream); + } + + public bool ReadBit() + { + if (byte_point == -1 || bit_arr == null) + { + bit_arr = new BitArray(new byte[1] + { + _reader.ReadByte() + }); + byte_point = 7; + } + bool result = bit_arr.Get(byte_point); + byte_point--; + return result; + } + + public byte[] ReadBit(int len) + { + int num = 0; + int num2 = len / 8 + ((len % 8 != 0) ? 1 : 0); + List list = new List(); + for (int i = 0; i < num2; i++) + { + byte b = 0; + int num3 = (len - num >= 8) ? 7 : (len - num - 1); + for (int num4 = num3; num4 >= 0; num4--) + { + b = ((!ReadBit()) ? ((byte)(b << ((num4 > 0) ? 1 : 0))) : ((byte)((1 | b) << ((num4 > 0) ? 1 : 0)))); + num++; + if (num == len) + { + break; + } + } + list.Add(b); + if (num == len) + { + break; + } + } + return list.ToArray(); + } + + public void Skip(int len) + { + ReadBit(len); + } + + public byte ReadByte(int len) + { + byte[] array = ReadBit(len); + return array[0]; + } + + public short ReadShort(int len) + { + byte[] array = ReadBit(len); + if (array.Length < 2) + { + List list = new List(); + list.AddRange(new byte[2 - array.Length]); + list.AddRange(array); + array = list.ToArray(); + } + Array.Reverse(array); + return BitConverter.ToInt16(array, 0); + } + + public int ReadInt(int len) + { + byte[] array = ReadBit(len); + if (array.Length < 4) + { + List list = new List(); + list.AddRange(new byte[4 - array.Length]); + list.AddRange(array); + array = list.ToArray(); + } + Array.Reverse(array); + return BitConverter.ToInt32(array, 0); + } + } +} diff --git a/Common.GLib/GLib.IO/BufferStream.cs b/Common.GLib/GLib.IO/BufferStream.cs new file mode 100644 index 0000000000000000000000000000000000000000..602f19ea1a040e273a1bae8046ad618e76e1a849 --- /dev/null +++ b/Common.GLib/GLib.IO/BufferStream.cs @@ -0,0 +1,146 @@ +using GLib.GeneralModel; +using System; +using System.IO; +using System.Threading; + +namespace GLib.IO +{ + public class BufferStream : Stream + { + private AQueue _queueMS = new AQueue(); + + private MemoryStream _curMS = null; + + private object _lock = new object(); + + public int _size = 0; + + public override long Length => _size; + + public virtual int Size => (int)Length; + + public override long Position + { + get + { + return 0L; + } + set + { + throw new NotImplementedException(); + } + } + + public override bool CanRead => true; + + public override bool CanSeek => false; + + public override bool CanWrite => true; + + public void Write(byte[] bs) + { + Write(bs, 0, bs.Length); + } + + public override void Write(byte[] bs, int index, int count) + { + lock (_lock) + { + _Write(bs, index, count); + } + } + + public byte[] Read(int len) + { + lock (_lock) + { + return _Read(len); + } + } + + public override int Read(byte[] buf, int offset, int len) + { + byte[] array = Read(len); + Array.Copy(array, 0, buf, offset, len); + return array.Length; + } + + private void _Write(byte[] bs, int index, int count) + { + MemoryStream memoryStream = new MemoryStream(bs, index, count); + memoryStream.Position = 0L; + lock (_queueMS.GetLock()) + { + _queueMS.Enqueue(memoryStream); + _size += count; + } + } + + private byte[] _Read(int len) + { + while (_size < len) + { + Thread.Sleep(10); + bool flag = true; + } + int size = _size; + byte[] array = new byte[len]; + int num = 0; + lock (_queueMS.GetLock()) + { + while (num < len) + { + if (_curMS == null) + { + _curMS = _queueMS.Dequeue(); + } + num += _curMS.Read(array, num, len - num); + if (_curMS.Length == _curMS.Position) + { + _curMS = null; + } + } + if (num != len) + { + throw new Exception(); + } + _size -= len; + } + return array; + } + + public override void Flush() + { + } + + public override void SetLength(long value) + { + throw new NotImplementedException(); + } + + public override long Seek(long offset, SeekOrigin origin) + { + throw new NotImplementedException(); + } + + public byte[] ToArray() + { + byte[] array = new byte[_size]; + Read(array, 0, array.Length); + return array; + } + + public override void Close() + { + base.Close(); + if (_curMS != null) + { + _queueMS.Clear(); + } + if (_curMS != null) + { + _curMS.Close(); + } + } + } +} diff --git a/Common.GLib/GLib.IO/IOStream.cs b/Common.GLib/GLib.IO/IOStream.cs new file mode 100644 index 0000000000000000000000000000000000000000..03e7d78e56047c8d4627047d97dd1808cb1b885d --- /dev/null +++ b/Common.GLib/GLib.IO/IOStream.cs @@ -0,0 +1,6 @@ +namespace GLib.IO +{ + public class IOStream : BufferStream + { + } +} diff --git a/Common.GLib/GLib.Linq/DynamicQueryable.cs b/Common.GLib/GLib.Linq/DynamicQueryable.cs new file mode 100644 index 0000000000000000000000000000000000000000..9fce18ed5287ad08ee519bc4847bc5d99a8e46d1 --- /dev/null +++ b/Common.GLib/GLib.Linq/DynamicQueryable.cs @@ -0,0 +1,30 @@ +using System.Collections.Generic; +using System.Linq; + +namespace GLib.Linq +{ + public static class DynamicQueryable + { + public static IQueryable Where(this IQueryable source, IFilterExpressionContainer container) + { + //IList expressions = container.GetExpressions(); + //foreach (FilterExpression item in expressions) + //{ + // //source = DynamicQueryable.Where(source, item.Predicate, item.Values); + //} + source = Where(source, container); + + return source; + } + + public static IQueryable OrderBy(this IQueryable source, string ordering) + { + if (!string.IsNullOrEmpty(ordering)) + { + // return DynamicQueryable.OrderBy(source, ordering, new object[0]); + OrderBy(source, ordering); + } + return source; + } + } +} diff --git a/Common.GLib/GLib.Linq/FilterExpression.cs b/Common.GLib/GLib.Linq/FilterExpression.cs new file mode 100644 index 0000000000000000000000000000000000000000..540027d004d167eec9d9221fd6d18736dee05e29 --- /dev/null +++ b/Common.GLib/GLib.Linq/FilterExpression.cs @@ -0,0 +1,20 @@ +using System; + +namespace GLib.Linq +{ + [Serializable] + public class FilterExpression + { + public string Predicate + { + get; + set; + } + + public object[] Values + { + get; + set; + } + } +} diff --git a/Common.GLib/GLib.Linq/IFilterExpressionContainer.cs b/Common.GLib/GLib.Linq/IFilterExpressionContainer.cs new file mode 100644 index 0000000000000000000000000000000000000000..32a031819919862ca7c905eaadb5a9dda29f4c22 --- /dev/null +++ b/Common.GLib/GLib.Linq/IFilterExpressionContainer.cs @@ -0,0 +1,17 @@ +using System.Collections.Generic; + +namespace GLib.Linq +{ + public interface IFilterExpressionContainer + { + IList GetExpressions(); + + void AddFilterExpression(string predicate, params object[] values); + + void RemoveFilterExpression(string predicate, params object[] values); + + void RemoveAllFilterExpression(string predicate); + + void RemoveAllFilterExpression(); + } +} diff --git a/Common.GLib/GLib.Logging/Log.cs b/Common.GLib/GLib.Logging/Log.cs new file mode 100644 index 0000000000000000000000000000000000000000..2624493be1f14dea17e38fe685c9d6f1c1c94996 --- /dev/null +++ b/Common.GLib/GLib.Logging/Log.cs @@ -0,0 +1,184 @@ +using System; +using System.Collections.Generic; +using System.IO; +using System.Text; +using System.Threading; + +namespace GLib.Logging +{ + public class Log : IDisposable + { + private static Queue logMessages; + + private static string path; + + private static bool state; + + private static LogType logtype; + + private static DateTime time; + + private static StreamWriter writer; + + public Log() + : this(AppDomain.CurrentDomain.BaseDirectory, LogType.Daily) + { + } + + public Log(LogType t) + : this(AppDomain.CurrentDomain.BaseDirectory, t) + { + } + + public Log(string filepath, LogType t) + { + if (logMessages == null) + { + state = true; + path = filepath; + logtype = t; + FileOpen(); + logMessages = new Queue(); + Thread thread = new Thread(Work); + thread.Start(); + } + } + + private void Work() + { + while (true) + { + bool flag = true; + if (logMessages.Count > 0) + { + LogMessage logMessage = null; + lock (logMessages) + { + logMessage = logMessages.Dequeue(); + } + if (logMessage != null) + { + WriteLogMessage(logMessage); + } + } + else if (state) + { + Thread.Sleep(1); + } + else + { + FileClose(); + } + } + } + + private void WriteLogMessage(LogMessage message) + { + try + { + if (writer == null) + { + FileOpen(); + } + else + { + if (DateTime.Now >= time) + { + FileClose(); + FileOpen(); + } + writer.Write(message.Time); + writer.Write("\t"); + writer.Write(message.Type); + writer.Write("\t\r\n"); + writer.Write(message.Content); + writer.Write("\r\n\r\n"); + writer.Flush(); + } + } + catch (Exception ex) + { + Console.WriteLine(ex.Message); + } + FileClose(); + } + + private string GetFileName() + { + DateTime now = DateTime.Now; + string format = ""; + switch (logtype) + { + case LogType.Daily: + time = new DateTime(now.Year, now.Month, now.Day); + time = time.AddDays(1.0); + format = "yyyyMMdd'.log'"; + break; + case LogType.Weekly: + time = new DateTime(now.Year, now.Month, now.Day); + time = time.AddDays(7.0); + format = "yyyyMMdd'.log'"; + break; + case LogType.Monthly: + time = new DateTime(now.Year, now.Month, 1); + time = time.AddMonths(1); + format = "yyyyMM'.log'"; + break; + case LogType.Annually: + time = new DateTime(now.Year, 1, 1); + time = time.AddYears(1); + format = "yyyy'.log'"; + break; + } + return now.ToString(format); + } + + public void Write(LogMessage message) + { + if (logMessages != null) + { + lock (logMessages) + { + logMessages.Enqueue(message); + } + } + } + + public void Write(string text, MessageType type) + { + Write(new LogMessage(text, type)); + } + + public void Write(DateTime now, string text, MessageType type) + { + Write(new LogMessage(now, text, type)); + } + + public void Write(Exception e, MessageType type) + { + Write(new LogMessage(e.Message, type)); + } + + private void FileOpen() + { + writer = new StreamWriter(path + GetFileName(), append: true, Encoding.Default); + } + + private void FileClose() + { + if (writer != null) + { + writer.Flush(); + writer.Close(); + writer.Dispose(); + writer = null; + } + } + + public void Dispose() + { + state = false; + GC.SuppressFinalize(this); + } + } +} diff --git a/Common.GLib/GLib.Logging/LogMessage.cs b/Common.GLib/GLib.Logging/LogMessage.cs new file mode 100644 index 0000000000000000000000000000000000000000..b24817fecbf548c3c8fa3f1e203af2bfb2ddbee2 --- /dev/null +++ b/Common.GLib/GLib.Logging/LogMessage.cs @@ -0,0 +1,71 @@ +using System; + +namespace GLib.Logging +{ + public class LogMessage + { + private DateTime _time; + + private string _content; + + private MessageType _type; + + public DateTime Time + { + get + { + return _time; + } + set + { + _time = value; + } + } + + public string Content + { + get + { + return _content; + } + set + { + _content = value; + } + } + + public MessageType Type + { + get + { + return _type; + } + set + { + _type = value; + } + } + + public LogMessage() + : this("", MessageType.Unkown) + { + } + + public LogMessage(string content, MessageType type) + : this(DateTime.Now, content, type) + { + } + + public LogMessage(DateTime time, string content, MessageType type) + { + _time = time; + _content = content; + _type = type; + } + + public override string ToString() + { + return _time.ToString() + "\t" + _content + "\t"; + } + } +} diff --git a/Common.GLib/GLib.Logging/LogType.cs b/Common.GLib/GLib.Logging/LogType.cs new file mode 100644 index 0000000000000000000000000000000000000000..7bcf7c23921b6a814affedc32207e832b562d6c4 --- /dev/null +++ b/Common.GLib/GLib.Logging/LogType.cs @@ -0,0 +1,10 @@ +namespace GLib.Logging +{ + public enum LogType + { + Daily = 0, + Weekly = 1, + Monthly = 2, + Annually = 3 + } +} diff --git a/Common.GLib/GLib.Logging/MessageType.cs b/Common.GLib/GLib.Logging/MessageType.cs new file mode 100644 index 0000000000000000000000000000000000000000..74fbecd527f4a7f375c0028a9261826ba6c0442b --- /dev/null +++ b/Common.GLib/GLib.Logging/MessageType.cs @@ -0,0 +1,11 @@ +namespace GLib.Logging +{ + public enum MessageType + { + Unkown = 0, + Common = 1, + Warning = 2, + Error = 3, + Success = 4 + } +} diff --git a/Common.GLib/GLib.Net/AnsycSocket4ByteLengthDespatcher.cs b/Common.GLib/GLib.Net/AnsycSocket4ByteLengthDespatcher.cs new file mode 100644 index 0000000000000000000000000000000000000000..5c67d4ab9e0f14b14c8f22711711d62228d38e37 --- /dev/null +++ b/Common.GLib/GLib.Net/AnsycSocket4ByteLengthDespatcher.cs @@ -0,0 +1,163 @@ +using System; +using System.Net.Sockets; + +namespace GLib.Net +{ + public class AnsycSocket4ByteLengthDespatcher + { + private AnsycSocketDespatcher _despatcher = null; + + private bool _isBeging = false; + + private bool _needTSLen = true; + + private bool _needTSData = true; + + private int _needTSDataLen = 0; + + private byte[] _bsLen = new byte[4]; + + private byte[] _bsData = null; + + private object _lock = new object(); + + private Action _DisoconnectHandle; + + private Action _Completed; + + private bool _isReceiveMode = false; + + private bool _isDisposed = false; + + public AnsycSocket4ByteLengthDespatcher(Socket socket, bool isReceiveMode, Action disoconnectHandle, Action _completed) + { + _isReceiveMode = isReceiveMode; + _DisoconnectHandle = disoconnectHandle; + _Completed = _completed; + _despatcher = new AnsycSocketDespatcher(socket, isReceiveMode, _despatcher_Disoconnect, _despatcher_Completed); + } + + public void BeginSend(byte[] buffer) + { + if (!_isDisposed && !_isBeging) + { + _needTSLen = true; + _needTSData = true; + _bsLen = BitConverter.GetBytes(buffer.Length); + _bsData = buffer; + _despatcher.Begin(_bsLen); + } + } + + public void EndSend() + { + if (_isBeging) + { + _isBeging = false; + _needTSLen = true; + _needTSData = true; + _bsData = null; + _despatcher.End(); + } + } + + public void BeginReceive() + { + if (!_isDisposed && !_isBeging) + { + _needTSLen = true; + _needTSData = true; + _bsData = null; + _despatcher.Begin(_bsLen); + } + } + + public void EndReceive() + { + if (_isBeging) + { + _isBeging = false; + _needTSLen = true; + _needTSData = true; + _bsData = null; + _despatcher.End(); + } + } + + private void OnCompleted(byte[] bytes) + { + if (!_isDisposed) + { + _isBeging = false; + if (_Completed != null) + { + _Completed(_bsData); + } + } + } + + private void _despatcher_Disoconnect() + { + if (_DisoconnectHandle != null) + { + _DisoconnectHandle(); + } + } + + private void _despatcher_Completed(AnsycSocketDespatcher.DespatcheStateModel model) + { + if (_isDisposed) + { + return; + } + if (!_isReceiveMode) + { + if (_needTSLen) + { + _needTSLen = false; + } + if (_needTSData) + { + _needTSData = false; + _despatcher.Begin(_bsData); + } + else + { + OnCompleted(model.Buffer); + } + return; + } + if (_needTSLen) + { + _needTSLen = false; + _needTSDataLen = BitConverter.ToInt32(model.Buffer, 0); + _bsData = new byte[_needTSDataLen]; + } + if (_needTSData) + { + _needTSData = false; + _despatcher.Begin(_bsData); + if (_bsData.Length != _needTSDataLen) + { + throw new Exception(); + } + } + else + { + OnCompleted(model.Buffer); + } + } + + private void Log(string msg) + { + } + + public void Dispose() + { + _isDisposed = false; + _despatcher.Dispose(); + _DisoconnectHandle = null; + _Completed = null; + } + } +} diff --git a/Common.GLib/GLib.Net/AnsycSocketDespatcher.cs b/Common.GLib/GLib.Net/AnsycSocketDespatcher.cs new file mode 100644 index 0000000000000000000000000000000000000000..8ba0a2d6906e751fb6d71bbc747ce51dc15d9fed --- /dev/null +++ b/Common.GLib/GLib.Net/AnsycSocketDespatcher.cs @@ -0,0 +1,232 @@ +using GLib.GeneralModel; +using System; +using System.Net.Sockets; + +namespace GLib.Net +{ + public class AnsycSocketDespatcher : IDisposable + { + public class DespatcheStateModel + { + public byte[] Buffer; + + public int Offset; + + public int Size; + + public bool IsCompleted; + } + + private bool _isBeging = false; + + private object _lockObj = new object(); + + private IAsyncResult _lasyAsyncResult = null; + + private Socket _socket = null; + + private bool _CompletedHandle_Invokeing = false; + + private AQueue _queueCompletedHandleInvoke = null; + + private Action _DisoconnectHandle; + + private Action _CompletedHandle; + + private bool _isDisposed = false; + + public bool IsReceiveMode + { + get; + private set; + } + + public AnsycSocketDespatcher(Socket socket, bool isReceiveMode, Action disoconnectHandle, Action completedHandle) + { + _socket = socket; + IsReceiveMode = isReceiveMode; + _DisoconnectHandle = disoconnectHandle; + _CompletedHandle = completedHandle; + } + + public void Begin(byte[] buffer) + { + Begin(buffer, 0, buffer.Length); + } + + public void Begin(byte[] buffer, int offset, int size) + { + DespatcheStateModel despatcheStateModel = new DespatcheStateModel(); + despatcheStateModel.Size = size; + despatcheStateModel.Buffer = buffer; + despatcheStateModel.Offset = offset; + despatcheStateModel.IsCompleted = false; + DespatcheStateModel so = despatcheStateModel; + Begin(so); + } + + public void Begin(DespatcheStateModel so) + { + if (!_isDisposed && !_isBeging) + { + _isBeging = true; + try + { + lock (_lockObj) + { + if (IsReceiveMode) + { + _lasyAsyncResult = _socket.BeginReceive(so.Buffer, so.Offset, so.Size, SocketFlags.None, ReadCallback, so); + } + else + { + _lasyAsyncResult = _socket.BeginSend(so.Buffer, so.Offset, so.Size, SocketFlags.None, ReadCallback, so); + } + } + } + catch (Exception e) + { + OnDisoconnect(e); + } + } + } + + public void End() + { + if (!_isDisposed && _isBeging) + { + _isBeging = false; + try + { + if (IsReceiveMode) + { + if (_lasyAsyncResult != null && !_lasyAsyncResult.IsCompleted) + { + _socket.EndReceive(_lasyAsyncResult); + } + } + else if (_lasyAsyncResult != null && !_lasyAsyncResult.IsCompleted) + { + _socket.EndSend(_lasyAsyncResult); + } + } + catch (Exception e) + { + if (!_isDisposed) + { + OnDisoconnect(e); + } + } + _lasyAsyncResult = null; + } + } + + private void Completed(DespatcheStateModel model) + { + if (!_isDisposed) + { + _isBeging = false; + _lasyAsyncResult = null; + lock (_lockObj) + { + if (_queueCompletedHandleInvoke == null) + { + _queueCompletedHandleInvoke = new AQueue(); + } + _queueCompletedHandleInvoke.Enqueue(model); + if (!_CompletedHandle_Invokeing) + { + model = _queueCompletedHandleInvoke.Dequeue(); + _CompletedHandle_Invokeing = true; + _CompletedHandle.BeginInvoke(model, _CompletedHandle_AsyncCallback, null); + } + } + } + } + + private void _CompletedHandle_AsyncCallback(IAsyncResult ar) + { + if (!_isDisposed) + { + lock (_lockObj) + { + _CompletedHandle.EndInvoke(ar); + if (_queueCompletedHandleInvoke.Count > 0) + { + DespatcheStateModel obj = _queueCompletedHandleInvoke.Dequeue(); + _CompletedHandle.BeginInvoke(obj, _CompletedHandle_AsyncCallback, null); + } + else + { + _CompletedHandle_Invokeing = false; + } + } + } + } + + private void ReadCallback(IAsyncResult ar) + { + if (!_isDisposed) + { + DespatcheStateModel despatcheStateModel = null; + despatcheStateModel = (DespatcheStateModel)ar.AsyncState; + try + { + int num = _socket.EndReceive(ar); + despatcheStateModel.Offset += num; + despatcheStateModel.Size -= num; + if (num == 0) + { + _ = _socket.Connected; + bool flag = 1 == 0; + if (_DisoconnectHandle != null) + { + _DisoconnectHandle.BeginInvoke(null, null); + } + } + else if (despatcheStateModel.Size == 0) + { + despatcheStateModel.IsCompleted = true; + Completed(despatcheStateModel); + } + else if (IsReceiveMode) + { + _lasyAsyncResult = _socket.BeginReceive(despatcheStateModel.Buffer, despatcheStateModel.Offset, despatcheStateModel.Size, SocketFlags.None, ReadCallback, despatcheStateModel); + } + else + { + _lasyAsyncResult = _socket.BeginSend(despatcheStateModel.Buffer, despatcheStateModel.Offset, despatcheStateModel.Size, SocketFlags.None, ReadCallback, despatcheStateModel); + } + } + catch (Exception e) + { + OnDisoconnect(e); + } + } + } + + protected void OnDisoconnect(Exception e) + { + if (!_isDisposed && _DisoconnectHandle != null) + { + _DisoconnectHandle.BeginInvoke(null, null); + } + } + + protected void OnDisoconnect() + { + if (!_isDisposed && _DisoconnectHandle != null) + { + _DisoconnectHandle.BeginInvoke(null, null); + } + } + + public void Dispose() + { + _isDisposed = true; + End(); + _DisoconnectHandle = null; + _CompletedHandle = null; + } + } +} diff --git a/Common.GLib/GLib.Net/ByteObjSocket.cs b/Common.GLib/GLib.Net/ByteObjSocket.cs new file mode 100644 index 0000000000000000000000000000000000000000..64a75d658ed00ed8c4a5632e0d460bfa6a2f26d5 --- /dev/null +++ b/Common.GLib/GLib.Net/ByteObjSocket.cs @@ -0,0 +1,21 @@ +namespace GLib.Net +{ + public class ByteObjSocket : SocketEx where T : IByteObj, new() + { + public virtual T ReadObj() + { + int len = ReadInt32(); + byte[] bytes = ReadBytes(len); + T result = new T(); + result.SetBytes(bytes); + return result; + } + + public virtual void Write(T t) + { + byte[] bytes = t.GetBytes(); + Write(bytes.Length); + Write(bytes); + } + } +} diff --git a/Common.GLib/GLib.Net/IByteObj.cs b/Common.GLib/GLib.Net/IByteObj.cs new file mode 100644 index 0000000000000000000000000000000000000000..67e5988bb02c0ed864535a1013d2e027d304df97 --- /dev/null +++ b/Common.GLib/GLib.Net/IByteObj.cs @@ -0,0 +1,9 @@ +namespace GLib.Net +{ + public interface IByteObj + { + byte[] GetBytes(); + + void SetBytes(byte[] buf); + } +} diff --git a/Common.GLib/GLib.Net/SocketEx.cs b/Common.GLib/GLib.Net/SocketEx.cs new file mode 100644 index 0000000000000000000000000000000000000000..938f2999c81c887592b8db471f1fa1031c59c81a --- /dev/null +++ b/Common.GLib/GLib.Net/SocketEx.cs @@ -0,0 +1,132 @@ +using System.IO; +using System.Net.Sockets; + +namespace GLib.Net +{ + public class SocketEx : Socket + { + private NetworkStream __ns = null; + + private BinaryReader __br = null; + + private BinaryWriter __bw = null; + + private NetworkStream _ns + { + get + { + if (__ns == null) + { + __ns = new NetworkStream(this); + } + return __ns; + } + } + + private BinaryReader _br + { + get + { + if (__br == null) + { + __br = new BinaryReader(_ns); + } + return __br; + } + } + + private BinaryWriter _bw + { + get + { + if (__bw == null) + { + __bw = new BinaryWriter(_ns); + } + return __bw; + } + } + + public SocketEx() + : this(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp) + { + } + + public SocketEx(AddressFamily addressFamily, SocketType socketType, ProtocolType protocolType) + : base(addressFamily, socketType, protocolType) + { + } + + public virtual byte[] ReadBytes(int len) + { + return _br.ReadBytes(len); + } + + public virtual byte ReadByte() + { + return _br.ReadByte(); + } + + public virtual short ReadInt16() + { + return _br.ReadInt16(); + } + + public virtual int ReadInt32() + { + return _br.ReadInt32(); + } + + public virtual long ReadInt64() + { + return _br.ReadInt64(); + } + + public virtual void Write(byte[] buffer, int index, int count) + { + _bw.Write(buffer, index, count); + } + + public virtual void Write(byte[] buffer) + { + _bw.Write(buffer); + } + + public virtual void Write(byte value) + { + _bw.Write(value); + } + + public virtual void Write(short value) + { + _bw.Write(value); + } + + public virtual void Write(int value) + { + _bw.Write(value); + } + + public virtual void Write(long value) + { + _bw.Write(value); + } + + protected override void Dispose(bool disposing) + { + if (__bw != null) + { + __bw.Close(); + } + if (__br != null) + { + __br.Close(); + } + if (__ns != null) + { + __ns.Close(); + } + base.Dispose(disposing); + } + } +} diff --git a/Common.GLib/GLib.Net/TCPService.cs b/Common.GLib/GLib.Net/TCPService.cs new file mode 100644 index 0000000000000000000000000000000000000000..04f01bacb5596da8155253a7f0a4e0020da7ff36 --- /dev/null +++ b/Common.GLib/GLib.Net/TCPService.cs @@ -0,0 +1,111 @@ +using GLib.GeneralModel; +using System; +using System.Net; +using System.Net.Sockets; +using System.Threading; + +namespace GLib.Net +{ + public class TCPService + { + private int _maxConnect = 256; + + private int _port = -1; + + private Socket _sock = null; + + private bool _working = false; + + private Thread _thread = null; + + public int Port => _port; + + public event EventHandler> Accepted; + + public TCPService(int port, int macConnect = 256) + { + _port = port; + _maxConnect = macConnect; + } + + public void Start() + { + lock (this) + { + if (!_working) + { + _working = true; + _thread = new Thread(AcceptThread); + _thread.Start(); + } + } + } + + public void Stop() + { + lock (this) + { + if (_working) + { + _working = false; + if (_thread != null) + { + _thread.Abort(); + _thread.Join(1000); + } + _thread = null; + try + { + if (_sock != null) + { + _sock.Close(); + _sock.Dispose(); + } + } + catch (Exception) + { + } + } + } + } + + private void AcceptThread() + { + _sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); + _sock.Bind(new IPEndPoint(IPAddress.Any, _port)); + _sock.Listen(_maxConnect); + while (true) + { + Socket state = _sock.Accept(); + ThreadPool.QueueUserWorkItem(OnAccept, state); + } + } + + private void OnAccept(object obj) + { + Socket socket = (Socket)obj; + try + { + if (this.Accepted != null) + { + this.Accepted(this, new EventArgsEx(socket)); + } + } + catch (Exception value) + { + try + { + if (socket != null) + { + socket.Close(); + socket.Dispose(); + } + } + catch + { + } + Console.WriteLine(value); + } + } + } +} diff --git a/Common.GLib/GLib.Net/TimeOutSocket.cs b/Common.GLib/GLib.Net/TimeOutSocket.cs new file mode 100644 index 0000000000000000000000000000000000000000..82446a63d5a196f7b0e3fed685a2c14e3764c192 --- /dev/null +++ b/Common.GLib/GLib.Net/TimeOutSocket.cs @@ -0,0 +1,59 @@ +using System; +using System.Net; +using System.Net.Sockets; +using System.Threading; + +namespace GLib.Net +{ + public static class TimeOutSocket + { + private static bool IsConnectionSuccessful = false; + + private static Exception socketexception; + + private static ManualResetEvent TimeoutObject = new ManualResetEvent(initialState: false); + + public static void Connect(Socket sock, string ip, int port, int timeoutMSec) + { + Connect(sock, new IPEndPoint(IPAddress.Parse(ip), port), timeoutMSec); + } + + public static void Connect(Socket sock, IPEndPoint remoteEndPoint, int timeoutMSec) + { + sock.BeginConnect(remoteEndPoint, CallBackMethod, sock); + if (TimeoutObject.WaitOne(timeoutMSec, exitContext: false)) + { + if (IsConnectionSuccessful) + { + return; + } + throw socketexception; + } + sock.Close(); + throw new TimeoutException("TimeOut Exception"); + } + + private static void CallBackMethod(IAsyncResult asyncresult) + { + try + { + IsConnectionSuccessful = false; + Socket socket = asyncresult.AsyncState as Socket; + if (socket != null) + { + socket.EndConnect(asyncresult); + IsConnectionSuccessful = true; + } + } + catch (Exception ex) + { + IsConnectionSuccessful = false; + socketexception = ex; + } + finally + { + TimeoutObject.Set(); + } + } + } +} diff --git a/Common.GLib/GLib.Serializer/SerializerHelper.cs b/Common.GLib/GLib.Serializer/SerializerHelper.cs new file mode 100644 index 0000000000000000000000000000000000000000..f126d955654925f0e45547de461ae22b5e2eba08 --- /dev/null +++ b/Common.GLib/GLib.Serializer/SerializerHelper.cs @@ -0,0 +1,105 @@ +using System; +using System.IO; +using System.Text; + +namespace GLib.Serializer +{ + public class SerializerHelper + { + public static string StringSerializer(object value) + { + string text = ""; + try + { + // NetDataContractSerializer netDataContractSerializer = new NetDataContractSerializer(); + MemoryStream memoryStream = new MemoryStream(); + // netDataContractSerializer.WriteObject(memoryStream, value); + byte[] array = memoryStream.ToArray(); + return Encoding.UTF8.GetString(array, 0, array.Length); + } + catch (Exception ex) + { + throw ex; + } + } + + public static object StringDeserialize(string value) + { + object obj = null; + try + { + // NetDataContractSerializer netDataContractSerializer = new NetDataContractSerializer(); + byte[] bytes = Encoding.UTF8.GetBytes(value); + MemoryStream memoryStream = new MemoryStream(bytes); + memoryStream.Seek(0L, SeekOrigin.Begin); + // return netDataContractSerializer.ReadObject(memoryStream); + return null; + } + catch (Exception ex) + { + throw ex; + } + } + + public static Stream StreamSerializer(object value) + { + Stream stream = null; + try + { + //NetDataContractSerializer netDataContractSerializer = new NetDataContractSerializer(); + MemoryStream memoryStream = new MemoryStream(); + // netDataContractSerializer.WriteObject(memoryStream, value); + stream = memoryStream; + stream.Seek(0L, SeekOrigin.Begin); + } + catch (Exception ex) + { + throw ex; + } + return stream; + } + + public static object StreamDeserialize(Stream value) + { + object obj = null; + if (!value.CanSeek) + { + value = GetNewStream(value); + } + try + { + //NetDataContractSerializer netDataContractSerializer = new NetDataContractSerializer(); + value.Seek(0L, SeekOrigin.Begin); + // return netDataContractSerializer.ReadObject(value); + return obj; + } + catch (Exception ex) + { + throw ex; + } + } + + public static T StreamDeserialize(Stream stream) + { + object obj = StreamDeserialize(stream); + if (obj is T) + { + return (T)obj; + } + return default(T); + } + + private static Stream GetNewStream(Stream value) + { + Stream stream = new MemoryStream(); + byte[] buffer = new byte[4096]; + int num = 0; + while ((num = value.Read(buffer, 0, 4096)) > 0) + { + stream.Write(buffer, 0, num); + } + stream.Seek(0L, SeekOrigin.Begin); + return stream; + } + } +} diff --git a/Common.GLib/GLib.Utilities.IO/DirectoryHelper.cs b/Common.GLib/GLib.Utilities.IO/DirectoryHelper.cs new file mode 100644 index 0000000000000000000000000000000000000000..4039662856b3f86ebbce81ddcbb254cf68d2ce51 --- /dev/null +++ b/Common.GLib/GLib.Utilities.IO/DirectoryHelper.cs @@ -0,0 +1,43 @@ +using System; +using System.IO; + +namespace GLib.Utilities.IO +{ + public class DirectoryHelper + { + public static string CreateMultiFolder(params string[] names) + { + string text = null; + if (names.Length > 0) + { + text = names[0]; + if (!Directory.Exists(text)) + { + Directory.CreateDirectory(text); + } + } + if (text != null) + { + for (int i = 1; i < names.Length; i++) + { + text = text + "\\" + names[i]; + if (!Directory.Exists(text)) + { + Directory.CreateDirectory(text); + } + } + return text + "\\"; + } + return null; + } + + public static string CreateMultiFolder(string path) + { + string[] names = path.Replace("\\\\", "\\").Split(new string[1] + { + "\\" + }, StringSplitOptions.RemoveEmptyEntries); + return CreateMultiFolder(names); + } + } +} diff --git a/Common.GLib/GLib.Utilities.IO/ExcelHelper.cs b/Common.GLib/GLib.Utilities.IO/ExcelHelper.cs new file mode 100644 index 0000000000000000000000000000000000000000..a94b434777578fdc4764be0ba4b0704409281dc9 --- /dev/null +++ b/Common.GLib/GLib.Utilities.IO/ExcelHelper.cs @@ -0,0 +1,37 @@ +using System.Data; +using System.Data.OleDb; + +namespace GLib.Utilities.IO +{ + public class ExcelHelper + { + public static DataTable ReadExcel(string fileName, string Sheet) + { + DataSet dataSet = new DataSet(); + string connectionString = "Provider=Microsoft.Jet.Oledb.4.0;Data Source=" + fileName + ";Extended Properties=Excel 8.0"; + OleDbConnection oleDbConnection = new OleDbConnection(connectionString); + try + { + oleDbConnection.Open(); + DataTable oleDbSchemaTable = oleDbConnection.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null); + string[] array = new string[oleDbSchemaTable.Rows.Count]; + int num = 0; + foreach (DataRow row in oleDbSchemaTable.Rows) + { + array[num] = row[2].ToString(); + num++; + } + for (int i = 0; i < array.Length; i++) + { + OleDbDataAdapter oleDbDataAdapter = new OleDbDataAdapter("SELECT * FROM [" + array[i] + "]", oleDbConnection); + oleDbDataAdapter.Fill(dataSet, "TEMPTABLE"); + } + } + catch + { + } + oleDbConnection.Close(); + return dataSet.Tables["TEMPTABLE"]; + } + } +} diff --git a/Common.GLib/GLib.Utilities.IO/FileHelper.cs b/Common.GLib/GLib.Utilities.IO/FileHelper.cs new file mode 100644 index 0000000000000000000000000000000000000000..9e9418dbcad21a0fba91eb9d30af292f1c872384 --- /dev/null +++ b/Common.GLib/GLib.Utilities.IO/FileHelper.cs @@ -0,0 +1,58 @@ +using System; +using System.IO; +using System.Text; + +namespace GLib.Utilities.IO +{ + public static class FileHelper + { + public static string CreateFileName() + { + Random random = new Random(); + return DateTime.Now.ToString("yyyyMMddHHmmss") + random.Next(1000, 9999); + } + + public static void WriteFile(string content) + { + WriteFile(string.Empty, string.Empty, content); + } + + public static void WriteFile(string fileName, string content) + { + WriteFile(string.Empty, fileName, content); + } + + public static void WriteFile(string path, string fileName, string content) + { + if (path == string.Empty) + { + path = AppDomain.CurrentDomain.BaseDirectory; + } + if (fileName == string.Empty) + { + fileName = CreateFileName() + ".log"; + } + if (!Directory.Exists(path)) + { + Directory.CreateDirectory(path); + } + path += fileName; + try + { + if (!File.Exists(path)) + { + FileStream fileStream = File.Create(path); + fileStream.Close(); + } + StreamWriter streamWriter = new StreamWriter(path, append: true, Encoding.Default); + streamWriter.Write(content); + streamWriter.Write("\r\n"); + streamWriter.Close(); + streamWriter.Dispose(); + } + catch (Exception) + { + } + } + } +} diff --git a/Common.GLib/GLib.Utilities.IO/FileType.cs b/Common.GLib/GLib.Utilities.IO/FileType.cs new file mode 100644 index 0000000000000000000000000000000000000000..65c81e3a0e3759522d79c488e6420308c8101b79 --- /dev/null +++ b/Common.GLib/GLib.Utilities.IO/FileType.cs @@ -0,0 +1,9 @@ +namespace GLib.Utilities.IO +{ + public enum FileType : short + { + Excel = 10, + Text = 20, + UnKnow = 0 + } +} diff --git a/Common.GLib/GLib.Utilities.IO/FileTypeHelper.cs b/Common.GLib/GLib.Utilities.IO/FileTypeHelper.cs new file mode 100644 index 0000000000000000000000000000000000000000..57be2af2866f0b31a5312fc0a987d89d283c3dd2 --- /dev/null +++ b/Common.GLib/GLib.Utilities.IO/FileTypeHelper.cs @@ -0,0 +1,21 @@ +using System.IO; + +namespace GLib.Utilities.IO +{ + public class FileTypeHelper + { + public static FileType GetFileType(string filename) + { + filename = filename.ToLower(); + switch (Path.GetExtension(filename)) + { + case ".txt": + return FileType.Text; + case ".xls": + return FileType.Excel; + default: + return FileType.UnKnow; + } + } + } +} diff --git a/Common.GLib/GLib.Utilities.IO/TxtHelper.cs b/Common.GLib/GLib.Utilities.IO/TxtHelper.cs new file mode 100644 index 0000000000000000000000000000000000000000..04f77b51aef0bf00a8e010bf56815c4abdf6eb4f --- /dev/null +++ b/Common.GLib/GLib.Utilities.IO/TxtHelper.cs @@ -0,0 +1,47 @@ +using System; +using System.Data; +using System.IO; +using System.Text; + +namespace GLib.Utilities.IO +{ + public class TxtHelper + { + public static DataTable ReadFile(string filename, string[] split) + { + try + { + StreamReader streamReader = new StreamReader(filename, Encoding.Default); + DataTable dataTable = new DataTable(); + int num = 0; + string text; + while ((text = streamReader.ReadLine()) != null) + { + string[] array = text.Split(split, StringSplitOptions.RemoveEmptyEntries); + if (num == 0) + { + for (int i = 0; i < array.Length; i++) + { + dataTable.Columns.Add(array[i]); + } + } + else + { + DataRow dataRow = dataTable.NewRow(); + for (int i = 0; i < array.Length; i++) + { + dataRow[i] = array[i]; + } + dataTable.Rows.Add(dataRow); + } + num++; + } + return dataTable; + } + catch (Exception) + { + } + return null; + } + } +} diff --git a/Common.GLib/GLib.Utilities.Security/DecryptHelper.cs b/Common.GLib/GLib.Utilities.Security/DecryptHelper.cs new file mode 100644 index 0000000000000000000000000000000000000000..fa7bea25c54cf9c7473d7f49c32fdb4b288094db --- /dev/null +++ b/Common.GLib/GLib.Utilities.Security/DecryptHelper.cs @@ -0,0 +1,37 @@ +using System; +using System.IO; +using System.Security.Cryptography; +using System.Text; + +namespace GLib.Utilities.Security +{ + public sealed class DecryptHelper + { + public static string DES(string source, string key) + { + DESCryptoServiceProvider dESCryptoServiceProvider = new DESCryptoServiceProvider(); + byte[] array = new byte[source.Length / 2]; + for (int i = 0; i < source.Length / 2; i++) + { + int num = Convert.ToInt32(source.Substring(i * 2, 2), 16); + array[i] = (byte)num; + } + dESCryptoServiceProvider.Key = Encoding.ASCII.GetBytes(key); + dESCryptoServiceProvider.IV = Encoding.ASCII.GetBytes(key); + MemoryStream memoryStream = new MemoryStream(); + CryptoStream cryptoStream = new CryptoStream(memoryStream, dESCryptoServiceProvider.CreateDecryptor(), CryptoStreamMode.Write); + cryptoStream.Write(array, 0, array.Length); + cryptoStream.FlushFinalBlock(); + return Encoding.Default.GetString(memoryStream.ToArray()); + } + + public static string Base64(string source) + { + if (!string.IsNullOrEmpty(source)) + { + return Encoding.ASCII.GetString(Convert.FromBase64String(source)); + } + return string.Empty; + } + } +} diff --git a/Common.GLib/GLib.Utilities.Security/EncryptHelper.cs b/Common.GLib/GLib.Utilities.Security/EncryptHelper.cs new file mode 100644 index 0000000000000000000000000000000000000000..245dda8563e022d5de53a5ec59c2dec438e7fec8 --- /dev/null +++ b/Common.GLib/GLib.Utilities.Security/EncryptHelper.cs @@ -0,0 +1,56 @@ +using System; +using System.IO; +using System.Security.Cryptography; +using System.Text; + +namespace GLib.Utilities.Security +{ + public sealed class EncryptHelper + { + public static string MD5(string source) + { + return GetMD5(source + "WEN@#!&*&*(~)_W#@!!@!^WEN!"); + } + + private static string GetMD5(string source) + { + MD5CryptoServiceProvider mD5CryptoServiceProvider = new MD5CryptoServiceProvider(); + mD5CryptoServiceProvider.ComputeHash(Encoding.ASCII.GetBytes(source)); + StringBuilder stringBuilder = new StringBuilder(); + byte[] hash = mD5CryptoServiceProvider.Hash; + foreach (byte b in hash) + { + stringBuilder.AppendFormat("{0:X2}", b); + } + return stringBuilder.ToString(); + } + + public static string DES(string source, string key) + { + DESCryptoServiceProvider dESCryptoServiceProvider = new DESCryptoServiceProvider(); + byte[] bytes = Encoding.Default.GetBytes(source); + dESCryptoServiceProvider.Key = Encoding.ASCII.GetBytes(key); + dESCryptoServiceProvider.IV = Encoding.ASCII.GetBytes(key); + MemoryStream memoryStream = new MemoryStream(); + CryptoStream cryptoStream = new CryptoStream(memoryStream, dESCryptoServiceProvider.CreateEncryptor(), CryptoStreamMode.Write); + cryptoStream.Write(bytes, 0, bytes.Length); + cryptoStream.FlushFinalBlock(); + StringBuilder stringBuilder = new StringBuilder(); + byte[] array = memoryStream.ToArray(); + foreach (byte b in array) + { + stringBuilder.AppendFormat("{0:X2}", b); + } + return stringBuilder.ToString(); + } + + public static string Base64(string source) + { + if (!string.IsNullOrEmpty(source)) + { + return Convert.ToBase64String(Encoding.Default.GetBytes(source)); + } + return string.Empty; + } + } +} diff --git a/Common.GLib/GLib.Utilities/Computer.cs b/Common.GLib/GLib.Utilities/Computer.cs new file mode 100644 index 0000000000000000000000000000000000000000..8a55d6da09bb38554b3bc618320c7deb8e978dae --- /dev/null +++ b/Common.GLib/GLib.Utilities/Computer.cs @@ -0,0 +1,207 @@ +using System; +using System.Management; + +namespace GLib.Utilities +{ + public class Computer + { + public string CpuID; + + public string MacAddress; + + public string DiskID; + + public string LoginUserName; + + public string ComputerName; + + public string SystemType; + + public string TotalPhysicalMemory; + + private static Computer _instance; + + public static Computer Instance() + { + if (_instance == null) + { + _instance = new Computer(); + } + return _instance; + } + + public Computer() + { + CpuID = GetCpuID(); + MacAddress = GetMacAddress(); + DiskID = GetDiskID(); + LoginUserName = GetUserName(); + SystemType = GetSystemType(); + TotalPhysicalMemory = GetTotalPhysicalMemory(); + ComputerName = GetComputerName(); + } + + private string GetCpuID() + { + try + { + string result = ""; + ManagementClass managementClass = new ManagementClass("Win32_Processor"); + ManagementObjectCollection instances = managementClass.GetInstances(); + foreach (ManagementObject item in instances) + { + result = item.Properties["ProcessorId"].Value.ToString(); + } + instances = null; + managementClass = null; + return result; + } + catch + { + return "unknow"; + } + finally + { + } + } + + private string GetMacAddress() + { + try + { + string result = ""; + ManagementClass managementClass = new ManagementClass("Win32_NetworkAdapterConfiguration"); + ManagementObjectCollection instances = managementClass.GetInstances(); + foreach (ManagementObject item in instances) + { + if ((bool)item["IPEnabled"]) + { + result = item["MacAddress"].ToString(); + break; + } + } + instances = null; + managementClass = null; + return result; + } + catch + { + return "unknow"; + } + finally + { + } + } + + private string GetDiskID() + { + try + { + string result = ""; + ManagementClass managementClass = new ManagementClass("Win32_DiskDrive"); + ManagementObjectCollection instances = managementClass.GetInstances(); + foreach (ManagementObject item in instances) + { + result = item.Properties["Model"].ToString(); + } + instances = null; + managementClass = null; + return result; + } + catch + { + return "unknow"; + } + finally + { + } + } + + private string GetUserName() + { + try + { + string result = ""; + ManagementClass managementClass = new ManagementClass("Win32_ComputerSystem"); + ManagementObjectCollection instances = managementClass.GetInstances(); + foreach (ManagementObject item in instances) + { + result = item["UserName"].ToString(); + } + instances = null; + managementClass = null; + return result; + } + catch + { + return "unknow"; + } + finally + { + } + } + + private string GetSystemType() + { + try + { + string result = ""; + ManagementClass managementClass = new ManagementClass("Win32_ComputerSystem"); + ManagementObjectCollection instances = managementClass.GetInstances(); + foreach (ManagementObject item in instances) + { + result = item["SystemType"].ToString(); + } + instances = null; + managementClass = null; + return result; + } + catch + { + return "unknow"; + } + finally + { + } + } + + private string GetTotalPhysicalMemory() + { + try + { + string result = ""; + ManagementClass managementClass = new ManagementClass("Win32_ComputerSystem"); + ManagementObjectCollection instances = managementClass.GetInstances(); + foreach (ManagementObject item in instances) + { + result = item["TotalPhysicalMemory"].ToString(); + } + instances = null; + managementClass = null; + return result; + } + catch + { + return "unknow"; + } + finally + { + } + } + + private string GetComputerName() + { + try + { + return Environment.GetEnvironmentVariable("ComputerName"); + } + catch + { + return "unknow"; + } + finally + { + } + } + } +} diff --git a/Common.GLib/GLib.Utilities/EmailSender.cs b/Common.GLib/GLib.Utilities/EmailSender.cs new file mode 100644 index 0000000000000000000000000000000000000000..4760ac99795b8b11ddef4a2915e50ef660c3a7ad --- /dev/null +++ b/Common.GLib/GLib.Utilities/EmailSender.cs @@ -0,0 +1,282 @@ +using System; +using System.Collections.Generic; +using System.Collections.Specialized; +using System.ComponentModel; +using System.Net; +using System.Net.Mail; +using System.Text; + +namespace GLib.Utilities +{ + public class EmailSender + { + private IList mailAttachmentList = new List(); + + private string message = ""; + + private SendState sendState = SendState.Sending; + + private StringCollection bcc = new StringCollection(); + + private StringCollection cc = new StringCollection(); + + private StringCollection to = new StringCollection(); + + public string Server + { + get; + set; + } + + public int ServerPort + { + get; + set; + } + + public string UserName + { + get; + set; + } + + public string Password + { + get; + set; + } + + public string From + { + get; + set; + } + + public string FromName + { + get; + set; + } + + public string Body + { + get; + set; + } + + public Encoding BodyEncoding + { + get; + set; + } + + public bool IsBodyHtml + { + get; + set; + } + + public MailPriority Priority + { + get; + set; + } + + public string ReplyTo + { + get; + set; + } + + public StringCollection Bcc => bcc; + + public StringCollection CC => cc; + + public MailAddress Sender + { + get; + set; + } + + public string Subject + { + get; + set; + } + + public Encoding SubjectEncoding + { + get; + set; + } + + public StringCollection To => to; + + public IList MailAttachmentList => mailAttachmentList; + + public char Delimiter + { + get; + set; + } + + public string Message => message; + + public SendState SendState => sendState; + + public EmailSender() + { + IsBodyHtml = true; + Priority = MailPriority.High; + BodyEncoding = Encoding.UTF8; + SubjectEncoding = Encoding.UTF8; + ServerPort = 25; + Delimiter = '='; + } + + public virtual bool Send() + { + if (string.IsNullOrEmpty(From)) + { + sendState = SendState.Error; + message = "没有发件人!"; + return false; + } + if (string.IsNullOrEmpty(Subject)) + { + sendState = SendState.Error; + message = "没有邮件标题!"; + return false; + } + if (string.IsNullOrEmpty(Body)) + { + sendState = SendState.Error; + message = "没有邮件正文!"; + return false; + } + if (To.Count < 1) + { + sendState = SendState.Error; + message = "没有收件人!"; + return false; + } + if (string.IsNullOrEmpty(Server)) + { + sendState = SendState.Error; + message = "没有设置邮件服务器地址!"; + return false; + } + if (string.IsNullOrEmpty(Password)) + { + sendState = SendState.Error; + message = "没有设置邮件服务器账号密码!"; + return false; + } + if (string.IsNullOrEmpty(UserName)) + { + UserName = From; + } + MailMessage mailMessage = new MailMessage(); + mailMessage.From = new MailAddress(From, FromName); + mailMessage.Subject = Subject.Trim(); + mailMessage.SubjectEncoding = SubjectEncoding; + mailMessage.Body = Body.Trim(); + mailMessage.BodyEncoding = BodyEncoding; + mailMessage.IsBodyHtml = IsBodyHtml; + foreach (string mailAttachment in mailAttachmentList) + { + mailMessage.Attachments.Add(new Attachment(mailAttachment)); + } + StringEnumerator enumerator2 = To.GetEnumerator(); + try + { + while (enumerator2.MoveNext()) + { + string current2 = enumerator2.Current; + string[] array = current2.Split(Delimiter); + MailAddress mailAddress = null; + mailAddress = ((array.Length <= 1) ? new MailAddress(array[0].Trim()) : new MailAddress(array[0].Trim(), array[1].Trim())); + mailMessage.To.Add(mailAddress); + } + } + finally + { + (enumerator2 as IDisposable)?.Dispose(); + } + if (Bcc.Count > 0) + { + enumerator2 = Bcc.GetEnumerator(); + try + { + while (enumerator2.MoveNext()) + { + string current3 = enumerator2.Current; + string[] array2 = current3.Split(Delimiter); + MailAddress mailAddress = null; + mailAddress = ((array2.Length <= 1) ? new MailAddress(array2[0].Trim()) : new MailAddress(array2[0].Trim(), array2[1].Trim())); + mailMessage.Bcc.Add(mailAddress); + } + } + finally + { + (enumerator2 as IDisposable)?.Dispose(); + } + } + if (CC.Count > 0) + { + enumerator2 = CC.GetEnumerator(); + try + { + while (enumerator2.MoveNext()) + { + string current3 = enumerator2.Current; + string[] array3 = current3.Split(Delimiter); + MailAddress mailAddress = null; + mailAddress = ((array3.Length <= 1) ? new MailAddress(array3[0].Trim()) : new MailAddress(array3[0].Trim(), array3[1].Trim())); + mailMessage.CC.Add(mailAddress); + } + } + finally + { + (enumerator2 as IDisposable)?.Dispose(); + } + } + try + { + SmtpClient smtpClient = new SmtpClient(Server, ServerPort); + smtpClient.Credentials = new NetworkCredential(UserName, Password); + smtpClient.SendCompleted += SendCompletedCallback; + string subject = Subject; + smtpClient.Send(mailMessage); + } + catch (Exception ex) + { + sendState = SendState.Error; + message = ex.Message; + return false; + } + mailMessage.Dispose(); + return true; + } + + private void SendCompletedCallback(object sender, AsyncCompletedEventArgs e) + { + string arg = (string)e.UserState; + if (e.Cancelled) + { + sendState = SendState.Canceled; + message = $"[{arg}] 发送取消"; + } + if (e.Error != null) + { + sendState = SendState.Error; + message = $"[{arg}] {e.Error.ToString()}"; + } + else + { + sendState = SendState.Succeed; + message = "发送成功"; + } + } + } +} diff --git a/Common.GLib/GLib.Utilities/ExportFormat.cs b/Common.GLib/GLib.Utilities/ExportFormat.cs new file mode 100644 index 0000000000000000000000000000000000000000..79cb227a1c7a63c9051d8f20f98417924d8a372e --- /dev/null +++ b/Common.GLib/GLib.Utilities/ExportFormat.cs @@ -0,0 +1,9 @@ +namespace GLib.Utilities +{ + public enum ExportFormat + { + CSV = 0, + DOC = 1, + TXT = 2 + } +} diff --git a/Common.GLib/GLib.Utilities/ExportHelper.cs b/Common.GLib/GLib.Utilities/ExportHelper.cs new file mode 100644 index 0000000000000000000000000000000000000000..4183fbdea6495544b51846887e3cc04d985172f1 --- /dev/null +++ b/Common.GLib/GLib.Utilities/ExportHelper.cs @@ -0,0 +1,206 @@ +using System.Collections.Generic; +using System.Data; +using System.IO; +using System.Text; +using System.Web; +using System.Xml; +using System.Xml.Xsl; + +namespace GLib.Utilities +{ + public class ExportHelper + { + public static void Export(DataTable dt, ExportFormat exportFormat, string fileName, Encoding encoding) + { + DataSet dataSet = new DataSet("Export"); + DataTable dataTable = dt.Copy(); + dataTable.TableName = "Values"; + dataSet.Tables.Add(dataTable); + string[] array = new string[dataTable.Columns.Count]; + string[] array2 = new string[dataTable.Columns.Count]; + for (int i = 0; i < dataTable.Columns.Count; i++) + { + array[i] = dataTable.Columns[i].ColumnName; + array2[i] = ReplaceSpecialChars(dataTable.Columns[i].ColumnName); + } + Export(dataSet, array, array2, exportFormat, fileName, encoding, null); + } + + public static void Export(DataTable dt, int[] columnIndexList, ExportFormat exportFormat, string fileName, Encoding encoding) + { + DataSet dataSet = new DataSet("Export"); + DataTable dataTable = dt.Copy(); + dataTable.TableName = "Values"; + dataSet.Tables.Add(dataTable); + string[] array = new string[columnIndexList.Length]; + string[] array2 = new string[columnIndexList.Length]; + for (int i = 0; i < columnIndexList.Length; i++) + { + array[i] = dataTable.Columns[columnIndexList[i]].ColumnName; + array2[i] = ReplaceSpecialChars(dataTable.Columns[columnIndexList[i]].ColumnName); + } + Export(dataSet, array, array2, exportFormat, fileName, encoding, null); + } + + public static void Export(DataTable dt, string[] columnNameList, ExportFormat exportFormat, string fileName, Encoding encoding) + { + List list = new List(); + DataColumnCollection columns = dt.Columns; + foreach (string columnName in columnNameList) + { + list.Add(GetColumnIndexByColumnName(columns, columnName)); + } + Export(dt, list.ToArray(), exportFormat, fileName, encoding); + } + + public static void Export(DataTable dt, int[] columnIndexList, string[] headers, ExportFormat exportFormat, string fileName, Encoding encoding) + { + DataSet dataSet = new DataSet("Export"); + DataTable dataTable = dt.Copy(); + dataTable.TableName = "Values"; + dataSet.Tables.Add(dataTable); + string[] array = new string[columnIndexList.Length]; + for (int i = 0; i < columnIndexList.Length; i++) + { + array[i] = ReplaceSpecialChars(dataTable.Columns[columnIndexList[i]].ColumnName); + } + Export(dataSet, headers, array, exportFormat, fileName, encoding, null); + } + + public static void Export(DataTable dt, int[] columnIndexList, string[] headers, ExportFormat exportFormat, string fileName, Encoding encoding, Dictionary function) + { + DataSet dataSet = new DataSet("Export"); + DataTable dataTable = dt.Copy(); + dataTable.TableName = "Values"; + dataSet.Tables.Add(dataTable); + string[] array = new string[columnIndexList.Length]; + for (int i = 0; i < columnIndexList.Length; i++) + { + array[i] = ReplaceSpecialChars(dataTable.Columns[columnIndexList[i]].ColumnName); + } + Export(dataSet, headers, array, exportFormat, fileName, encoding, function); + } + + public static void Export(DataTable dt, string[] columnNameList, string[] headers, ExportFormat exportFormat, string fileName, Encoding encoding) + { + List list = new List(); + DataColumnCollection columns = dt.Columns; + foreach (string columnName in columnNameList) + { + list.Add(GetColumnIndexByColumnName(columns, columnName)); + } + Export(dt, list.ToArray(), headers, exportFormat, fileName, encoding); + } + + public static void Export(DataTable dt, string[] columnNameList, string[] headers, ExportFormat exportFormat, string fileName, Encoding encoding, Dictionary function) + { + List list = new List(); + DataColumnCollection columns = dt.Columns; + foreach (string columnName in columnNameList) + { + list.Add(GetColumnIndexByColumnName(columns, columnName)); + } + Export(dt, list.ToArray(), headers, exportFormat, fileName, encoding, function); + } + + private static void Export(DataSet ds, string[] headers, string[] fields, ExportFormat exportFormat, string fileName, Encoding encoding, Dictionary function) + { + //HttpContext.Current.Response.Clear(); + //HttpContext.Current.Response.Buffer = true; + //HttpContext.Current.Response.ContentType = $"text/{exportFormat.ToString().ToLower()}"; + //HttpContext.Current.Response.AddHeader("content-disposition", $"attachment;filename={fileName}.{exportFormat.ToString().ToLower()}"); + //HttpContext.Current.Response.ContentEncoding = encoding; + MemoryStream memoryStream = new MemoryStream(); + XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream, encoding); + CreateStylesheet(xmlTextWriter, headers, fields, exportFormat, function); + xmlTextWriter.Flush(); + memoryStream.Seek(0L, SeekOrigin.Begin); + //XmlDataDocument input = new XmlDataDocument(ds); + XslCompiledTransform xslCompiledTransform = new XslCompiledTransform(); + xslCompiledTransform.Load(new XmlTextReader(memoryStream)); + StringWriter stringWriter = new StringWriter(); + //xslCompiledTransform.Transform(input, null, stringWriter); + // HttpContext.Current.Response.Write(stringWriter.ToString()); + stringWriter.Close(); + xmlTextWriter.Close(); + memoryStream.Close(); + // HttpContext.Current.Response.End(); + } + + private static void CreateStylesheet(XmlTextWriter writer, string[] headers, string[] fields, ExportFormat exportFormat, Dictionary function) + { + string ns = "http://www.w3.org/1999/XSL/Transform"; + writer.Formatting = Formatting.Indented; + writer.WriteStartDocument(); + writer.WriteStartElement("xsl", "stylesheet", ns); + writer.WriteAttributeString("version", "1.0"); + writer.WriteStartElement("xsl:output"); + writer.WriteAttributeString("method", "text"); + writer.WriteAttributeString("version", "4.0"); + writer.WriteEndElement(); + writer.WriteStartElement("xsl:template"); + writer.WriteAttributeString("match", "/"); + for (int i = 0; i < headers.Length; i++) + { + writer.WriteString("\""); + writer.WriteStartElement("xsl:value-of"); + writer.WriteAttributeString("select", "'" + headers[i] + "'"); + writer.WriteEndElement(); + writer.WriteString("\""); + if (i != fields.Length - 1) + { + writer.WriteString((exportFormat == ExportFormat.CSV) ? "," : "\t"); + } + } + writer.WriteStartElement("xsl:for-each"); + writer.WriteAttributeString("select", "Export/Values"); + writer.WriteString("\r\n"); + for (int i = 0; i < fields.Length; i++) + { + writer.WriteString("\""); + writer.WriteStartElement("xsl:value-of"); + if (function != null && function.ContainsKey(fields[i])) + { + string value = ""; + function.TryGetValue(fields[i], out value); + writer.WriteAttributeString("select", value); + } + else + { + writer.WriteAttributeString("select", fields[i]); + } + writer.WriteEndElement(); + writer.WriteString("\""); + if (i != fields.Length - 1) + { + writer.WriteString((exportFormat == ExportFormat.CSV) ? "," : "\t"); + } + } + writer.WriteEndElement(); + writer.WriteEndElement(); + writer.WriteEndElement(); + } + + public static string ReplaceSpecialChars(string input) + { + input = input.Replace(" ", "_x0020_").Replace("%", "_x0025_").Replace("#", "_x0023_") + .Replace("&", "_x0026_") + .Replace("/", "_x002F_"); + return input; + } + + public static int GetColumnIndexByColumnName(DataColumnCollection dcc, string columnName) + { + int result = -1; + for (int i = 0; i < dcc.Count; i++) + { + if (dcc[i].ColumnName.ToLower() == columnName.ToLower()) + { + result = i; + break; + } + } + return result; + } + } +} diff --git a/Common.GLib/GLib.Utilities/HtmlTag.cs b/Common.GLib/GLib.Utilities/HtmlTag.cs new file mode 100644 index 0000000000000000000000000000000000000000..54306f2eeae4ffe6074d1fb0380f84bfd5c633e0 --- /dev/null +++ b/Common.GLib/GLib.Utilities/HtmlTag.cs @@ -0,0 +1,176 @@ +using System.Collections; +using System.Collections.Generic; +using System.IO; +using System.Net; +using System.Text; +using System.Text.RegularExpressions; + +namespace GLib.Utilities +{ + public class HtmlTag + { + private string m_Name; + + private string m_BeginTag; + + private string m_InnerHTML; + + private Hashtable m_Attributes = new Hashtable(); + + private static Regex attrReg = new Regex("([a-zA-Z1-9_-]+)\\s*=\\s*(\\x27|\\x22)([^\\x27\\x22]*)(\\x27|\\x22)", RegexOptions.IgnoreCase); + + public string TagName => m_Name; + + public string InnerHTML => m_InnerHTML; + + private HtmlTag(string name, string beginTag, string innerHTML) + { + m_Name = name; + m_BeginTag = beginTag; + m_InnerHTML = innerHTML; + MatchCollection matchCollection = attrReg.Matches(beginTag); + foreach (Match item in matchCollection) + { + m_Attributes[item.Groups[1].Value.ToUpper()] = item.Groups[3].Value; + } + } + + public List FindTag(string name) + { + return FindTag(m_InnerHTML, name, $"<{name}(\\s[^<>]*|)>"); + } + + public List FindTag(string name, string format) + { + return FindTag(m_InnerHTML, name, format); + } + + public List FindTagByAttr(string tagName, string attrName, string attrValue) + { + return FindTagByAttr(m_InnerHTML, tagName, attrName, attrValue); + } + + public List FindNoEndTag(string name) + { + return FindNoEndTag(m_InnerHTML, name, $"<{name}(\\s[^<>]*|)>"); + } + + public List FindNoEndTag(string name, string format) + { + return FindNoEndTag(m_InnerHTML, name, format); + } + + public List FindNoEndTagByAttr(string tagName, string attrName, string attrValue) + { + return FindNoEndTagByAttr(m_InnerHTML, tagName, attrName, attrValue); + } + + public string GetAttribute(string name) + { + return m_Attributes[name.ToUpper()] as string; + } + + public static string GetHtml(string url) + { + try + { + HttpWebRequest httpWebRequest = WebRequest.Create(url) as HttpWebRequest; + httpWebRequest.Timeout = 30000; + HttpWebResponse httpWebResponse = httpWebRequest.GetResponse() as HttpWebResponse; + Stream responseStream = httpWebResponse.GetResponseStream(); + MemoryStream memoryStream = new MemoryStream(); + byte[] buffer = new byte[4096]; + int num = 0; + while ((num = responseStream.Read(buffer, 0, 4096)) > 0) + { + memoryStream.Write(buffer, 0, num); + } + return Encoding.GetEncoding(httpWebResponse.CharacterSet).GetString(memoryStream.GetBuffer()); + } + catch + { + return string.Empty; + } + } + + public static List FindTagByAttr(string html, string tagName, string attrName, string attrValue) + { + string format = $"<{tagName}\\s[^<>]*{attrName}\\s*=\\s*(\\x27|\\x22){attrValue}(\\x27|\\x22)[^<>]*>"; + return FindTag(html, tagName, format); + } + + public static List FindTag(string html, string name, string format) + { + Regex regex = new Regex(format, RegexOptions.IgnoreCase); + Regex regex2 = new Regex($"<(\\/|)({name})(\\s[^<>]*|)>", RegexOptions.IgnoreCase); + List list = new List(); + int startat = 0; + while (true) + { + bool flag = true; + Match match = regex.Match(html, startat); + if (!match.Success) + { + break; + } + startat = match.Index + match.Length; + Match match2 = null; + int num = 1; + do + { + flag = true; + match2 = regex2.Match(html, startat); + if (!match2.Success) + { + match2 = null; + break; + } + startat = match2.Index + match2.Length; + num = ((!(match2.Groups[1].Value == "/")) ? (num + 1) : (num - 1)); + } + while (num != 0); + if (match2 != null) + { + HtmlTag item = new HtmlTag(name, match.Value, html.Substring(match.Index + match.Length, match2.Index - match.Index - match.Length)); + list.Add(item); + continue; + } + break; + } + return list; + } + + public static List FindNoEndTagByAttr(string html, string tagName, string attrName, string attrValue) + { + string format = $"<{tagName}\\s[^<>]*{attrName}\\s*=\\s*(\\x27|\\x22){attrValue}(\\x27|\\x22)[^<>]*>"; + return FindNoEndTag(html, tagName, format); + } + + public static List FindNoEndTag(string html, string name, string format) + { + Regex regex = new Regex(format, RegexOptions.IgnoreCase); + Regex regex2 = new Regex($"<({name})(\\s[^<>]*|)(\\/)+>", RegexOptions.IgnoreCase); + List list = new List(); + int startat = 0; + while (true) + { + bool flag = true; + Match match = regex.Match(html, startat); + if (match.Success) + { + startat = match.Index + match.Length; + Match match2 = match; + if (match2 != null) + { + HtmlTag item = new HtmlTag(name, match.Value, string.Empty); + list.Add(item); + continue; + } + break; + } + break; + } + return list; + } + } +} diff --git a/Common.GLib/GLib.Utilities/IPHelper.cs b/Common.GLib/GLib.Utilities/IPHelper.cs new file mode 100644 index 0000000000000000000000000000000000000000..73ef1f72f1dd82b13fc0e43c29cfa3b50f9a801d --- /dev/null +++ b/Common.GLib/GLib.Utilities/IPHelper.cs @@ -0,0 +1,53 @@ +using System.Management; +using System.Web; + +namespace GLib.Utilities +{ + public class IPHelper + { + public static string GetServerIPAddress() + { + string result = ""; + ManagementClass managementClass = new ManagementClass("Win32_NetworkAdapterConfiguration"); + ManagementObjectCollection instances = managementClass.GetInstances(); + foreach (ManagementObject item in instances) + { + if ((bool)item["IPEnabled"]) + { + string[] array = (string[])item["IPAddress"]; + if (array.Length > 0) + { + result = array[0]; + } + } + } + return result; + } + + public static string GetServerMACAddress() + { + string text = ""; + ManagementClass managementClass = new ManagementClass("Win32_NetworkAdapterConfiguration"); + ManagementObjectCollection instances = managementClass.GetInstances(); + foreach (ManagementObject item in instances) + { + if ((bool)item["IPEnabled"]) + { + text += item["MACAddress"].ToString(); + } + } + return text; + } + + public static string GetIPAddress() + { + //string text = (HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != null && HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] != string.Empty) ? HttpContext.Current.Request.ServerVariables["HTTP_X_FORWARDED_FOR"] : HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"]; + //if (string.IsNullOrEmpty(text)) + //{ + // text = HttpContext.Current.Request.UserHostAddress; + //} + //return text; + return string.Empty; + } + } +} diff --git a/Common.GLib/GLib.Utilities/IniFile.cs b/Common.GLib/GLib.Utilities/IniFile.cs new file mode 100644 index 0000000000000000000000000000000000000000..dfdf9c748e00e0c5581fedb3a08660d8cf944ff6 --- /dev/null +++ b/Common.GLib/GLib.Utilities/IniFile.cs @@ -0,0 +1,214 @@ +using System; +using System.Collections.Specialized; +using System.IO; +using System.Runtime.InteropServices; +using System.Text; + +namespace GLib.Utilities +{ + public class IniFile + { + public string FileName; + + [DllImport("kernel32")] + private static extern bool WritePrivateProfileString(string section, string key, string val, string filePath); + + [DllImport("kernel32")] + private static extern int GetPrivateProfileString(string section, string key, string def, byte[] retVal, int size, string filePath); + + public IniFile(string IniFileName, bool ForceCreate) + { + FileInfo fileInfo = new FileInfo(IniFileName); + if (!fileInfo.Exists) + { + if (!ForceCreate) + { + throw new ApplicationException("Ini文件不存在"); + } + fileInfo.Directory.Create(); + fileInfo.Create(); + } + FileName = fileInfo.FullName; + } + + public void WriteString(string Section, string Ident, string Value) + { + if (!WritePrivateProfileString(Section, Ident, Value, FileName)) + { + throw new ApplicationException("写Ini文件出错"); + } + } + + public string ReadString(string Section, string Ident, string Default) + { + byte[] array = new byte[65535]; + int privateProfileString = GetPrivateProfileString(Section, Ident, Default, array, array.GetUpperBound(0), FileName); + string @string = Encoding.GetEncoding(0).GetString(array); + @string = @string.Substring(0, privateProfileString); + return @string.Trim(); + } + + public int ReadInteger(string Section, string Ident, int Default) + { + string value = ReadString(Section, Ident, Default.ToString()); + try + { + return Convert.ToInt32(value); + } + catch (Exception) + { + return Default; + } + } + + public void WriteInteger(string Section, string Ident, int Value) + { + WriteString(Section, Ident, Value.ToString()); + } + + public bool ReadBool(string Section, string Ident, bool Default) + { + try + { + return Convert.ToBoolean(ReadString(Section, Ident, Default.ToString())); + } + catch (Exception) + { + return Default; + } + } + + public void WriteBool(string Section, string Ident, bool Value) + { + WriteString(Section, Ident, Value.ToString()); + } + + public void WriteDateTime(string Section, string Ident, DateTime Value) + { + WriteString(Section, Ident, Value.ToString()); + } + + public DateTime ReadDateTime(string Section, string Ident, DateTime Default) + { + try + { + return Convert.ToDateTime(ReadString(Section, Ident, Default.ToString())); + } + catch (Exception) + { + return Default; + } + } + + public void WriteDouble(string Section, string Ident, double Value) + { + WriteString(Section, Ident, Value.ToString()); + } + + public double ReadFloat(string Section, string Ident, double Default) + { + try + { + return Convert.ToDouble(ReadString(Section, Ident, Default.ToString())); + } + catch (Exception) + { + return Default; + } + } + + public StringCollection ReadSection(string Section) + { + byte[] array = new byte[16384]; + StringCollection stringCollection = new StringCollection(); + int privateProfileString = GetPrivateProfileString(Section, null, null, array, array.GetUpperBound(0), FileName); + GetStringsFromBuffer(array, privateProfileString, stringCollection); + return stringCollection; + } + + private void GetStringsFromBuffer(byte[] Buffer, int bufLen, StringCollection Strings) + { + Strings.Clear(); + if (bufLen == 0) + { + return; + } + int num = 0; + for (int i = 0; i < bufLen; i++) + { + if (Buffer[i] == 0 && i - num > 0) + { + string @string = Encoding.GetEncoding(0).GetString(Buffer, num, i - num); + Strings.Add(@string); + num = i + 1; + } + } + } + + public StringCollection ReadSections() + { + StringCollection stringCollection = new StringCollection(); + byte[] array = new byte[65535]; + int num = 0; + num = GetPrivateProfileString(null, null, null, array, array.GetUpperBound(0), FileName); + GetStringsFromBuffer(array, num, stringCollection); + return stringCollection; + } + + public NameValueCollection ReadSectionValues(string Section) + { + NameValueCollection nameValueCollection = new NameValueCollection(); + StringCollection stringCollection = ReadSection(Section); + nameValueCollection.Clear(); + StringEnumerator enumerator = stringCollection.GetEnumerator(); + try + { + while (enumerator.MoveNext()) + { + string current = enumerator.Current; + nameValueCollection.Add(current, ReadString(Section, current, "")); + } + } + finally + { + (enumerator as IDisposable)?.Dispose(); + } + return nameValueCollection; + } + + public void EraseSection(string Section) + { + if (!WritePrivateProfileString(Section, null, null, FileName)) + { + throw new ApplicationException("无法清除Ini文件中的Section"); + } + } + + public void DeleteKey(string Section, string Ident) + { + WritePrivateProfileString(Section, Ident, null, FileName); + } + + public void UpdateFile() + { + WritePrivateProfileString(null, null, null, FileName); + } + + public bool SectionExists(string Section) + { + StringCollection stringCollection = ReadSections(); + return stringCollection.IndexOf(Section) > -1; + } + + public bool ValueExists(string Section, string Ident) + { + StringCollection stringCollection = ReadSection(Section); + return stringCollection.IndexOf(Ident) > -1; + } + + ~IniFile() + { + UpdateFile(); + } + } +} diff --git a/Common.GLib/GLib.Utilities/JsonSerializer.cs b/Common.GLib/GLib.Utilities/JsonSerializer.cs new file mode 100644 index 0000000000000000000000000000000000000000..ea243eaf0a6f927a4f22e3042c713447968aa998 --- /dev/null +++ b/Common.GLib/GLib.Utilities/JsonSerializer.cs @@ -0,0 +1,20 @@ +using System; +using System.IO; +using System.Runtime.Serialization.Json; +using System.Text; + +namespace GLib.Utilities +{ + public class JsonSerializer + { + public static T ParseFromJson(string szJson) + { + T val = Activator.CreateInstance(); + using (MemoryStream stream = new MemoryStream(Encoding.UTF8.GetBytes(szJson))) + { + DataContractJsonSerializer dataContractJsonSerializer = new DataContractJsonSerializer(val.GetType()); + return (T)dataContractJsonSerializer.ReadObject(stream); + } + } + } +} diff --git a/Common.GLib/GLib.Utilities/SendState.cs b/Common.GLib/GLib.Utilities/SendState.cs new file mode 100644 index 0000000000000000000000000000000000000000..2b8a0ee062c0db2ebd50e61112170c9bb86ca400 --- /dev/null +++ b/Common.GLib/GLib.Utilities/SendState.cs @@ -0,0 +1,10 @@ +namespace GLib.Utilities +{ + public enum SendState + { + Canceled = 0, + Succeed = 1, + Error = 2, + Sending = 3 + } +} diff --git a/Common.GLib/GLib.Utilities/StringHelper.cs b/Common.GLib/GLib.Utilities/StringHelper.cs new file mode 100644 index 0000000000000000000000000000000000000000..340e2e6f9e9d3cf94d3057ea029daecc9d6d8dbf --- /dev/null +++ b/Common.GLib/GLib.Utilities/StringHelper.cs @@ -0,0 +1,48 @@ +using GLib.Data.Entity; +using System; +using System.Collections.Generic; +using System.Data; +using System.Text; + +namespace GLib.Utilities +{ + public class StringHelper + { + public static string GetOrSelector(string col, string strid, out IList outlist) + { + string[] array = strid.Split(new char[1] + { + ',' + }, StringSplitOptions.RemoveEmptyEntries); + StringBuilder stringBuilder = new StringBuilder(); + outlist = new List(); + for (int i = 0; i < array.Length; i++) + { + if (i == 0) + { + stringBuilder.Append(" " + col + "=@" + i); + } + else + { + stringBuilder.Append(" or " + col + "=@" + i); + } + outlist.Add(new DBParam + { + ParamDbType = DbType.Int32, + ParamValue = int.Parse(array[i]) + }); + } + return stringBuilder.ToString(); + } + + public static string FormatSqlString(string strInput) + { + return strInput.Replace("'", "''"); + } + + public static string FormatDataTime(DateTime dt) + { + return dt.ToString("yyyy-MM-dd HH:mm"); + } + } +} diff --git a/Common.GLib/GLib.Web/HttpCache.cs b/Common.GLib/GLib.Web/HttpCache.cs new file mode 100644 index 0000000000000000000000000000000000000000..9f208f8b3a6224339e1ee89c0f1bf068c190a9b4 --- /dev/null +++ b/Common.GLib/GLib.Web/HttpCache.cs @@ -0,0 +1,114 @@ +using System; +using System.Collections.Generic; +using System.Web; +//using System.Web.Caching; + +namespace GLib.Web +{ + + class Cache + { + + } + + + public class HttpCache + { + //protected static Cache _cache = null; + + private static void InitCache() + { + try + { +// _cache = HttpRuntime.Cache; + } + catch (Exception ex) + { + throw ex; + } + } + + public static bool SetCache(string cacheKey, object value) + { + //if (_cache == null) + //{ + // InitCache(); + //} + bool flag = false; + try + { + // _cache[cacheKey] = value; + return true; + } + catch (Exception ex) + { + throw ex; + } + } + + public static bool SetCache(string cacheKey, object value, int hours) + { + TimeSpan span = new TimeSpan(hours, 0, 0); + return SetCache(cacheKey, value, span); + } + + public static bool SetCache(string cacheKey, object value, TimeSpan span) + { + //if (_cache == null) + //{ + // InitCache(); + //} + bool flag = false; + try + { + // _cache.Insert(cacheKey, value, null, DateTime.MaxValue, span); + return true; + } + catch (Exception ex) + { + throw ex; + } + } + + public static object GetCache(string cacheKey) + { + //if (_cache == null) + //{ + // return null; + //} + object obj = null; + try + { + // obj = _cache[cacheKey]; + } + catch (Exception ex) + { + throw ex; + } + return obj; + } + + public static T GetCache(string cacheKey) where T : new() + { + //if (_cache == null) + //{ + // return default(T); + //} + T val = default(T); + try + { + //// object obj = _cache[cacheKey]; + // if (!(obj is T)) + // { + // throw new Exception("未能将对象强制转换"); + // } + // val = (T)obj; + } + catch (Exception ex) + { + throw ex; + } + return val; + } + } +} diff --git a/Common.GLib/GLib.Web/HttpSession.cs b/Common.GLib/GLib.Web/HttpSession.cs new file mode 100644 index 0000000000000000000000000000000000000000..a96a4fe8cb3b01f601b119d5bbad79ef9a0d51c9 --- /dev/null +++ b/Common.GLib/GLib.Web/HttpSession.cs @@ -0,0 +1,76 @@ +using System; +using System.Web; + +namespace GLib.Web +{ + public class HttpSession + { + public static bool SetSession(string sessionKey, object value) + { + bool result = false; + //if (HttpContext.Current != null && HttpContext.Current.Session != null) + //{ + // try + // { + // HttpContext.Current.Session[sessionKey] = value; + // result = true; + // } + // catch (Exception ex) + // { + // throw ex; + // } + //} + return result; + } + + public static object GetSession(string sessionKey) + { + object result = null; + //if (HttpContext.Current != null && HttpContext.Current.Session != null) + //{ + // try + // { + // result = HttpContext.Current.Session[sessionKey]; + // } + // catch (Exception ex) + // { + // throw ex; + // } + //} + return result; + } + + public static T GetSession(string sessionKey) + { + T result = default(T); + object session = GetSession(sessionKey); + if (session != null) + { + if (session is T) + { + return (T)session; + } + throw new Exception($"对象不能强制转换为\"{typeof(T).ToString()}\"类型"); + } + return result; + } + + public static void ClearSession() + { + //if (HttpContext.Current != null && HttpContext.Current.Session != null) + //{ + // HttpContext.Current.Session.Clear(); + //} + } + + public static string GetSessionId() + { + //if (HttpContext.Current != null && HttpContext.Current.Session != null) + //{ + // return HttpContext.Current.Session.SessionID; + //} + //throw new Exception("Session未实例化"); + return string.Empty; + } + } +} diff --git a/Common.GLib/GLib.Web/Warn.cs b/Common.GLib/GLib.Web/Warn.cs new file mode 100644 index 0000000000000000000000000000000000000000..81c7a6ec57f3ce4b16acdd29279f2b6ffdaf1df8 --- /dev/null +++ b/Common.GLib/GLib.Web/Warn.cs @@ -0,0 +1,42 @@ +using System; + +namespace GLib.Web +{ + public abstract class Warn : Exception + { + public virtual Warn InnerWarn + { + get; + protected set; + } + + public virtual WarnDescription Description + { + get; + protected set; + } + + public Warn(WarnDescription wd) + : base(wd.Description) + { + Description = wd; + } + + public Warn(WarnDescription wd, Warn inner) + { + InnerWarn = inner; + Description = wd; + } + + public void Execute() + { + if (InnerWarn != null) + { + InnerWarn.Execute(); + } + DoExecute(); + } + + protected abstract void DoExecute(); + } +} diff --git a/Common.GLib/GLib.Web/WarnDescription.cs b/Common.GLib/GLib.Web/WarnDescription.cs new file mode 100644 index 0000000000000000000000000000000000000000..dfaebf37fdcb45e7ceaba9b7298a896e85c9a25d --- /dev/null +++ b/Common.GLib/GLib.Web/WarnDescription.cs @@ -0,0 +1,46 @@ +using System; + +namespace GLib.Web +{ + public class WarnDescription + { + public string Title + { + get; + set; + } + + public string Description + { + get; + set; + } + + public int HelpCode + { + get; + set; + } + + public virtual Exception Original + { + get; + set; + } + + protected WarnDescription() + { + } + + public WarnDescription(string description) + { + Description = description; + } + + public WarnDescription(Exception exc) + { + Description = exc.Message; + Original = exc; + } + } +} diff --git a/Common.GLib/GLib/AuxiliaryFieldAttribute.cs b/Common.GLib/GLib/AuxiliaryFieldAttribute.cs new file mode 100644 index 0000000000000000000000000000000000000000..0492257ca393039ebb26f4d2de7a58ce26868d54 --- /dev/null +++ b/Common.GLib/GLib/AuxiliaryFieldAttribute.cs @@ -0,0 +1,9 @@ +using System; + +namespace GLib +{ + [AttributeUsage(AttributeTargets.Enum | AttributeTargets.Field)] + public class AuxiliaryFieldAttribute : Attribute + { + } +} diff --git a/Common.GLib/GLib/DebugEx.cs b/Common.GLib/GLib/DebugEx.cs new file mode 100644 index 0000000000000000000000000000000000000000..4824a63ca9fc44ec2fc2958c95917ad9cbb2ad8f --- /dev/null +++ b/Common.GLib/GLib/DebugEx.cs @@ -0,0 +1,119 @@ +using System; +using System.Reflection; +using System.Text; +using System.Threading; + +namespace GLib +{ + public class DebugEx + { + private static string _appName = ""; + + private static Action _unhandledExceptionCallBack = null; + + private static bool _alertExceptionMsg = false; + + //public static string LogPath = Application.StartupPath + "\\log\\"; + + public static string Version = Assembly.GetExecutingAssembly().GetName().Version.ToString(); + + public static event Action EvtTrace; + + public static void Trace(string flag, string msg) + { + string text = $"{flag}___{msg}"; + Console.WriteLine(text); + if (EvtTrace != null) + { + EvtTrace(text); + } + } + + public static void RegisterUnHandldException() + { + //RegisterUnHandldException(Application.ProductName, null, alertExceptionMsg: true); + } + + public static void RegisterUnHandldException(string appName, Action unhandledExceptionCallBack, bool alertExceptionMsg = false) + { + _appName = appName; + _alertExceptionMsg = alertExceptionMsg; + _unhandledExceptionCallBack = unhandledExceptionCallBack; + // Application.ThreadException += Application_ThreadException; + AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException; + } + + private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e) + { + OnFatalException(e.ExceptionObject as Exception); + if (e.IsTerminating && _unhandledExceptionCallBack != null) + { + _unhandledExceptionCallBack(e); + } + } + + private static void Application_ThreadException(object sender, ThreadExceptionEventArgs e) + { + OnFatalException(e.Exception); + } + + public static void OnFatalException(Exception ex, bool isEnd = false) + { + StringBuilder stringBuilder = new StringBuilder(); + string text = ""; + string version = Version; + text = $"{_appName} {version} {DateTime.Now}"; + if (isEnd) + { + text = string.Format("=================致命错误==================\r\n{0} {1}", _appName, ""); + } + stringBuilder.AppendLine(text); + stringBuilder.AppendLine(GetErrorString(ex)); + WriteLog(stringBuilder.ToString()); + string text2 = $"{text}出现一个未处理的异常\r\n请将程序安装目录下的日志反馈给软件提供商。\r\n详细信息:{ex.Message + ex.StackTrace}\r\n发生时间:{DateTime.Now}"; + if (!_alertExceptionMsg) + { + } + } + + public static string GetLog(Exception ex, bool isEnd = false) + { + StringBuilder stringBuilder = new StringBuilder(); + string text = ""; + string arg = Assembly.GetExecutingAssembly().GetName().Version.ToString(); + text = $"{_appName} {arg} {DateTime.Now}"; + if (isEnd) + { + text = string.Format("=================致命错误==================\r\n{0} {1}", _appName, ""); + } + stringBuilder.AppendLine(text); + stringBuilder.AppendLine(GetErrorString(ex)); + return stringBuilder.ToString(); + } + + public static void WriteLog(string msg) + { + //// string text = LogPath.ToSystemPath(); + // if (!Directory.Exists(text)) + // { + // Directory.CreateDirectory(text); + // } + // string path = string.Format("{0}\\Log_{1}.txt", text, DateTime.Now.ToString("yyyy-MM-dd")).ToSystemPath(); + // File.AppendAllText(path, msg + "\r\n", Encoding.UTF8); + } + + private static string GetErrorString(Exception ex, string pleft = "") + { + StringBuilder stringBuilder = new StringBuilder(); + stringBuilder.AppendLine(pleft + ex.Message); + stringBuilder.AppendLine(pleft + ex.GetType().Name); + stringBuilder.AppendLine(pleft + ex.StackTrace); + if (ex.InnerException != null) + { + stringBuilder.AppendLine("---------------------------------------------->"); + stringBuilder.AppendLine(GetErrorString(ex.InnerException, pleft + " ")); + } + return stringBuilder.ToString(); + } + } +} diff --git a/Common.GLib/GLib/DescriptionAttribute.cs b/Common.GLib/GLib/DescriptionAttribute.cs new file mode 100644 index 0000000000000000000000000000000000000000..a1c5c5454b1a0a4ad23acd2f47a174f14174d8c9 --- /dev/null +++ b/Common.GLib/GLib/DescriptionAttribute.cs @@ -0,0 +1,133 @@ +using System; +using System.Collections.Generic; +using System.Reflection; + +namespace GLib +{ + [AttributeUsage(AttributeTargets.All)] + public class DescriptionAttribute : Attribute + { + public string Description + { + get; + set; + } + + public string Name + { + get; + set; + } + + public object DefaultValue + { + get; + set; + } + + public static DescriptionAttribute GetDescription(object value) + { + return GetDescription(value.GetType(), DescriptionObjectType.Type, null, inherit: false); + } + + public static DescriptionAttribute GetDescription(Type attributeType) + { + return GetDescription(attributeType, DescriptionObjectType.Type, null, inherit: false); + } + + public static DescriptionAttribute GetDescription(Type attributeType, bool inherit) + { + return GetDescription(attributeType, DescriptionObjectType.Type, null, inherit); + } + + public static DescriptionAttribute GetDescription(Type attributeType, DescriptionObjectType objectType, string name) + { + return GetDescription(attributeType, objectType, name, inherit: false); + } + + public static DescriptionAttribute GetDescription(Type attributeType, DescriptionObjectType objectType, string name, bool inherit) + { + MemberInfo memberInfo = null; + object[] array = null; + Type typeFromHandle = typeof(DescriptionAttribute); + switch (objectType) + { + case DescriptionObjectType.Event: + memberInfo = attributeType.GetEvent(name); + break; + case DescriptionObjectType.Field: + memberInfo = attributeType.GetField(name); + break; + case DescriptionObjectType.Method: + memberInfo = attributeType.GetMethod(name); + break; + case DescriptionObjectType.Property: + memberInfo = attributeType.GetProperty(name); + break; + } + array = ((DescriptionObjectType.Type != objectType) ? memberInfo.GetCustomAttributes(typeFromHandle, inherit) : attributeType.GetCustomAttributes(typeFromHandle, inherit)); + if (array != null && array.Length > 0) + { + return (DescriptionAttribute)array[0]; + } + return null; + } + + public static DescriptionAttribute GetEnumDescription(object value) + { + Type type = value.GetType(); + if (!type.IsEnum) + { + throw new ArgumentNullException("参数类型必须为枚举类型"); + } + string[] array = value.ToString().Split(','); + IList list = new List(); + string[] array2 = array; + foreach (string text in array2) + { + if (!(text.Trim() != "")) + { + continue; + } + FieldInfo field = type.GetField(text.Trim()); + if (field != null && field.GetCustomAttributes(typeof(AuxiliaryFieldAttribute), inherit: true).Length == 0) + { + object[] customAttributes = field.GetCustomAttributes(typeof(DescriptionAttribute), inherit: true); + if (customAttributes.Length > 0) + { + list.Add((DescriptionAttribute)customAttributes[0]); + } + } + } + if (list.Count > 1) + { + DescriptionAttribute descriptionAttribute = new DescriptionAttribute(); + int num = 0; + foreach (DescriptionAttribute item in list) + { + if (num == 0) + { + descriptionAttribute = item; + } + else + { + DescriptionAttribute descriptionAttribute2 = descriptionAttribute; + descriptionAttribute2.Name = descriptionAttribute2.Name + "," + item.Name; + } + num++; + } + return descriptionAttribute; + } + if (list.Count > 0) + { + return list[0]; + } + return null; + } + + public override string ToString() + { + return Name; + } + } +} diff --git a/Common.GLib/GLib/DescriptionObjectType.cs b/Common.GLib/GLib/DescriptionObjectType.cs new file mode 100644 index 0000000000000000000000000000000000000000..7be48eb544724e95a1cdae788a45a000b0a13632 --- /dev/null +++ b/Common.GLib/GLib/DescriptionObjectType.cs @@ -0,0 +1,11 @@ +namespace GLib +{ + public enum DescriptionObjectType + { + Event = 1, + Method = 2, + Field = 4, + Property = 8, + Type = 0x10 + } +} diff --git a/Common.GLib/GLib/MyTask.cs b/Common.GLib/GLib/MyTask.cs new file mode 100644 index 0000000000000000000000000000000000000000..aaf1e39ed92fa437ff59b409d942064c99e1543e --- /dev/null +++ b/Common.GLib/GLib/MyTask.cs @@ -0,0 +1,48 @@ +using System; +using System.Threading; + +namespace GLib +{ + public static class MyTask + { + private static ApartmentState ApartmentState = ApartmentState.MTA; + + public static TResult CallTask(this Func fun, TArg arg) + { + TResult result = default(TResult); + Thread thread = new Thread(((Action)delegate + { + result = fun(arg); + }).Invoke); + thread.IsBackground = true; + thread.Priority = ThreadPriority.Lowest; + thread.SetApartmentState(ApartmentState); + thread.Start(); + thread.Join(); + return result; + } + + public static void CallTask(this Action act, TArg arg) + { + Thread thread = new Thread(((Action)delegate + { + act(arg); + }).Invoke); + thread.IsBackground = true; + thread.Priority = ThreadPriority.Lowest; + thread.SetApartmentState(ApartmentState); + thread.Start(); + thread.Join(); + } + + public static void CallTask(this Action act) + { + Thread thread = new Thread(act.Invoke); + thread.IsBackground = true; + thread.Priority = ThreadPriority.Lowest; + thread.SetApartmentState(ApartmentState); + thread.Start(); + thread.Join(); + } + } +} diff --git a/Common.GLib/MSQueue.cs b/Common.GLib/MSQueue.cs new file mode 100644 index 0000000000000000000000000000000000000000..89e9237855d9784f7a967caac3545bd4115705ac --- /dev/null +++ b/Common.GLib/MSQueue.cs @@ -0,0 +1,126 @@ +using System.Threading; + +public class MSQueue +{ + private class node_t + { + public T value; + + public pointer_t next; + } + + private struct pointer_t + { + public long count; + + public node_t ptr; + + public pointer_t(pointer_t p) + { + ptr = p.ptr; + count = p.count; + } + + public pointer_t(node_t node, long c) + { + ptr = node; + count = c; + } + } + + private pointer_t Head; + + private pointer_t Tail; + + public int Count; + + public MSQueue() + { + node_t ptr = new node_t(); + Head.ptr = (Tail.ptr = ptr); + Count = 0; + } + + private bool CAS(ref pointer_t destination, pointer_t compared, pointer_t exchange) + { + if (compared.ptr == Interlocked.CompareExchange(ref destination.ptr, exchange.ptr, compared.ptr)) + { + Interlocked.Exchange(ref destination.count, exchange.count); + return true; + } + return false; + } + + public bool deque(ref T t) + { + bool flag = true; + while (flag) + { + pointer_t head = Head; + pointer_t tail = Tail; + pointer_t next = head.ptr.next; + if (head.count != Head.count || head.ptr != Head.ptr) + { + continue; + } + if (head.ptr == tail.ptr) + { + if (null == next.ptr) + { + return false; + } + CAS(ref Tail, tail, new pointer_t(next.ptr, tail.count + 1)); + } + else + { + t = next.ptr.value; + if (CAS(ref Head, head, new pointer_t(next.ptr, head.count + 1))) + { + flag = false; + } + } + } + Interlocked.Decrement(ref Count); + return true; + } + + public void enqueue(T t) + { + node_t node_t = new node_t(); + node_t.value = t; + bool flag = true; + while (flag) + { + pointer_t tail = Tail; + pointer_t next = tail.ptr.next; + if (tail.count != Tail.count || tail.ptr != Tail.ptr) + { + continue; + } + if (null == next.ptr) + { + if (CAS(ref tail.ptr.next, next, new pointer_t(node_t, next.count + 1))) + { + Interlocked.Increment(ref Count); + flag = false; + } + } + else + { + CAS(ref Tail, tail, new pointer_t(next.ptr, tail.count + 1)); + } + } + } + + public T Dequeue() + { + T t = default(T); + deque(ref t); + return t; + } + + public void Enqueue(T item) + { + enqueue(item); + } +} diff --git a/Common.GLib/MyGather.BLL.UserControls/HttpClient.cs b/Common.GLib/MyGather.BLL.UserControls/HttpClient.cs new file mode 100644 index 0000000000000000000000000000000000000000..c0d4ae8146798ee85f62554ea59e604937d15e9e --- /dev/null +++ b/Common.GLib/MyGather.BLL.UserControls/HttpClient.cs @@ -0,0 +1,145 @@ +using System; +using System.Drawing; +using System.IO; +using System.Net; +using System.Text; +using System.Web; + +namespace MyGather.BLL.UserControls +{ + public class HttpClient : WebClient + { + private CookieContainer cookieContainer; + + public CookieContainer Cookies + { + get + { + return cookieContainer; + } + set + { + cookieContainer = value; + } + } + + public static HttpClient Create() + { + return new HttpClient(); + } + + public static HttpClient Create(CookieContainer cookieContainer) + { + return new HttpClient(cookieContainer); + } + + public HttpClient() + { + cookieContainer = new CookieContainer(); + } + + public HttpClient(CookieContainer cookies) + { + cookieContainer = cookies; + } + + protected override WebRequest GetWebRequest(Uri address) + { + WebRequest webRequest = base.GetWebRequest(address); + if (webRequest is HttpWebRequest) + { + HttpWebRequest httpWebRequest = webRequest as HttpWebRequest; + httpWebRequest.CookieContainer = cookieContainer; + } + return webRequest; + } + + public string PostData(string uriString, string postString, string postStringEncoding, string dataEncoding, out string msg) + { + try + { + byte[] bytes = Encoding.GetEncoding(postStringEncoding).GetBytes(postString); + base.Headers.Add("Content-Type", "application/x-www-form-urlencoded"); + byte[] bytes2 = UploadData(uriString, "POST", bytes); + string @string = Encoding.GetEncoding(dataEncoding).GetString(bytes2); + msg = string.Empty; + return @string; + } + catch (WebException ex) + { + msg = ex.Message; + return string.Empty; + } + } + + public string PostData(string uriString, string postString, out string msg) + { + return PostData(uriString, postString, "gb2312", "gb2312", out msg); + } + + public string GetSrc(string uriString, string dataEncoding, out string msg) + { + try + { + byte[] bytes = DownloadData(uriString); + string @string = Encoding.GetEncoding(dataEncoding).GetString(bytes); + @string = @string.Replace("\t", ""); + @string = @string.Replace("\r", ""); + @string = @string.Replace("\n", ""); + msg = string.Empty; + return @string; + } + catch (WebException ex) + { + msg = ex.Message; + return string.Empty; + } + } + + public string GetSrc(string uriString, out string msg) + { + return GetSrc(uriString, "gb2312", out msg); + } + + public Stream GetSteam(string uriString, string dataEncoding, out string msg) + { + try + { + byte[] array = DownloadData(uriString); + MemoryStream memoryStream = new MemoryStream(array); + Image image = new Bitmap(memoryStream); + string @string = Encoding.GetEncoding(dataEncoding).GetString(array); + @string = @string.Replace("\t", ""); + @string = @string.Replace("\r", ""); + @string = @string.Replace("\n", ""); + msg = string.Empty; + return memoryStream; + } + catch (WebException ex) + { + msg = ex.Message; + return null; + } + } + + public bool GetFile(string urlString, string fileName, out string msg) + { + try + { + DownloadFile(urlString, fileName); + msg = string.Empty; + return true; + } + catch (WebException ex) + { + msg = ex.Message; + return false; + } + } + + public string UrlEncode(string url) + { + return HttpUtility.UrlEncode(url); + } + } +} diff --git a/Common.GLib/Properties/AssemblyInfo.cs b/Common.GLib/Properties/AssemblyInfo.cs new file mode 100644 index 0000000000000000000000000000000000000000..fd24936bab1b98d5596a5110e90fb1f236c8e3d8 --- /dev/null +++ b/Common.GLib/Properties/AssemblyInfo.cs @@ -0,0 +1,20 @@ +using System.Diagnostics; +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using System.Runtime.Versioning; + +[assembly: AssemblyFileVersion("1.0.0.0")] +[assembly: Guid("078f0b5e-24dd-4c6b-b186-d9f5e2644d9e")] +[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)] +[assembly: CompilationRelaxations(8)] +[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] +[assembly: AssemblyTitle("GLib")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyProduct("GLib")] +[assembly: AssemblyCopyright("Copyright © 2010")] +[assembly: AssemblyTrademark("")] +[assembly: ComVisible(false)] +[assembly: AssemblyVersion("1.0.0.0")] diff --git a/Common.GLib/RegexUtils.cs b/Common.GLib/RegexUtils.cs new file mode 100644 index 0000000000000000000000000000000000000000..32e399c87ebad101280197b2dffe540a033e5b43 --- /dev/null +++ b/Common.GLib/RegexUtils.cs @@ -0,0 +1,93 @@ +using System.Text.RegularExpressions; + +public class RegexUtils +{ + public class Pattern + { + public static bool matches(string regex, string str) + { + Regex regex2 = new Regex(regex); + int count = regex2.Matches(str).Count; + return count > 0; + } + } + + public static bool checkEmail(string email) + { + string regex = "\\w+@\\w+\\.[a-z]+(\\.[a-z]+)?"; + string regex2 = "\\w+\\.[a-z]+(\\.[a-z]+)?@\\w+\\.[a-z]+(\\.[a-z]+)?"; + return Pattern.matches(regex, email) || Pattern.matches(regex2, email); + } + + public static bool checkIdCard(string idCard) + { + string regex = "[1-9]\\d{13,16}[a-zA-Z0-9]{1}"; + return Pattern.matches(regex, idCard); + } + + public static bool checkMobile(string mobile) + { + string regex = "(\\+\\d+)?1[3458]\\d{9}$"; + return Pattern.matches(regex, mobile); + } + + public static bool checkPhone(string phone) + { + string regex = "(\\+\\d+)?(\\d{3,4}\\-?)?\\d{7,8}$"; + return Pattern.matches(regex, phone); + } + + public static bool checkDigit(string digit) + { + string regex = "\\-?[1-9]\\d+"; + return Pattern.matches(regex, digit); + } + + public static bool checkDecimals(string decimals) + { + string regex = "\\-?[1-9]\\d+(\\.\\d+)?"; + return Pattern.matches(regex, decimals); + } + + public static bool checkBlankSpace(string blankSpace) + { + string regex = "\\s+"; + return Pattern.matches(regex, blankSpace); + } + + public static bool checkChinese(string chinese) + { + string regex = "^[一-龥]+$"; + return Pattern.matches(regex, chinese); + } + + public static bool checkBirthday(string birthday) + { + string regex = "[1-9]{4}([-./])\\d{1,2}\\1\\d{1,2}"; + return Pattern.matches(regex, birthday); + } + + public static bool checkURL(string url) + { + string regex = "(https?://(w{3}\\.)?)?\\w+\\.\\w+(\\.[a-zA-Z]+)*(:\\d{1,5})?(/\\w*)*(\\??(.+=.*)?(&.+=.*)?)?"; + return Pattern.matches(regex, url); + } + + public static bool checkPostcode(string postcode) + { + string regex = "[1-9]\\d{5}"; + return Pattern.matches(regex, postcode); + } + + public static bool checkIpAddress(string ipAddress) + { + string regex = "[1-9](\\d{1,2})?\\.(0|([1-9](\\d{1,2})?))\\.(0|([1-9](\\d{1,2})?))\\.(0|([1-9](\\d{1,2})?))"; + return Pattern.matches(regex, ipAddress); + } + + public static bool checkAccount(string account) + { + string regex = "[a-zA-Z0-9]{4,15}"; + return Pattern.matches(regex, account); + } +} diff --git a/Common.GLib/RegistryHelper.cs b/Common.GLib/RegistryHelper.cs new file mode 100644 index 0000000000000000000000000000000000000000..b524f5c32de0dae1054239e3c8d85f2f2d4d7982 --- /dev/null +++ b/Common.GLib/RegistryHelper.cs @@ -0,0 +1,80 @@ +using Microsoft.Win32; +using System; +using System.Diagnostics; + +public class RegistryHelper +{ + public static bool ConfigAutoStart(bool isAutoStart, string[] args) + { + try + { + string processName = Process.GetCurrentProcess().ProcessName; + RegistryKey registryKey = null; + using (registryKey = OpenKeyForWrite("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run")) + { + if (registryKey == null) + { + return false; + } + string text = ""; // $"\"{Application.ExecutablePath}\""; + for (int i = 0; i < args.Length; i++) + { + text = ((i != 2) ? (text + " " + args[i]) : (text + " " + $"\"{args[i]}\"")); + } + if (isAutoStart) + { + registryKey.SetValue(processName, text); + } + else + { + registryKey.DeleteValue(processName, throwOnMissingValue: false); + } + registryKey.Close(); + return true; + } + } + catch (Exception) + { + return false; + } + } + + public static RegistryKey OpenKeyForWrite(string subKey) + { + return OpenKeyForWrite(Registry.LocalMachine, subKey); + } + + public static RegistryKey OpenKeyForWrite(RegistryKey key, string subKey) + { + RegistryKey registryKey = null; + registryKey = key.OpenSubKey(subKey, writable: true); + if (registryKey == null) + { + registryKey = key.CreateSubKey(subKey); + } + return registryKey; + } + + public static void WriteAutoLoginWindowRegistryKey(bool isAutoLogin, string defaultUserName, string defaultPassword) + { + try + { + RegistryKey registryKey = Registry.LocalMachine.OpenSubKey("SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Winlogon", writable: true); + if (isAutoLogin) + { + registryKey.SetValue("AutoAdminLogon", "1"); + registryKey.SetValue("DefaultUserName", defaultUserName); + registryKey.SetValue("DefaultPassword", defaultPassword); + } + else + { + registryKey.SetValue("AutoAdminLogon", "0"); + registryKey.SetValue("DefaultPassword", string.Empty); + } + registryKey.Close(); + } + catch (Exception) + { + } + } +} diff --git a/Common.GLib/Watchdog.cs b/Common.GLib/Watchdog.cs new file mode 100644 index 0000000000000000000000000000000000000000..900eb979d6df45dc3cbd38f6a3dcfba329a09c17 --- /dev/null +++ b/Common.GLib/Watchdog.cs @@ -0,0 +1,236 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.IO; +using System.Linq; +using System.Runtime.InteropServices; +using System.Text; +using System.Threading; +//using System.Windows.Forms; + +public static class Watchdog +{ + private static void Application_ThreadException(object sender, ThreadExceptionEventArgs e) + { + OnFatalException(e.Exception); + } + + private static int CheckActive(string appName) + { + int num = 0; + Process[] processes = Process.GetProcesses(); + foreach (Process process in processes) + { + if (process.ProcessName == appName) + { + num++; + } + } + return num; + } + + private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e) + { + OnFatalException(e.ExceptionObject as Exception); + } + + [DllImport("user32.dll", CharSet = CharSet.Unicode)] + public static extern IntPtr FindWindow(string lpClassName, string lpWindowName); + + [DllImport("User32.dll", CharSet = CharSet.Unicode)] + public static extern IntPtr FindWindowEx(IntPtr hwndParent, IntPtr hwndChildAfter, string strClassName, string strWindowName); + + [DllImport("user32.dll")] + private static extern int GetWindowThreadProcessId(IntPtr hWnd, out int ProcessId); + + private static void HideConsoleWindow() + { + //Console.Title = Application.ProductName; + //IntPtr intPtr = FindWindow("ConsoleWindowClass", Application.ProductName); + //if (intPtr != IntPtr.Zero) + //{ + // ShowWindow(intPtr, 0u); + //} + } + + private static void KillDApp(string appName) + { + List list = Enumerable.ToList(Enumerable.Select(new string[6] + { + "WerFault.exe", + "dwwin.exe", + "dw20.exe", + "WerFault", + "dwwin", + "dw20" + }, (string p) => p.ToUpper())); + Process[] processes = Process.GetProcesses(); + Process[] array = processes; + foreach (Process process in array) + { + try + { + if (list.Contains(process.ProcessName.ToUpper().Replace(" *32", ""))) + { + Log($"异常进程:{process.ProcessName}"); + process.Kill(); + } + } + catch (Exception) + { + } + } + try + { + IntPtr intPtr = FindWindowEx(IntPtr.Zero, IntPtr.Zero, null, $"{appName}.exe - 应用程序错误"); + if (intPtr != IntPtr.Zero) + { + int ProcessId = 0; + GetWindowThreadProcessId(intPtr, out ProcessId); + if (ProcessId != 0) + { + Process.GetProcessById(ProcessId).Kill(); + Log($"异常窗口 {appName}.exe - 应用程序错误"); + } + } + intPtr = FindWindowEx(IntPtr.Zero, IntPtr.Zero, null, "Microsoft Visual C++ Runtime Library"); + if (intPtr != IntPtr.Zero) + { + int ProcessId2 = 0; + GetWindowThreadProcessId(intPtr, out ProcessId2); + if (ProcessId2 != 0) + { + Process.GetProcessById(ProcessId2).Kill(); + Log($"异常窗口 {appName}.exe - Microsoft Visual C++ Runtime Library"); + } + } + } + catch (Exception) + { + } + } + + private static void KillOtherDog() + { + Process currentProcess = Process.GetCurrentProcess(); + Process[] processes = Process.GetProcesses(); + foreach (Process process in processes) + { + if (process.ProcessName.ToUpper() == currentProcess.ProcessName.ToUpper()) + { + try + { + if (currentProcess.Id != process.Id) + { + process.Kill(); + } + } + catch (Exception) + { + } + } + } + } + + private static void Log(string msg) + { + //msg = $"{DateTime.Now} {msg}"; + //Console.WriteLine(msg); + //string text = Application.StartupPath + "\\Watchdog"; + //if (!Directory.Exists(text)) + //{ + // Directory.CreateDirectory(text); + //} + //File.AppendAllText(string.Format("{0}\\{1}.txt", text, DateTime.Now.ToString("yyyy_MM")), msg + "\r\n"); + } + + private static void Main(string[] args) + { + try + { + RegisterUnHandldException(); + HideConsoleWindow(); + string text = args[0]; + string text2 = args[1]; + string text3 = args[2]; + int num = int.Parse(args[3]); + string text4 = args[4]; + string text5 = args[5]; + string text6 = (args.Length > 6) ? args[6] : null; + string text7 = (args.Length > 7) ? args[7] : null; + Console.WriteLine(string.Format("{0} {1} {2} {3} {4} {5} {6}", text, text2, text3, num, text4, text5, text6, text7)); + if (!(text == "0")) + { + RegistryHelper.ConfigAutoStart(text4 == "1", args); + KillOtherDog(); + DateTime now = DateTime.Now; + while (true) + { + bool flag = true; + KillDApp(text2); + if (CheckActive(text2) > 0) + { + now = DateTime.Now; + } + if (now.AddSeconds(num) < DateTime.Now) + { + StartApp(text2, text3); + now = DateTime.Now; + } + Thread.Sleep(1000); + } + } + RegistryHelper.ConfigAutoStart(isAutoStart: false, args); + KillOtherDog(); + } + catch (Exception ex) + { + Console.WriteLine(ex.ToString()); + Console.Read(); + } + } + + private static void OnFatalException(Exception ex) + { + StringBuilder stringBuilder = new StringBuilder(); + string value = string.Format("{0} {1}", "Watchdog", ""); + stringBuilder.AppendLine(value); + stringBuilder.AppendLine(ex.Message); + stringBuilder.AppendLine(ex.GetType().Name); + stringBuilder.AppendLine(ex.StackTrace); + Log(stringBuilder.ToString()); + } + + private static void RegisterUnHandldException() + { + //Application.ThreadException += Application_ThreadException; + AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException; + } + + [DllImport("user32.dll")] + public static extern bool ShowWindow(IntPtr hWnd, uint nCmdShow); + + private static void StartApp(string appName, string exe) + { + try + { + int num = CheckActive(appName); + Log($"尝试启动 {appName} 路径:{exe}"); + Directory.SetCurrentDirectory(new FileInfo(exe).Directory.ToString()); + Process.Start(exe); + if (CheckActive(appName) > num) + { + Log($"启动成功 {appName} 路径:{exe}"); + } + else + { + Log($"启动失败 {appName} 路径:{exe}"); + } + Thread.Sleep(3000); + } + catch (Exception arg) + { + Log($"启动异常 {appName} 路径:{exe} \r\n异常信息 {arg}"); + } + } +} diff --git a/GB28181.SIPSorcery/GB28181.SIPSorcery.csproj b/GB28181.SIPSorcery/GB28181.SIPSorcery.csproj index 079ebb56af22cd290ab06b68edffe6c305db0d09..d2a267f495b0710d95f43c461629d9c60c6ea998 100644 --- a/GB28181.SIPSorcery/GB28181.SIPSorcery.csproj +++ b/GB28181.SIPSorcery/GB28181.SIPSorcery.csproj @@ -20,6 +20,10 @@ + + all + runtime; build; native; contentfiles; analyzers; buildtransitive + diff --git a/GB28181.SIPSorcery/Persistence/SIPAssetPersistorFactory.cs b/GB28181.SIPSorcery/Persistence/SIPAssetPersistorFactory.cs index e31a3357571375f9a509423bb32b81570794e8c8..b6556819c78ddf06f8ae88c0d2639aad5e9beb37 100644 --- a/GB28181.SIPSorcery/Persistence/SIPAssetPersistorFactory.cs +++ b/GB28181.SIPSorcery/Persistence/SIPAssetPersistorFactory.cs @@ -41,10 +41,11 @@ using GB28181.SIPSorcery.SIP.App; using GB28181.SIPSorcery.Sys; using GB28181.Logger4Net; using GB28181.SIPSorcery.Persistence.XML; +using SIPSorcery.GB28181.Persistence; namespace GB28181.SIPSorcery.Persistence { - public class SIPAssetPersistorFactory where T : class, ISIPAsset, new() + public static class SIPAssetPersistorFactory where T : class, ISIPAsset, new() { private static ILog logger = AppState.logger; diff --git a/GB28181.SIPSorcery/Persistence/SQL/SQLAssetPersistor.cs b/GB28181.SIPSorcery/Persistence/SQL/SQLAssetPersistor.cs new file mode 100644 index 0000000000000000000000000000000000000000..f7d21d512f9e8a2bd2d5df256b7025cae06dab0b --- /dev/null +++ b/GB28181.SIPSorcery/Persistence/SQL/SQLAssetPersistor.cs @@ -0,0 +1,608 @@ +// ============================================================================ +// FileName: SQLAssetPersistor.cs +// +// Description: +// An asset persistor for Amazon's SimpleDB data store. +// +// Author(s): +// Aaron Clauson +// +// History: +// 24 Oct 2009 Aaron Clauson Created. +// +// License: +// This software is licensed under the BSD License http://www.opensource.org/licenses/bsd-license.php +// +// Copyright (c) 2009 Aaron Clauson (aaron@sipsorcery.com), SIP Sorcery PTY LTD, Hobart, Australia (www.sipsorcery.com) +// All rights reserved. +// +// Redistribution and use in source and binary forms, with or without modification, are permitted provided that +// the following conditions are met: +// +// Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. +// Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following +// disclaimer in the documentation and/or other materials provided with the distribution. Neither the name of SIP Sorcery PTY LTD +// nor the names of its contributors may be used to endorse or promote products derived from this software without specific +// prior written permission. +// +// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, +// BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. +// IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, +// OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, +// OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE +// POSSIBILITY OF SUCH DAMAGE. +// ============================================================================ + +using GB28181.Logger4Net; +using GB28181.SIPSorcery.Persistence; +using GB28181.SIPSorcery.SIP.App; +using GB28181.SIPSorcery.Sys; +using System; +using System.Collections.Generic; +using System.Data; +using System.Data.Common; +using System.Linq; +using System.Linq.Expressions; +using System.Text; + +namespace SIPSorcery.GB28181.Persistence +{ + public class SQLAssetPersistor : SIPAssetPersistor where T : class, ISIPAsset, new() + { + public override event SIPAssetDelegate Added; + public override event SIPAssetDelegate Updated; + public override event SIPAssetDelegate Deleted; + public override event SIPAssetsModifiedDelegate Modified; + private static ILog logger = AppState.logger; + protected DbProviderFactory m_dbProviderFactory; + protected string m_dbConnectionStr; + protected ObjectMapper m_objectMapper; + public SQLAssetPersistor(DbProviderFactory factory, string dbConnStr) + { + m_dbProviderFactory = factory; + m_dbConnectionStr = dbConnStr; + m_objectMapper = new ObjectMapper(); + } + + public override List Add(List assets) + { + using (IDbConnection connection = m_dbProviderFactory.CreateConnection()) + { + connection.ConnectionString = m_dbConnectionStr; + connection.Open(); + using (IDbTransaction trans = connection.BeginTransaction()) + { + try + { + IDbCommand insertCommand = connection.CreateCommand(); + insertCommand.Transaction = trans; + foreach (var asset in assets) + { + + + var insertQuery = new StringBuilder("insert into " + m_objectMapper.TableName + " ("); + var parametersStr = new StringBuilder("("); + List dbParameters = new List(); + + int paramNumber = 1; + Dictionary allPropertyValues = m_objectMapper.GetAllValues(asset); + foreach (KeyValuePair propertyValue in allPropertyValues) + { + DbParameter dbParameter = base.GetParameter(m_dbProviderFactory, propertyValue.Key, propertyValue.Value, paramNumber.ToString()); + insertCommand.Parameters.Add(dbParameter); + + insertQuery.Append(propertyValue.Key + ","); + parametersStr.Append("?" + paramNumber + ","); + paramNumber++; + } + + string insertCommandText = insertQuery.ToString().TrimEnd(',') + ") values " + parametersStr.ToString().TrimEnd(',') + ")"; + + //logger.Debug("SQLAssetPersistor insert SQL: " + insertCommandText + "."); + + insertCommand.CommandText = insertCommandText; + insertCommand.ExecuteNonQuery(); + Added?.Invoke(asset); + } + trans.Commit(); + + } + catch (Exception excp) + { + trans.Rollback(); + logger.Error("Exception SQLAssetPersistor Add (for " + typeof(T).Name + "). " + excp.Message); + throw; + } + } + return assets; + } + } + + public override T Add(T asset) + { + using (IDbConnection connection = m_dbProviderFactory.CreateConnection()) + { + connection.ConnectionString = m_dbConnectionStr; + connection.Open(); + using (IDbTransaction trans = connection.BeginTransaction()) + { + try + { + + IDbCommand insertCommand = connection.CreateCommand(); + insertCommand.Transaction = trans; + StringBuilder insertQuery = new StringBuilder("insert into " + m_objectMapper.TableName + " ("); + StringBuilder parametersStr = new StringBuilder("("); + List dbParameters = new List(); + + int paramNumber = 1; + Dictionary allPropertyValues = m_objectMapper.GetAllValues(asset); + foreach (KeyValuePair propertyValue in allPropertyValues) + { + DbParameter dbParameter = base.GetParameter(m_dbProviderFactory, propertyValue.Key, propertyValue.Value, paramNumber.ToString()); + insertCommand.Parameters.Add(dbParameter); + + insertQuery.Append(propertyValue.Key + ","); + parametersStr.Append("?" + paramNumber + ","); + paramNumber++; + } + + string insertCommandText = insertQuery.ToString().TrimEnd(',') + ") values " + parametersStr.ToString().TrimEnd(',') + ")"; + + //logger.Debug("SQLAssetPersistor insert SQL: " + insertCommandText + "."); + + insertCommand.CommandText = insertCommandText; + insertCommand.ExecuteNonQuery(); + trans.Commit(); + if (Added != null) + { + Added(asset); + } + } + catch (Exception excp) + { + trans.Rollback(); + logger.Error("Exception SQLAssetPersistor Add (for " + typeof(T).Name + "). " + excp.Message); + throw; + } + } + return asset; + } + return null; + } + + public override T Update(T asset) + { + try + { + using (var connection = m_dbProviderFactory.CreateConnection()) + { + connection.ConnectionString = m_dbConnectionStr; + connection.Open(); + + IDbCommand insertCommand = connection.CreateCommand(); + + IDbCommand updateCommand = connection.CreateCommand(); + + StringBuilder updateQuery = new StringBuilder("update " + m_objectMapper.TableName + " set "); + List dbParameters = new List(); + + int paramNumber = 1; + Dictionary allPropertyValues = m_objectMapper.GetAllValues(asset); + foreach (KeyValuePair propertyValue in allPropertyValues) + { + // if (!propertyValue.Key.IsPrimaryKey) + { + DbParameter dbParameter = base.GetParameter(m_dbProviderFactory, propertyValue.Key, propertyValue.Value, paramNumber.ToString()); + updateCommand.Parameters.Add(dbParameter); + + updateQuery.Append(propertyValue.Key + "= ?" + paramNumber + ","); + paramNumber++; + } + } + + string updateCommandText = updateQuery.ToString().TrimEnd(',') + " where id = '" + asset.Id + "'"; + + //logger.Debug("SQLAssetPersistor update SQL: " + updateCommandText + "."); + + updateCommand.CommandText = updateCommandText; + updateCommand.ExecuteNonQuery(); + + if (Updated != null) + { + Updated(asset); + } + + return asset; + } + } + catch (Exception excp) + { + logger.Error("Exception SQLAssetPersistor Update (for " + typeof(T).Name + "). " + excp.Message); + throw; + } + // return null; + } + + public override void UpdateProperty(Guid id, string propertyName, object value) + { + try + { + using (IDbConnection connection = m_dbProviderFactory.CreateConnection()) + { + connection.ConnectionString = m_dbConnectionStr; + connection.Open(); + + IDbCommand updateCommand = connection.CreateCommand(); + + MetaDataMember member = m_objectMapper.GetMember(propertyName); + string parameterName = "1"; + DbParameter dbParameter = base.GetParameter(m_dbProviderFactory, member, value, parameterName); + updateCommand.Parameters.Add(dbParameter); + + updateCommand.CommandText = "update " + m_objectMapper.TableName + " set " + propertyName + " = ?" + parameterName + " where id = '" + id + "'"; + updateCommand.ExecuteNonQuery(); + } + } + catch (Exception excp) + { + logger.Error("Exception SQLAssetPersistor UpdateProperty (for " + typeof(T).Name + "). " + excp.Message); + throw; + } + } + + public override void IncrementProperty(Guid id, string propertyName) + { + base.Increment(id, propertyName); + } + + public override void DecrementProperty(Guid id, string propertyName) + { + base.Decrement(id, propertyName); + } + + public override void Delete() + { + + using (IDbConnection connection = m_dbProviderFactory.CreateConnection()) + { + connection.ConnectionString = m_dbConnectionStr; + connection.Open(); + using (IDbTransaction trans = connection.BeginTransaction()) + { + try + { + + + IDbCommand deleteCommand = connection.CreateCommand(); + deleteCommand.Transaction = trans; + deleteCommand.CommandText = "delete from " + m_objectMapper.TableName; + deleteCommand.ExecuteNonQuery(); + trans.Commit(); + } + catch (Exception excp) + { + trans.Rollback(); + logger.Error("Exception SQLAssetPersistor Delete (for " + typeof(T).Name + "). " + excp.Message); + throw; + } + } + } + + } + + public override void Delete(T asset) + { + using (IDbConnection connection = m_dbProviderFactory.CreateConnection()) + { + connection.ConnectionString = m_dbConnectionStr; + connection.Open(); + using (IDbTransaction trans = connection.BeginTransaction()) + { + try + { + + + IDbCommand deleteCommand = connection.CreateCommand(); + deleteCommand.Transaction = trans; + deleteCommand.CommandText = "delete from " + m_objectMapper.TableName + " where id = '" + asset.Id + "'"; + deleteCommand.ExecuteNonQuery(); + trans.Commit(); + // Deleted?.(asset); + + } + catch (Exception excp) + { + trans.Rollback(); + logger.Error("Exception SQLAssetPersistor Delete (for " + typeof(T).Name + "). " + excp.Message); + throw; + } + } + } + + } + + public override void Delete(Expression> where) + { + + SQLQueryProvider sqlQueryProvider = new SQLQueryProvider(m_dbProviderFactory, m_dbConnectionStr, m_objectMapper.TableName, m_objectMapper.SetValue); + string whereStr = sqlQueryProvider.GetQueryText(where); + + using (IDbConnection connection = m_dbProviderFactory.CreateConnection()) + { + connection.ConnectionString = m_dbConnectionStr; + connection.Open(); + using (IDbTransaction trans = connection.BeginTransaction()) + { + try + { + + IDbCommand deleteCommand = connection.CreateCommand(); + deleteCommand.Transaction = trans; + deleteCommand.CommandText = "delete from " + m_objectMapper.TableName + " where " + whereStr; + deleteCommand.ExecuteNonQuery(); + trans.Commit(); + } + catch (Exception excp) + { + trans.Rollback(); + logger.Error("Exception SQLAssetPersistor Delete (for " + typeof(T).Name + "). " + excp.Message); + throw; + } + } + } + + } + + public override T Get(Guid id) + { + try + { + using (IDbConnection connection = m_dbProviderFactory.CreateConnection()) + { + connection.ConnectionString = m_dbConnectionStr; + connection.Open(); + + IDbCommand command = connection.CreateCommand(); + command.CommandText = "select * from " + m_objectMapper.TableName + " where id = '" + id + "'"; + IDbDataAdapter adapter = m_dbProviderFactory.CreateDataAdapter(); + adapter.SelectCommand = command; + var resultSet = new DataSet(); + adapter.Fill(resultSet); + + if (resultSet != null && resultSet.Tables[0].Rows.Count == 1) + { + T instance = new T(); + instance.Load(resultSet.Tables[0].Rows[0]); + return instance; + } + else if (resultSet != null && resultSet.Tables[0].Rows.Count > 1) + { + throw new ApplicationException("Multiple rows were returned for Get with id=" + id + "."); + } + else + { + return null; + } + } + } + catch (Exception excp) + { + logger.Error("Exception SQLAssetPersistor Get (id) (for " + typeof(T).Name + "). " + excp.Message); + throw; + } + } + + public override object GetProperty(Guid id, string propertyName) + { + try + { + using (IDbConnection connection = m_dbProviderFactory.CreateConnection()) + { + connection.ConnectionString = m_dbConnectionStr; + connection.Open(); + + IDbCommand command = connection.CreateCommand(); + command.CommandText = "select " + propertyName + " from " + m_objectMapper.TableName + " where id = '" + id + "'"; + + return command.ExecuteScalar(); + } + } + catch (Exception excp) + { + logger.Error("Exception SQLAssetPersistor GetProperty (for " + typeof(T).Name + "). " + excp.Message); + throw; + } + } + + public override int Count(Expression> whereClause) + { + try + { + SQLQueryProvider sqlQueryProvider = new SQLQueryProvider(m_dbProviderFactory, m_dbConnectionStr, m_objectMapper.TableName, m_objectMapper.SetValue); + Query assets = new Query(sqlQueryProvider); + if (whereClause != null) + { + return assets.Where(whereClause).Count(); + } + else + { + return assets.Count(); + } + } + catch (Exception excp) + { + logger.Error("Exception SQLAssetPersistor Count (for " + typeof(T).Name + "). " + excp.Message); + throw; + } + } + + public override T Get(Expression> whereClause) + { + try + { + SQLQueryProvider sqlQueryProvider = new SQLQueryProvider(m_dbProviderFactory, m_dbConnectionStr, m_objectMapper.TableName, m_objectMapper.SetValue); + Query assets = new Query(sqlQueryProvider); + IQueryable getList = null; + if (whereClause != null) + { + getList = from asset in assets.Where(whereClause) select asset; + } + else + { + getList = from asset in assets select asset; + } + return getList.FirstOrDefault(); + } + catch (Exception excp) + { + string whereClauseStr = (whereClause != null) ? whereClause.ToString() + ". " : null; + logger.Error("Exception SQLAssetPersistor Get (where) (for " + typeof(T).Name + "). " + whereClauseStr + excp); + throw; + } + } + + public override List Get(Expression> whereClause, string orderByField, int offset, int count) + { + try + { + SQLQueryProvider sqlQueryProvider = new SQLQueryProvider(m_dbProviderFactory, m_dbConnectionStr, m_objectMapper.TableName, m_objectMapper.SetValue); + Query assetList = new Query(sqlQueryProvider); + //IQueryable getList = from asset in assetList.Where(whereClause) orderby orderByField select asset; + IQueryable getList = null; + if (whereClause != null) + { + getList = from asset in assetList.Where(whereClause) select asset; + } + else + { + getList = from asset in assetList select asset; + } + + if (!orderByField.IsNullOrBlank()) + { + sqlQueryProvider.OrderBy = orderByField; + } + + if (offset != 0) + { + sqlQueryProvider.Offset = offset; + } + + if (count != Int32.MaxValue) + { + sqlQueryProvider.Count = count; + } + + return getList.ToList() ?? new List(); + } + catch (Exception excp) + { + string whereClauseStr = (whereClause != null) ? whereClause.ToString() + ". " : null; + logger.Error("Exception SQLAssetPersistor Get (list) (for " + typeof(T).Name + "). " + whereClauseStr + excp.Message); + throw; + } + } + + public override List Get() + { + try + { + SQLQueryProvider sqlQueryProvider = new SQLQueryProvider(m_dbProviderFactory, m_dbConnectionStr, m_objectMapper.TableName, m_objectMapper.SetValue); + Query assetList = new Query(sqlQueryProvider); + //IQueryable getList = from asset in assetList.Where(whereClause) orderby orderByField select asset; + IQueryable getList = null; + getList = from asset in assetList select asset; + + + return getList.ToList() ?? new List(); + } + catch (Exception excp) + { + logger.Error("Exception SQLAssetPersistor Get (list) (for " + excp.Message); + throw; + } + } + } + + #region Unit testing. + +#if UNITTEST + + [TestFixture] + public class SQLAssetPersistorUnitTest { + + // [Table(Name="table")] + private class MockSIPAsset : ISIPAsset { + + private Guid m_id; + public Guid Id { + get { return m_id; } + set { m_id = value; } + } + + public DataTable GetTable() { + throw new NotImplementedException(); + } + + public void Load(DataRow row) { + throw new NotImplementedException(); + } + + public Dictionary Load(System.Xml.XmlDocument dom) { + throw new NotImplementedException(); + } + + public string ToXML() { + throw new NotImplementedException(); + } + + public string ToXMLNoParent() { + throw new NotImplementedException(); + } + + public string GetXMLElementName() { + throw new NotImplementedException(); + } + + public string GetXMLDocumentElementName() { + throw new NotImplementedException(); + } + } + + [TestFixtureSetUp] + public void Init() { } + + [TestFixtureTearDown] + public void Dispose() { } + + [Test] + public void SampleTest() { + Console.WriteLine(System.Reflection.MethodBase.GetCurrentMethod().Name); + } + + /*[Test] + public void BuildSingleParameterSelectQueryUnitTest() { + Console.WriteLine(System.Reflection.MethodBase.GetCurrentMethod().Name); + SimpleDBAssetPersistor persistor = new SimpleDBAssetPersistor(null, null); + string selectQuery = persistor.BuildSelectQuery("select * from table where inserted < ?1", new SqlParameter("1", DateTime.Now)); + Console.WriteLine(selectQuery); + } + + [Test] + public void BuildMultipleParameterSelectQueryUnitTest() { + Console.WriteLine(System.Reflection.MethodBase.GetCurrentMethod().Name); + SimpleDBAssetPersistor persistor = new SimpleDBAssetPersistor(null, null); + SqlParameter[] parameters = new SqlParameter[2]; + parameters[0] = new SqlParameter("1", DateTime.Now); + parameters[1] = new SqlParameter("2", "test"); + string selectQuery = persistor.BuildSelectQuery("select * from table where inserted < ?1 and name = ?2", parameters); + Console.WriteLine(selectQuery); + }*/ + } + +#endif + + #endregion +} diff --git a/GB28181.SIPSorcery/Persistence/SQL/SQLExpressionVisitor.cs b/GB28181.SIPSorcery/Persistence/SQL/SQLExpressionVisitor.cs new file mode 100644 index 0000000000000000000000000000000000000000..b516fac177c28c89978cf8f60639cffd68ff67de --- /dev/null +++ b/GB28181.SIPSorcery/Persistence/SQL/SQLExpressionVisitor.cs @@ -0,0 +1,226 @@ +using System; +using System.Linq; +using System.Linq.Expressions; +using System.Text; + +namespace GB28181.SIPSorcery.Persistence +{ + + internal class SQLExpressionVisitor : ExpressionVisitor { + + private StringBuilder sb; + private bool m_isLeaf; + private bool m_whereAdded; + + internal SQLExpressionVisitor() { } + + internal string Translate(Expression expression) { + this.sb = new StringBuilder(); + this.Visit(expression); + string query = this.sb.ToString().Trim(); + return query; + } + + private static Expression StripQuotes(Expression e) { + while (e.NodeType == ExpressionType.Quote) { + e = ((UnaryExpression)e).Operand; + } + return e; + } + + protected override Expression VisitMethodCall(MethodCallExpression m) { + if (m.Method.DeclaringType == typeof(Queryable) && + (m.Method.Name == "Where" || m.Method.Name == "Select" || m.Method.Name == "Count" || + m.Method.Name == "FirstOrDefault")) { + + if (m_isLeaf) { + if (m.Method.Name == "Where" && !m_whereAdded) { + sb.Append(" where "); + m_whereAdded = true; + } + + this.Visit(m.Arguments[0]); + LambdaExpression lambda = (LambdaExpression)StripQuotes(m.Arguments[1]); + this.Visit(lambda.Body); + return m; + } + else { + if (m.Method.Name == "Select") { + m_isLeaf = true; + sb.Append("select * from {0}"); + this.Visit(m.Arguments[0]); + LambdaExpression lambda = (LambdaExpression)StripQuotes(m.Arguments[1]); + this.Visit(lambda.Body); + return m; + } + else if (m.Method.Name == "Where") { + m_isLeaf = true; + m_whereAdded = true; + sb.Append("select * from {0} where "); + this.Visit(m.Arguments[0]); + LambdaExpression lambda = (LambdaExpression)StripQuotes(m.Arguments[1]); + this.Visit(lambda.Body); + return m; + } + else if (m.Method.Name == "Count") { + m_isLeaf = true; + sb.Append("select count(*) from {0}"); + this.Visit(m.Arguments[0]); + return m; + } + else if (m.Method.Name == "FirstOrDefault") { + m_isLeaf = true; + sb.Append("select * from {0}"); + this.Visit(m.Arguments[0]); + sb.Append(" limit 1"); + return m; + } + } + } + + throw new NotSupportedException(string.Format("The method '{0}' is not supported by SQL.", m.Method.Name)); + } + + protected override Expression VisitUnary(UnaryExpression u) { + switch (u.NodeType) { + case ExpressionType.Not: + sb.Append("not ("); + this.Visit(u.Operand); + sb.Append(")"); + break; + default: + throw new NotSupportedException(string.Format("The unary operator '{0}' is not supported by SQL.", u.NodeType)); + } + return u; + } + + protected override Expression VisitBinary(BinaryExpression b) { + this.Visit(b.Left); + switch (b.NodeType) { + case ExpressionType.And | ExpressionType.AndAlso: + sb.Append(" and "); + break; + case ExpressionType.Or: + sb.Append(" or "); + break; + case ExpressionType.Equal: + sb.Append(" = "); + break; + case ExpressionType.NotEqual: + sb.Append(" != "); + break; + case ExpressionType.LessThan: + sb.Append(" < "); + break; + case ExpressionType.LessThanOrEqual: + sb.Append(" <= "); + break; + case ExpressionType.GreaterThan: + sb.Append(" > "); + break; + case ExpressionType.GreaterThanOrEqual: + sb.Append(" >= "); + break; + default: + throw new NotSupportedException(string.Format("The binary operator '{0}' is not supported by SQL.", b.NodeType)); + } + + this.Visit(b.Right); + return b; + } + + protected override Expression VisitConstant(ConstantExpression c) { + IQueryable q = c.Value as IQueryable; + if (q != null) { + //throw new ApplicationException("Nested expressions not supported."); + } + else if (c.Value == null) { + sb.Append("null"); + } + else { + if (c.Value.GetType() == typeof(Guid)) { + sb.Append("'"); + sb.Append(c.Value); + sb.Append("'"); + } + else { + switch (Type.GetTypeCode(c.Value.GetType())) { + case TypeCode.DateTime: + sb.Append("'"); + sb.Append(((DateTime)c.Value).ToString("o")); + sb.Append("'"); + break; + case TypeCode.Object: + if (c.Value is DateTimeOffset) + { + sb.Append("'"); + sb.Append(((DateTimeOffset)c.Value).ToString("o")); + sb.Append("'"); + } + else + { + throw new NotSupportedException(string.Format("The constant for '{0}' is not supported by SQL.", c.Value)); + } + break; + default: + sb.Append("'"); + sb.Append(c.Value.ToString().Replace("'", "''")); + sb.Append("'"); + break; + } + } + } + return c; + } + + protected override Expression VisitMemberAccess(MemberExpression m) { + if (m.Expression != null && m.Expression.NodeType == ExpressionType.Parameter) { + if (GetMemberType(m) == typeof(Boolean)) { + sb.Append(m.Member.Name.ToLower() + " = '1'"); + } + else { + sb.Append(m.Member.Name.ToLower()); + } + return m; + } + throw new NotSupportedException(string.Format("The member '{0}' is not supported by SQL.", m.Member.Name)); + } + + private string GetTableName(MethodCallExpression m) { + IQueryable q = ((ConstantExpression)m.Arguments[0]).Value as IQueryable; + return GetTableName(q.ElementType); + } + + private string GetTableName(Type tableType) { + //AttributeMappingSource mappingSource = new AttributeMappingSource(); + //MetaModel mapping = mappingSource.GetModel(tableType); + //MetaTable table = mapping.GetTable(tableType); + //return table.TableName; + return null; + } + + private bool IsPrimaryKey(MemberExpression m) { + //AttributeMappingSource mappingSource = new AttributeMappingSource(); + //MetaModel mapping = mappingSource.GetModel(m.Member.DeclaringType); + //MetaTable table = mapping.GetTable(m.Member.DeclaringType); + //foreach (MetaDataMember dataMember in table.RowType.PersistentDataMembers) { + // if (dataMember.Name == m.Member.Name) { + // return dataMember.IsPrimaryKey; + // } + //} + return false; + } + + private Type GetMemberType(MemberExpression m) { + //AttributeMappingSource mappingSource = new AttributeMappingSource(); + //MetaModel mapping = mappingSource.GetModel(m.Member.DeclaringType); + //MetaTable table = mapping.GetTable(m.Member.DeclaringType); + //foreach (MetaDataMember dataMember in table.RowType.PersistentDataMembers) { + // if (dataMember.Name == m.Member.Name) { + // return dataMember.Type; + // } + //} + return null; + } + } +} diff --git a/GB28181.SIPSorcery/Persistence/SQL/SQLObjectReader.cs b/GB28181.SIPSorcery/Persistence/SQL/SQLObjectReader.cs new file mode 100644 index 0000000000000000000000000000000000000000..d23f1c1274d7114629b77f6b7f80d3bcae2016e1 --- /dev/null +++ b/GB28181.SIPSorcery/Persistence/SQL/SQLObjectReader.cs @@ -0,0 +1,88 @@ +using System; +using System.Collections; +using System.Collections.Generic; +using System.Data; +using GB28181.SIPSorcery.SIP.App; +using GB28181.SIPSorcery.Sys; +using GB28181.Logger4Net; + +namespace GB28181.SIPSorcery.Persistence { + + public class SQLObjectReader : IEnumerable, IEnumerable where T : class, ISIPAsset, new() + { + + private static ILog logger = AppState.logger; + + Enumerator enumerator; + private DataSet m_selectResult; + private SetterDelegate m_setter; + + public SQLObjectReader(DataSet selectResult) { + m_selectResult = selectResult; + } + + public SQLObjectReader(DataSet selectResult, SetterDelegate setter) { + m_selectResult = selectResult; + m_setter = setter; + this.enumerator = new Enumerator(selectResult, setter); + } + + public IEnumerator GetEnumerator() { + Enumerator e = this.enumerator; + + if (e == null) + { + throw new InvalidOperationException("Cannot enumerate more than once"); + } + this.enumerator = null; + return e; + } + + IEnumerator IEnumerable.GetEnumerator() { + return this.GetEnumerator(); + } + + public T First() { + T instance = new T(); + instance.Load(m_selectResult.Tables[0].Rows[0]); + return instance; + } + + class Enumerator : IEnumerator, IEnumerator, IDisposable { + + private DataSet m_selectResult; + private SetterDelegate m_setter; + int m_selectIndex; + T current; + + internal Enumerator(DataSet selectResult, SetterDelegate setter) { + m_selectResult = selectResult; + m_setter = setter; + } + + public T Current { + get { return this.current; } + } + + object IEnumerator.Current { + get { return this.current; } + } + + public bool MoveNext() { + + if (m_selectIndex < m_selectResult.Tables[0].Rows.Count) { + T instance = new T(); + instance.Load(m_selectResult.Tables[0].Rows[m_selectIndex]); + this.current = instance; + m_selectIndex++; + return true; + } + return false; + } + + public void Reset() { } + + public void Dispose() { } + } + } +} diff --git a/GB28181.SIPSorcery/Persistence/SQL/SQLQueryProvider.cs b/GB28181.SIPSorcery/Persistence/SQL/SQLQueryProvider.cs new file mode 100644 index 0000000000000000000000000000000000000000..1d6373c28a1fde9980f2c25634904d6ac8427326 --- /dev/null +++ b/GB28181.SIPSorcery/Persistence/SQL/SQLQueryProvider.cs @@ -0,0 +1,426 @@ +using System; +using System.Collections; +using System.Data; +using System.Data.Common; +using System.Linq.Expressions; +using System.Reflection; +using System.Transactions; +using GB28181.SIPSorcery.SIP.App; +using GB28181.SIPSorcery.Sys; +using GB28181.Logger4Net; + +namespace GB28181.SIPSorcery.Persistence { + + public class SQLQueryProvider : QueryProvider { + + private static ILog logger = AppState.logger; + + private DbProviderFactory m_dbFactory; + private string m_dbConnStr; + private string m_tableName; + private SetterDelegate m_setter; + + public string OrderBy; + public int Offset; + public int Count = Int32.MaxValue; + + public SQLQueryProvider(DbProviderFactory dbFactory, string dbConnStr, string tableName, SetterDelegate setter) { + + m_dbFactory = dbFactory; + m_dbConnStr = dbConnStr; + m_tableName = tableName; + m_setter = setter; + } + + public override string GetQueryText(Expression expression) { + return this.Translate(expression); + } + + public override object Execute(Expression expression) { + + try { + Type elementType = TypeSystem.GetElementType(expression.Type); + string methodName = ((MethodCallExpression)expression).Method.Name; + bool isIQueryable = (expression.Type.FullName.StartsWith("System.Linq.IQueryable") || expression.Type.FullName.StartsWith("System.Linq.IOrderedQueryable")); + string queryString = String.Format(this.Translate(expression), m_tableName); + + if (m_tableName == "sipaccounts") + { + Console.WriteLine(); + } + if (!OrderBy.IsNullOrBlank()) { + queryString += " order by " + OrderBy; + } + + if (Count != Int32.MaxValue) { + queryString += " limit " + Count; + } + + if (Offset != 0) { + queryString += " offset " + Offset; + } + + //logger.Debug(queryString); + + if (!queryString.IsNullOrBlank()) { + + using(TransactionScope transactionScope = new TransactionScope(TransactionScopeOption.Suppress)) + { + using (IDbConnection connection = m_dbFactory.CreateConnection()) { + connection.ConnectionString = m_dbConnStr; + connection.Open(); + + if (elementType == typeof(Int32)) + { + // This is a count. + IDbCommand command = connection.CreateCommand(); + command.CommandText = queryString; + return Convert.ToInt32(command.ExecuteScalar()); + } + else + { + //logger.Debug("SimpleDB select: " + queryString + "."); + IDbCommand command = connection.CreateCommand(); + command.CommandText = queryString; + IDbDataAdapter adapter = m_dbFactory.CreateDataAdapter(); + adapter.SelectCommand = command; + DataSet resultSet = new DataSet(); + adapter.Fill(resultSet); + + if (resultSet != null && resultSet.Tables[0] != null) + { + + object result = Activator.CreateInstance( + typeof(SQLObjectReader<>).MakeGenericType(elementType), + BindingFlags.Instance | BindingFlags.Public, null, + new object[] { resultSet, m_setter }, + null); + + if (isIQueryable) + { + return result; + } + else + { + IEnumerator enumerator = ((IEnumerable)result).GetEnumerator(); + if (enumerator.MoveNext()) + { + return enumerator.Current; + } + else + { + return null; + } + } + } + } + } + throw new ApplicationException("No results for SQL query."); + } + } + else { + throw new ApplicationException("The expression translation by the SQLQueryProvider resulted in an empty select string."); + } + } + catch (Exception excp) { + logger.Error("Exception SQLQueryProvider Execute. " + expression.ToString() + ". " + excp.Message); + throw; + } + } + + private string Translate(Expression expression) { + //Stopwatch timer = new Stopwatch(); + //timer.Start(); + expression = Evaluator.PartialEval(expression); + string translation = new SQLExpressionVisitor().Translate(expression); + //timer.Stop(); + //logger.Debug("SQL query took " + timer.ElapsedMilliseconds + "ms: " + translation + "."); + return translation; + } + + #region Unit testing. + + #if UNITTEST + + [TestFixture] + public class SQLQueryProviderUnitTest { + + // [Table(Name = "table")] + private class MockSIPAsset : ISIPAsset { + + private Guid m_id; + [Column(Storage = "m_id", Name = "id", DbType = "character varying(36)", IsPrimaryKey = true, CanBeNull = false)] + public Guid Id { + get { return m_id; } + set { m_id = value; } + } + + private string m_username; + public string Username { + get { return m_username; } + set { m_username = value; } + } + + private string m_adminId; + public string AdminId { + get { return m_adminId; } + set { m_adminId = value; } + } + + private bool m_expired; + // [Column(Name = "expired", DbType = "boolean", CanBeNull = false)] + public bool Expired { + get { return m_expired; } + set { m_expired = value; } + } + + private DateTime m_inserted; + public DateTime Inserted { + get { return m_inserted; } + set { m_inserted = value; } + } + + public DataTable GetTable() { + throw new NotImplementedException(); + } + + public void Load(DataRow row) { + throw new NotImplementedException(); + } + + public Dictionary Load(System.Xml.XmlDocument dom) { + throw new NotImplementedException(); + } + + public string ToXML() { + throw new NotImplementedException(); + } + + public string ToXMLNoParent() { + throw new NotImplementedException(); + } + + public string GetXMLElementName() { + throw new NotImplementedException(); + } + + public string GetXMLDocumentElementName() { + throw new NotImplementedException(); + } + } + + [TestFixtureSetUp] + public void Init() { + Logger4Net.Config.BasicConfigurator.Configure(); + } + + [TestFixtureTearDown] + public void Dispose() { } + + [Test] + public void SampleTest() { + Console.WriteLine(System.Reflection.MethodBase.GetCurrentMethod().Name); + } + + /// + /// Check that the query text is generated correctly for a select based on an object's id. + /// + [Test] + public void SimpleSelectOnIdTest() { + Console.WriteLine(System.Reflection.MethodBase.GetCurrentMethod().Name); + + SQLQueryProvider queryProvider = new SQLQueryProvider(null, null, null, null); + Guid id = Guid.NewGuid(); + Expression> whereClause = (asset) => asset.Id == id; + string querytext = queryProvider.GetQueryText(whereClause); + Console.WriteLine("Query: " + querytext); + + Assert.IsTrue(querytext == "id = '" + id + "'", "The query text was incorrect."); + } + + /// + /// Check that the query text is generated correctly for a select containing a DateTime. + /// + [Test] + public void SimpleSelectOnDateTest() { + Console.WriteLine(System.Reflection.MethodBase.GetCurrentMethod().Name); + + SQLQueryProvider queryProvider = new SQLQueryProvider(null, null, null, null); + DateTime checkDate = DateTime.Now; + Expression> whereClause = (asset) => asset.Inserted >= checkDate; + string querytext = queryProvider.GetQueryText(whereClause); + Console.WriteLine("Query: " + querytext); + + Assert.IsTrue(querytext == "inserted >= '" + checkDate.ToString("o") + "'", "The query text was incorrect."); + } + + /// + /// Check that the query text is generated correctly for a select containing an "and" operator. + /// + [Test] + public void SelectWithAndOperatorTest() { + Console.WriteLine(System.Reflection.MethodBase.GetCurrentMethod().Name); + + SQLQueryProvider queryProvider = new SQLQueryProvider(null, null, null, null); + Expression> whereClause = (asset) => asset.AdminId == "1234" && asset.Username == "abcd"; + string querytext = queryProvider.GetQueryText(whereClause); + Console.WriteLine("Query: " + querytext); + + Assert.IsTrue(querytext == "adminid = '1234' and username = 'abcd'", "The query text was incorrect."); + } + + /// + /// Check that the query text is generated correctly when the select contains a locally scoped variable. + /// + [Test] + public void SelectWithLocallyScopedVariableOperatorTest() { + + Console.WriteLine(System.Reflection.MethodBase.GetCurrentMethod().Name); + + SQLQueryProvider queryProvider = new SQLQueryProvider(null, null, null, null); + string username = "efgh"; + Expression> whereClause = (asset) => asset.Username == username; + string querytext = queryProvider.GetQueryText(whereClause); + Console.WriteLine("Query: " + querytext); + + Assert.IsTrue(querytext == "username = '" + username + "'", "The query text was incorrect."); + } + + /// + /// Check that the query text is generated correctly when the select contains a locally scoped embedded variable. + /// + [Test] + public void SelectWithLocallyScopedEmbeddedVariableOperatorTest() { + + Console.WriteLine(System.Reflection.MethodBase.GetCurrentMethod().Name); + + SimpleDBQueryProvider queryProvider = new SimpleDBQueryProvider(null, null, null); + Expression> whereClause = (asset) => asset.Inserted < DateTime.UtcNow; + string querytext = queryProvider.GetQueryText(whereClause); + Console.WriteLine("Query: " + querytext); + + Assert.IsTrue(Regex.Match(querytext, @"inserted < '\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}\.\d{7}Z'").Success, "The query text was incorrect."); + } + + /// + /// Check that the query text is generated correctly when the select contains a boolean not operator + /// + [Test] + public void SelectWithNotOperatorTest() { + Console.WriteLine(System.Reflection.MethodBase.GetCurrentMethod().Name); + + SQLQueryProvider queryProvider = new SQLQueryProvider(null, null, null, null); + Expression> whereClause = (asset) => !asset.Expired; + string querytext = queryProvider.GetQueryText(whereClause); + Console.WriteLine("Query: " + querytext + "."); + + Assert.IsTrue(querytext == "not (expired = '1')", "The query text was incorrect."); + } + + /// + /// Check that the query text is generated correctly when the select contains a boolean not operator. + /// + [Test] + public void SelectWithBooleanTest() { + Console.WriteLine(System.Reflection.MethodBase.GetCurrentMethod().Name); + + SQLQueryProvider queryProvider = new SQLQueryProvider(null, null, null, null); + Expression> whereClause = (asset) => asset.Expired; + string querytext = queryProvider.GetQueryText(whereClause); + Console.WriteLine("Query: " + querytext + "."); + + Assert.IsTrue(querytext == "expired = '1'", "The query text was incorrect."); + } + + /// + /// Check that the query text is generated correctly when the select contains a boolean not operator + /// and an And clause. + /// + [Test] + public void SelectWithNotCombinedWithAndOperatorTest() { + Console.WriteLine(System.Reflection.MethodBase.GetCurrentMethod().Name); + + SQLQueryProvider queryProvider = new SQLQueryProvider(null, null, null, null); + DateTime checkDate = DateTime.Now; + Expression> whereClause = (asset) => !asset.Expired && asset.Inserted >= checkDate; + string querytext = queryProvider.GetQueryText(whereClause); + Console.WriteLine("Query: " + querytext + "."); + + Assert.IsTrue(querytext == "not (expired = '1') and inserted >= '" + checkDate.ToString("o") + "'", "The query text was incorrect."); + } + + /// + /// Check that the query text is generated correctly when the select contains a member variable. + /// + [Test] + public void SelectWithMemberVariableOperatorTest() { + Console.WriteLine(System.Reflection.MethodBase.GetCurrentMethod().Name); + + SQLQueryProvider queryProvider = new SQLQueryProvider(null, null, null, null); + var myObj = new { Name = "xyz" }; + Expression> whereClause = (asset) => asset.Username == myObj.Name; + string querytext = queryProvider.GetQueryText(whereClause); + Console.WriteLine("Query: " + querytext); + + Assert.IsTrue(querytext == "username = '" + myObj.Name + "'", "The query text was incorrect."); + } + + /// + /// Check that the query text is generated correctly when the select contains a member variable. + /// + [Test] + public void SelectWithNotEqualMemberVariableOperatorTest() { + Console.WriteLine(System.Reflection.MethodBase.GetCurrentMethod().Name); + + SQLQueryProvider queryProvider = new SQLQueryProvider(null, null, null, null); + var myObj = new { Name = "xyz" }; + Expression> whereClause = (asset) => asset.Username != myObj.Name; + string querytext = queryProvider.GetQueryText(whereClause); + Console.WriteLine("Query: " + querytext); + + Assert.IsTrue(querytext == "username != '" + myObj.Name + "'", "The query text was incorrect."); + } + + /// + /// Check that the query text is generated correctly when the select contains a member variable + /// combined with an And clause. + /// + [Test] + public void SelectWithMemberVariableCombinedWithAndClauseOperatorTest() { + Console.WriteLine(System.Reflection.MethodBase.GetCurrentMethod().Name); + + SQLQueryProvider queryProvider = new SQLQueryProvider(null, null, null, null); + var myObj = new { Name = "xyz" }; + DateTime checkDate = DateTime.Now; + Expression> whereClause = (asset) => asset.Username == myObj.Name && !asset.Expired && asset.Inserted >= checkDate; + string querytext = queryProvider.GetQueryText(whereClause); + Console.WriteLine("Query: " + querytext); + + Assert.IsTrue(querytext == "username = '" + myObj.Name + "' and not (expired = '1') and inserted >= '" + checkDate.ToString("o") + "'", "The query text was incorrect."); + } + + /// + /// Check that the query text is generated correctly when the select expression includes an orderby clause. + /// + [Test] + public void OrderedSelectTest() { + + Console.WriteLine(System.Reflection.MethodBase.GetCurrentMethod().Name); + + SQLQueryProvider queryProvider = new SQLQueryProvider(null, null, null, null); + Query assetList = new Query(queryProvider); + + DateTime checkDate = DateTime.Now; + var dummyResult = from asset in assetList orderby asset.Inserted select asset; + string querytext = queryProvider.GetQueryText(dummyResult.Expression); + Console.WriteLine("Query: " + querytext); + + //Assert.IsTrue(querytext == "username = '" + myObj.Name + "' and not (expired = '1') and inserted >= '" + checkDate.ToString("o") + "'", "The query text was incorrect."); + } + } + + #endif + + #endregion + } +} diff --git a/GB28181.SIPSorcery/SIP.App/SIPUserAgents/JingleUserAgent.cs b/GB28181.SIPSorcery/SIP.App/SIPUserAgents/JingleUserAgent.cs new file mode 100644 index 0000000000000000000000000000000000000000..a1905136b504a11895d61ba45dc6271c7e7fe38f --- /dev/null +++ b/GB28181.SIPSorcery/SIP.App/SIPUserAgents/JingleUserAgent.cs @@ -0,0 +1,97 @@ +using System; +using System.Collections.Generic; +using System.Linq; +using System.Net; +using System.Text; +using System.Threading; +using GB28181.SIPSorcery.Net; +using GB28181.SIPSorcery.Sys; + +namespace GB28181.SIPSorcery.SIP.App +{ + public class JingleUserAgent : ISIPClientUserAgent + { + private static string m_CRLF = SDP.CRLF; + + private SIPMonitorLogDelegate Log_External; + + // private XMPPClient m_xmppClient; + + public string Owner { get; private set; } + public string AdminMemberId { get; private set; } + public UACInviteTransaction ServerTransaction { get; private set; } + public SIPDialogue SIPDialogue { get; private set; } + public SIPCallDescriptor CallDescriptor { get; private set; } + public bool IsUACAnswered { get; private set; } + + public event SIPCallResponseDelegate CallTrying; + public event SIPCallResponseDelegate CallRinging; + public event SIPCallResponseDelegate CallAnswered; + public event SIPCallFailedDelegate CallFailed; + + public JingleUserAgent( + string owner, + string adminMemberId, + SIPMonitorLogDelegate logDelegate) + { + Owner = owner; + AdminMemberId = adminMemberId; + Log_External = logDelegate; + + // If external logging is not required assign an empty handler to stop null reference exceptions. + if (Log_External == null) + { + Log_External = (e) => { }; + } + } + + public void Call(SIPCallDescriptor sipCallDescriptor) + { + //CallDescriptor = sipCallDescriptor; + //m_xmppClient = new XMPPClient("talk.google.com", 5222, "google.com", null, null); + //m_xmppClient.IsBound += IsBound; + //m_xmppClient.Answered += Answered; + + //IPEndPoint sdpEndPoint = SDP.GetSDPRTPEndPoint(CallDescriptor.Content); + //if (IPSocket.IsPrivateAddress(sdpEndPoint.Address.ToString())) + //{ + // bool wasSDPMangled; + // CallDescriptor.Content = SIPPacketMangler.MangleSDP(CallDescriptor.Content, CallDescriptor.MangleIPAddress.ToString(), out wasSDPMangled); + //} + + //ThreadPool.QueueUserWorkItem(delegate { m_xmppClient.Connect(); }); + } + + private void IsBound() + { + Console.WriteLine("XMPP client IsBound"); + // m_xmppClient.PlaceCall(SIPURI.ParseSIPURI(CallDescriptor.To).User + "@voice.google.com", SDP.ParseSDPDescription(CallDescriptor.Content)); + } + + private void Answered(SDP sdp) + { + Console.WriteLine("XMPP client call answered."); + + IsUACAnswered = true; + + SIPResponse okResponse = new SIPResponse(SIPResponseStatusCodesEnum.Ok, "Ok", new SIPEndPoint(new IPEndPoint(IPAddress.Loopback, 0))); + okResponse.Header.ContentType = SDP.SDP_MIME_CONTENTTYPE; + okResponse.Body = sdp.ToString(); + + SIPDialogue = new SIPDialogue(null, null, null, null, -1, null, null, null, Guid.NewGuid(), Owner, AdminMemberId, null, sdp.ToString()); + SIPDialogue.CallDurationLimit = CallDescriptor.CallDurationLimit; + + CallAnswered(this, okResponse); + } + + public void Cancel() + { + throw new NotImplementedException(); + } + + public void Update(CRMHeaders crmHeaders) + { + throw new NotImplementedException(); + } + } +} diff --git a/GB28181.SIPSorcery/SIP.Core/SIP/SIPConstants.cs b/GB28181.SIPSorcery/SIP.Core/SIP/SIPConstants.cs index e126eee21bd59e240e2050efa9230b6bfd8a2620..ff38403365dec9c345fb60608578e22b926f8958 100644 --- a/GB28181.SIPSorcery/SIP.Core/SIP/SIPConstants.cs +++ b/GB28181.SIPSorcery/SIP.Core/SIP/SIPConstants.cs @@ -66,7 +66,7 @@ namespace GB28181.SIPSorcery.SIP public const int DEFAULT_MAX_FORWARDS = 70; public const int DEFAULT_REGISTEREXPIRY_SECONDS = 600; public const int DEFAULT_SIP_PORT = 5060; - public const int DEFAULT_SIP_TLS_PORT = 5061; + public const int DEFAULT_SIP_TLS_PORT = 5060; public const int MAX_SIP_PORT = 65535; public const string NAT_SENDKEEPALIVES_VALUE = "y"; diff --git a/GB28181.SIPSorcery/SIP.Core/SIP/SIPResponse.cs b/GB28181.SIPSorcery/SIP.Core/SIP/SIPResponse.cs index cbd98e3b27935c62ad9748389507831a4ea8bd86..83f719ffdd4304e866444de6de7d330bae0c593b 100644 --- a/GB28181.SIPSorcery/SIP.Core/SIP/SIPResponse.cs +++ b/GB28181.SIPSorcery/SIP.Core/SIP/SIPResponse.cs @@ -413,15 +413,15 @@ namespace GB28181.SIPSorcery.SIP "SIP/2.0 200 OK" + m_CRLF + "From: Blue Face;tag=as5fd53de7" + m_CRLF + "To: sip:xxx@127.0.0.1;tag=MTHf2-ol1Yn0" + m_CRLF + - "Call-ID: 3e7df9d805ac596f3f091510164115e2@212.159.110.30:5061" + m_CRLF + + "Call-ID: 3e7df9d805ac596f3f091510164115e2@212.159.110.30:5060" + m_CRLF + "CSeq: 102 INVITE" + m_CRLF + "Via: SIP/2.0/UDP 213.168.225.133:5060;branch=z9hG4bKG+WGOVwLyT6vOW9s" + m_CRLF + - "Via: SIP/2.0/UDP 213.168.225.133:5061;branch=z9hG4bK09db9c73" + m_CRLF + - "Contact: +3535xxx" + m_CRLF + + "Via: SIP/2.0/UDP 213.168.225.133:5060;branch=z9hG4bK09db9c73" + m_CRLF + + "Contact: +3535xxx" + m_CRLF + "User-Agent: MSC/VC510 Build-Date Nov 7 2005" + m_CRLF + "Allow: INVITE,BYE,CANCEL,OPTIONS,PRACK,NOTIFY,UPDATE,REFER" + m_CRLF + "Supported: timer,replaces" + m_CRLF + - "Record-Route: ," + m_CRLF + + "Record-Route: ," + m_CRLF + "Content-Type: application/sdp" + m_CRLF + "Content-Length: 182" + m_CRLF + m_CRLF + @@ -532,9 +532,9 @@ namespace GB28181.SIPSorcery.SIP string sipMsg = "SIP/2.0 200 OK" + m_CRLF + - "Via: SIP/2.0/UDP 194.213.29.100:5060;branch=z9hG4bK5feb18267ce40fb05969b4ba843681dbfc9ffcff, SIP/2.0/UDP 194.213.29.54:5061;branch=z9hG4bK52b6a8b7" + m_CRLF + + "Via: SIP/2.0/UDP 194.213.29.100:5060;branch=z9hG4bK5feb18267ce40fb05969b4ba843681dbfc9ffcff, SIP/2.0/UDP 194.213.29.54:5060;branch=z9hG4bK52b6a8b7" + m_CRLF + "Record-Route: " + m_CRLF + - "From: Unknown ;tag=as58cbdbd1" + m_CRLF + + "From: Unknown ;tag=as58cbdbd1" + m_CRLF + "To: ;tag=1144090013" + m_CRLF + "Call-ID: 40741a72794b85ed197e1e020bf42bb9@194.213.29.54" + m_CRLF + "CSeq: 102 INVITE" + m_CRLF + diff --git a/GB28181.SIPSorcery/SIP.Core/SIP/SIPTransport.cs b/GB28181.SIPSorcery/SIP.Core/SIP/SIPTransport.cs index 0a6b7c4eea20e03b77c98c0018d8b5b3b5019748..87795ed8325aeda812cd0d09b3c009ef5d57e543 100644 --- a/GB28181.SIPSorcery/SIP.Core/SIP/SIPTransport.cs +++ b/GB28181.SIPSorcery/SIP.Core/SIP/SIPTransport.cs @@ -1268,6 +1268,7 @@ namespace GB28181.SIPSorcery.SIP else { //rawSIPMessage = Encoding.Default.GetString(buffer, 0, buffer.Length); + Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);//ע,ʹGB2312쳣System.Text.Encoding.CodePagesʹ rawSIPMessage = Encoding.GetEncoding("GB2312").GetString(buffer, 0, buffer.Length); if (!rawSIPMessage.StartsWith("REGISTER") && !rawSIPMessage.StartsWith("MESSAGE")) { diff --git a/GB28181.SIPSorcery/Servers.Cores/IMediaService.cs b/GB28181.SIPSorcery/Servers.Cores/IMediaService.cs index f642f9bfe6acfab34a93173e157b856a8d40611b..c7c620e7427a510d2689c59e265841e76caff024 100644 --- a/GB28181.SIPSorcery/Servers.Cores/IMediaService.cs +++ b/GB28181.SIPSorcery/Servers.Cores/IMediaService.cs @@ -6,6 +6,12 @@ namespace GB28181.SIPSorcery.Servers { public interface IMediaAction { + + /// + /// 实时视频请求 + /// + void RealVideoReq(); + /// /// 实时视频请求 /// @@ -31,7 +37,7 @@ namespace GB28181.SIPSorcery.Servers /// /// 视频流回调完成 /// - // event Action OnStreamReady; + event Action OnStreamReady; #region 录像点播 diff --git a/GB28181.SIPSorcery/Servers.Cores/SIPMessage/SIPMessageCore.cs b/GB28181.SIPSorcery/Servers.Cores/SIPMessage/SIPMessageCore.cs index d5b1908081b4d74dbf0379c57c2874326e04afce..f6aa93f44e4ca13b63a0ef0ef70df22a0de05755 100644 --- a/GB28181.SIPSorcery/Servers.Cores/SIPMessage/SIPMessageCore.cs +++ b/GB28181.SIPSorcery/Servers.Cores/SIPMessage/SIPMessageCore.cs @@ -24,6 +24,24 @@ using System.Threading.Tasks; namespace GB28181.SIPSorcery.Servers.SIPMessage { + public struct MonitorKey + { + /// + /// 设备编码 + /// + public string DeviceID { get; set; } + + /// + /// 命令类型 + /// + public CommandType CmdType { get; set; } + + public override string ToString() + { + return this.DeviceID; + } + } + /// /// sip消息核心处理 /// @@ -148,13 +166,13 @@ namespace GB28181.SIPSorcery.Servers.SIPMessage // MessageCore = new SIPMessageCore(m_sipTransport, SIPConstants.SIP_SERVER_STRING); public SIPMessageCore(ISIPTransport sipTransport, string sipServerAgentStr) { + // _registrarCore = new SIPRegistrarCore(); _transport = sipTransport; _sipServerAgent = sipServerAgentStr; // Configure the SIP transport layer. _transport.SIPTransportRequestReceived += AddMessageRequest; _transport.SIPTransportResponseReceived += AddMessageResponse; - - _cameraCache.OnItemAdded += _cameraCache_OnItemAdded; + //_cameraCache.OnItemAdded += _cameraCache_OnItemAdded; } @@ -209,6 +227,14 @@ namespace GB28181.SIPSorcery.Servers.SIPMessage public void Start() { _serviceState = ServiceStatus.Wait; + + if (_LocalSipAccount == null) + { + _LocalSipAccount = new SIPAccount(); + _LocalSipAccount.MsgProtocol = ProtocolType.Udp; + _LocalSipAccount.LocalIP = IPAddress.Parse("127.0.0.1"); + _LocalSipAccount.LocalPort = ushort.Parse("5060"); + } LocalEP = SIPEndPoint.ParseSIPEndPoint(_LocalSipAccount.MsgProtocol + ":" + _LocalSipAccount.LocalIP.ToString() + ":" + _LocalSipAccount.LocalPort); LocalSIPId = _LocalSipAccount.LocalID; @@ -258,6 +284,8 @@ namespace GB28181.SIPSorcery.Servers.SIPMessage } } + + public void PtzControl(PTZCommand ptzcmd, int dwSpeed, string deviceId) { try @@ -637,8 +665,15 @@ namespace GB28181.SIPSorcery.Servers.SIPMessage { _serviceState = ServiceStatus.Complete; - try { OnServiceChanged.Invoke(msg, state); } - catch { } + if (OnServiceChanged == null) + { + // OnServiceChanged+= MessageHub.OnServiceChanged; + } + else + { + try { OnServiceChanged.Invoke(msg, state); } + catch { } + } //OnServiceChanged?.GetInvocationList().ToList().ForEach((item) => //{ // var handler = item as Action; diff --git a/GB28181.SIPSorcery/Servers.Cores/SIPMonitor/SIPMonitorCore.cs b/GB28181.SIPSorcery/Servers.Cores/SIPMonitor/SIPMonitorCore.cs index e3c492b8a98b9ae50600eeda73def3b2f36985cb..0503e5db4e892275d384d1d16d8ef68de86656a7 100644 --- a/GB28181.SIPSorcery/Servers.Cores/SIPMonitor/SIPMonitorCore.cs +++ b/GB28181.SIPSorcery/Servers.Cores/SIPMonitor/SIPMonitorCore.cs @@ -23,7 +23,6 @@ namespace GB28181.SIPSorcery.Servers.SIPMonitor #region 私有字段 private static ILog logger = AppState.logger; private AutoResetEvent _autoResetEventForRpc = new AutoResetEvent(false); - //concurent requet/reply private ConcurrentDictionary _syncRequestContext = new ConcurrentDictionary(); private ConcurrentQueue> _syncResponseContext = new ConcurrentQueue>(); @@ -38,7 +37,6 @@ namespace GB28181.SIPSorcery.Servers.SIPMonitor // RTP wil be established from other place // private Channel _channel; public string DeviceId { get; set; } - private SIPRequest _reqSession; private int[] _mediaPort; // private SIPContactHeader _contact; @@ -47,18 +45,14 @@ namespace GB28181.SIPSorcery.Servers.SIPMonitor private int _recordTotal = -1; // private DevStatus _Status; private SIPAccount _sipAccount; - private ISIPTransport _sipTransport; - #endregion - #region 事件回调 /// /// 视频流回调 /// - // public event Action OnStreamReady; + public event Action OnStreamReady; #endregion - #region 初始化监控 //public SIPMonitorCore(ISipMessageCore sipMsgCoreService, ISIPTransport sipTransport, ISipAccountStorage sipAccountStorage) public SIPMonitorCore(ISipMessageCore sipMessageCore, ISIPTransport sipTransport, ISipAccountStorage sipAccountStorage) @@ -71,6 +65,43 @@ namespace GB28181.SIPSorcery.Servers.SIPMonitor #endregion #region 实时视频 + + /// + /// 实时视频请求 + /// + /// 设备编码 + public void RealVideoReq() + { + //_mediaPort = _sipMsgCoreService.SetMediaPort(); + //string localIp = _sipMsgCoreService.LocalEP.Address.ToString(); + //string fromTag = CallProperties.CreateNewTag(); + //int cSeq = CallProperties.CreateNewCSeq(); + //string callId = CallProperties.CreateNewCallId(); + + //SIPURI remoteUri = new SIPURI(_deviceId, _remoteEP.ToHost(), ""); + //SIPURI localUri = new SIPURI(_msgCore.LocalSIPId, _msgCore.LocalEP.ToHost(), ""); + //SIPFromHeader from = new SIPFromHeader(null, localUri, fromTag); + //SIPToHeader to = new SIPToHeader(null, remoteUri, null); + //SIPRequest realReq = _sipMsgCoreService.Transport.GetRequest(SIPMethodsEnum.INVITE, remoteUri); + //SIPContactHeader contactHeader = new SIPContactHeader(null, localUri); + //realReq.Header.Contact.Clear(); + //realReq.Header.Contact.Add(contactHeader); + + //realReq.Header.Allow = null; + //realReq.Header.From = from; + //realReq.Header.To = to; + //realReq.Header.UserAgent = SIPConstants.SIP_USERAGENT_STRING; + //realReq.Header.CSeq = cSeq; + //realReq.Header.CallId = callId; + //realReq.Header.Subject = SetSubject(); + //realReq.Header.ContentType = "application/sdp"; + + //realReq.Body = SetMediaReq(localIp, _mediaPort); + //_sipMsgCoreService.SendReliableRequest(_remoteEP, realReq); + //_reqSession = realReq; + } + + /// /// 实时视频请求 /// diff --git a/GB28181.SIPSorcery/Sys/Config/SIPSqlite.cs b/GB28181.SIPSorcery/Sys/Config/SIPSqlite.cs new file mode 100644 index 0000000000000000000000000000000000000000..8fda920f80f50850969ce8beff88f21f6416c811 --- /dev/null +++ b/GB28181.SIPSorcery/Sys/Config/SIPSqlite.cs @@ -0,0 +1,84 @@ +using GB28181.SIPSorcery.Persistence; +using GB28181.SIPSorcery.SIP.App; +using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; + +namespace GB28181.SIPSorcery.Sys.Config +{ + public class SIPSqlite + { + private static readonly string m_storageTypeKey = SIPSorceryConfiguration.PERSISTENCE_STORAGETYPE_KEY; + private static readonly string m_connStrKey = SIPSorceryConfiguration.PERSISTENCE_STORAGECONNSTR_KEY; + private static readonly string m_XMLFilename = "gb28181.xml"; + + private static StorageTypes m_storageType; + private static string m_connStr; + + private static SIPSqlite _instance; + + private List _accounts; + + public List Accounts + { + get { return _accounts; } + set { _accounts = value; } + } + private SIPAssetPersistor _sipAccount; + + public SIPAssetPersistor SipAccount + { + get { return _sipAccount; } + } + + public static SIPSqlite Instance + { + get + { + if (_instance == null) + { + _instance = new SIPSqlite(); + } + return _instance; + } + } + + static SIPSqlite() + { + string path = AppDomain.CurrentDomain.BaseDirectory + "Config\\"; + m_storageType = (AppState.GetConfigSetting(m_storageTypeKey) != null) ? StorageTypesConverter.GetStorageType(AppState.GetConfigSetting(m_storageTypeKey)) : StorageTypes.Unknown; + m_connStr = AppState.GetConfigSetting(m_connStrKey); + if (m_storageType == StorageTypes.SQLite) + { + m_connStr = string.Format(m_connStr, path); + + } + if (m_storageType == StorageTypes.Unknown || m_connStr.IsNullOrBlank()) + { + throw new ApplicationException("The SIP Registrar cannot start with no persistence settings."); + } + } + + public void Read() + { + SIPAssetPersistor account = SIPAssetPersistorFactory.CreateSIPAssetPersistor(m_storageType, m_connStr, m_XMLFilename); + _sipAccount = account; + _accounts = account.Get(); + } + + public void Save(SIPAccount account) + { + if (_accounts.Any(d => d.SIPUsername == account.SIPUsername || d.SIPDomain == account.SIPDomain)) + { + SipAccount.Update(account); + } + else + { + SipAccount.Add(account); + _accounts.Add(account); + } + } + } +} diff --git a/GB28181.SIPSorcery/Sys/EnvironmentVariables.cs b/GB28181.SIPSorcery/Sys/EnvironmentVariables.cs index 534439b675d5e466828f6c77d2f2f85cb9c370e5..32b2a59ddec571b429e95b8f9be2903499c171e6 100644 --- a/GB28181.SIPSorcery/Sys/EnvironmentVariables.cs +++ b/GB28181.SIPSorcery/Sys/EnvironmentVariables.cs @@ -54,7 +54,7 @@ namespace GB28181.SIPSorcery.Sys } public static int GbServiceLocalPort //obsolete { - get { return 5061; } + get { return 5060; } } } } diff --git a/GB28181.SIPSorcery/Sys/WrapperImpersonationContext.cs b/GB28181.SIPSorcery/Sys/WrapperImpersonationContext.cs new file mode 100644 index 0000000000000000000000000000000000000000..327c82f5d48e4bacffa4075dde700983e93d409b --- /dev/null +++ b/GB28181.SIPSorcery/Sys/WrapperImpersonationContext.cs @@ -0,0 +1,144 @@ +// ============================================================================ +// FileName: WrapperImpersonationContext.cs +// +// Description: +// Creates a Windows impersonation context for a specified set of login credentials. +// +// Author(s): +// Aaron Clauson +// +// History: +// 18 Jul 2010 Aaron Clauson Created from http://www.vanotegem.nl/PermaLink,guid,36633846-2eca-40fe-9957-2859d8a244dc.aspx. +// +// License: +// Public domain. +// ============================================================================ + +using System; +using System.ComponentModel; +using System.Runtime.InteropServices; +using System.Security.Permissions; +using System.Security.Principal; + +#if UNITTEST +using NUnit.Framework; +#endif + +public class WrapperImpersonationContext +{ + [DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)] + public static extern bool LogonUser(String lpszUsername, String lpszDomain, + String lpszPassword, int dwLogonType, int dwLogonProvider, ref IntPtr phToken); + + [DllImport("kernel32.dll", CharSet = CharSet.Auto)] + public extern static bool CloseHandle(IntPtr handle); + + private const int LOGON32_PROVIDER_DEFAULT = 0; + private const int LOGON32_LOGON_INTERACTIVE = 2; + + private string m_Domain; + private string m_Password; + private string m_Username; + private IntPtr m_Token; + + // private WindowsImpersonationContext m_Context = null; + + protected bool IsInContext { get; } + //{ + // get { return m_Context != null; } + //} + + public WrapperImpersonationContext(string domain, string username, string password) + { + m_Domain = domain; + m_Username = username; + m_Password = password; + } + + [PermissionSetAttribute(SecurityAction.Demand, Name = "FullTrust")] + public void Enter() + { + if (this.IsInContext) return; + m_Token = new IntPtr(0); + try + { + m_Token = IntPtr.Zero; + bool logonSuccessfull = LogonUser( + m_Username, + m_Domain, + m_Password, + LOGON32_LOGON_INTERACTIVE, + LOGON32_PROVIDER_DEFAULT, + ref m_Token); + if (logonSuccessfull == false) + { + int error = Marshal.GetLastWin32Error(); + throw new Win32Exception(error); + } + WindowsIdentity identity = new WindowsIdentity(m_Token); + // m_Context = identity.Impersonate(); + } + catch + { + throw; + } + } + + [PermissionSetAttribute(SecurityAction.Demand, Name = "FullTrust")] + public void Leave() + { + if (this.IsInContext == false) return; + // m_Context.Undo(); + + if (m_Token != IntPtr.Zero) CloseHandle(m_Token); + // m_Context = null; + } + + #region Unit testing. + + #if UNITTEST + + [TestFixture] + public class WrapperImpersonationContextUnitTest + { + [TestFixtureSetUp] + public void Init() { } + + [TestFixtureTearDown] + public void Dispose() { } + + [Test] + public void SampleTest() + { + Console.WriteLine(System.Reflection.MethodBase.GetCurrentMethod().Name); + } + + [Test] + public void EnterContextUnitTest() + { + Console.WriteLine(System.Reflection.MethodBase.GetCurrentMethod().Name); + + Console.WriteLine("identity=" + WindowsIdentity.GetCurrent().Name + "."); + using (StreamReader sr = new StreamReader(@"c:\temp\impersonationtest.txt")) + { + Console.WriteLine(sr.ReadToEnd()); + } + + WrapperImpersonationContext context = new WrapperImpersonationContext(null, "sipsorcery-appsvr", "password"); + context.Enter(); + Console.WriteLine("identity=" + WindowsIdentity.GetCurrent().Name + "."); + + using (StreamReader sr = new StreamReader(@"c:\temp\impersonationtest.txt")) + { + Console.WriteLine(sr.ReadToEnd()); + } + + context.Leave(); + Console.WriteLine("identity=" + WindowsIdentity.GetCurrent().Name + "."); + } + } + + #endif + + #endregion +} \ No newline at end of file diff --git a/GB28181.Server/Config/gb28181.xml b/GB28181.Server/Config/gb28181.xml index 68fb26b6b2a41739a6c73f2915736ecd876df01b..d6d67382818080a3d6a0574cc5ff29a31df4c049 100644 --- a/GB28181.Server/Config/gb28181.xml +++ b/GB28181.Server/Config/gb28181.xml @@ -3,9 +3,9 @@ 10 上级平台 GB-2016 - 42010000002100000002 - 10.78.115.182 - 5061 + 34020000002000000001 + 127.0.0.1 + 5060 5060 false admin diff --git a/GB28181.Server/Main/Initialize.cs b/GB28181.Server/Main/Initialize.cs index 3b45ac4fd6f132b985f7a447a59c751ca4cdc891..8a046d159a35a94c7265c098e304a4d9b868e06c 100644 --- a/GB28181.Server/Main/Initialize.cs +++ b/GB28181.Server/Main/Initialize.cs @@ -28,9 +28,9 @@ namespace GB28181.Server.Main obj.Id = Guid.NewGuid(); //obj.Owner = item.Name; obj.GbVersion = string.IsNullOrEmpty(item.GbVersion) ? "GB-2016" : item.GbVersion; - obj.LocalID = string.IsNullOrEmpty(item.LocalID) ? "42010000002100000002" : item.LocalID; + obj.LocalID = string.IsNullOrEmpty(item.LocalID) ? "34020000002000000001" : item.LocalID; obj.LocalIP = HostsEnv.GetRawIP(); - obj.LocalPort = string.IsNullOrEmpty(item.LocalPort) ? Convert.ToUInt16(5061) : Convert.ToUInt16(item.LocalPort); + obj.LocalPort = string.IsNullOrEmpty(item.LocalPort) ? Convert.ToUInt16(5060) : Convert.ToUInt16(item.LocalPort); obj.RemotePort = string.IsNullOrEmpty(item.RemotePort) ? Convert.ToUInt16(5060) : Convert.ToUInt16(item.RemotePort); obj.Authentication = string.IsNullOrEmpty(item.Authentication) ? false : bool.Parse(item.Authentication); obj.SIPUsername = string.IsNullOrEmpty(item.SIPUsername) ? "admin" : item.SIPUsername; diff --git a/GB28181.Server/Main/MainProcess.cs b/GB28181.Server/Main/MainProcess.cs index 80cdcd78b5a07a1e6020db16a7cd2f04aba8dea4..383b304b7b40ceb8ac6e2a59b37b0d6a1e990580 100644 --- a/GB28181.Server/Main/MainProcess.cs +++ b/GB28181.Server/Main/MainProcess.cs @@ -1,19 +1,8 @@ using GB28181.Logger4Net; -using GB28181.Server.Message; -using GB28181.Service; -using GB28181.Service.Protos.DeviceCatalog; -using GB28181.Service.Protos.DeviceFeature; -using GB28181.Service.Protos.Ptz; -using GB28181.Service.Protos.Video; -using GB28181.Service.Protos.VideoRecord; using GB28181.SIPSorcery.Servers; using GB28181.SIPSorcery.Servers.SIPMessage; -using GB28181.SIPSorcery.Servers.SIPMonitor; -using GB28181.SIPSorcery.SIP; using GB28181.SIPSorcery.Sys; -using GB28181.SIPSorcery.Sys.Cache; using GB28181.SIPSorcery.Sys.Config; -using GB28181.SIPSorcery.Sys.Model; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using System; @@ -40,8 +29,20 @@ namespace GB28181.Server.Main private readonly CancellationTokenSource _deviceStatusReportToken = new CancellationTokenSource(); // private Queue _keepAliveQueue = new Queue(); - private readonly IServiceCollection servicesContainer = new ServiceCollection(); + //private readonly IServiceCollection servicesContainer = new ServiceCollection(); + // private ServiceProvider _serviceProvider = null; + private ISipMessageCore _mainSipService; + private MessageHub messageCenter; + private ISIPRegistrarCore registry; + + public MainProcess(ISipMessageCore sipMessageCore, MessageHub messageHub, ISIPRegistrarCore sipRegistrarCore) + { + _mainSipService = sipMessageCore; + messageCenter = messageHub; + registry = sipRegistrarCore; + // _serviceProvider = services.BuildServiceProvider();//, IServiceCollection services + } public void Stop() { @@ -60,48 +61,28 @@ namespace GB28181.Server.Main //InitServer SipAccountStorage.RPCGBServerConfigReceived += SipAccountStorage_RPCGBServerConfigReceived; - //Config Service & and run - ConfigServices(config); + ////Config Service & and run + //ConfigServices(config); //Start the sip main service Task.Factory.StartNew(() => Processing(), _processingServiceToken.Token); } - private void ConfigServices(IConfigurationRoot config) - { - //we should initialize resource here then use them. - servicesContainer.AddSingleton() - .AddSingleton(config) // add configuration - .AddSingleton() - .AddSingleton() - .AddSingleton() - .AddSingleton() - .AddSingleton() - .AddSingleton() - .AddScoped() - .AddTransient() - .AddSingleton() - .AddSingleton() - .AddTransient() - .AddSingleton() - .AddSingleton, DeviceObjectCache>() - .AddScoped() - .AddScoped() - .AddScoped() - .AddScoped() - .AddScoped() - .AddSingleton(servicesContainer); // add itself - _serviceProvider = servicesContainer.BuildServiceProvider(); - } + //private void ConfigServices(IConfigurationRoot config) + //{ + // //we should initialize resource here then use them. + // servicesContainer.AddSingleton(servicesContainer); // add itself + // _serviceProvider = servicesContainer.BuildServiceProvider(); + //} private void Processing() { // _keepaliveTime = DateTime.Now; try { - var _mainSipService = _serviceProvider.GetRequiredService(); + // var _mainSipService = _serviceProvider.GetRequiredService(); //Get meassage Handler - var messageCenter = _serviceProvider.GetRequiredService(); + // var messageCenter = _serviceProvider.GetRequiredService(); // start the Listening SipService in main Service Task.Run(() => { @@ -122,16 +103,17 @@ namespace GB28181.Server.Main }); // run the register service - var registry = _serviceProvider.GetRequiredService(); + // var registry = _serviceProvider.GetRequiredService(); Task.Factory.StartNew(() => registry.ProcessRegisterRequest(), _registryServiceToken.Token); - //Device Status Report - Task.Factory.StartNew(() => messageCenter.DeviceStatusReport(), _deviceStatusReportToken.Token); + //Device Status Report 设备状态 + //Task.Factory.StartNew(() => messageCenter.DeviceStatusReport(), _deviceStatusReportToken.Token); } catch (Exception exMsg) { logger.Error(exMsg.Message); + throw exMsg; } } diff --git a/GB28181.Server/Main/MessageHub.cs b/GB28181.Server/Main/MessageHub.cs index 07d5cb82c963c99af81766648074e01529afd2da..77ae7fe0f0903de1762ac953781a86616d279c57 100644 --- a/GB28181.Server/Main/MessageHub.cs +++ b/GB28181.Server/Main/MessageHub.cs @@ -396,7 +396,7 @@ namespace GB28181.Server.Main _device.Name = gbname; _device.LoginUser.Add(new LoginUser() { LoginName = _SIPAccount.SIPUsername ?? "admin", LoginPwd = _SIPAccount.SIPPassword ?? "123456" });//same to GB config service _device.Port = Convert.ToUInt32(sipTransaction.TransactionRequest.RemoteSIPEndPoint.Port);//5060 - _device.GBID = sipTransaction.TransactionRequestFrom.URI.User;//42010000001180000184 + _device.GBID = sipTransaction.TransactionRequestFrom.URI.User;//78978201001320000015 _device.PtzType = 0; _device.ProtocolType = 0; _device.ShapeType = ShapeType.Dome; @@ -462,6 +462,7 @@ namespace GB28181.Server.Main /// private bool IsDeviceExisted(string deviceid) { + //return true; bool tf = false; //var options = new List { new ChannelOption(ChannelOptions.MaxMessageLength, int.MaxValue) }; // Channel channel = new Channel(EnvironmentVariables.DeviceManagementServiceAddress ?? "devicemanagementservice:8080", ChannelCredentials.Insecure); diff --git a/GB28181.Server/Main/MockProcess.cs b/GB28181.Server/Main/MockProcess.cs index 3b2530fd1379a379b9a9dc2491f28caa3dcc27b4..71b590ecea0c372c7d62a526bfdaebfb4790822d 100644 --- a/GB28181.Server/Main/MockProcess.cs +++ b/GB28181.Server/Main/MockProcess.cs @@ -53,7 +53,7 @@ namespace GB28181.Server.Main case ConsoleKey.I: { var mockCaller = _serviceProvider.GetService(); - //mockCaller.MakeVideoRequest("42010000001180000184", new int[] { 5060 }, EnvironmentVariables.LocalIp); + //mockCaller.MakeVideoRequest("78978201001320000015", new int[] { 5060 }, EnvironmentVariables.LocalIp); } break; case ConsoleKey.E: diff --git a/GB28181.Server/Program.cs b/GB28181.Server/Program.cs index c382d4a62b17dc3d0b6c14c34a7071181c3a478c..414feec92ff4865c09f4dc1b5bd3afe9756e1490 100644 --- a/GB28181.Server/Program.cs +++ b/GB28181.Server/Program.cs @@ -1,11 +1,10 @@ using Microsoft.AspNetCore.Hosting; -using Microsoft.Extensions.DependencyInjection; +using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Hosting; -using System; -using System.Threading.Tasks; using Microsoft.Extensions.Logging; -using Microsoft.Extensions.Configuration; +using System; using System.IO; +using System.Threading.Tasks; namespace GB28181.Service { diff --git a/GB28181.Server/Protos/AsClient/system_config.proto b/GB28181.Server/Protos/AsClient/system_config.proto index 2837aa6d521742241dcb6db0ff766d4d0b2311b2..8e7adef58298e750eb0f6b81480bc5fd5f5a1247 100644 --- a/GB28181.Server/Protos/AsClient/system_config.proto +++ b/GB28181.Server/Protos/AsClient/system_config.proto @@ -44,7 +44,7 @@ message GBPlatformConfig{ string GbVersion = 3;//版本,例如:GB-2018 string LocalID = 4;//SIP服务器编号*,例如:42010000002100000002 string LocalIP = 5;//SIP服务器IP*,例如:10.78.115.182 - string LocalPort = 6;//SIP服务器端口号*,例如:5061 + string LocalPort = 6;//SIP服务器端口号*,例如:5060 string RemotePort = 7;//Device本地端口*,例如:5060 string Authentication = 8;//授权,例如:false string SIPUsername = 9;//帐号*,例如:admin diff --git a/GB28181.Server/Services/DeviceManageImpl.cs b/GB28181.Server/Services/DeviceManageImpl.cs index e05781a81101b6dcd63a8a0642a29eac3b101b4a..53f113d5253ea32847ddaba97dc107f07cdc1f27 100644 --- a/GB28181.Server/Services/DeviceManageImpl.cs +++ b/GB28181.Server/Services/DeviceManageImpl.cs @@ -29,7 +29,7 @@ namespace GB28181.Service.Protos.AsClient.DeviceManagement _device.Name = "gb" + _device.IP; _device.LoginUser.Add(new LoginUser() { LoginName = sIPAccount.SIPUsername ?? "admin", LoginPwd = sIPAccount.SIPPassword ?? "123456" }); _device.Port = Convert.ToUInt32(sipTransaction.TransactionRequest.RemoteSIPEndPoint.Port);//5060 - _device.GBID = sipTransaction.TransactionRequestFrom.URI.User;//42010000001180000184 + _device.GBID = sipTransaction.TransactionRequestFrom.URI.User;//78978201001320000015 _device.PtzType = 0; _device.ProtocolType = 0; _device.ShapeType = ShapeType.Dome; diff --git a/GB28181.Server/Services/SSMediaSessionImpl.cs b/GB28181.Server/Services/SSMediaSessionImpl.cs index 0ad9217acfdbb74e6b39411941d77177dddd81f9..6e5402c983aa17ec475a1717c9b6e7e85089ebf1 100644 --- a/GB28181.Server/Services/SSMediaSessionImpl.cs +++ b/GB28181.Server/Services/SSMediaSessionImpl.cs @@ -174,13 +174,13 @@ namespace GB28181.Service.Protos.Video switch (request.BusinessType) { case BusinessType.BtLiveplay: - tf = _sipServiceDirector.Stop(string.IsNullOrEmpty(request.Gbid) ? "42010000001180000184" : request.Gbid, request.Hdr.Sessionid); + tf = _sipServiceDirector.Stop(string.IsNullOrEmpty(request.Gbid) ? "78978201001320000015" : request.Gbid, request.Hdr.Sessionid); break; case BusinessType.BtPlayback: - tf = _sipServiceDirector.BackVideoStopPlayingControlReq(string.IsNullOrEmpty(request.Gbid) ? "42010000001180000184" : request.Gbid, request.Hdr.Sessionid); + tf = _sipServiceDirector.BackVideoStopPlayingControlReq(string.IsNullOrEmpty(request.Gbid) ? "78978201001320000015" : request.Gbid, request.Hdr.Sessionid); break; default: - tf = _sipServiceDirector.Stop(string.IsNullOrEmpty(request.Gbid) ? "42010000001180000184" : request.Gbid, request.Hdr.Sessionid); + tf = _sipServiceDirector.Stop(string.IsNullOrEmpty(request.Gbid) ? "78978201001320000015" : request.Gbid, request.Hdr.Sessionid); break; } msg = tf ? "Stop Successful!" : "Stop Failed!"; @@ -227,19 +227,19 @@ namespace GB28181.Service.Protos.Video switch (request.PlaybackType) { case PlaybackControlType.Moveto: - tf = _sipServiceDirector.BackVideoPlayPositionControlReq(string.IsNullOrEmpty(request.Gbid) ? "42010000001180000184" : request.Gbid, request.Hdr.Sessionid, request.StartTime); + tf = _sipServiceDirector.BackVideoPlayPositionControlReq(string.IsNullOrEmpty(request.Gbid) ? "78978201001320000015" : request.Gbid, request.Hdr.Sessionid, request.StartTime); break; case PlaybackControlType.Pause: - tf = _sipServiceDirector.BackVideoPauseControlReq(string.IsNullOrEmpty(request.Gbid) ? "42010000001180000184" : request.Gbid, request.Hdr.Sessionid); + tf = _sipServiceDirector.BackVideoPauseControlReq(string.IsNullOrEmpty(request.Gbid) ? "78978201001320000015" : request.Gbid, request.Hdr.Sessionid); break; case PlaybackControlType.Resume: - tf = _sipServiceDirector.BackVideoContinuePlayingControlReq(string.IsNullOrEmpty(request.Gbid) ? "42010000001180000184" : request.Gbid, request.Hdr.Sessionid); + tf = _sipServiceDirector.BackVideoContinuePlayingControlReq(string.IsNullOrEmpty(request.Gbid) ? "78978201001320000015" : request.Gbid, request.Hdr.Sessionid); break; case PlaybackControlType.Scale: - tf = _sipServiceDirector.BackVideoPlaySpeedControlReq(string.IsNullOrEmpty(request.Gbid) ? "42010000001180000184" : request.Gbid, request.Hdr.Sessionid, request.Scale); + tf = _sipServiceDirector.BackVideoPlaySpeedControlReq(string.IsNullOrEmpty(request.Gbid) ? "78978201001320000015" : request.Gbid, request.Hdr.Sessionid, request.Scale); break; default: - tf = _sipServiceDirector.Stop(string.IsNullOrEmpty(request.Gbid) ? "42010000001180000184" : request.Gbid, request.Hdr.Sessionid); + tf = _sipServiceDirector.Stop(string.IsNullOrEmpty(request.Gbid) ? "78978201001320000015" : request.Gbid, request.Hdr.Sessionid); break; } msg = tf ? "PlaybackControl Successful!" : "PlaybackControl Failed!"; diff --git a/GB28181.Server/Startup.cs b/GB28181.Server/Startup.cs index 85fd1f0f183f40ee712869a75fdbba05e958dc42..e379f9701889afed56f3383e9d857a680a6e98ca 100644 --- a/GB28181.Server/Startup.cs +++ b/GB28181.Server/Startup.cs @@ -10,6 +10,15 @@ using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Configuration; using GB28181.Server.Main; +using GB28181.SIPSorcery.Sys.Config; +using GB28181.Server.Message; +using GB28181.SIPSorcery.Servers; +using GB28181.SIPSorcery.Servers.SIPMonitor; +using GB28181.SIPSorcery.Servers.SIPMessage; +using GB28181.SIPSorcery.SIP; +using GB28181.SIPSorcery.Sys.Cache; +using GB28181.SIPSorcery.Sys.Model; +using GB28181.Logger4Net; namespace GB28181.Service { @@ -32,6 +41,26 @@ namespace GB28181.Service services.AddSingleton(); services.AddHostedService(); services.AddGrpc(); + services.AddSingleton() + .AddSingleton() + .AddSingleton() + .AddSingleton() + .AddSingleton() + .AddSingleton() + .AddSingleton() + .AddScoped() + .AddTransient() + .AddSingleton() + .AddSingleton() + .AddTransient() + .AddSingleton() + .AddSingleton, DeviceObjectCache>() + .AddScoped() + .AddScoped() + .AddScoped() + .AddScoped() + .AddScoped(); + } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. diff --git a/GB28181.Server/appsettings.json b/GB28181.Server/appsettings.json index 5d859fd5213da1234714a3fc2e74ff7025b0b40f..3455b61a3e667461a58cd3c83db3a6c0ea51aae7 100644 --- a/GB28181.Server/appsettings.json +++ b/GB28181.Server/appsettings.json @@ -4,9 +4,9 @@ "ID": "10", "Name": "ϼƽ̨", "GbVersion": "GB-2016", - "LocalID": "42010000002100000002", - "LocalIP": "10.78.115.182", - "LocalPort": "5061", + "LocalID": "34020000002000000001", + "LocalIP": "127.0.0.1", + "LocalPort": "5060", "RemotePort": "5060", "Authentication": "false", "SIPUsername": "admin", @@ -21,7 +21,7 @@ "ServiceType": "Device" } }, - "urls": "https://localhost:8080;http://*:80", + "urls": "https://localhost:8082;http://*:82", "Logging": { "LogLevel": { "Default": "Information", diff --git a/GB28181.Solution.sln b/GB28181.Solution.sln index 2d4084773c61af2c9204dfe0fefdca8172f936e4..c04c85c6e6d4958d93569675070bc9aabaec2542 100644 --- a/GB28181.Solution.sln +++ b/GB28181.Solution.sln @@ -9,12 +9,18 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Test.GB28181.Service", "Tes EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Win.GB28181.Client", "Win.GB28181.Client\Win.GB28181.Client.csproj", "{3E2F1C35-7354-4F55-ABA4-44CBCE2E18B5}" EndProject -Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Win.MediaNetEngine", "Win.MeidaNetEngine\Win.MediaNetEngine.csproj", "{8332828E-DA9A-4813-9569-9DBA95DF8FF8}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "SS.MediaNetEngine", "SS.MediaNetEngine\SS.MediaNetEngine.csproj", "{8332828E-DA9A-4813-9569-9DBA95DF8FF8}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "GB28181.SIPSorcery", "GB28181.SIPSorcery\GB28181.SIPSorcery.csproj", "{42050B07-B393-4292-A89F-7ECE14989E0F}" EndProject Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "GB28181.Server", "GB28181.Server\GB28181.Server.csproj", "{A10D6BA9-C42F-4B3A-BBFB-D820FB1597EF}" EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Common.GLib", "Common.GLib\Common.GLib.csproj", "{E377051D-1FF6-4F36-BA54-33F5BBF11154}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "SS.VideoConver", "SS.VideoConver\SS.VideoConver.csproj", "{D6783F96-45F9-488C-8507-9DB2BF0012E2}" +EndProject +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "Common.GLib.WinControls", "Common.GLib.WinControls\Common.GLib.WinControls.csproj", "{C8399060-DEA1-4222-A863-E6F9940D23B0}" +EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Any CPU = Debug|Any CPU @@ -123,6 +129,54 @@ Global {A10D6BA9-C42F-4B3A-BBFB-D820FB1597EF}.Release|x64.Build.0 = Release|Any CPU {A10D6BA9-C42F-4B3A-BBFB-D820FB1597EF}.Release|x86.ActiveCfg = Release|Any CPU {A10D6BA9-C42F-4B3A-BBFB-D820FB1597EF}.Release|x86.Build.0 = Release|Any CPU + {E377051D-1FF6-4F36-BA54-33F5BBF11154}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {E377051D-1FF6-4F36-BA54-33F5BBF11154}.Debug|Any CPU.Build.0 = Debug|Any CPU + {E377051D-1FF6-4F36-BA54-33F5BBF11154}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU + {E377051D-1FF6-4F36-BA54-33F5BBF11154}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU + {E377051D-1FF6-4F36-BA54-33F5BBF11154}.Debug|x64.ActiveCfg = Debug|Any CPU + {E377051D-1FF6-4F36-BA54-33F5BBF11154}.Debug|x64.Build.0 = Debug|Any CPU + {E377051D-1FF6-4F36-BA54-33F5BBF11154}.Debug|x86.ActiveCfg = Debug|Any CPU + {E377051D-1FF6-4F36-BA54-33F5BBF11154}.Debug|x86.Build.0 = Debug|Any CPU + {E377051D-1FF6-4F36-BA54-33F5BBF11154}.Release|Any CPU.ActiveCfg = Release|Any CPU + {E377051D-1FF6-4F36-BA54-33F5BBF11154}.Release|Any CPU.Build.0 = Release|Any CPU + {E377051D-1FF6-4F36-BA54-33F5BBF11154}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU + {E377051D-1FF6-4F36-BA54-33F5BBF11154}.Release|Mixed Platforms.Build.0 = Release|Any CPU + {E377051D-1FF6-4F36-BA54-33F5BBF11154}.Release|x64.ActiveCfg = Release|Any CPU + {E377051D-1FF6-4F36-BA54-33F5BBF11154}.Release|x64.Build.0 = Release|Any CPU + {E377051D-1FF6-4F36-BA54-33F5BBF11154}.Release|x86.ActiveCfg = Release|Any CPU + {E377051D-1FF6-4F36-BA54-33F5BBF11154}.Release|x86.Build.0 = Release|Any CPU + {D6783F96-45F9-488C-8507-9DB2BF0012E2}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {D6783F96-45F9-488C-8507-9DB2BF0012E2}.Debug|Any CPU.Build.0 = Debug|Any CPU + {D6783F96-45F9-488C-8507-9DB2BF0012E2}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU + {D6783F96-45F9-488C-8507-9DB2BF0012E2}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU + {D6783F96-45F9-488C-8507-9DB2BF0012E2}.Debug|x64.ActiveCfg = Debug|Any CPU + {D6783F96-45F9-488C-8507-9DB2BF0012E2}.Debug|x64.Build.0 = Debug|Any CPU + {D6783F96-45F9-488C-8507-9DB2BF0012E2}.Debug|x86.ActiveCfg = Debug|Any CPU + {D6783F96-45F9-488C-8507-9DB2BF0012E2}.Debug|x86.Build.0 = Debug|Any CPU + {D6783F96-45F9-488C-8507-9DB2BF0012E2}.Release|Any CPU.ActiveCfg = Release|Any CPU + {D6783F96-45F9-488C-8507-9DB2BF0012E2}.Release|Any CPU.Build.0 = Release|Any CPU + {D6783F96-45F9-488C-8507-9DB2BF0012E2}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU + {D6783F96-45F9-488C-8507-9DB2BF0012E2}.Release|Mixed Platforms.Build.0 = Release|Any CPU + {D6783F96-45F9-488C-8507-9DB2BF0012E2}.Release|x64.ActiveCfg = Release|Any CPU + {D6783F96-45F9-488C-8507-9DB2BF0012E2}.Release|x64.Build.0 = Release|Any CPU + {D6783F96-45F9-488C-8507-9DB2BF0012E2}.Release|x86.ActiveCfg = Release|Any CPU + {D6783F96-45F9-488C-8507-9DB2BF0012E2}.Release|x86.Build.0 = Release|Any CPU + {C8399060-DEA1-4222-A863-E6F9940D23B0}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {C8399060-DEA1-4222-A863-E6F9940D23B0}.Debug|Any CPU.Build.0 = Debug|Any CPU + {C8399060-DEA1-4222-A863-E6F9940D23B0}.Debug|Mixed Platforms.ActiveCfg = Debug|Any CPU + {C8399060-DEA1-4222-A863-E6F9940D23B0}.Debug|Mixed Platforms.Build.0 = Debug|Any CPU + {C8399060-DEA1-4222-A863-E6F9940D23B0}.Debug|x64.ActiveCfg = Debug|Any CPU + {C8399060-DEA1-4222-A863-E6F9940D23B0}.Debug|x64.Build.0 = Debug|Any CPU + {C8399060-DEA1-4222-A863-E6F9940D23B0}.Debug|x86.ActiveCfg = Debug|Any CPU + {C8399060-DEA1-4222-A863-E6F9940D23B0}.Debug|x86.Build.0 = Debug|Any CPU + {C8399060-DEA1-4222-A863-E6F9940D23B0}.Release|Any CPU.ActiveCfg = Release|Any CPU + {C8399060-DEA1-4222-A863-E6F9940D23B0}.Release|Any CPU.Build.0 = Release|Any CPU + {C8399060-DEA1-4222-A863-E6F9940D23B0}.Release|Mixed Platforms.ActiveCfg = Release|Any CPU + {C8399060-DEA1-4222-A863-E6F9940D23B0}.Release|Mixed Platforms.Build.0 = Release|Any CPU + {C8399060-DEA1-4222-A863-E6F9940D23B0}.Release|x64.ActiveCfg = Release|Any CPU + {C8399060-DEA1-4222-A863-E6F9940D23B0}.Release|x64.Build.0 = Release|Any CPU + {C8399060-DEA1-4222-A863-E6F9940D23B0}.Release|x86.ActiveCfg = Release|Any CPU + {C8399060-DEA1-4222-A863-E6F9940D23B0}.Release|x86.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE diff --git a/README.md b/README.md index 0bbe1ed656fc6ed418a926014164b2c3033ab3a8..b52497b4f5a8eb27af5dc6e81c67ffb9dfe5ec94 100644 --- a/README.md +++ b/README.md @@ -1,8 +1,10 @@ # GB28181 Standard -+ 当前版本以GB2014为基础逐渐增加GB2016的国标要求,最新国标是:【[GB28181-2016](docs/GBT%2028181-2016%20公共安全视频监控联网系统信息传输、交换、控制技术要求-目录版.pdf)】 ++ GB28181开源的目标是:通过代码复用,适当降低工作难度和减少业务代码的重复性,并非替代你的开发工作或者让你几乎不用开发工作。 ++ 最新国标是:【[GB28181-2016](docs/GBT%2028181-2016%20公共安全视频监控联网系统信息传输、交换、控制技术要求-目录版.pdf)】 + 项目结构、代码结仍存在不少问题,待完善,因为时间问题,也是希望大家能一起完善 + 希望每一个对本项目感兴趣的朋友,都能成为本项目的共同作者或者贡献者 ++ 注意:**代码一直在更新,GB28181系列项目,并不是生产就绪的,往往须要根据自己的项目和产品架构,做适当的调整和适配!!** ## 运行环境(environment) @@ -27,12 +29,12 @@ running on aspnetcore 3.1+ 打勾的是已完成的,没打勾的是正在做的,需要大家一起完成的。 -+ Architecture架构 ++ Architecture & framework + [x] 设计与流媒体服务交互的GRPC接口 + [x] 设计与系统配置服务(或数据服务)交互的GRPC接口 + [x] 精简服务模块,调整代码结构关系 + [ ] 为配置接口和流媒体服务接口提供mock数据,使得服务可以独立运行 - + [ ] 以GRPC方式对接流媒体服务[EasydarwinGo](https://www.github.com/gb28181/easydawingo) + + [ ] 以GRPC方式对接流媒体服务【[monibuca](https://github.com/langhuihui/monibuca)】 + [ ] 以GRPC方式从系统配置服务(或者数据服务)中获取GB信令服务的配置信息,包括名称、ID、端口、协议等 + [ ] 使服务注册组件变成可配置的,(当前是consul,并且k8s环境中也不需要) + [x] 将GRPC服务的实现改为apsnetcore3.1+的内置实现方式. @@ -50,8 +52,9 @@ running on aspnetcore 3.1+ + [x] 注册到服务的设备信息缓存 + [ ] 注册到服务的平台信息缓存,待进一步测试 -+ Streaming Media(流媒体,以EasydarwinGo为基础) - + [ ] 实现SIP信令服务与流媒体服务交互的GRPC接口。 ++ Streaming Media(流媒体,以【[monibuca](https://github.com/langhuihui/monibuca)】为基础) + + [x] 定义SIP信令服务与流媒体服务交互的RTSP接口 + + [ ] 定义SIP信令服务与流媒体服务交互的GRPC接口 + [ ] 实现完整的实时视频播放功能, Video Live Play + [ ] 实现完整的历史视频搜索功能,History Video Record Search + [ ] 实现完整的历史视频播放功能, History Video PlayBack @@ -71,7 +74,7 @@ BSD v2 ## 讨论、成为共同作者、近距离贡献 -微信扫描二维码,添加好友,进入微信讨论群(注明:GB28181=公司+姓名): +微信扫描二维码,添加好友,进入微信讨论群(注明:GB28181+公司+姓名): ![qrcode](./docs/crazybber.jpg) diff --git a/Win.MeidaNetEngine/Base/_DebugEx.cs b/SS.MediaNetEngine/Base/_DebugEx.cs similarity index 96% rename from Win.MeidaNetEngine/Base/_DebugEx.cs rename to SS.MediaNetEngine/Base/_DebugEx.cs index 008cebc0f9e2917ae85639aa30b864e28bbb0179..12926493a707a79689eaebc65246d3781e0dc687 100644 --- a/Win.MeidaNetEngine/Base/_DebugEx.cs +++ b/SS.MediaNetEngine/Base/_DebugEx.cs @@ -1,6 +1,6 @@ using System; using System.Linq; -namespace Win.Comm +namespace SS.Comm { public class _DebugEx { diff --git a/Win.MeidaNetEngine/Media/AAC_ADTS.cs b/SS.MediaNetEngine/Media/AAC_ADTS.cs similarity index 99% rename from Win.MeidaNetEngine/Media/AAC_ADTS.cs rename to SS.MediaNetEngine/Media/AAC_ADTS.cs index ed50d882a8f163ae3fb21bf6f8d0bce072cc4785..82965f8f78d5f7452ce7ce6fa14eff1bad61fa6a 100644 --- a/Win.MeidaNetEngine/Media/AAC_ADTS.cs +++ b/SS.MediaNetEngine/Media/AAC_ADTS.cs @@ -3,7 +3,7 @@ using System; using System.Collections.Generic; using System.IO; -namespace Win.MediaServer.Media +namespace SS.MediaServer.Media { public class AAC_ADTS { diff --git a/Win.MeidaNetEngine/Media/AVCodecCfg.cs b/SS.MediaNetEngine/Media/AVCodecCfg.cs similarity index 99% rename from Win.MeidaNetEngine/Media/AVCodecCfg.cs rename to SS.MediaNetEngine/Media/AVCodecCfg.cs index 631ca6eb979118541163bc362a4c40566e061420..1b7cba2d382587a18bf70e4968ad0a9a1cb6f963 100644 --- a/Win.MeidaNetEngine/Media/AVCodecCfg.cs +++ b/SS.MediaNetEngine/Media/AVCodecCfg.cs @@ -3,7 +3,7 @@ using System.Collections.Generic; using System.IO; using System.Text; -namespace Win.Media.Codec +namespace SS.Media.Codec { //编码配置基类 diff --git a/Win.MeidaNetEngine/Media/MediaFrame.cs b/SS.MediaNetEngine/Media/MediaFrame.cs similarity index 99% rename from Win.MeidaNetEngine/Media/MediaFrame.cs rename to SS.MediaNetEngine/Media/MediaFrame.cs index 2dd71b20e899ae25eccbefda657afee0ce95c17c..5369059392bff7829e251c38af321b948fd3b14c 100644 --- a/Win.MeidaNetEngine/Media/MediaFrame.cs +++ b/SS.MediaNetEngine/Media/MediaFrame.cs @@ -1,10 +1,10 @@ using GLib.Extension; using GLib.Net; -using Win.Media.Codec; +using SS.Media.Codec; using System; using System.IO; using System.Text; -namespace Win.Media +namespace SS.Media { public enum AVCode { diff --git a/Win.MeidaNetEngine/Media/PATPMT.cs b/SS.MediaNetEngine/Media/PATPMT.cs similarity index 99% rename from Win.MeidaNetEngine/Media/PATPMT.cs rename to SS.MediaNetEngine/Media/PATPMT.cs index cd08f45805287ed57e616711c536483cd3d2cc5c..5598fa361b0945423daf8b820c0f9b5c830e0df1 100644 --- a/Win.MeidaNetEngine/Media/PATPMT.cs +++ b/SS.MediaNetEngine/Media/PATPMT.cs @@ -5,7 +5,7 @@ using System.Linq; using System.Text; -namespace Win.MediaServer.Media.TS +namespace SS.MediaServer.Media.TS { #region PAT diff --git a/Win.MeidaNetEngine/Media/PES.cs b/SS.MediaNetEngine/Media/PES.cs similarity index 99% rename from Win.MeidaNetEngine/Media/PES.cs rename to SS.MediaNetEngine/Media/PES.cs index 7dffd4b87be4b3b93dc5da62651aef7b8734e105..3a9f948b5d0584cbc45367ca8cceecbe829f4904 100644 --- a/Win.MeidaNetEngine/Media/PES.cs +++ b/SS.MediaNetEngine/Media/PES.cs @@ -1,12 +1,12 @@ using GLib.IO; using GLib.Net; -using Win.Media; +using SS.Media; using System; using System.Collections.Generic; using System.IO; using System.Net; -namespace Win.MediaServer.Media.TS +namespace SS.MediaServer.Media.TS { //http://www.360doc.com/content/13/0512/11/532901_284774233.shtml diff --git a/Win.MeidaNetEngine/Media/StreamFileHelper.cs b/SS.MediaNetEngine/Media/StreamFileHelper.cs similarity index 98% rename from Win.MeidaNetEngine/Media/StreamFileHelper.cs rename to SS.MediaNetEngine/Media/StreamFileHelper.cs index 0fd26e2c8a821500144ecc79a6f221eaea3a5d6f..f60766a34d657c2ae9bee930189d4d508753e32b 100644 --- a/Win.MeidaNetEngine/Media/StreamFileHelper.cs +++ b/SS.MediaNetEngine/Media/StreamFileHelper.cs @@ -1,10 +1,10 @@ -using Win.Media; +using SS.Media; using System; using System.Collections.Generic; using System.IO; using System.Linq; -namespace Win.MediaServer.Media +namespace SS.MediaServer.Media { public class ReadFile { public static List GetBuffByFile1(string file) { diff --git a/Win.MeidaNetEngine/Media/TS/PSAnalyze.cs b/SS.MediaNetEngine/Media/TS/PSAnalyze.cs similarity index 99% rename from Win.MeidaNetEngine/Media/TS/PSAnalyze.cs rename to SS.MediaNetEngine/Media/TS/PSAnalyze.cs index 6446e34be87ebb3f827827500d6efae8e63d6003..9c134863ef3af3a9c1b89c40e6e3784f90463dba 100644 --- a/Win.MeidaNetEngine/Media/TS/PSAnalyze.cs +++ b/SS.MediaNetEngine/Media/TS/PSAnalyze.cs @@ -2,7 +2,7 @@ using GLib.GeneralModel; using GLib.IO; using GLib.Net; -using Win.Media; +using SS.Media; using System; using System.Collections.Generic; using System.IO; @@ -10,7 +10,7 @@ using System.Linq; using System.Net; using System.Threading; -namespace Win.MediaServer.Media.TS +namespace SS.MediaServer.Media.TS { public class HikPSAnalyze : PSAnalyze { @@ -151,7 +151,7 @@ namespace Win.MediaServer.Media.TS } catch (Exception) { - //if (_isWorking && Win.Base.AppConfig._D) + //if (_isWorking && SS.Base.AppConfig._D) //{ // //GLib.DebugEx.WriteLog(e); // throw; diff --git a/Win.MeidaNetEngine/Media/TS/Rtsp/NetSDK.cs b/SS.MediaNetEngine/Media/TS/Rtsp/NetSDK.cs similarity index 95% rename from Win.MeidaNetEngine/Media/TS/Rtsp/NetSDK.cs rename to SS.MediaNetEngine/Media/TS/Rtsp/NetSDK.cs index 2b791c05da12608f32d8391a28b7762a8d25719b..357ad144a894ddc8bfa02ae8e65c8a21ccd446ff 100644 --- a/Win.MeidaNetEngine/Media/TS/Rtsp/NetSDK.cs +++ b/SS.MediaNetEngine/Media/TS/Rtsp/NetSDK.cs @@ -1,4 +1,4 @@ -namespace Win.MediaServer.Media.TS.Rtsp +namespace SS.MediaServer.Media.TS.Rtsp { using System; using System.Runtime.InteropServices; diff --git a/Win.MeidaNetEngine/Media/TS/Rtsp/StreamDataCallBack.cs b/SS.MediaNetEngine/Media/TS/Rtsp/StreamDataCallBack.cs similarity index 85% rename from Win.MeidaNetEngine/Media/TS/Rtsp/StreamDataCallBack.cs rename to SS.MediaNetEngine/Media/TS/Rtsp/StreamDataCallBack.cs index ada1642e251401f89fa2cea3a02ce1b71bb99577..4b9acd19adf37993f98d50554d84c37c5e7761d9 100644 --- a/Win.MeidaNetEngine/Media/TS/Rtsp/StreamDataCallBack.cs +++ b/SS.MediaNetEngine/Media/TS/Rtsp/StreamDataCallBack.cs @@ -1,4 +1,4 @@ -namespace Win.MediaServer.Media.TS.Rtsp +namespace SS.MediaServer.Media.TS.Rtsp { using System; diff --git a/Win.MeidaNetEngine/Media/TS/TSStreamInput/GB28181TSStreamInput.cs b/SS.MediaNetEngine/Media/TS/TSStreamInput/GB28181TSStreamInput.cs similarity index 96% rename from Win.MeidaNetEngine/Media/TS/TSStreamInput/GB28181TSStreamInput.cs rename to SS.MediaNetEngine/Media/TS/TSStreamInput/GB28181TSStreamInput.cs index b344aafc3e6c8d9cd07b92d48aaa74354a3237ac..ec8c4f9f5c7428f7910b843ee7b9498ba641dd6c 100644 --- a/Win.MeidaNetEngine/Media/TS/TSStreamInput/GB28181TSStreamInput.cs +++ b/SS.MediaNetEngine/Media/TS/TSStreamInput/GB28181TSStreamInput.cs @@ -1,13 +1,13 @@ using GLib.AXLib.Utility; -using Win.Media; -using Win.MediaServer.Media.TS; +using SS.Media; +using SS.MediaServer.Media.TS; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; -namespace Win.MeidaNetEngine.Media.TS +namespace SS.MeidaNetEngine.Media.TS { public class GB28181TSStreamInput : TSStreamInput { diff --git a/Win.MeidaNetEngine/Media/TS/TSStreamInput/TSStreamInput.cs b/SS.MediaNetEngine/Media/TS/TSStreamInput/TSStreamInput.cs similarity index 99% rename from Win.MeidaNetEngine/Media/TS/TSStreamInput/TSStreamInput.cs rename to SS.MediaNetEngine/Media/TS/TSStreamInput/TSStreamInput.cs index 0fb16c8dac494478e6e1d6ac1bc032a5ca8fd9be..e4b81510bcda6b41fe945a5ecc7c7ec34b0b8f3b 100644 --- a/Win.MeidaNetEngine/Media/TS/TSStreamInput/TSStreamInput.cs +++ b/SS.MediaNetEngine/Media/TS/TSStreamInput/TSStreamInput.cs @@ -1,15 +1,15 @@ using GLib.AXLib.Utility; using GLib.GeneralModel; using GLib.IO; -using Win.Comm; -using Win.Media; +using SS.Comm; +using SS.Media; using System; using System.IO; using System.Linq; using System.Threading; using System.Xml.Serialization; -namespace Win.MediaServer.Media.TS +namespace SS.MediaServer.Media.TS { public class WSIPTVChannelInfo diff --git a/Win.MeidaNetEngine/Media/TS/mp4parser/AspectRatio.cs b/SS.MediaNetEngine/Media/TS/mp4parser/AspectRatio.cs similarity index 100% rename from Win.MeidaNetEngine/Media/TS/mp4parser/AspectRatio.cs rename to SS.MediaNetEngine/Media/TS/mp4parser/AspectRatio.cs diff --git a/Win.MeidaNetEngine/Media/TS/mp4parser/BTree.cs b/SS.MediaNetEngine/Media/TS/mp4parser/BTree.cs similarity index 100% rename from Win.MeidaNetEngine/Media/TS/mp4parser/BTree.cs rename to SS.MediaNetEngine/Media/TS/mp4parser/BTree.cs diff --git a/Win.MeidaNetEngine/Media/TS/mp4parser/BitstreamReader.cs b/SS.MediaNetEngine/Media/TS/mp4parser/BitstreamReader.cs similarity index 100% rename from Win.MeidaNetEngine/Media/TS/mp4parser/BitstreamReader.cs rename to SS.MediaNetEngine/Media/TS/mp4parser/BitstreamReader.cs diff --git a/Win.MeidaNetEngine/Media/TS/mp4parser/BitstreamWriter.cs b/SS.MediaNetEngine/Media/TS/mp4parser/BitstreamWriter.cs similarity index 100% rename from Win.MeidaNetEngine/Media/TS/mp4parser/BitstreamWriter.cs rename to SS.MediaNetEngine/Media/TS/mp4parser/BitstreamWriter.cs diff --git a/Win.MeidaNetEngine/Media/TS/mp4parser/CAVLCReader.cs b/SS.MediaNetEngine/Media/TS/mp4parser/CAVLCReader.cs similarity index 100% rename from Win.MeidaNetEngine/Media/TS/mp4parser/CAVLCReader.cs rename to SS.MediaNetEngine/Media/TS/mp4parser/CAVLCReader.cs diff --git a/Win.MeidaNetEngine/Media/TS/mp4parser/CAVLCWriter.cs b/SS.MediaNetEngine/Media/TS/mp4parser/CAVLCWriter.cs similarity index 100% rename from Win.MeidaNetEngine/Media/TS/mp4parser/CAVLCWriter.cs rename to SS.MediaNetEngine/Media/TS/mp4parser/CAVLCWriter.cs diff --git a/Win.MeidaNetEngine/Media/TS/mp4parser/CharCache.cs b/SS.MediaNetEngine/Media/TS/mp4parser/CharCache.cs similarity index 100% rename from Win.MeidaNetEngine/Media/TS/mp4parser/CharCache.cs rename to SS.MediaNetEngine/Media/TS/mp4parser/CharCache.cs diff --git a/Win.MeidaNetEngine/Media/TS/mp4parser/ChromaFormat.cs b/SS.MediaNetEngine/Media/TS/mp4parser/ChromaFormat.cs similarity index 100% rename from Win.MeidaNetEngine/Media/TS/mp4parser/ChromaFormat.cs rename to SS.MediaNetEngine/Media/TS/mp4parser/ChromaFormat.cs diff --git a/Win.MeidaNetEngine/Media/TS/mp4parser/HRDParameters.cs b/SS.MediaNetEngine/Media/TS/mp4parser/HRDParameters.cs similarity index 100% rename from Win.MeidaNetEngine/Media/TS/mp4parser/HRDParameters.cs rename to SS.MediaNetEngine/Media/TS/mp4parser/HRDParameters.cs diff --git a/Win.MeidaNetEngine/Media/TS/mp4parser/PictureParameterSet.cs b/SS.MediaNetEngine/Media/TS/mp4parser/PictureParameterSet.cs similarity index 100% rename from Win.MeidaNetEngine/Media/TS/mp4parser/PictureParameterSet.cs rename to SS.MediaNetEngine/Media/TS/mp4parser/PictureParameterSet.cs diff --git a/Win.MeidaNetEngine/Media/TS/mp4parser/ScalingList.cs b/SS.MediaNetEngine/Media/TS/mp4parser/ScalingList.cs similarity index 100% rename from Win.MeidaNetEngine/Media/TS/mp4parser/ScalingList.cs rename to SS.MediaNetEngine/Media/TS/mp4parser/ScalingList.cs diff --git a/Win.MeidaNetEngine/Media/TS/mp4parser/ScalingMatrix.cs b/SS.MediaNetEngine/Media/TS/mp4parser/ScalingMatrix.cs similarity index 100% rename from Win.MeidaNetEngine/Media/TS/mp4parser/ScalingMatrix.cs rename to SS.MediaNetEngine/Media/TS/mp4parser/ScalingMatrix.cs diff --git a/Win.MeidaNetEngine/Media/TS/mp4parser/SeqParameterSet.cs b/SS.MediaNetEngine/Media/TS/mp4parser/SeqParameterSet.cs similarity index 100% rename from Win.MeidaNetEngine/Media/TS/mp4parser/SeqParameterSet.cs rename to SS.MediaNetEngine/Media/TS/mp4parser/SeqParameterSet.cs diff --git a/Win.MeidaNetEngine/Media/TS/mp4parser/SliceHeader.cs b/SS.MediaNetEngine/Media/TS/mp4parser/SliceHeader.cs similarity index 100% rename from Win.MeidaNetEngine/Media/TS/mp4parser/SliceHeader.cs rename to SS.MediaNetEngine/Media/TS/mp4parser/SliceHeader.cs diff --git a/Win.MeidaNetEngine/Media/TS/mp4parser/VUIParameters.cs b/SS.MediaNetEngine/Media/TS/mp4parser/VUIParameters.cs similarity index 100% rename from Win.MeidaNetEngine/Media/TS/mp4parser/VUIParameters.cs rename to SS.MediaNetEngine/Media/TS/mp4parser/VUIParameters.cs diff --git a/Win.MeidaNetEngine/Media/TSPacket.cs b/SS.MediaNetEngine/Media/TSPacket.cs similarity index 99% rename from Win.MeidaNetEngine/Media/TSPacket.cs rename to SS.MediaNetEngine/Media/TSPacket.cs index a09591627b2fd459191e538b66af12856865de9b..7258b3c0e733545d0d3d03cf142edd84419fc868 100644 --- a/Win.MeidaNetEngine/Media/TSPacket.cs +++ b/SS.MediaNetEngine/Media/TSPacket.cs @@ -1,11 +1,11 @@ using GLib.IO; -using Win.Media; +using SS.Media; using System; using System.IO; using System.Text; -namespace Win.MediaServer.Media.TS +namespace SS.MediaServer.Media.TS { //http://www.360doc.com/content/13/0512/11/532901_284774233.shtml diff --git a/Win.MeidaNetEngine/Media/TSProgramManage.cs b/SS.MediaNetEngine/Media/TSProgramManage.cs similarity index 99% rename from Win.MeidaNetEngine/Media/TSProgramManage.cs rename to SS.MediaNetEngine/Media/TSProgramManage.cs index e4d293580ac1d1451fb1031300a6f5b68de4ca23..283a8800ae5cf3b37350cf7d0c855e2fb38009bd 100644 --- a/Win.MeidaNetEngine/Media/TSProgramManage.cs +++ b/SS.MediaNetEngine/Media/TSProgramManage.cs @@ -2,9 +2,9 @@ using System.Collections.Generic; using System.IO; using System.Linq; -using Win.Media; +using SS.Media; -namespace Win.MediaServer.Media.TS +namespace SS.MediaServer.Media.TS { //http://www.360doc.com/content/13/0512/11/532901_284774233.shtml diff --git a/SS.MediaNetEngine/SS.MediaNetEngine.csproj b/SS.MediaNetEngine/SS.MediaNetEngine.csproj new file mode 100644 index 0000000000000000000000000000000000000000..7b4b19182f3c9fe55501e3e9383815e8d6cab13a --- /dev/null +++ b/SS.MediaNetEngine/SS.MediaNetEngine.csproj @@ -0,0 +1,18 @@ + + + Library + netstandard2.0 + 8.0 + false + SS.MediaNetEngine + SS.MediaNetEngine + true + + + TRACE;DEBUG;NETCOREAPP3_1 + + + + + + \ No newline at end of file diff --git a/SS.VideoConver/Properties/AssemblyInfo.cs b/SS.VideoConver/Properties/AssemblyInfo.cs new file mode 100644 index 0000000000000000000000000000000000000000..1d2aa920c8582f5f4a3ad8cbec458f7096190162 --- /dev/null +++ b/SS.VideoConver/Properties/AssemblyInfo.cs @@ -0,0 +1,20 @@ +using System.Diagnostics; +using System.Reflection; +using System.Runtime.CompilerServices; +using System.Runtime.InteropServices; +using System.Runtime.Versioning; + +[assembly: ComVisible(false)] +[assembly: AssemblyFileVersion("1.0.0.0")] +[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)] +[assembly: AssemblyTrademark("")] +[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] +[assembly: AssemblyCopyright("Copyright © 2012")] +[assembly: Guid("e8d0c7d8-16f2-4e43-95d6-ae6f9c7629f8")] +[assembly: CompilationRelaxations(8)] +[assembly: AssemblyTitle("StarEye.VideoConver")] +[assembly: AssemblyDescription("")] +[assembly: AssemblyProduct("StarEye.VideoConver")] +[assembly: AssemblyConfiguration("")] +[assembly: AssemblyCompany("")] +[assembly: AssemblyVersion("1.0.0.0")] diff --git a/SS.VideoConver/QuickAudioEncodingCommands.cs b/SS.VideoConver/QuickAudioEncodingCommands.cs new file mode 100644 index 0000000000000000000000000000000000000000..add0be444819cd5e6a1459ffe3de089a5360b810 --- /dev/null +++ b/SS.VideoConver/QuickAudioEncodingCommands.cs @@ -0,0 +1,10 @@ +public class QuickAudioEncodingCommands +{ + public static string MP3128Kbps = "-y -ab 128k -ar 44100"; + + public static string MP396Kbps = "-y -ab 96k -ar 44100"; + + public static string MP364Kbps = "-y -ab 64k -ar 44100"; + + public static string MP332Kbps = "-y -ab 32k -ar 44100"; +} diff --git a/SS.VideoConver/SS.VideoConver.csproj b/SS.VideoConver/SS.VideoConver.csproj new file mode 100644 index 0000000000000000000000000000000000000000..c758d09701dfea2234850439fa2987fd5d7996a4 --- /dev/null +++ b/SS.VideoConver/SS.VideoConver.csproj @@ -0,0 +1,11 @@ + + + netstandard2.0 + false + SS.VideoConver + SS.VideoConver + + + TRACE;DEBUG;NETCOREAPP3_1 + + diff --git a/SS.VideoConver/StarEye.VideoConver.sln b/SS.VideoConver/StarEye.VideoConver.sln new file mode 100644 index 0000000000000000000000000000000000000000..3dbe32fe7b065204373cbb2260171730ca6bb223 --- /dev/null +++ b/SS.VideoConver/StarEye.VideoConver.sln @@ -0,0 +1,25 @@ + +Microsoft Visual Studio Solution File, Format Version 12.00 +# Visual Studio Version 16 +VisualStudioVersion = 16.0.29806.167 +MinimumVisualStudioVersion = 10.0.40219.1 +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "StarEye.VideoConver", "StarEye.VideoConver.csproj", "{D6783F96-45F9-488C-8507-9DB2BF0012E2}" +EndProject +Global + GlobalSection(SolutionConfigurationPlatforms) = preSolution + Debug|x86 = Debug|x86 + Release|x86 = Release|x86 + EndGlobalSection + GlobalSection(ProjectConfigurationPlatforms) = postSolution + {D6783F96-45F9-488C-8507-9DB2BF0012E2}.Debug|x86.ActiveCfg = Debug|x86 + {D6783F96-45F9-488C-8507-9DB2BF0012E2}.Debug|x86.Build.0 = Debug|x86 + {D6783F96-45F9-488C-8507-9DB2BF0012E2}.Release|x86.ActiveCfg = Release|x86 + {D6783F96-45F9-488C-8507-9DB2BF0012E2}.Release|x86.Build.0 = Release|x86 + EndGlobalSection + GlobalSection(SolutionProperties) = preSolution + HideSolutionNode = FALSE + EndGlobalSection + GlobalSection(ExtensibilityGlobals) = postSolution + SolutionGuid = {F24FB382-B4DD-476E-AEA0-2605E8F0E016} + EndGlobalSection +EndGlobal diff --git a/SS.VideoConver/VideoEncoder/EncodedVideo.cs b/SS.VideoConver/VideoEncoder/EncodedVideo.cs new file mode 100644 index 0000000000000000000000000000000000000000..50fc3d3714275d552a3614cf97c7bfb05bfba251 --- /dev/null +++ b/SS.VideoConver/VideoEncoder/EncodedVideo.cs @@ -0,0 +1,29 @@ +namespace VideoEncoder +{ + public class EncodedVideo + { + public string EncodedVideoPath + { + get; + set; + } + + public string ThumbnailPath + { + get; + set; + } + + public string EncodingLog + { + get; + set; + } + + public bool Success + { + get; + set; + } + } +} diff --git a/SS.VideoConver/VideoEncoder/Encoder.cs b/SS.VideoConver/VideoEncoder/Encoder.cs new file mode 100644 index 0000000000000000000000000000000000000000..ac014b5f539a74f507df8101289c75bd64c16a7a --- /dev/null +++ b/SS.VideoConver/VideoEncoder/Encoder.cs @@ -0,0 +1,211 @@ +using System; +using System.Diagnostics; +using System.IO; +using System.Text.RegularExpressions; + +namespace VideoEncoder +{ + public class Encoder + { + public string FFmpegPath + { + get; + set; + } + + private string Params + { + get; + set; + } + + public EncodedVideo EncodeVideo(VideoFile input, string encodingCommand, string outputFile, bool getVideoThumbnail) + { + EncodedVideo encodedVideo = new EncodedVideo(); + Params = $"-i {input.File} {encodingCommand} {outputFile}"; + string text2 = encodedVideo.EncodingLog = RunProcess(Params); + encodedVideo.EncodedVideoPath = outputFile; + if (File.Exists(outputFile)) + { + encodedVideo.Success = true; + if (getVideoThumbnail) + { + string text3 = outputFile + "_thumb.jpg"; + if (GetVideoThumbnail(input, text3)) + { + encodedVideo.ThumbnailPath = text3; + } + } + } + else + { + encodedVideo.Success = false; + } + return encodedVideo; + } + + public bool GetVideoThumbnail(VideoFile input, string saveThumbnailTo) + { + if (!input.infoGathered) + { + GetVideoInfo(input); + } + int num = (int)Math.Round(TimeSpan.FromTicks(input.Duration.Ticks / 3).TotalSeconds, 0); + string parameters = $"-i {input.File} {saveThumbnailTo} -vcodec mjpeg -ss {num} -vframes 1 -an -f rawvideo"; + string text = RunProcess(parameters); + if (File.Exists(saveThumbnailTo)) + { + return true; + } + parameters = $"-i {input.File} {saveThumbnailTo} -vcodec mjpeg -ss {1} -vframes 1 -an -f rawvideo"; + text = RunProcess(parameters); + if (File.Exists(saveThumbnailTo)) + { + return true; + } + return false; + } + + public void GetVideoInfo(VideoFile input) + { + string parameters = $"-i {input.File}"; + string text2 = input.RawInfo = RunProcess(parameters); + input.Duration = ExtractDuration(input.RawInfo); + input.BitRate = ExtractBitrate(input.RawInfo); + input.RawAudioFormat = ExtractRawAudioFormat(input.RawInfo); + input.AudioFormat = ExtractAudioFormat(input.RawAudioFormat); + input.RawVideoFormat = ExtractRawVideoFormat(input.RawInfo); + input.VideoFormat = ExtractVideoFormat(input.RawVideoFormat); + input.Width = ExtractVideoWidth(input.RawInfo); + input.Height = ExtractVideoHeight(input.RawInfo); + input.infoGathered = true; + } + + private string RunProcess(string Parameters) + { + ProcessStartInfo processStartInfo = new ProcessStartInfo(FFmpegPath, Parameters); + processStartInfo.UseShellExecute = false; + processStartInfo.CreateNoWindow = true; + processStartInfo.RedirectStandardOutput = true; + processStartInfo.RedirectStandardError = true; + string result = null; + StreamReader streamReader = null; + try + { + Process process = Process.Start(processStartInfo); + process.WaitForExit(); + streamReader = process.StandardError; + result = streamReader.ReadToEnd(); + process.Close(); + } + catch (Exception) + { + result = string.Empty; + } + finally + { + if (streamReader != null) + { + streamReader.Close(); + streamReader.Dispose(); + } + } + return result; + } + + private TimeSpan ExtractDuration(string rawInfo) + { + TimeSpan result = new TimeSpan(0L); + Regex regex = new Regex("[D|d]uration:.((\\d|:|\\.)*)", RegexOptions.Compiled); + Match match = regex.Match(rawInfo); + if (match.Success) + { + string value = match.Groups[1].Value; + string[] array = value.Split(':', '.'); + if (array.Length == 4) + { + result = new TimeSpan(0, Convert.ToInt16(array[0]), Convert.ToInt16(array[1]), Convert.ToInt16(array[2]), Convert.ToInt16(array[3])); + } + } + return result; + } + + private double ExtractBitrate(string rawInfo) + { + Regex regex = new Regex("[B|b]itrate:.((\\d|:)*)", RegexOptions.Compiled); + Match match = regex.Match(rawInfo); + double result = 0.0; + if (match.Success) + { + double.TryParse(match.Groups[1].Value, out result); + } + return result; + } + + private string ExtractRawAudioFormat(string rawInfo) + { + string text = string.Empty; + Regex regex = new Regex("[A|a]udio:.*", RegexOptions.Compiled); + Match match = regex.Match(rawInfo); + if (match.Success) + { + text = match.Value; + } + return text.Replace("Audio: ", ""); + } + + private string ExtractAudioFormat(string rawAudioFormat) + { + string[] array = rawAudioFormat.Split(new string[1] + { + ", " + }, StringSplitOptions.None); + return array[0].Replace("Audio: ", ""); + } + + private string ExtractRawVideoFormat(string rawInfo) + { + string text = string.Empty; + Regex regex = new Regex("[V|v]ideo:.*", RegexOptions.Compiled); + Match match = regex.Match(rawInfo); + if (match.Success) + { + text = match.Value; + } + return text.Replace("Video: ", ""); + } + + private string ExtractVideoFormat(string rawVideoFormat) + { + string[] array = rawVideoFormat.Split(new string[1] + { + ", " + }, StringSplitOptions.None); + return array[0].Replace("Video: ", ""); + } + + private int ExtractVideoWidth(string rawInfo) + { + int result = 0; + Regex regex = new Regex("(\\d{2,4})x(\\d{2,4})", RegexOptions.Compiled); + Match match = regex.Match(rawInfo); + if (match.Success) + { + int.TryParse(match.Groups[1].Value, out result); + } + return result; + } + + private int ExtractVideoHeight(string rawInfo) + { + int result = 0; + Regex regex = new Regex("(\\d{2,4})x(\\d{2,4})", RegexOptions.Compiled); + Match match = regex.Match(rawInfo); + if (match.Success) + { + int.TryParse(match.Groups[2].Value, out result); + } + return result; + } + } +} diff --git a/SS.VideoConver/VideoEncoder/QuickVideoEncodingCommands.cs b/SS.VideoConver/VideoEncoder/QuickVideoEncodingCommands.cs new file mode 100644 index 0000000000000000000000000000000000000000..78351ee5fd2593504b3b3b94f01f7d238c06ebd7 --- /dev/null +++ b/SS.VideoConver/VideoEncoder/QuickVideoEncodingCommands.cs @@ -0,0 +1,91 @@ +namespace VideoEncoder +{ + public class QuickVideoEncodingCommands + { + private static string LQVideoBitrate = "256k"; + + private static string MQVideoBitrate = "512k"; + + private static string HQVideoBitrate = "756k"; + + private static string VHQVideoBitrate = "1024k"; + + private static string LQAudioBitrate = "32k"; + + private static string MQAudioBitrate = "64k"; + + private static string HQAudioBitrate = "96k"; + + private static string VHQAudioBitrate = "128k"; + + private static string LQAudioSamplingFrequency = "22050"; + + private static string MQAudioSamplingFrequency = "44100"; + + private static string HQAudioSamplingFrequency = "44100"; + + private static string SQCIF = "sqcif"; + + private static string QCIF = "qcif"; + + private static string QVGA = "qvga"; + + private static string CIF = "cif"; + + private static string VGA = "vga"; + + private static string SVGA = "svga"; + + private static string N43 = "480x360"; + + public static string FLVLowQualityQCIF = $"-y -b {LQVideoBitrate} -ab {LQAudioBitrate} -ar {LQAudioSamplingFrequency} -s {QVGA} -f flv"; + + public static string FLVMediumQualityCIF = $"-y -b {MQVideoBitrate} -ab {MQAudioBitrate} -ar {MQAudioSamplingFrequency} -s {CIF} -f flv"; + + public static string FLVHighQualityVGA = $"-y -b {HQVideoBitrate} -ab {HQAudioBitrate} -ar {HQAudioSamplingFrequency} -s {VGA} -f flv"; + + public static string FLVVeryHighQualitySVGA = $"-y -b {VHQVideoBitrate} -ab {VHQAudioBitrate} -ar {HQAudioSamplingFrequency} -s {SVGA} -f flv"; + + public static string FLVLowQualityKeepOriginalSize = string.Format("-y -b {0} -ab {1} -ar {2} -f flv", LQVideoBitrate, LQAudioBitrate, LQAudioSamplingFrequency, QVGA); + + public static string FLVMediumQualityKeepOriginalSize = string.Format("-y -b {0} -ab {1} -ar {2} -f flv", MQVideoBitrate, MQAudioBitrate, MQAudioSamplingFrequency, CIF); + + public static string FLVHighQualityKeepOriginalSize = string.Format("-y -b {0} -ab {1} -ar {2} -f flv", HQVideoBitrate, HQAudioBitrate, HQAudioSamplingFrequency, VGA); + + public static string FLVVeryHighQualityKeepOriginalSize = string.Format("-y -b {0} -ab {1} -ar {2} -f flv", VHQVideoBitrate, VHQAudioBitrate, HQAudioSamplingFrequency, SVGA); + + public static string THREEGPLowQualitySQCIF = $"-y -acodec aac -ac 1 -b {LQVideoBitrate} -ab {LQAudioBitrate} -ar {LQAudioSamplingFrequency} -s {SQCIF} -f 3gp"; + + public static string THREEGPMediumQualityQCIF = $"-y -acodec aac -b {MQVideoBitrate} -ab {MQAudioBitrate} -ar {MQAudioSamplingFrequency} -s {QCIF} -f 3gp"; + + public static string THREEGPHighQualityCIF = $"-y -acodec aac -b {VHQVideoBitrate} -ab {VHQAudioBitrate} -ar {HQAudioSamplingFrequency} -s {CIF} -f 3gp"; + + public static string MP4LowQualityKeepOriginalSize = string.Format("-y -b {0} -ab {1} -ar {2} -f mp4", LQVideoBitrate, LQAudioBitrate, LQAudioSamplingFrequency, QVGA); + + public static string MP4MediumQualityKeepOriginalSize = string.Format("-y -b {0} -ab {1} -ar {2} -f mp4", MQVideoBitrate, MQAudioBitrate, MQAudioSamplingFrequency, CIF); + + public static string MP4HighQualityKeepOriginalSize = string.Format("-y -b {0} -ab {1} -ar {2} -f mp4", HQVideoBitrate, HQAudioBitrate, HQAudioSamplingFrequency, VGA); + + public static string MP4LowQualityQVGA = $"-y -b {LQVideoBitrate} -ab {LQAudioBitrate} -ar {LQAudioSamplingFrequency} -s {QVGA} -f mp4"; + + public static string MP4MediumQualityCIF = $"-y -b {MQVideoBitrate} -ab {MQAudioBitrate} -ar {MQAudioSamplingFrequency} -s {CIF} -f mp4"; + + public static string MP4HighQualityVGA = $"-y -b {HQVideoBitrate} -ab {HQAudioBitrate} -ar {HQAudioSamplingFrequency} -s {VGA} -f mp4"; + + public static string WMVLowQualityQVGA = $"-y -vcodec wmv2 -acodec wmav2 -b {LQVideoBitrate} -ab {LQAudioBitrate} -ar {LQAudioSamplingFrequency} -s {QVGA}"; + + public static string WMVMediumQualityCIF = $"-y -vcodec wmv2 -acodec wmav2 -b {MQVideoBitrate} -ab {MQAudioBitrate} -ar {MQAudioSamplingFrequency} -s {CIF}"; + + public static string WMVHighQualityVGA = $"-y -vcodec wmv2 -acodec wmav2 -b {HQVideoBitrate} -ab {HQAudioBitrate} -ar {HQAudioSamplingFrequency} -s {VGA}"; + + public static string WMVVeryHighQualitySVGA = $"-y -vcodec wmv2 -acodec wmav2 -b {VHQVideoBitrate} -ab {VHQAudioBitrate} -ar {HQAudioSamplingFrequency} -s {SVGA}"; + + public static string WMVLowQualityKeepOriginalSize = string.Format("-y -vcodec wmv2 -acodec wmav2 -b {0} -ab {1} -ar {2}", LQVideoBitrate, LQAudioBitrate, LQAudioSamplingFrequency, QVGA); + + public static string WMVMediumQualityKeepOriginalSize = string.Format("-y -vcodec wmv2 -acodec wmav2 -b {0} -ab {1} -ar {2}", MQVideoBitrate, MQAudioBitrate, MQAudioSamplingFrequency, CIF); + + public static string WMVHighQualityKeepOriginalSize = string.Format("-y -vcodec wmv2 -acodec wmav2 -b {0} -ab {1} -ar {2}", HQVideoBitrate, HQAudioBitrate, HQAudioSamplingFrequency, VGA); + + public static string WMVVeryHighQualityKeepOriginalSize = string.Format("-y -vcodec wmv2 -acodec wmav2 -b {0} -ab {1} -ar {2}", VHQVideoBitrate, VHQAudioBitrate, HQAudioSamplingFrequency, SVGA); + } +} diff --git a/SS.VideoConver/VideoEncoder/VideoFile.cs b/SS.VideoConver/VideoEncoder/VideoFile.cs new file mode 100644 index 0000000000000000000000000000000000000000..b17d4dd50b7a2ddb9c4a3b69449f1f34b8d146de --- /dev/null +++ b/SS.VideoConver/VideoEncoder/VideoFile.cs @@ -0,0 +1,106 @@ +using System; +using System.IO; + +namespace VideoEncoder +{ + public class VideoFile + { + private string _File; + + public string File + { + get + { + return _File; + } + set + { + _File = value; + } + } + + public TimeSpan Duration + { + get; + set; + } + + public double BitRate + { + get; + set; + } + + public string RawAudioFormat + { + get; + set; + } + + public string AudioFormat + { + get; + set; + } + + public string RawVideoFormat + { + get; + set; + } + + public string VideoFormat + { + get; + set; + } + + public int Height + { + get; + set; + } + + public int Width + { + get; + set; + } + + public string RawInfo + { + get; + set; + } + + public bool infoGathered + { + get; + set; + } + + public VideoFile(string path) + { + _File = path; + Initialize(); + } + + private void Initialize() + { + infoGathered = false; + if (string.IsNullOrEmpty(_File)) + { + throw new Exception("Video file Path not set or empty."); + } + if (!System.IO.File.Exists(_File)) + { + throw new Exception("The video file " + _File + " does not exist."); + } + } + + public override string ToString() + { + return $"w*h:{Width}*{Height}, time:{Duration}, format:{VideoFormat}, raw:{RawVideoFormat}, "; + } + } +} diff --git a/SS.VideoConver/VideoThumbnail/Program.cs b/SS.VideoConver/VideoThumbnail/Program.cs new file mode 100644 index 0000000000000000000000000000000000000000..da6c06ec746e0a00700e46d70ad8c11f6ab2a093 --- /dev/null +++ b/SS.VideoConver/VideoThumbnail/Program.cs @@ -0,0 +1,133 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.IO; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +using videoconver; +using VideoEncoder; + +namespace VideoThumbnail +{ + public class Thumbnail + { + private const string Thumbnails_cmd_format = " -y -i {0} -f image2 -ss {1}.001 -s 240x180 {2}"; + + private const string ffmpeg_param_format = " -y -i {0} {1}"; + + private static string ffmpeg = "ffmpeg.exe"; + + private static List ProcessList = new List(); + + public static event Action OnProcessData; + + public static event Action Trace; + + + public static void CreateThumbnails(string iFile, string oFile) + { + VideoFile videoInfo = GetVideoInfo(iFile); + CreateThumbnails(iFile, oFile, (int)videoInfo.Duration.TotalSeconds / 2); + } + + public static void CreateThumbnails(string iFile, string oFile, int time) + { + VideoFile videoInfo = GetVideoInfo(iFile); + oFile = ShellPathNameConvert.ToShortPathName(Path.GetDirectoryName(oFile)) + "\\" + Path.GetFileName(oFile); + iFile = ShellPathNameConvert.ToShortPathName(iFile); + var num = videoInfo.Duration.TotalSeconds / 2.0; + if (num > 8.0) + { + num = 8.0; + } + var arguments = string.Format(" -y -i {0} -f image2 -ss {2}.001 -s 240x180 {1}", iFile, oFile, time); + var p = CreateProcess(ffmpeg, arguments); + RunProcess(p); + } + + public static void RunProcess(Process p) + { + DateTime dt = DateTime.Now; + try + { + ProcessList.Add(p); + p.Start(); + p.BeginOutputReadLine(); + p.BeginErrorReadLine(); + DataReceivedEventHandler value = delegate(object sender, DataReceivedEventArgs e) + { + dt = DateTime.Now; + OnProcessData?.Invoke(e.Data); + }; + p.ErrorDataReceived += value; + p.OutputDataReceived += value; + Task task = new Task(delegate + { + p.WaitForExit(); + }); + task.Start(); + do + { + Thread.Sleep(100); + } + while (dt.AddMinutes(1.0) > DateTime.Now && !task.IsCompleted && !task.IsFaulted && !task.IsCanceled); + p.ErrorDataReceived -= value; + p.OutputDataReceived -= value; + p.CancelOutputRead(); + p.CancelErrorRead(); + if (!p.HasExited) + { + p.Kill(); + } + p.Close(); + p.Dispose(); + ProcessList.Remove(p); + } + catch + { + p.Dispose(); + throw; + } + } + + public static VideoFile GetVideoInfo(string iFile) + { + VideoEncoder.Encoder encoder = new VideoEncoder.Encoder(); + encoder.FFmpegPath = ffmpeg; + VideoFile videoFile = new VideoFile(iFile); + encoder.GetVideoInfo(videoFile); + TimeSpan duration = videoFile.Duration; + StringBuilder stringBuilder = new StringBuilder(); + string arg = $"{(int)duration.TotalHours:00}:{duration.Minutes:00}:{duration.Seconds:00}"; + stringBuilder.AppendFormat("时间长度:{0}\n", arg); + stringBuilder.AppendFormat("高度:{0}\n", videoFile.Height); + stringBuilder.AppendFormat("宽度:{0}\n", videoFile.Width); + stringBuilder.AppendFormat("数据格式:{0}\n", videoFile.VideoFormat); + stringBuilder.AppendFormat("比特率:{0}\n", videoFile.BitRate); + stringBuilder.AppendFormat("文件路径:{0}\n", videoFile.File); + return videoFile; + } + + public static Process CreateProcess(string exe, string arguments) + { + string text = $"{exe} {arguments}"; + Process process = new Process(); + process.StartInfo.WindowStyle = ProcessWindowStyle.Normal; + process.StartInfo.FileName = exe; + process.StartInfo.Arguments = arguments; + process.StartInfo.UseShellExecute = false; + process.StartInfo.RedirectStandardError = true; + process.StartInfo.RedirectStandardOutput = true; + process.StartInfo.CreateNoWindow = true; + return process; + } + + public static void MP42TS(string mp4, string ts) + { + string arguments = $" -y -i {mp4} -codec copy -bsf h264_mp4toannexb {ts}"; + Process p = CreateProcess(ffmpeg, arguments); + RunProcess(p); + } + } +} diff --git a/SS.VideoConver/videoconver/ShellPathNameConvert.cs b/SS.VideoConver/videoconver/ShellPathNameConvert.cs new file mode 100644 index 0000000000000000000000000000000000000000..6f3ef29d5405ecba1fe2712855345083f34e3fbf --- /dev/null +++ b/SS.VideoConver/videoconver/ShellPathNameConvert.cs @@ -0,0 +1,33 @@ +using System.Runtime.InteropServices; +using System.Text; + +namespace videoconver +{ + public class ShellPathNameConvert + { + [DllImport("kernel32.dll", CharSet = CharSet.Unicode)] + private static extern uint GetLongPathName(string shortname, StringBuilder longnamebuff, uint buffersize); + + [DllImport("kernel32.dll", CharSet = CharSet.Auto)] + private static extern int GetShortPathName([MarshalAs(UnmanagedType.LPWStr)] string path, [MarshalAs(UnmanagedType.LPWStr)] StringBuilder shortPath, int shortPathLength); + + public static string ToLongPathName(string shortName) + { + StringBuilder stringBuilder = new StringBuilder(256); + uint capacity = (uint)stringBuilder.Capacity; + GetLongPathName(shortName, stringBuilder, capacity); + return stringBuilder.ToString(); + } + + public static string ToShortPathName(string longName) + { + StringBuilder stringBuilder = new StringBuilder(256); + int capacity = stringBuilder.Capacity; + if (GetShortPathName(longName, stringBuilder, capacity) == 0) + { + return longName; + } + return stringBuilder.ToString(); + } + } +} diff --git a/Test.GB28181.Service/Config/gb28181.xml b/Test.GB28181.Service/Config/gb28181.xml index 468cd2c75b812a218c2f16022d681737af3fbaeb..8082bbfd07a9f2043b0ea15d41337aabbf67172e 100644 --- a/Test.GB28181.Service/Config/gb28181.xml +++ b/Test.GB28181.Service/Config/gb28181.xml @@ -3,9 +3,9 @@ 10 上级平台 GB-2016 - 42010000002100000002 + 34020000002000000001 10.77.38.86 - 5061 + 5060 5060 false admin diff --git a/Test.GB28181.Service/Test.GB28181.Service.csproj b/Test.GB28181.Service/Test.GB28181.Service.csproj index eb53ae5cbd7399e5f8849ce1639ec6428bfcc179..9061b5a63b607567585d4be4a2e7d5d599fd8ffa 100644 --- a/Test.GB28181.Service/Test.GB28181.Service.csproj +++ b/Test.GB28181.Service/Test.GB28181.Service.csproj @@ -20,6 +20,7 @@ + diff --git a/Test.GB28181.Service/TestMainProcess.cs b/Test.GB28181.Service/TestMainProcess.cs index 781e9eb4a7a77d518fd3f5cbb6647daeadb6075d..a35170010a1422b9bca0685c6554b7715d153bd5 100644 --- a/Test.GB28181.Service/TestMainProcess.cs +++ b/Test.GB28181.Service/TestMainProcess.cs @@ -19,10 +19,10 @@ namespace Test.GB28181.Service //SipAccountStorage sas = new SipAccountStorage(); ////ISipAccountStorageMock.Setup(accouts=> accouts.Accounts.Add(new GB28181.SIPSorcery.SIP.App.SIPAccount { })) ; //var IMemoCacheMock = new Mock>(); - var obj = new MainProcess(); - obj.Run(); + //var obj = new MainProcess(); + //obj.Run(); - Assert.NotNull(obj); + //Assert.NotNull(obj); } } } diff --git a/Test.GB28181.Service/TestVideoThubnail.cs b/Test.GB28181.Service/TestVideoThubnail.cs new file mode 100644 index 0000000000000000000000000000000000000000..8c1143a7d2c45f278e3a9ad99bfa0367412f66a7 --- /dev/null +++ b/Test.GB28181.Service/TestVideoThubnail.cs @@ -0,0 +1,140 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.IO; +using System.Text; +using System.Threading; +using System.Threading.Tasks; +using videoconver; +using VideoEncoder; +using Xunit; + +namespace Test.VideoThumbnail +{ + public class TestVideoThubnail + { + private const string Thumbnails_cmd_format = " -y -i {0} -f image2 -ss {1}.001 -s 240x180 {2}"; + + private const string ffmpeg_param_format = " -y -i {0} {1}"; + + private static string ffmpeg = "ffmpeg.exe"; + + private static List ProcessList = new List(); + + public static event Action OnProcessData; + + public static event Action Trace; + + [Fact] + public void Test() + { + VideoFile videoInfo = GetVideoInfo("record\\tmp4.mp4"); + CreateThumbnails("record\\tmp4.mp4", "record\\abc.jpg"); + } + + static void CreateThumbnails(string iFile, string oFile) + { + VideoFile videoInfo = GetVideoInfo(iFile); + CreateThumbnails(iFile, oFile, (int)videoInfo.Duration.TotalSeconds / 2); + } + + static void CreateThumbnails(string iFile, string oFile, int time) + { + VideoFile videoInfo = GetVideoInfo(iFile); + oFile = ShellPathNameConvert.ToShortPathName(Path.GetDirectoryName(oFile)) + "\\" + Path.GetFileName(oFile); + iFile = ShellPathNameConvert.ToShortPathName(iFile); + double num = videoInfo.Duration.TotalSeconds / 2.0; + if (num > 8.0) + { + num = 8.0; + } + string arguments = string.Format(" -y -i {0} -f image2 -ss {2}.001 -s 240x180 {1}", iFile, oFile, time); + Process p = CreateProcess(ffmpeg, arguments); + RunProcess(p); + } + + static void RunProcess(Process p) + { + DateTime dt = DateTime.Now; + try + { + ProcessList.Add(p); + p.Start(); + p.BeginOutputReadLine(); + p.BeginErrorReadLine(); + DataReceivedEventHandler value = delegate (object sender, DataReceivedEventArgs e) + { + dt = DateTime.Now; + OnProcessData?.Invoke(e.Data); + }; + p.ErrorDataReceived += value; + p.OutputDataReceived += value; + Task task = new Task(delegate + { + p.WaitForExit(); + }); + task.Start(); + do + { + Thread.Sleep(100); + } + while (dt.AddMinutes(1.0) > DateTime.Now && !task.IsCompleted && !task.IsFaulted && !task.IsCanceled); + p.ErrorDataReceived -= value; + p.OutputDataReceived -= value; + p.CancelOutputRead(); + p.CancelErrorRead(); + if (!p.HasExited) + { + p.Kill(); + } + p.Close(); + p.Dispose(); + ProcessList.Remove(p); + } + catch + { + p.Dispose(); + throw; + } + } + + static VideoFile GetVideoInfo(string iFile) + { + VideoEncoder.Encoder encoder = new VideoEncoder.Encoder(); + encoder.FFmpegPath = ffmpeg; + VideoFile videoFile = new VideoFile(iFile); + encoder.GetVideoInfo(videoFile); + TimeSpan duration = videoFile.Duration; + StringBuilder stringBuilder = new StringBuilder(); + string arg = $"{(int)duration.TotalHours:00}:{duration.Minutes:00}:{duration.Seconds:00}"; + stringBuilder.AppendFormat("时间长度:{0}\n", arg); + stringBuilder.AppendFormat("高度:{0}\n", videoFile.Height); + stringBuilder.AppendFormat("宽度:{0}\n", videoFile.Width); + stringBuilder.AppendFormat("数据格式:{0}\n", videoFile.VideoFormat); + stringBuilder.AppendFormat("比特率:{0}\n", videoFile.BitRate); + stringBuilder.AppendFormat("文件路径:{0}\n", videoFile.File); + return videoFile; + } + + static Process CreateProcess(string exe, string arguments) + { + string text = $"{exe} {arguments}"; + Process process = new Process(); + process.StartInfo.WindowStyle = ProcessWindowStyle.Normal; + process.StartInfo.FileName = exe; + process.StartInfo.Arguments = arguments; + process.StartInfo.UseShellExecute = false; + process.StartInfo.RedirectStandardError = true; + process.StartInfo.RedirectStandardOutput = true; + process.StartInfo.CreateNoWindow = true; + return process; + } + + public static void MP42TS(string mp4, string ts) + { + string arguments = $" -y -i {mp4} -codec copy -bsf h264_mp4toannexb {ts}"; + Process p = CreateProcess(ffmpeg, arguments); + RunProcess(p); + } + } +} diff --git a/Build/Config/gb28181.xml b/Win.GB28181.Client/Config/gb28181.bak.xml similarity index 46% rename from Build/Config/gb28181.xml rename to Win.GB28181.Client/Config/gb28181.bak.xml index e5f699b22958138573ae25b042df9b6edd79b94f..a296d258cf69462dc02ab668f25c46972ee9f30e 100644 --- a/Build/Config/gb28181.xml +++ b/Win.GB28181.Client/Config/gb28181.bak.xml @@ -1,21 +1,21 @@  - -10 - 下级平台 - GB-2011 + 10 + 上级平台 + GB-2016 34010000002000000001 - 192.168.1.21 - 5060 - 0 + 10.77.38.86 + 7777 + 5060 false admin - 34010000001360000001 - Udp - Udp + 12345678 + UDP + UDP passive GB2312 true - 5060 + 5000 3 \ No newline at end of file diff --git a/Win.GB28181.Client/Config/gb28181.xml b/Win.GB28181.Client/Config/gb28181.xml new file mode 100644 index 0000000000000000000000000000000000000000..d6d67382818080a3d6a0574cc5ff29a31df4c049 --- /dev/null +++ b/Win.GB28181.Client/Config/gb28181.xml @@ -0,0 +1,23 @@ + + + 10 + 上级平台 + GB-2016 + 34020000002000000001 + 127.0.0.1 + 5060 + 5060 + false + admin + 123456 + UDP + UDP + passive + GB2312 + true + 5000 + 3 + + + + \ No newline at end of file diff --git a/Win.GB28181.Client/Form1.Designer.cs b/Win.GB28181.Client/Form1.Designer.cs index 5bff8eb7c8881dd8db6bb84f9f01e7ccb1248df3..215e0f231594d16bba0fd496b8eb1f2526eca8cf 100644 --- a/Win.GB28181.Client/Form1.Designer.cs +++ b/Win.GB28181.Client/Form1.Designer.cs @@ -165,19 +165,21 @@ // // btnStart // - this.btnStart.Location = new System.Drawing.Point(6, 7); + this.btnStart.Location = new System.Drawing.Point(8, 9); + this.btnStart.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4); this.btnStart.Name = "btnStart"; - this.btnStart.Size = new System.Drawing.Size(75, 23); + this.btnStart.Size = new System.Drawing.Size(100, 29); this.btnStart.TabIndex = 0; this.btnStart.Text = "启动"; this.btnStart.UseVisualStyleBackColor = true; - this.btnStart.Click += new System.EventHandler(this.BtnStart_Click); + this.btnStart.Click += new System.EventHandler(this.btnStart_Click); // // btnStop // - this.btnStop.Location = new System.Drawing.Point(93, 7); + this.btnStop.Location = new System.Drawing.Point(124, 9); + this.btnStop.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4); this.btnStop.Name = "btnStop"; - this.btnStop.Size = new System.Drawing.Size(75, 23); + this.btnStop.Size = new System.Drawing.Size(100, 29); this.btnStop.TabIndex = 1; this.btnStop.Text = "停止"; this.btnStop.UseVisualStyleBackColor = true; @@ -187,17 +189,19 @@ // this.lblStatus.AutoSize = true; this.lblStatus.ForeColor = System.Drawing.Color.Red; - this.lblStatus.Location = new System.Drawing.Point(179, 13); + this.lblStatus.Location = new System.Drawing.Point(239, 16); + this.lblStatus.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0); this.lblStatus.Name = "lblStatus"; - this.lblStatus.Size = new System.Drawing.Size(77, 12); + this.lblStatus.Size = new System.Drawing.Size(97, 15); this.lblStatus.TabIndex = 2; this.lblStatus.Text = "等待中。。。"; // // btnCatalogSearch // - this.btnCatalogSearch.Location = new System.Drawing.Point(709, 54); + this.btnCatalogSearch.Location = new System.Drawing.Point(945, 68); + this.btnCatalogSearch.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4); this.btnCatalogSearch.Name = "btnCatalogSearch"; - this.btnCatalogSearch.Size = new System.Drawing.Size(75, 23); + this.btnCatalogSearch.Size = new System.Drawing.Size(100, 29); this.btnCatalogSearch.TabIndex = 3; this.btnCatalogSearch.Text = "目录查询"; this.btnCatalogSearch.UseVisualStyleBackColor = true; @@ -205,9 +209,10 @@ // // btnReal // - this.btnReal.Location = new System.Drawing.Point(6, 18); + this.btnReal.Location = new System.Drawing.Point(8, 22); + this.btnReal.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4); this.btnReal.Name = "btnReal"; - this.btnReal.Size = new System.Drawing.Size(75, 23); + this.btnReal.Size = new System.Drawing.Size(100, 29); this.btnReal.TabIndex = 8; this.btnReal.Text = "直播视频"; this.btnReal.UseVisualStyleBackColor = true; @@ -215,9 +220,10 @@ // // btnBye // - this.btnBye.Location = new System.Drawing.Point(6, 47); + this.btnBye.Location = new System.Drawing.Point(8, 59); + this.btnBye.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4); this.btnBye.Name = "btnBye"; - this.btnBye.Size = new System.Drawing.Size(75, 23); + this.btnBye.Size = new System.Drawing.Size(100, 29); this.btnBye.TabIndex = 10; this.btnBye.Text = "终止直播"; this.btnBye.UseVisualStyleBackColor = true; @@ -231,10 +237,11 @@ this.devState}); this.lvDev.FullRowSelect = true; this.lvDev.HideSelection = false; - this.lvDev.Location = new System.Drawing.Point(348, 54); + this.lvDev.Location = new System.Drawing.Point(464, 68); + this.lvDev.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4); this.lvDev.MultiSelect = false; this.lvDev.Name = "lvDev"; - this.lvDev.Size = new System.Drawing.Size(355, 203); + this.lvDev.Size = new System.Drawing.Size(472, 253); this.lvDev.TabIndex = 11; this.lvDev.UseCompatibleStateImageBehavior = false; this.lvDev.View = System.Windows.Forms.View.Details; @@ -254,65 +261,72 @@ // // btnRecord // - this.btnRecord.Location = new System.Drawing.Point(12, 145); + this.btnRecord.Location = new System.Drawing.Point(16, 181); + this.btnRecord.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4); this.btnRecord.Name = "btnRecord"; - this.btnRecord.Size = new System.Drawing.Size(68, 23); + this.btnRecord.Size = new System.Drawing.Size(91, 29); this.btnRecord.TabIndex = 12; this.btnRecord.Text = "录像点播"; this.btnRecord.UseVisualStyleBackColor = true; - this.btnRecord.Click += new System.EventHandler(this.BtnRecord_Click); + this.btnRecord.Click += new System.EventHandler(this.btnRecord_Click); // // btnStopRecord // - this.btnStopRecord.Location = new System.Drawing.Point(95, 145); + this.btnStopRecord.Location = new System.Drawing.Point(127, 181); + this.btnStopRecord.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4); this.btnStopRecord.Name = "btnStopRecord"; - this.btnStopRecord.Size = new System.Drawing.Size(68, 23); + this.btnStopRecord.Size = new System.Drawing.Size(91, 29); this.btnStopRecord.TabIndex = 13; this.btnStopRecord.Text = "终止点播"; this.btnStopRecord.UseVisualStyleBackColor = true; - this.btnStopRecord.Click += new System.EventHandler(this.BtnStopRecord_Click); + this.btnStopRecord.Click += new System.EventHandler(this.btnStopRecord_Click); // // txtStartTime // - this.txtStartTime.Location = new System.Drawing.Point(69, 6); + this.txtStartTime.Location = new System.Drawing.Point(92, 8); + this.txtStartTime.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4); this.txtStartTime.Name = "txtStartTime"; - this.txtStartTime.Size = new System.Drawing.Size(125, 21); + this.txtStartTime.Size = new System.Drawing.Size(165, 25); this.txtStartTime.TabIndex = 14; // // txtStopTime // - this.txtStopTime.Location = new System.Drawing.Point(69, 33); + this.txtStopTime.Location = new System.Drawing.Point(92, 41); + this.txtStopTime.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4); this.txtStopTime.Name = "txtStopTime"; - this.txtStopTime.Size = new System.Drawing.Size(125, 21); + this.txtStopTime.Size = new System.Drawing.Size(165, 25); this.txtStopTime.TabIndex = 15; // // label2 // this.label2.AutoSize = true; - this.label2.Location = new System.Drawing.Point(493, 63); + this.label2.Location = new System.Drawing.Point(657, 79); + this.label2.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0); this.label2.Name = "label2"; - this.label2.Size = new System.Drawing.Size(53, 12); + this.label2.Size = new System.Drawing.Size(67, 15); this.label2.TabIndex = 16; this.label2.Text = "开始时间"; // // label3 // this.label3.AutoSize = true; - this.label3.Location = new System.Drawing.Point(493, 97); + this.label3.Location = new System.Drawing.Point(657, 121); + this.label3.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0); this.label3.Name = "label3"; - this.label3.Size = new System.Drawing.Size(53, 12); + this.label3.Size = new System.Drawing.Size(67, 15); this.label3.TabIndex = 17; this.label3.Text = "结束时间"; // // btnRecordGet // - this.btnRecordGet.Location = new System.Drawing.Point(200, 31); + this.btnRecordGet.Location = new System.Drawing.Point(267, 39); + this.btnRecordGet.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4); this.btnRecordGet.Name = "btnRecordGet"; - this.btnRecordGet.Size = new System.Drawing.Size(68, 23); + this.btnRecordGet.Size = new System.Drawing.Size(91, 29); this.btnRecordGet.TabIndex = 18; this.btnRecordGet.Text = "录像查询"; this.btnRecordGet.UseVisualStyleBackColor = true; - this.btnRecordGet.Click += new System.EventHandler(this.BtnRecordGet_Click); + this.btnRecordGet.Click += new System.EventHandler(this.btnRecordGet_Click); // // lvRecord // @@ -321,10 +335,12 @@ this.columnHeader3, this.columnHeader4}); this.lvRecord.FullRowSelect = true; - this.lvRecord.Location = new System.Drawing.Point(6, 174); + this.lvRecord.HideSelection = false; + this.lvRecord.Location = new System.Drawing.Point(8, 218); + this.lvRecord.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4); this.lvRecord.MultiSelect = false; this.lvRecord.Name = "lvRecord"; - this.lvRecord.Size = new System.Drawing.Size(319, 88); + this.lvRecord.Size = new System.Drawing.Size(424, 109); this.lvRecord.TabIndex = 19; this.lvRecord.UseCompatibleStateImageBehavior = false; this.lvRecord.View = System.Windows.Forms.View.Details; @@ -346,9 +362,10 @@ // // btnCatalogSubscribe // - this.btnCatalogSubscribe.Location = new System.Drawing.Point(709, 90); + this.btnCatalogSubscribe.Location = new System.Drawing.Point(945, 112); + this.btnCatalogSubscribe.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4); this.btnCatalogSubscribe.Name = "btnCatalogSubscribe"; - this.btnCatalogSubscribe.Size = new System.Drawing.Size(75, 23); + this.btnCatalogSubscribe.Size = new System.Drawing.Size(100, 29); this.btnCatalogSubscribe.TabIndex = 26; this.btnCatalogSubscribe.Text = "目录订阅"; this.btnCatalogSubscribe.UseVisualStyleBackColor = true; @@ -356,9 +373,10 @@ // // btnEventSubscribe // - this.btnEventSubscribe.Location = new System.Drawing.Point(709, 126); + this.btnEventSubscribe.Location = new System.Drawing.Point(945, 158); + this.btnEventSubscribe.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4); this.btnEventSubscribe.Name = "btnEventSubscribe"; - this.btnEventSubscribe.Size = new System.Drawing.Size(75, 23); + this.btnEventSubscribe.Size = new System.Drawing.Size(100, 29); this.btnEventSubscribe.TabIndex = 27; this.btnEventSubscribe.Text = "事件订阅"; this.btnEventSubscribe.UseVisualStyleBackColor = true; @@ -366,19 +384,21 @@ // // btnStateSearch // - this.btnStateSearch.Location = new System.Drawing.Point(12, 14); + this.btnStateSearch.Location = new System.Drawing.Point(16, 18); + this.btnStateSearch.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4); this.btnStateSearch.Name = "btnStateSearch"; - this.btnStateSearch.Size = new System.Drawing.Size(75, 23); + this.btnStateSearch.Size = new System.Drawing.Size(100, 29); this.btnStateSearch.TabIndex = 28; this.btnStateSearch.Text = "状态查询"; this.btnStateSearch.UseVisualStyleBackColor = true; - this.btnStateSearch.Click += new System.EventHandler(this.BtnStateSearch_Click); + this.btnStateSearch.Click += new System.EventHandler(this.btnStateSearch_Click); // // btnSetGuard // - this.btnSetGuard.Location = new System.Drawing.Point(709, 162); + this.btnSetGuard.Location = new System.Drawing.Point(945, 202); + this.btnSetGuard.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4); this.btnSetGuard.Name = "btnSetGuard"; - this.btnSetGuard.Size = new System.Drawing.Size(75, 23); + this.btnSetGuard.Size = new System.Drawing.Size(100, 29); this.btnSetGuard.TabIndex = 29; this.btnSetGuard.Text = "布防"; this.btnSetGuard.UseVisualStyleBackColor = true; @@ -386,9 +406,10 @@ // // btResetGuard // - this.btResetGuard.Location = new System.Drawing.Point(709, 198); + this.btResetGuard.Location = new System.Drawing.Point(945, 248); + this.btResetGuard.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4); this.btResetGuard.Name = "btResetGuard"; - this.btResetGuard.Size = new System.Drawing.Size(75, 23); + this.btResetGuard.Size = new System.Drawing.Size(100, 29); this.btResetGuard.TabIndex = 31; this.btResetGuard.Text = "撤防"; this.btResetGuard.UseVisualStyleBackColor = true; @@ -396,9 +417,10 @@ // // btnDevSearch // - this.btnDevSearch.Location = new System.Drawing.Point(12, 74); + this.btnDevSearch.Location = new System.Drawing.Point(16, 92); + this.btnDevSearch.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4); this.btnDevSearch.Name = "btnDevSearch"; - this.btnDevSearch.Size = new System.Drawing.Size(93, 23); + this.btnDevSearch.Size = new System.Drawing.Size(124, 29); this.btnDevSearch.TabIndex = 32; this.btnDevSearch.Text = "设备信息查询"; this.btnDevSearch.UseVisualStyleBackColor = true; @@ -406,9 +428,10 @@ // // brnRenboot // - this.brnRenboot.Location = new System.Drawing.Point(12, 44); + this.brnRenboot.Location = new System.Drawing.Point(16, 55); + this.brnRenboot.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4); this.brnRenboot.Name = "brnRenboot"; - this.brnRenboot.Size = new System.Drawing.Size(75, 23); + this.brnRenboot.Size = new System.Drawing.Size(100, 29); this.brnRenboot.TabIndex = 33; this.brnRenboot.Text = "设备重启"; this.brnRenboot.UseVisualStyleBackColor = true; @@ -416,9 +439,10 @@ // // btnAlarmReset // - this.btnAlarmReset.Location = new System.Drawing.Point(709, 234); + this.btnAlarmReset.Location = new System.Drawing.Point(945, 292); + this.btnAlarmReset.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4); this.btnAlarmReset.Name = "btnAlarmReset"; - this.btnAlarmReset.Size = new System.Drawing.Size(75, 23); + this.btnAlarmReset.Size = new System.Drawing.Size(100, 29); this.btnAlarmReset.TabIndex = 34; this.btnAlarmReset.Text = "报警复位"; this.btnAlarmReset.UseVisualStyleBackColor = true; @@ -427,9 +451,10 @@ // label4 // this.label4.AutoSize = true; - this.label4.Location = new System.Drawing.Point(9, 21); + this.label4.Location = new System.Drawing.Point(12, 26); + this.label4.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0); this.label4.Name = "label4"; - this.label4.Size = new System.Drawing.Size(53, 12); + this.label4.Size = new System.Drawing.Size(67, 15); this.label4.TabIndex = 51; this.label4.Text = "云台速度"; // @@ -437,7 +462,7 @@ // this.txtLengthY.Location = new System.Drawing.Point(260, 73); this.txtLengthY.Name = "txtLengthY"; - this.txtLengthY.Size = new System.Drawing.Size(43, 21); + this.txtLengthY.Size = new System.Drawing.Size(43, 25); this.txtLengthY.TabIndex = 37; // // label11 @@ -453,7 +478,7 @@ // this.txtLengthX.Location = new System.Drawing.Point(260, 46); this.txtLengthX.Name = "txtLengthX"; - this.txtLengthX.Size = new System.Drawing.Size(43, 21); + this.txtLengthX.Size = new System.Drawing.Size(43, 25); this.txtLengthX.TabIndex = 35; // // label10 @@ -469,7 +494,7 @@ // this.txtMidPointY.Location = new System.Drawing.Point(263, 19); this.txtMidPointY.Name = "txtMidPointY"; - this.txtMidPointY.Size = new System.Drawing.Size(40, 21); + this.txtMidPointY.Size = new System.Drawing.Size(40, 25); this.txtMidPointY.TabIndex = 33; // // label9 @@ -485,7 +510,7 @@ // this.txtMidPointX.Location = new System.Drawing.Point(117, 72); this.txtMidPointX.Name = "txtMidPointX"; - this.txtMidPointX.Size = new System.Drawing.Size(43, 21); + this.txtMidPointX.Size = new System.Drawing.Size(43, 25); this.txtMidPointX.TabIndex = 31; // // label8 @@ -501,7 +526,7 @@ // this.txtWidth.Location = new System.Drawing.Point(117, 46); this.txtWidth.Name = "txtWidth"; - this.txtWidth.Size = new System.Drawing.Size(43, 21); + this.txtWidth.Size = new System.Drawing.Size(43, 25); this.txtWidth.TabIndex = 29; // // label7 @@ -517,7 +542,7 @@ // this.txtLength.Location = new System.Drawing.Point(117, 19); this.txtLength.Name = "txtLength"; - this.txtLength.Size = new System.Drawing.Size(43, 21); + this.txtLength.Size = new System.Drawing.Size(43, 25); this.txtLength.TabIndex = 27; // // label6 @@ -537,9 +562,10 @@ this.cataName}); this.lvCata.FullRowSelect = true; this.lvCata.HideSelection = false; - this.lvCata.Location = new System.Drawing.Point(332, 328); + this.lvCata.Location = new System.Drawing.Point(443, 410); + this.lvCata.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4); this.lvCata.Name = "lvCata"; - this.lvCata.Size = new System.Drawing.Size(11, 156); + this.lvCata.Size = new System.Drawing.Size(602, 194); this.lvCata.TabIndex = 36; this.lvCata.UseCompatibleStateImageBehavior = false; this.lvCata.View = System.Windows.Forms.View.Details; @@ -562,18 +588,20 @@ // lblKeepalive // this.lblKeepalive.AutoSize = true; - this.lblKeepalive.Location = new System.Drawing.Point(475, 13); + this.lblKeepalive.Location = new System.Drawing.Point(633, 16); + this.lblKeepalive.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0); this.lblKeepalive.Name = "lblKeepalive"; - this.lblKeepalive.Size = new System.Drawing.Size(89, 12); + this.lblKeepalive.Size = new System.Drawing.Size(112, 15); this.lblKeepalive.TabIndex = 38; this.lblKeepalive.Text = "等待心跳。。。"; // // chbSave // this.chbSave.AutoSize = true; - this.chbSave.Location = new System.Drawing.Point(495, 35); + this.chbSave.Location = new System.Drawing.Point(660, 44); + this.chbSave.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4); this.chbSave.Name = "chbSave"; - this.chbSave.Size = new System.Drawing.Size(48, 16); + this.chbSave.Size = new System.Drawing.Size(59, 19); this.chbSave.TabIndex = 39; this.chbSave.Text = "存储"; this.chbSave.UseVisualStyleBackColor = true; @@ -581,26 +609,29 @@ // lblExport // this.lblExport.AutoSize = true; - this.lblExport.Location = new System.Drawing.Point(607, 365); + this.lblExport.Location = new System.Drawing.Point(809, 456); + this.lblExport.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0); this.lblExport.Name = "lblExport"; - this.lblExport.Size = new System.Drawing.Size(0, 12); + this.lblExport.Size = new System.Drawing.Size(0, 15); this.lblExport.TabIndex = 41; // // btnStopRd // - this.btnStopRd.Location = new System.Drawing.Point(95, 116); + this.btnStopRd.Location = new System.Drawing.Point(127, 145); + this.btnStopRd.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4); this.btnStopRd.Name = "btnStopRd"; - this.btnStopRd.Size = new System.Drawing.Size(68, 22); + this.btnStopRd.Size = new System.Drawing.Size(91, 28); this.btnStopRd.TabIndex = 2; this.btnStopRd.Text = "停止录像"; this.btnStopRd.UseVisualStyleBackColor = true; - this.btnStopRd.Click += new System.EventHandler(this.BtnStopRd_Click); + this.btnStopRd.Click += new System.EventHandler(this.btnStopRd_Click); // // btnStartRecord // - this.btnStartRecord.Location = new System.Drawing.Point(12, 116); + this.btnStartRecord.Location = new System.Drawing.Point(16, 145); + this.btnStartRecord.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4); this.btnStartRecord.Name = "btnStartRecord"; - this.btnStartRecord.Size = new System.Drawing.Size(68, 22); + this.btnStartRecord.Size = new System.Drawing.Size(91, 28); this.btnStartRecord.TabIndex = 0; this.btnStartRecord.Text = "开始录像"; this.btnStartRecord.UseVisualStyleBackColor = true; @@ -609,74 +640,82 @@ // label5 // this.label5.AutoSize = true; - this.label5.Location = new System.Drawing.Point(10, 92); + this.label5.Location = new System.Drawing.Point(13, 115); + this.label5.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0); this.label5.Name = "label5"; - this.label5.Size = new System.Drawing.Size(59, 12); + this.label5.Size = new System.Drawing.Size(75, 15); this.label5.TabIndex = 29; this.label5.Text = "拖动播放:"; // // txtDragDrop // - this.txtDragDrop.Location = new System.Drawing.Point(69, 89); + this.txtDragDrop.Location = new System.Drawing.Point(92, 111); + this.txtDragDrop.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4); this.txtDragDrop.Name = "txtDragDrop"; - this.txtDragDrop.Size = new System.Drawing.Size(125, 21); + this.txtDragDrop.Size = new System.Drawing.Size(165, 25); this.txtDragDrop.TabIndex = 28; // // button17 // - this.button17.Location = new System.Drawing.Point(200, 88); + this.button17.Location = new System.Drawing.Point(267, 110); + this.button17.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4); this.button17.Name = "button17"; - this.button17.Size = new System.Drawing.Size(68, 23); + this.button17.Size = new System.Drawing.Size(91, 29); this.button17.TabIndex = 27; this.button17.Text = "播放"; this.button17.UseVisualStyleBackColor = true; - this.button17.Click += new System.EventHandler(this.Button17_Click); + this.button17.Click += new System.EventHandler(this.button17_Click); // // label1 // this.label1.AutoSize = true; - this.label1.Location = new System.Drawing.Point(10, 63); + this.label1.Location = new System.Drawing.Point(13, 79); + this.label1.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0); this.label1.Name = "label1"; - this.label1.Size = new System.Drawing.Size(59, 12); + this.label1.Size = new System.Drawing.Size(75, 15); this.label1.TabIndex = 26; this.label1.Text = "播放倍数:"; // // txtScale // - this.txtScale.Location = new System.Drawing.Point(69, 60); + this.txtScale.Location = new System.Drawing.Point(92, 75); + this.txtScale.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4); this.txtScale.Name = "txtScale"; - this.txtScale.Size = new System.Drawing.Size(125, 21); + this.txtScale.Size = new System.Drawing.Size(165, 25); this.txtScale.TabIndex = 26; // // btnSdu // - this.btnSdu.Location = new System.Drawing.Point(200, 59); + this.btnSdu.Location = new System.Drawing.Point(267, 74); + this.btnSdu.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4); this.btnSdu.Name = "btnSdu"; - this.btnSdu.Size = new System.Drawing.Size(68, 23); + this.btnSdu.Size = new System.Drawing.Size(91, 29); this.btnSdu.TabIndex = 19; this.btnSdu.Text = "设置"; this.btnSdu.UseVisualStyleBackColor = true; - this.btnSdu.Click += new System.EventHandler(this.BtnSdu_Click); + this.btnSdu.Click += new System.EventHandler(this.btnSdu_Click); // // btnPlay // - this.btnPlay.Location = new System.Drawing.Point(178, 145); + this.btnPlay.Location = new System.Drawing.Point(237, 181); + this.btnPlay.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4); this.btnPlay.Name = "btnPlay"; - this.btnPlay.Size = new System.Drawing.Size(68, 23); + this.btnPlay.Size = new System.Drawing.Size(91, 29); this.btnPlay.TabIndex = 15; this.btnPlay.Text = "播放继续"; this.btnPlay.UseVisualStyleBackColor = true; - this.btnPlay.Click += new System.EventHandler(this.BtnPlay_Click); + this.btnPlay.Click += new System.EventHandler(this.btnPlay_Click); // // btnPause // - this.btnPause.Location = new System.Drawing.Point(178, 116); + this.btnPause.Location = new System.Drawing.Point(237, 145); + this.btnPause.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4); this.btnPause.Name = "btnPause"; - this.btnPause.Size = new System.Drawing.Size(68, 23); + this.btnPause.Size = new System.Drawing.Size(91, 29); this.btnPause.TabIndex = 14; this.btnPause.Text = "播放暂停"; this.btnPause.UseVisualStyleBackColor = true; - this.btnPause.Click += new System.EventHandler(this.BtnPause_Click); + this.btnPause.Click += new System.EventHandler(this.btnPause_Click); // // tabControl1 // @@ -686,20 +725,22 @@ this.tabControl1.Controls.Add(this.tbOther); this.tabControl1.Controls.Add(this.tabNew); this.tabControl1.Controls.Add(this.tabPage1); - this.tabControl1.Location = new System.Drawing.Point(6, 32); + this.tabControl1.Location = new System.Drawing.Point(8, 40); + this.tabControl1.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4); this.tabControl1.Name = "tabControl1"; this.tabControl1.SelectedIndex = 0; - this.tabControl1.Size = new System.Drawing.Size(340, 294); + this.tabControl1.Size = new System.Drawing.Size(453, 368); this.tabControl1.TabIndex = 47; // // tbReal // this.tbReal.Controls.Add(this.btnReal); this.tbReal.Controls.Add(this.btnBye); - this.tbReal.Location = new System.Drawing.Point(4, 22); + this.tbReal.Location = new System.Drawing.Point(4, 25); + this.tbReal.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4); this.tbReal.Name = "tbReal"; - this.tbReal.Padding = new System.Windows.Forms.Padding(3); - this.tbReal.Size = new System.Drawing.Size(332, 268); + this.tbReal.Padding = new System.Windows.Forms.Padding(4, 4, 4, 4); + this.tbReal.Size = new System.Drawing.Size(445, 339); this.tbReal.TabIndex = 0; this.tbReal.Text = "实时"; this.tbReal.UseVisualStyleBackColor = true; @@ -729,10 +770,11 @@ this.tbRecord.Controls.Add(this.txtStartTime); this.tbRecord.Controls.Add(this.label2); this.tbRecord.Controls.Add(this.label3); - this.tbRecord.Location = new System.Drawing.Point(4, 22); + this.tbRecord.Location = new System.Drawing.Point(4, 25); + this.tbRecord.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4); this.tbRecord.Name = "tbRecord"; - this.tbRecord.Padding = new System.Windows.Forms.Padding(3); - this.tbRecord.Size = new System.Drawing.Size(332, 268); + this.tbRecord.Padding = new System.Windows.Forms.Padding(4, 4, 4, 4); + this.tbRecord.Size = new System.Drawing.Size(445, 339); this.tbRecord.TabIndex = 1; this.tbRecord.Text = "录像"; this.tbRecord.UseVisualStyleBackColor = true; @@ -741,16 +783,18 @@ // this.cbxRecordType.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.cbxRecordType.FormattingEnabled = true; - this.cbxRecordType.Location = new System.Drawing.Point(200, 6); + this.cbxRecordType.Location = new System.Drawing.Point(267, 8); + this.cbxRecordType.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4); this.cbxRecordType.Name = "cbxRecordType"; - this.cbxRecordType.Size = new System.Drawing.Size(68, 20); + this.cbxRecordType.Size = new System.Drawing.Size(89, 23); this.cbxRecordType.TabIndex = 50; // // btnRecordDownload // - this.btnRecordDownload.Location = new System.Drawing.Point(250, 116); + this.btnRecordDownload.Location = new System.Drawing.Point(333, 145); + this.btnRecordDownload.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4); this.btnRecordDownload.Name = "btnRecordDownload"; - this.btnRecordDownload.Size = new System.Drawing.Size(75, 23); + this.btnRecordDownload.Size = new System.Drawing.Size(100, 29); this.btnRecordDownload.TabIndex = 49; this.btnRecordDownload.Text = "录像下载"; this.btnRecordDownload.UseVisualStyleBackColor = true; @@ -759,18 +803,20 @@ // label13 // this.label13.AutoSize = true; - this.label13.Location = new System.Drawing.Point(10, 38); + this.label13.Location = new System.Drawing.Point(13, 48); + this.label13.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0); this.label13.Name = "label13"; - this.label13.Size = new System.Drawing.Size(53, 12); + this.label13.Size = new System.Drawing.Size(67, 15); this.label13.TabIndex = 48; this.label13.Text = "结束时间"; // // label12 // this.label12.AutoSize = true; - this.label12.Location = new System.Drawing.Point(10, 11); + this.label12.Location = new System.Drawing.Point(13, 14); + this.label12.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0); this.label12.Name = "label12"; - this.label12.Size = new System.Drawing.Size(53, 12); + this.label12.Size = new System.Drawing.Size(67, 15); this.label12.TabIndex = 40; this.label12.Text = "开始时间"; // @@ -802,9 +848,10 @@ this.tbPTZ.Controls.Add(this.btnRight); this.tbPTZ.Controls.Add(this.btnSetPreset); this.tbPTZ.Controls.Add(this.btnLeft); - this.tbPTZ.Location = new System.Drawing.Point(4, 22); + this.tbPTZ.Location = new System.Drawing.Point(4, 25); + this.tbPTZ.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4); this.tbPTZ.Name = "tbPTZ"; - this.tbPTZ.Size = new System.Drawing.Size(332, 268); + this.tbPTZ.Size = new System.Drawing.Size(445, 339); this.tbPTZ.TabIndex = 2; this.tbPTZ.Text = "云台"; this.tbPTZ.UseVisualStyleBackColor = true; @@ -813,16 +860,18 @@ // this.cbxPreset.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.cbxPreset.FormattingEnabled = true; - this.cbxPreset.Location = new System.Drawing.Point(243, 18); + this.cbxPreset.Location = new System.Drawing.Point(324, 22); + this.cbxPreset.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4); this.cbxPreset.Name = "cbxPreset"; - this.cbxPreset.Size = new System.Drawing.Size(86, 20); + this.cbxPreset.Size = new System.Drawing.Size(113, 23); this.cbxPreset.TabIndex = 73; // // btnPositionClose // - this.btnPositionClose.Location = new System.Drawing.Point(199, 219); + this.btnPositionClose.Location = new System.Drawing.Point(265, 274); + this.btnPositionClose.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4); this.btnPositionClose.Name = "btnPositionClose"; - this.btnPositionClose.Size = new System.Drawing.Size(75, 23); + this.btnPositionClose.Size = new System.Drawing.Size(100, 29); this.btnPositionClose.TabIndex = 72; this.btnPositionClose.Text = "看守位关"; this.btnPositionClose.UseVisualStyleBackColor = true; @@ -830,9 +879,10 @@ // // btnPositionOpen // - this.btnPositionOpen.Location = new System.Drawing.Point(199, 190); + this.btnPositionOpen.Location = new System.Drawing.Point(265, 238); + this.btnPositionOpen.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4); this.btnPositionOpen.Name = "btnPositionOpen"; - this.btnPositionOpen.Size = new System.Drawing.Size(75, 23); + this.btnPositionOpen.Size = new System.Drawing.Size(100, 29); this.btnPositionOpen.TabIndex = 71; this.btnPositionOpen.Text = "看守位开"; this.btnPositionOpen.UseVisualStyleBackColor = true; @@ -840,9 +890,10 @@ // // btnZoomOut // - this.btnZoomOut.Location = new System.Drawing.Point(199, 161); + this.btnZoomOut.Location = new System.Drawing.Point(265, 201); + this.btnZoomOut.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4); this.btnZoomOut.Name = "btnZoomOut"; - this.btnZoomOut.Size = new System.Drawing.Size(75, 23); + this.btnZoomOut.Size = new System.Drawing.Size(100, 29); this.btnZoomOut.TabIndex = 70; this.btnZoomOut.Text = "拉框缩小"; this.btnZoomOut.UseVisualStyleBackColor = true; @@ -850,9 +901,10 @@ // // btnZoomIn // - this.btnZoomIn.Location = new System.Drawing.Point(199, 132); + this.btnZoomIn.Location = new System.Drawing.Point(265, 165); + this.btnZoomIn.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4); this.btnZoomIn.Name = "btnZoomIn"; - this.btnZoomIn.Size = new System.Drawing.Size(75, 23); + this.btnZoomIn.Size = new System.Drawing.Size(100, 29); this.btnZoomIn.TabIndex = 69; this.btnZoomIn.Text = "拉框放大"; this.btnZoomIn.UseVisualStyleBackColor = true; @@ -861,9 +913,10 @@ // btnPTZStop // this.btnPTZStop.ForeColor = System.Drawing.Color.Red; - this.btnPTZStop.Location = new System.Drawing.Point(75, 103); + this.btnPTZStop.Location = new System.Drawing.Point(100, 129); + this.btnPTZStop.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4); this.btnPTZStop.Name = "btnPTZStop"; - this.btnPTZStop.Size = new System.Drawing.Size(37, 36); + this.btnPTZStop.Size = new System.Drawing.Size(49, 45); this.btnPTZStop.TabIndex = 63; this.btnPTZStop.Text = "█"; this.btnPTZStop.UseVisualStyleBackColor = true; @@ -871,9 +924,10 @@ // // btnFocus2 // - this.btnFocus2.Location = new System.Drawing.Point(66, 234); + this.btnFocus2.Location = new System.Drawing.Point(88, 292); + this.btnFocus2.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4); this.btnFocus2.Name = "btnFocus2"; - this.btnFocus2.Size = new System.Drawing.Size(55, 23); + this.btnFocus2.Size = new System.Drawing.Size(73, 29); this.btnFocus2.TabIndex = 61; this.btnFocus2.Text = "聚焦-"; this.btnFocus2.UseVisualStyleBackColor = true; @@ -881,9 +935,10 @@ // // btnZoom2 // - this.btnZoom2.Location = new System.Drawing.Point(4, 234); + this.btnZoom2.Location = new System.Drawing.Point(5, 292); + this.btnZoom2.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4); this.btnZoom2.Name = "btnZoom2"; - this.btnZoom2.Size = new System.Drawing.Size(55, 23); + this.btnZoom2.Size = new System.Drawing.Size(73, 29); this.btnZoom2.TabIndex = 60; this.btnZoom2.Text = "变倍-"; this.btnZoom2.UseVisualStyleBackColor = true; @@ -891,9 +946,10 @@ // // btnIris2 // - this.btnIris2.Location = new System.Drawing.Point(128, 234); + this.btnIris2.Location = new System.Drawing.Point(171, 292); + this.btnIris2.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4); this.btnIris2.Name = "btnIris2"; - this.btnIris2.Size = new System.Drawing.Size(55, 23); + this.btnIris2.Size = new System.Drawing.Size(73, 29); this.btnIris2.TabIndex = 59; this.btnIris2.Text = "光圈关"; this.btnIris2.UseVisualStyleBackColor = true; @@ -901,9 +957,10 @@ // // btnIris1 // - this.btnIris1.Location = new System.Drawing.Point(128, 205); + this.btnIris1.Location = new System.Drawing.Point(171, 256); + this.btnIris1.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4); this.btnIris1.Name = "btnIris1"; - this.btnIris1.Size = new System.Drawing.Size(55, 23); + this.btnIris1.Size = new System.Drawing.Size(73, 29); this.btnIris1.TabIndex = 58; this.btnIris1.Text = "光圈开"; this.btnIris1.UseVisualStyleBackColor = true; @@ -911,30 +968,33 @@ // // btnFocus1 // - this.btnFocus1.Location = new System.Drawing.Point(66, 205); + this.btnFocus1.Location = new System.Drawing.Point(88, 256); + this.btnFocus1.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4); this.btnFocus1.Name = "btnFocus1"; - this.btnFocus1.Size = new System.Drawing.Size(55, 23); + this.btnFocus1.Size = new System.Drawing.Size(73, 29); this.btnFocus1.TabIndex = 57; this.btnFocus1.Text = "聚焦+"; this.btnFocus1.UseVisualStyleBackColor = true; - this.btnFocus1.Click += new System.EventHandler(this.BtnFocus1_Click); + this.btnFocus1.Click += new System.EventHandler(this.btnFocus1_Click); // // btnZoom1 // - this.btnZoom1.Location = new System.Drawing.Point(4, 205); + this.btnZoom1.Location = new System.Drawing.Point(5, 256); + this.btnZoom1.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4); this.btnZoom1.Name = "btnZoom1"; - this.btnZoom1.Size = new System.Drawing.Size(55, 23); + this.btnZoom1.Size = new System.Drawing.Size(73, 29); this.btnZoom1.TabIndex = 62; this.btnZoom1.Text = "变倍+"; this.btnZoom1.UseVisualStyleBackColor = true; - this.btnZoom1.Click += new System.EventHandler(this.BtnZoom1_Click); + this.btnZoom1.Click += new System.EventHandler(this.btnZoom1_Click); // // btnRightDown // - this.btnRightDown.Font = new System.Drawing.Font("宋体", 11.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(134))); - this.btnRightDown.Location = new System.Drawing.Point(137, 156); + this.btnRightDown.Font = new System.Drawing.Font("SimSun", 11.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(134))); + this.btnRightDown.Location = new System.Drawing.Point(183, 195); + this.btnRightDown.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4); this.btnRightDown.Name = "btnRightDown"; - this.btnRightDown.Size = new System.Drawing.Size(37, 36); + this.btnRightDown.Size = new System.Drawing.Size(49, 45); this.btnRightDown.TabIndex = 56; this.btnRightDown.Text = "↘"; this.btnRightDown.UseVisualStyleBackColor = true; @@ -942,10 +1002,11 @@ // // btnLeftDown // - this.btnLeftDown.Font = new System.Drawing.Font("宋体", 11.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(134))); - this.btnLeftDown.Location = new System.Drawing.Point(13, 156); + this.btnLeftDown.Font = new System.Drawing.Font("SimSun", 11.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(134))); + this.btnLeftDown.Location = new System.Drawing.Point(17, 195); + this.btnLeftDown.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4); this.btnLeftDown.Name = "btnLeftDown"; - this.btnLeftDown.Size = new System.Drawing.Size(37, 36); + this.btnLeftDown.Size = new System.Drawing.Size(49, 45); this.btnLeftDown.TabIndex = 55; this.btnLeftDown.Text = "↙"; this.btnLeftDown.UseVisualStyleBackColor = true; @@ -953,10 +1014,11 @@ // // btnRightUP // - this.btnRightUP.Font = new System.Drawing.Font("宋体", 11.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(134))); - this.btnRightUP.Location = new System.Drawing.Point(137, 50); + this.btnRightUP.Font = new System.Drawing.Font("SimSun", 11.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(134))); + this.btnRightUP.Location = new System.Drawing.Point(183, 62); + this.btnRightUP.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4); this.btnRightUP.Name = "btnRightUP"; - this.btnRightUP.Size = new System.Drawing.Size(37, 36); + this.btnRightUP.Size = new System.Drawing.Size(49, 45); this.btnRightUP.TabIndex = 54; this.btnRightUP.Text = "↗"; this.btnRightUP.UseVisualStyleBackColor = true; @@ -964,9 +1026,10 @@ // // btnRemovePreset // - this.btnRemovePreset.Location = new System.Drawing.Point(199, 103); + this.btnRemovePreset.Location = new System.Drawing.Point(265, 129); + this.btnRemovePreset.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4); this.btnRemovePreset.Name = "btnRemovePreset"; - this.btnRemovePreset.Size = new System.Drawing.Size(75, 23); + this.btnRemovePreset.Size = new System.Drawing.Size(100, 29); this.btnRemovePreset.TabIndex = 67; this.btnRemovePreset.Text = "删除预置位"; this.btnRemovePreset.UseVisualStyleBackColor = true; @@ -974,10 +1037,11 @@ // // btnLeftUP // - this.btnLeftUP.Font = new System.Drawing.Font("宋体", 11.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(134))); - this.btnLeftUP.Location = new System.Drawing.Point(13, 50); + this.btnLeftUP.Font = new System.Drawing.Font("SimSun", 11.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(134))); + this.btnLeftUP.Location = new System.Drawing.Point(17, 62); + this.btnLeftUP.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4); this.btnLeftUP.Name = "btnLeftUP"; - this.btnLeftUP.Size = new System.Drawing.Size(37, 36); + this.btnLeftUP.Size = new System.Drawing.Size(49, 45); this.btnLeftUP.TabIndex = 53; this.btnLeftUP.Text = "↖"; this.btnLeftUP.UseVisualStyleBackColor = true; @@ -990,7 +1054,8 @@ 0, 0, 0}); - this.numberSpeed.Location = new System.Drawing.Point(69, 16); + this.numberSpeed.Location = new System.Drawing.Point(92, 20); + this.numberSpeed.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4); this.numberSpeed.Maximum = new decimal(new int[] { 255, 0, @@ -1002,7 +1067,7 @@ 0, 0}); this.numberSpeed.Name = "numberSpeed"; - this.numberSpeed.Size = new System.Drawing.Size(93, 21); + this.numberSpeed.Size = new System.Drawing.Size(124, 25); this.numberSpeed.TabIndex = 52; this.numberSpeed.Value = new decimal(new int[] { 10, @@ -1012,10 +1077,11 @@ // // btnDown // - this.btnDown.Font = new System.Drawing.Font("宋体", 11.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(134))); - this.btnDown.Location = new System.Drawing.Point(75, 156); + this.btnDown.Font = new System.Drawing.Font("SimSun", 11.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(134))); + this.btnDown.Location = new System.Drawing.Point(100, 195); + this.btnDown.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4); this.btnDown.Name = "btnDown"; - this.btnDown.Size = new System.Drawing.Size(37, 36); + this.btnDown.Size = new System.Drawing.Size(49, 45); this.btnDown.TabIndex = 50; this.btnDown.Text = "↓"; this.btnDown.UseVisualStyleBackColor = true; @@ -1023,9 +1089,10 @@ // // btnGetPreset // - this.btnGetPreset.Location = new System.Drawing.Point(199, 74); + this.btnGetPreset.Location = new System.Drawing.Point(265, 92); + this.btnGetPreset.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4); this.btnGetPreset.Name = "btnGetPreset"; - this.btnGetPreset.Size = new System.Drawing.Size(75, 23); + this.btnGetPreset.Size = new System.Drawing.Size(100, 29); this.btnGetPreset.TabIndex = 66; this.btnGetPreset.Text = "调用预置位"; this.btnGetPreset.UseVisualStyleBackColor = true; @@ -1033,10 +1100,11 @@ // // btnUP // - this.btnUP.Font = new System.Drawing.Font("宋体", 11.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(134))); - this.btnUP.Location = new System.Drawing.Point(75, 50); + this.btnUP.Font = new System.Drawing.Font("SimSun", 11.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(134))); + this.btnUP.Location = new System.Drawing.Point(100, 62); + this.btnUP.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4); this.btnUP.Name = "btnUP"; - this.btnUP.Size = new System.Drawing.Size(37, 36); + this.btnUP.Size = new System.Drawing.Size(49, 45); this.btnUP.TabIndex = 47; this.btnUP.Text = "↑"; this.btnUP.UseVisualStyleBackColor = true; @@ -1044,9 +1112,10 @@ // // btnSearchPreset // - this.btnSearchPreset.Location = new System.Drawing.Point(199, 45); + this.btnSearchPreset.Location = new System.Drawing.Point(265, 56); + this.btnSearchPreset.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4); this.btnSearchPreset.Name = "btnSearchPreset"; - this.btnSearchPreset.Size = new System.Drawing.Size(75, 23); + this.btnSearchPreset.Size = new System.Drawing.Size(100, 29); this.btnSearchPreset.TabIndex = 65; this.btnSearchPreset.Text = "预置位查询"; this.btnSearchPreset.UseVisualStyleBackColor = true; @@ -1054,10 +1123,11 @@ // // btnRight // - this.btnRight.Font = new System.Drawing.Font("宋体", 11.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(134))); - this.btnRight.Location = new System.Drawing.Point(137, 103); + this.btnRight.Font = new System.Drawing.Font("SimSun", 11.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(134))); + this.btnRight.Location = new System.Drawing.Point(183, 129); + this.btnRight.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4); this.btnRight.Name = "btnRight"; - this.btnRight.Size = new System.Drawing.Size(37, 36); + this.btnRight.Size = new System.Drawing.Size(49, 45); this.btnRight.TabIndex = 49; this.btnRight.Text = "→"; this.btnRight.UseVisualStyleBackColor = true; @@ -1065,9 +1135,10 @@ // // btnSetPreset // - this.btnSetPreset.Location = new System.Drawing.Point(165, 16); + this.btnSetPreset.Location = new System.Drawing.Point(220, 20); + this.btnSetPreset.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4); this.btnSetPreset.Name = "btnSetPreset"; - this.btnSetPreset.Size = new System.Drawing.Size(75, 23); + this.btnSetPreset.Size = new System.Drawing.Size(100, 29); this.btnSetPreset.TabIndex = 64; this.btnSetPreset.Text = "预置位设置"; this.btnSetPreset.UseVisualStyleBackColor = true; @@ -1075,10 +1146,11 @@ // // btnLeft // - this.btnLeft.Font = new System.Drawing.Font("宋体", 11.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(134))); - this.btnLeft.Location = new System.Drawing.Point(13, 103); + this.btnLeft.Font = new System.Drawing.Font("SimSun", 11.25F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(134))); + this.btnLeft.Location = new System.Drawing.Point(17, 129); + this.btnLeft.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4); this.btnLeft.Name = "btnLeft"; - this.btnLeft.Size = new System.Drawing.Size(37, 36); + this.btnLeft.Size = new System.Drawing.Size(49, 45); this.btnLeft.TabIndex = 48; this.btnLeft.Text = "←"; this.btnLeft.UseVisualStyleBackColor = true; @@ -1095,18 +1167,20 @@ this.tbOther.Controls.Add(this.btnDevSearch); this.tbOther.Controls.Add(this.txtMsg); this.tbOther.Controls.Add(this.brnRenboot); - this.tbOther.Location = new System.Drawing.Point(4, 22); + this.tbOther.Location = new System.Drawing.Point(4, 25); + this.tbOther.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4); this.tbOther.Name = "tbOther"; - this.tbOther.Size = new System.Drawing.Size(332, 268); + this.tbOther.Size = new System.Drawing.Size(445, 339); this.tbOther.TabIndex = 3; this.tbOther.Text = "其他"; this.tbOther.UseVisualStyleBackColor = true; // // btnKeyFrame // - this.btnKeyFrame.Location = new System.Drawing.Point(156, 44); + this.btnKeyFrame.Location = new System.Drawing.Point(208, 55); + this.btnKeyFrame.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4); this.btnKeyFrame.Name = "btnKeyFrame"; - this.btnKeyFrame.Size = new System.Drawing.Size(75, 23); + this.btnKeyFrame.Size = new System.Drawing.Size(100, 29); this.btnKeyFrame.TabIndex = 51; this.btnKeyFrame.Text = "关键帧"; this.btnKeyFrame.UseVisualStyleBackColor = true; @@ -1114,9 +1188,10 @@ // // button1 // - this.button1.Location = new System.Drawing.Point(156, 14); + this.button1.Location = new System.Drawing.Point(208, 18); + this.button1.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4); this.button1.Name = "button1"; - this.button1.Size = new System.Drawing.Size(75, 23); + this.button1.Size = new System.Drawing.Size(100, 29); this.button1.TabIndex = 50; this.button1.Text = "Test"; this.button1.UseVisualStyleBackColor = true; @@ -1125,9 +1200,10 @@ // label14 // this.label14.AutoSize = true; - this.label14.Location = new System.Drawing.Point(11, 112); + this.label14.Location = new System.Drawing.Point(15, 140); + this.label14.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0); this.label14.Name = "label14"; - this.label14.Size = new System.Drawing.Size(53, 12); + this.label14.Size = new System.Drawing.Size(67, 15); this.label14.TabIndex = 49; this.label14.Text = "配置参数"; // @@ -1135,28 +1211,31 @@ // this.cbxConfig.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.cbxConfig.FormattingEnabled = true; - this.cbxConfig.Location = new System.Drawing.Point(71, 108); + this.cbxConfig.Location = new System.Drawing.Point(95, 135); + this.cbxConfig.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4); this.cbxConfig.Name = "cbxConfig"; - this.cbxConfig.Size = new System.Drawing.Size(121, 20); + this.cbxConfig.Size = new System.Drawing.Size(160, 23); this.cbxConfig.TabIndex = 48; // // btnConfigQuery // - this.btnConfigQuery.Location = new System.Drawing.Point(201, 106); + this.btnConfigQuery.Location = new System.Drawing.Point(268, 132); + this.btnConfigQuery.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4); this.btnConfigQuery.Name = "btnConfigQuery"; - this.btnConfigQuery.Size = new System.Drawing.Size(98, 23); + this.btnConfigQuery.Size = new System.Drawing.Size(131, 29); this.btnConfigQuery.TabIndex = 47; this.btnConfigQuery.Text = "设备配置查询"; this.btnConfigQuery.UseVisualStyleBackColor = true; - this.btnConfigQuery.Click += new System.EventHandler(this.BtnConfigQuery_Click); + this.btnConfigQuery.Click += new System.EventHandler(this.btnConfigQuery_Click); // // txtMsg // - this.txtMsg.Location = new System.Drawing.Point(12, 136); + this.txtMsg.Location = new System.Drawing.Point(16, 170); + this.txtMsg.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4); this.txtMsg.Multiline = true; this.txtMsg.Name = "txtMsg"; this.txtMsg.ScrollBars = System.Windows.Forms.ScrollBars.Vertical; - this.txtMsg.Size = new System.Drawing.Size(306, 93); + this.txtMsg.Size = new System.Drawing.Size(407, 115); this.txtMsg.TabIndex = 46; // // tabNew @@ -1168,19 +1247,21 @@ this.tabNew.Controls.Add(this.label22); this.tabNew.Controls.Add(this.btnSubPositionInfo); this.tabNew.Controls.Add(this.btnAudioNotify); - this.tabNew.Location = new System.Drawing.Point(4, 22); + this.tabNew.Location = new System.Drawing.Point(4, 25); + this.tabNew.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4); this.tabNew.Name = "tabNew"; - this.tabNew.Padding = new System.Windows.Forms.Padding(3); - this.tabNew.Size = new System.Drawing.Size(332, 268); + this.tabNew.Padding = new System.Windows.Forms.Padding(4, 4, 4, 4); + this.tabNew.Size = new System.Drawing.Size(445, 339); this.tabNew.TabIndex = 4; this.tabNew.Text = "新加12/23"; this.tabNew.UseVisualStyleBackColor = true; // // button2 // - this.button2.Location = new System.Drawing.Point(20, 144); + this.button2.Location = new System.Drawing.Point(27, 180); + this.button2.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4); this.button2.Name = "button2"; - this.button2.Size = new System.Drawing.Size(119, 23); + this.button2.Size = new System.Drawing.Size(159, 29); this.button2.TabIndex = 7; this.button2.Text = "目录订阅取消订阅"; this.button2.UseVisualStyleBackColor = true; @@ -1188,33 +1269,36 @@ // // btnSubscribeCancel // - this.btnSubscribeCancel.Location = new System.Drawing.Point(171, 71); + this.btnSubscribeCancel.Location = new System.Drawing.Point(228, 89); + this.btnSubscribeCancel.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4); this.btnSubscribeCancel.Name = "btnSubscribeCancel"; - this.btnSubscribeCancel.Size = new System.Drawing.Size(119, 23); + this.btnSubscribeCancel.Size = new System.Drawing.Size(159, 29); this.btnSubscribeCancel.TabIndex = 5; this.btnSubscribeCancel.Text = "移动位置取消订阅"; this.btnSubscribeCancel.UseVisualStyleBackColor = true; - this.btnSubscribeCancel.Click += new System.EventHandler(this.BtnSubscribeCancel_Click); + this.btnSubscribeCancel.Click += new System.EventHandler(this.btnSubscribeCancel_Click); // // label23 // this.label23.AutoSize = true; - this.label23.Location = new System.Drawing.Point(181, 114); + this.label23.Location = new System.Drawing.Point(241, 142); + this.label23.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0); this.label23.Name = "label23"; - this.label23.Size = new System.Drawing.Size(47, 12); + this.label23.Size = new System.Drawing.Size(60, 15); this.label23.TabIndex = 4; this.label23.Text = "单位/秒"; // // numInterval // - this.numInterval.Location = new System.Drawing.Point(101, 109); + this.numInterval.Location = new System.Drawing.Point(135, 136); + this.numInterval.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4); this.numInterval.Minimum = new decimal(new int[] { 5, 0, 0, 0}); this.numInterval.Name = "numInterval"; - this.numInterval.Size = new System.Drawing.Size(74, 21); + this.numInterval.Size = new System.Drawing.Size(99, 25); this.numInterval.TabIndex = 3; this.numInterval.Value = new decimal(new int[] { 5, @@ -1225,27 +1309,30 @@ // label22 // this.label22.AutoSize = true; - this.label22.Location = new System.Drawing.Point(18, 113); + this.label22.Location = new System.Drawing.Point(24, 141); + this.label22.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0); this.label22.Name = "label22"; - this.label22.Size = new System.Drawing.Size(77, 12); + this.label22.Size = new System.Drawing.Size(97, 15); this.label22.TabIndex = 2; this.label22.Text = "上报时间间隔"; // // btnSubPositionInfo // - this.btnSubPositionInfo.Location = new System.Drawing.Point(20, 71); + this.btnSubPositionInfo.Location = new System.Drawing.Point(27, 89); + this.btnSubPositionInfo.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4); this.btnSubPositionInfo.Name = "btnSubPositionInfo"; - this.btnSubPositionInfo.Size = new System.Drawing.Size(138, 23); + this.btnSubPositionInfo.Size = new System.Drawing.Size(184, 29); this.btnSubPositionInfo.TabIndex = 1; this.btnSubPositionInfo.Text = "移动位置数据订阅"; this.btnSubPositionInfo.UseVisualStyleBackColor = true; - this.btnSubPositionInfo.Click += new System.EventHandler(this.BtnSubPositionInfo_Click); + this.btnSubPositionInfo.Click += new System.EventHandler(this.btnSubPositionInfo_Click); // // btnAudioNotify // - this.btnAudioNotify.Location = new System.Drawing.Point(20, 22); + this.btnAudioNotify.Location = new System.Drawing.Point(27, 28); + this.btnAudioNotify.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4); this.btnAudioNotify.Name = "btnAudioNotify"; - this.btnAudioNotify.Size = new System.Drawing.Size(138, 23); + this.btnAudioNotify.Size = new System.Drawing.Size(184, 29); this.btnAudioNotify.TabIndex = 0; this.btnAudioNotify.Text = "语音广播通知"; this.btnAudioNotify.UseVisualStyleBackColor = true; @@ -1265,10 +1352,11 @@ this.tabPage1.Controls.Add(this.label15); this.tabPage1.Controls.Add(this.txtDevName); this.tabPage1.Controls.Add(this.btnDevConfig); - this.tabPage1.Location = new System.Drawing.Point(4, 22); + this.tabPage1.Location = new System.Drawing.Point(4, 25); + this.tabPage1.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4); this.tabPage1.Name = "tabPage1"; - this.tabPage1.Padding = new System.Windows.Forms.Padding(3); - this.tabPage1.Size = new System.Drawing.Size(332, 268); + this.tabPage1.Padding = new System.Windows.Forms.Padding(4, 4, 4, 4); + this.tabPage1.Size = new System.Drawing.Size(445, 339); this.tabPage1.TabIndex = 5; this.tabPage1.Text = "设备配置"; this.tabPage1.UseVisualStyleBackColor = true; @@ -1276,42 +1364,47 @@ // label21 // this.label21.AutoSize = true; - this.label21.Location = new System.Drawing.Point(174, 76); + this.label21.Location = new System.Drawing.Point(232, 95); + this.label21.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0); this.label21.Name = "label21"; - this.label21.Size = new System.Drawing.Size(47, 12); + this.label21.Size = new System.Drawing.Size(60, 15); this.label21.TabIndex = 11; this.label21.Text = "单位/秒"; // // label20 // this.label20.AutoSize = true; - this.label20.Location = new System.Drawing.Point(174, 106); + this.label20.Location = new System.Drawing.Point(232, 132); + this.label20.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0); this.label20.Name = "label20"; - this.label20.Size = new System.Drawing.Size(47, 12); + this.label20.Size = new System.Drawing.Size(60, 15); this.label20.TabIndex = 10; this.label20.Text = "单位/秒"; // // label19 // this.label19.AutoSize = true; - this.label19.Location = new System.Drawing.Point(174, 49); + this.label19.Location = new System.Drawing.Point(232, 61); + this.label19.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0); this.label19.Name = "label19"; - this.label19.Size = new System.Drawing.Size(47, 12); + this.label19.Size = new System.Drawing.Size(60, 15); this.label19.TabIndex = 9; this.label19.Text = "单位/秒"; // // label18 // this.label18.AutoSize = true; - this.label18.Location = new System.Drawing.Point(4, 105); + this.label18.Location = new System.Drawing.Point(5, 131); + this.label18.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0); this.label18.Name = "label18"; - this.label18.Size = new System.Drawing.Size(77, 12); + this.label18.Size = new System.Drawing.Size(97, 15); this.label18.TabIndex = 8; this.label18.Text = "心跳超时次数"; // // numIntervalTotal // - this.numIntervalTotal.Location = new System.Drawing.Point(83, 101); + this.numIntervalTotal.Location = new System.Drawing.Point(111, 126); + this.numIntervalTotal.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4); this.numIntervalTotal.Maximum = new decimal(new int[] { 10, 0, @@ -1323,7 +1416,7 @@ 0, 0}); this.numIntervalTotal.Name = "numIntervalTotal"; - this.numIntervalTotal.Size = new System.Drawing.Size(85, 21); + this.numIntervalTotal.Size = new System.Drawing.Size(113, 25); this.numIntervalTotal.TabIndex = 7; this.numIntervalTotal.Value = new decimal(new int[] { 3, @@ -1334,22 +1427,24 @@ // label17 // this.label17.AutoSize = true; - this.label17.Location = new System.Drawing.Point(4, 77); + this.label17.Location = new System.Drawing.Point(5, 96); + this.label17.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0); this.label17.Name = "label17"; - this.label17.Size = new System.Drawing.Size(77, 12); + this.label17.Size = new System.Drawing.Size(97, 15); this.label17.TabIndex = 6; this.label17.Text = "心跳间隔时间"; // // numIntervalTime // - this.numIntervalTime.Location = new System.Drawing.Point(83, 72); + this.numIntervalTime.Location = new System.Drawing.Point(111, 90); + this.numIntervalTime.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4); this.numIntervalTime.Minimum = new decimal(new int[] { 5, 0, 0, 0}); this.numIntervalTime.Name = "numIntervalTime"; - this.numIntervalTime.Size = new System.Drawing.Size(85, 21); + this.numIntervalTime.Size = new System.Drawing.Size(113, 25); this.numIntervalTime.TabIndex = 5; this.numIntervalTime.Value = new decimal(new int[] { 30, @@ -1360,22 +1455,24 @@ // label16 // this.label16.AutoSize = true; - this.label16.Location = new System.Drawing.Point(4, 49); + this.label16.Location = new System.Drawing.Point(5, 61); + this.label16.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0); this.label16.Name = "label16"; - this.label16.Size = new System.Drawing.Size(77, 12); + this.label16.Size = new System.Drawing.Size(97, 15); this.label16.TabIndex = 4; this.label16.Text = "注册过期时间"; // // numIntervalTimeOut // - this.numIntervalTimeOut.Location = new System.Drawing.Point(83, 44); + this.numIntervalTimeOut.Location = new System.Drawing.Point(111, 55); + this.numIntervalTimeOut.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4); this.numIntervalTimeOut.Maximum = new decimal(new int[] { 8000, 0, 0, 0}); this.numIntervalTimeOut.Name = "numIntervalTimeOut"; - this.numIntervalTimeOut.Size = new System.Drawing.Size(85, 21); + this.numIntervalTimeOut.Size = new System.Drawing.Size(113, 25); this.numIntervalTimeOut.TabIndex = 3; this.numIntervalTimeOut.Value = new decimal(new int[] { 3600, @@ -1386,25 +1483,28 @@ // label15 // this.label15.AutoSize = true; - this.label15.Location = new System.Drawing.Point(28, 21); + this.label15.Location = new System.Drawing.Point(37, 26); + this.label15.Margin = new System.Windows.Forms.Padding(4, 0, 4, 0); this.label15.Name = "label15"; - this.label15.Size = new System.Drawing.Size(53, 12); + this.label15.Size = new System.Drawing.Size(67, 15); this.label15.TabIndex = 2; this.label15.Text = "设备名称"; // // txtDevName // - this.txtDevName.Location = new System.Drawing.Point(83, 17); + this.txtDevName.Location = new System.Drawing.Point(111, 21); + this.txtDevName.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4); this.txtDevName.Name = "txtDevName"; - this.txtDevName.Size = new System.Drawing.Size(131, 21); + this.txtDevName.Size = new System.Drawing.Size(173, 25); this.txtDevName.TabIndex = 1; this.txtDevName.Text = "测试"; // // btnDevConfig // - this.btnDevConfig.Location = new System.Drawing.Point(83, 144); + this.btnDevConfig.Location = new System.Drawing.Point(111, 180); + this.btnDevConfig.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4); this.btnDevConfig.Name = "btnDevConfig"; - this.btnDevConfig.Size = new System.Drawing.Size(75, 23); + this.btnDevConfig.Size = new System.Drawing.Size(100, 29); this.btnDevConfig.TabIndex = 0; this.btnDevConfig.Text = "设备配置"; this.btnDevConfig.UseVisualStyleBackColor = true; @@ -1412,15 +1512,16 @@ // // tvCalatog // - this.tvCalatog.Location = new System.Drawing.Point(6, 328); + this.tvCalatog.Location = new System.Drawing.Point(8, 410); + this.tvCalatog.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4); this.tvCalatog.Name = "tvCalatog"; - this.tvCalatog.Size = new System.Drawing.Size(320, 156); + this.tvCalatog.Size = new System.Drawing.Size(425, 194); this.tvCalatog.TabIndex = 49; this.tvCalatog.AfterSelect += new System.Windows.Forms.TreeViewEventHandler(this.tvCalatog_AfterSelect); // // Form1 // - this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F); + this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 15F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(1055, 614); this.Controls.Add(this.tvCalatog); @@ -1438,9 +1539,10 @@ this.Controls.Add(this.lblStatus); this.Controls.Add(this.btnStop); this.Controls.Add(this.btnStart); - this.Name = "Form1"; + this.Margin = new System.Windows.Forms.Padding(4, 4, 4, 4); + this.Name = "Win.GB28181.Client(Alpha) - This is a Test Tool"; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; - this.Text = "Form1"; + this.Text = "Win.GB28181.Client(Alpha) - This is a Test Tool"; this.tabControl1.ResumeLayout(false); this.tbReal.ResumeLayout(false); this.tbRecord.ResumeLayout(false); @@ -1463,7 +1565,7 @@ } - + #endregion @@ -1588,7 +1690,7 @@ private System.Windows.Forms.Button btnKeyFrame; private System.Windows.Forms.TreeView tvCalatog; private System.Windows.Forms.Button button2; - private Win.ClientBase.PlayerControl playerWin; + private SS.ClientBase.PlayerControl playerWin; } } diff --git a/Win.GB28181.Client/Form1.cs b/Win.GB28181.Client/Form1.cs index 36a555e659d03d53d5268522a7aa5167f5edf9ea..e71d98834b455cf5c557f99262d07339c6c45e51 100644 --- a/Win.GB28181.Client/Form1.cs +++ b/Win.GB28181.Client/Form1.cs @@ -1,5 +1,4 @@ -using GB28181.Logger4Net; -using GB28181.SIPSorcery.Net; +using GB28181.SIPSorcery.Net; using GB28181.SIPSorcery.Servers; using GB28181.SIPSorcery.Servers.SIPMessage; using GB28181.SIPSorcery.Servers.SIPMonitor; @@ -8,20 +7,25 @@ using GB28181.SIPSorcery.Sys; using GB28181.SIPSorcery.Sys.Config; using GB28181.SIPSorcery.Sys.Model; using GB28181.SIPSorcery.Sys.XML; +using GB28181.Logger4Net; +using SS.Media; +using SS.MediaServer.Media.TS; using System; using System.Collections.Generic; -using System.ComponentModel; using System.Drawing; using System.IO; using System.Linq; -using System.Reflection; using System.Text; -using System.Text.RegularExpressions; using System.Threading; using System.Windows.Forms; using Win.GB28181.Client.Player.Analyzer; -using Win.Media; -using Win.MediaServer.Media.TS; +using GB28181.SIPSorcery.SIP.App; +using Autofac; +using GB28181.Server.Message; +using GB28181.Service; +using GB28181.Server.Main; +using GB28181.SIPSorcery.Sys.Cache; +using System.Threading.Tasks; namespace Win.GB28181.Client { @@ -35,8 +39,8 @@ namespace Win.GB28181.Client private string _dir = AppDomain.CurrentDomain.BaseDirectory + "Config"; private DateTime _keepaliveTime; private Thread _keepaliveThread; - private readonly Queue _keepQueue = new Queue(); - //private int _count = 0; + private Queue _keepQueue = new Queue(); + private int _count = 0; private SIPMessageCore _messageCore; #endregion @@ -44,7 +48,7 @@ namespace Win.GB28181.Client /// /// 选择的设备键 /// - private string DevKey + private MonitorKey DevKey { get { @@ -53,13 +57,12 @@ namespace Win.GB28181.Client { devItem = item; } - // MonitorKey key = new MonitorKey() - // { - // DeviceID = devItem.ImageKey, - // CmdType = CommandType.Play - // }; - // return key; - return devItem.ImageKey; + var key = new MonitorKey() + { + DeviceID = devItem.ImageKey, + CmdType = CommandType.Play + }; + return key; } } #endregion @@ -90,63 +93,125 @@ namespace Win.GB28181.Client #endregion #region 初始化服务 + //在类中定义变量 + private IContainer container; + private readonly CancellationTokenSource _registryServiceToken = new CancellationTokenSource(); public Form1() { + + //构造函数中添加如下代码 + var builder = new ContainerBuilder(); + //.AddSingleton() + // .AddSingleton() + // .AddSingleton() + // .AddSingleton() + // .AddSingleton() + // .AddSingleton() + // .AddScoped() + // .AddTransient() + // .AddSingleton() + // .AddSingleton() + // .AddTransient() + // .AddSingleton() + // .AddSingleton, DeviceObjectCache>() + // .AddScoped() + // .AddScoped() + // .AddScoped() + // .AddScoped() + // .AddScoped(); + + + //builder.RegisterType(); + //builder.RegisterType(); + //builder.RegisterType(); + //builder.RegisterType(); + //builder.RegisterType(); + + //builder.RegisterAssemblyTypes(typeof(ISIPServiceDirector).Assembly).AsImplementedInterfaces(); + //builder.RegisterAssemblyTypes(typeof(ISIPMonitorCore).Assembly).AsImplementedInterfaces(); + //builder.RegisterAssemblyTypes(typeof(ISipMessageCore).Assembly).AsImplementedInterfaces(); + //builder.RegisterType().Named("SIPMessageCore"); + + //builder.RegisterAssemblyTypes(typeof(ISIPTransport).Assembly).AsImplementedInterfaces(); + //builder.RegisterAssemblyTypes(typeof(ISIPTransactionEngine).Assembly).AsImplementedInterfaces(); + //builder.RegisterAssemblyTypes(typeof(ISIPRegistrarCore).Assembly).AsImplementedInterfaces(); + //builder.RegisterAssemblyTypes(typeof(IMemoCache).Assembly).AsImplementedInterfaces(); + + + //builder.RegisterInstance(this).As
(); + //container = builder.Build(); + + + + InitializeComponent(); - Initialize(); } - + private ISIPRegistrarCore registry; private void Initialize() { + + + _devList = new List(); txtStartTime.Text = DateTime.Now.ToString("yyyy-MM-dd 8:00:00"); txtStopTime.Text = DateTime.Now.ToString("yyyy-MM-dd 9:00:00"); //txtDragDrop.Text = DateTime.Now.ToString("yyyy-MM-dd 14:00:00"); - var configType = new Dictionary - { - { "BasicParam", "基本参数配置" }, - { "VideoParamOpt", "视频参数范围" }, - { "SVACEncodeConfig", "SVAC编码配置" }, - { "SVACDecodeConfig", "SVAC解码配置" } - }; - BindingSource bs = new BindingSource - { - DataSource = configType - }; + Dictionary configType = new Dictionary(); + configType.Add("BasicParam", "基本参数配置"); + configType.Add("VideoParamOpt", "视频参数范围"); + configType.Add("SVACEncodeConfig", "SVAC编码配置"); + configType.Add("SVACDecodeConfig", "SVAC解码配置"); + BindingSource bs = new BindingSource(); + bs.DataSource = configType; cbxConfig.DataSource = bs; cbxConfig.DisplayMember = "Value"; cbxConfig.ValueMember = "Key"; - Dictionary recordType = new Dictionary - { - { "time", "time" }, - { "alarm", "alarm" }, - { "manual", "manual" }, - { "all", "all" } - }; - BindingSource bsRecord = new BindingSource - { - DataSource = recordType - }; + Dictionary recordType = new Dictionary(); + recordType.Add("time", "time"); + recordType.Add("alarm", "alarm"); + recordType.Add("manual", "manual"); + recordType.Add("all", "all"); + BindingSource bsRecord = new BindingSource(); + bsRecord.DataSource = recordType; cbxRecordType.DataSource = bsRecord; cbxRecordType.DisplayMember = "Value"; cbxRecordType.ValueMember = "Key"; - SipAccountStorage.Instance.Read(); - IList cameras = new List(); - var account = SipAccountStorage.Instance.Accounts.First(); - if (account == null) - { - logger.Error("Account Config NULL,SIP not started"); - return; - } + //SIPSqlite.Instance.Read(); + // var cameras = new List(); + // var account = SIPSqlite.Instance.Accounts.First(); + //if (account == null) + //{ + // logger.Error("Account Config NULL,SIP not started"); + // return; + //} _keepaliveTime = DateTime.Now; _cataThread = new Thread(new ThreadStart(HandleCata)); _keepaliveThread = new Thread(new ThreadStart(HandleKeepalive)); - // _messageCore = new SIPMessageCore(cameras, account); + + + SIPTransport m_sipTransport; + + m_sipTransport = new SIPTransport(SIPDNSManager.ResolveSIPService, new SIPTransactionEngine(), false); + m_sipTransport.PerformanceMonitorPrefix = SIPSorceryPerformanceMonitor.REGISTRAR_PREFIX; + SIPAccount account = SipAccountStorage.Instance.Accounts.FirstOrDefault(); + var sipChannels = SIPTransportConfig.ParseSIPChannelsNode(account.LocalIP, account.LocalPort); + m_sipTransport.AddSIPChannel(sipChannels); + + SipAccountStorage sipAccountStorage = new SipAccountStorage(); + IMemoCache memocache = new DeviceObjectCache(); + SIPRegistrarCore sipRegistrarCore = new SIPRegistrarCore(m_sipTransport, sipAccountStorage, memocache, true, true); + // _messageCore = new SIPMessageCore(m_sipTransport, SIPConstants.SIP_SERVER_STRING); + _messageCore = new SIPMessageCore(sipRegistrarCore, m_sipTransport, sipAccountStorage, memocache); + + Task.Factory.StartNew(() => sipRegistrarCore.ProcessRegisterRequest(), _registryServiceToken.Token); + + // sipRegistrarCore.ProcessRegisterRequest(); + } #endregion @@ -159,28 +224,28 @@ namespace Win.GB28181.Client #endregion #region 开始/停止服务 - private void BtnStart_Click(object sender, System.EventArgs e) + private void btnStart_Click(object sender, System.EventArgs e) { - //_tn = new TreeNode(); //tvCalatog.Nodes.Add(_tn); //_bg = new TreeNode(); //_tn.Nodes.Add(_bg); //tvCalatog.Nodes.Add(_tn); - txtStartTime.Text = DateTime.Now.ToString("yyyy-MM-dd 8:00:00"); _keepaliveTime = DateTime.Now; + playerWin = new SS.ClientBase.PlayerControl(); playerWin.Start(); Initialize(); _cataThread.Start(); _keepaliveThread.Start(); - + // _messageCore = new SIPMessageCore(); _messageCore.Start(); _messageCore.OnServiceChanged += SIPServiceChangeHandle; _messageCore.OnCatalogReceived += m_msgCore_OnCatalogReceived; _messageCore.OnNotifyCatalogReceived += MessageCore_OnNotifyCatalogReceived; _messageCore.OnAlarmReceived += MessageCore_OnAlarmReceived; + _messageCore.OnRecordInfoReceived += MessageCore_OnRecordInfoReceived; _messageCore.OnKeepaliveReceived += MessageCore_OnKeepaliveReceived; _messageCore.OnDeviceStatusReceived += DeviceStatusReceived; @@ -303,13 +368,12 @@ namespace Win.GB28181.Client Invoke(new Action(() => { MessageBox.Show(msg); - // var key = new MonitorKey() - // { - // CmdType = CommandType.Play, - // DeviceID = alarm.DeviceID - // }; - var key = alarm.DeviceID; - _messageCore.NodeMonitorService[key].AlarmResponse(alarm); + var key = new MonitorKey() + { + CmdType = CommandType.Play, + DeviceID = alarm.DeviceID + }; + _messageCore.NodeMonitorService[key.ToString()].AlarmResponse(alarm); //txtMsg.Text = msg; })); } @@ -463,22 +527,22 @@ namespace Win.GB28181.Client #region 其他接口 //系统设备配置查询 - private void BtnConfigQuery_Click(object sender, EventArgs e) + private void btnConfigQuery_Click(object sender, EventArgs e) { string configType = cbxConfig.SelectedValue.ToString(); - _messageCore.NodeMonitorService[DevKey].DeviceConfigQuery(configType); + _messageCore.NodeMonitorService[DevKey.ToString()].DeviceConfigQuery(configType); } //设备状态查询 - private void BtnStateSearch_Click(object sender, EventArgs e) + private void btnStateSearch_Click(object sender, EventArgs e) { - _messageCore.NodeMonitorService[DevKey].DeviceStateQuery(); + _messageCore.NodeMonitorService[DevKey.ToString()].DeviceStateQuery(); } //设备详细信息查询 private void btnDevSearch_Click(object sender, EventArgs e) { - _messageCore.NodeMonitorService[DevKey].DeviceInfoQuery(); + _messageCore.NodeMonitorService[DevKey.ToString()].DeviceInfoQuery(); } //设备信息查询回调函数 @@ -509,7 +573,7 @@ namespace Win.GB28181.Client //设备重启 private void brnRenboot_Click(object sender, EventArgs e) { - _messageCore.NodeMonitorService[DevKey].DeviceReboot(); + _messageCore.NodeMonitorService[DevKey.ToString()].DeviceReboot(); } //设备配置 @@ -523,10 +587,12 @@ namespace Win.GB28181.Client int expiration = (int)numIntervalTimeOut.Value; int heartBeatInterval = (int)numIntervalTime.Value; int heartBeatToal = (int)numIntervalTotal.Value; - _messageCore.NodeMonitorService[DevKey].DeviceConfig(name, expiration, heartBeatInterval, heartBeatToal); + _messageCore.NodeMonitorService[DevKey.ToString()].DeviceConfig(name, expiration, heartBeatInterval, heartBeatToal); } - public static byte[] ConvertUnicodeToUTF8(string message) + public byte[] ConvertUnicodeToUTF8(string message) { + System.Text.Encoding utf8, gb2312; + utf8 = System.Text.Encoding.GetEncoding("utf-8"); byte[] array = Encoding.Default.GetBytes(message); byte[] s4 = System.Text.Encoding.Convert(System.Text.Encoding.GetEncoding("gb2312"), System.Text.Encoding.UTF8, array); return s4; @@ -543,25 +609,25 @@ namespace Win.GB28181.Client //事件订阅 private void btnEventSubscribe_Click(object sender, EventArgs e) { - _messageCore.NodeMonitorService[DevKey].DeviceEventSubscribe(); + _messageCore.NodeMonitorService[DevKey.ToString()].DeviceEventSubscribe(); } //布防 private void btnSetGuard_Click(object sender, EventArgs e) { - _messageCore.NodeMonitorService[DevKey].DeviceControlSetGuard(); + _messageCore.NodeMonitorService[DevKey.ToString()].DeviceControlSetGuard(); } //撤防 private void btResetGuard_Click(object sender, EventArgs e) { - _messageCore.NodeMonitorService[DevKey].DeviceControlResetGuard(); + _messageCore.NodeMonitorService[DevKey.ToString()].DeviceControlResetGuard(); } //报警复位 private void btnAlarmReset_Click(object sender, EventArgs e) { - _messageCore.NodeMonitorService[DevKey].DeviceControlResetAlarm(); + _messageCore.NodeMonitorService[DevKey.ToString()].DeviceControlResetAlarm(); } #endregion @@ -569,7 +635,7 @@ namespace Win.GB28181.Client //目录订阅 private void btnCatalogSubscribe_Click(object sender, EventArgs e) { - _messageCore.NodeMonitorService[DevKey].DeviceCatalogSubscribe(true); + _messageCore.NodeMonitorService[DevKey.ToString()].DeviceCatalogSubscribe(true); } //目录查询 @@ -588,25 +654,22 @@ namespace Win.GB28181.Client //开始实时视频 private void BtnReal_Click(object sender, EventArgs e) { + int[] mediaPort = { 1000,2000 }; _analyzer = new StreamAnalyzer(); -// _messageCore.NodeMonitorService[DevKey].RealVideoReq(); - // _messageCore.NodeMonitorService[DevKey].OnStreamReady += Form1_OnStreamReady; + _messageCore.NodeMonitorService[DevKey.ToString()].RealVideoReq(mediaPort, "192.168.197.33", true); + _messageCore.NodeMonitorService[DevKey.ToString()].OnStreamReady += Form1_OnStreamReady; } //停止实时视频 private void BtnBye_Click(object sender, EventArgs e) { - // _messageCore.NodeMonitorService[DevKey].OnStreamReady -= Form1_OnStreamReady; - _messageCore.NodeMonitorService[DevKey].ByeVideoReq(); + _messageCore.NodeMonitorService[DevKey.ToString()].OnStreamReady -= Form1_OnStreamReady; + _messageCore.NodeMonitorService[DevKey.ToString()].ByeVideoReq(); } FileStream m_fs; void Form1_OnStreamReady(RTPFrame rtpFrame) { - if (rtpFrame == null) - { - throw new ArgumentNullException(nameof(rtpFrame)); - } //byte[] buffer = rtpFrame.GetFramePayload(); //if (this.m_fs == null) //{ @@ -655,96 +718,95 @@ namespace Win.GB28181.Client } //录像播放(点播) - private void BtnRecord_Click(object sender, EventArgs e) + private void btnRecord_Click(object sender, EventArgs e) { _analyzer = new StreamAnalyzer(); var key = DevKey; - // key.CmdType = CommandType.Playback; + key.CmdType = CommandType.Playback; DateTime startTime = DateTime.Parse(txtStartTime.Text.Trim()); DateTime stopTime = DateTime.Parse(txtStopTime.Text.Trim()); - _messageCore.NodeMonitorService[key].BackVideoReq(startTime, stopTime); - // _messageCore.NodeMonitorService[key].OnStreamReady += Form1_OnStreamReady; + _messageCore.NodeMonitorService[key.ToString()].BackVideoReq(startTime, stopTime); + // _messageCore.NodeMonitorService[key.ToString()].OnStreamReady += Form1_OnStreamReady; } //终止点播(停止) - private void BtnStopRecord_Click(object sender, EventArgs e) + private void btnStopRecord_Click(object sender, EventArgs e) { var key = DevKey; - // key.CmdType = CommandType.Playback; - _messageCore.NodeMonitorService[key].ByeVideoReq(); - // _messageCore.NodeMonitorService[key].OnStreamReady -= Form1_OnStreamReady; + key.CmdType = CommandType.Playback; + _messageCore.NodeMonitorService[key.ToString()].ByeVideoReq(); + _messageCore.NodeMonitorService[key.ToString()].OnStreamReady -= Form1_OnStreamReady; } //暂停播放 - private void BtnPause_Click(object sender, EventArgs e) + private void btnPause_Click(object sender, EventArgs e) { var key = DevKey; -// key.CmdType = CommandType.Playback; - _messageCore.NodeMonitorService[key].BackVideoPauseControlReq(); + key.CmdType = CommandType.Playback; + _messageCore.NodeMonitorService[key.ToString()].BackVideoPauseControlReq(); } //继续播放 - private void BtnPlay_Click(object sender, EventArgs e) + private void btnPlay_Click(object sender, EventArgs e) { var key = DevKey; -// key.CmdType = CommandType.Playback; - _messageCore.NodeMonitorService[key].BackVideoContinuePlayingControlReq(); + key.CmdType = CommandType.Playback; + _messageCore.NodeMonitorService[key.ToString()].BackVideoContinuePlayingControlReq(); } //播放倍数设置 - private void BtnSdu_Click(object sender, EventArgs e) + private void btnSdu_Click(object sender, EventArgs e) { var key = DevKey; - // key.CmdType = CommandType.Playback; + key.CmdType = CommandType.Playback; string range = txtScale.Text.Trim(); - _messageCore.NodeMonitorService[key].BackVideoPlaySpeedControlReq(range); + _messageCore.NodeMonitorService[key.ToString()].BackVideoPlaySpeedControlReq(range); } //拖动播放 - private void Button17_Click(object sender, EventArgs e) + private void button17_Click(object sender, EventArgs e) { var key = DevKey; - // key.CmdType = CommandType.Playback; + key.CmdType = CommandType.Playback; int time = int.Parse(txtDragDrop.Text.Trim()); - _messageCore.NodeMonitorService[key].BackVideoPlayPositionControlReq(time); + _messageCore.NodeMonitorService[key.ToString()].BackVideoPlayPositionControlReq(time); } //录像文件查询 - private void BtnRecordGet_Click(object sender, EventArgs e) + private void btnRecordGet_Click(object sender, EventArgs e) { _recordSN = 1; lvRecord.Items.Clear(); DateTime startTime = DateTime.Parse(txtStartTime.Text.Trim()); DateTime stopTime = DateTime.Parse(txtStopTime.Text.Trim()); - var key = DevKey; - // key.CmdType = CommandType.Playback; + //key.CmdType = CommandType.Playback; string type = cbxRecordType.SelectedValue.ToString(); - _messageCore.NodeMonitorService[key].RecordFileQuery(startTime, stopTime, type); + _messageCore.NodeMonitorService[DevKey.ToString()].RecordFileQuery(startTime, stopTime, type); } //录像文件下载 private void btnRecordDownload_Click(object sender, EventArgs e) { var key = DevKey; - // key.CmdType = CommandType.Playback; + key.CmdType = CommandType.Playback; DateTime startTime = DateTime.Parse(txtStartTime.Text.Trim()); DateTime stopTime = DateTime.Parse(txtStopTime.Text.Trim()); - _messageCore.NodeMonitorService[key].VideoDownloadReq(startTime, stopTime); - // _messageCore.NodeMonitorService[key].OnStreamReady += Form1_OnStreamReady; + _messageCore.NodeMonitorService[key.ToString()].VideoDownloadReq(startTime, stopTime); + _messageCore.NodeMonitorService[key.ToString()].OnStreamReady += Form1_OnStreamReady; } //开始手动录像 private void btnStartRecord_Click(object sender, EventArgs e) { - _messageCore.NodeMonitorService[DevKey].DeviceControlRecord(true); + _messageCore.NodeMonitorService[DevKey.ToString()].DeviceControlRecord(true); } //停止手动录像 - private void BtnStopRd_Click(object sender, EventArgs e) + private void btnStopRd_Click(object sender, EventArgs e) { - _messageCore.NodeMonitorService[DevKey].DeviceControlRecord(false); + _messageCore.NodeMonitorService[DevKey.ToString()].DeviceControlRecord(false); } #endregion @@ -753,55 +815,55 @@ namespace Win.GB28181.Client //上 private void btnUP_Click(object sender, EventArgs e) { - _messageCore.NodeMonitorService[DevKey].PtzContrl(PTZCommand.Up, int.Parse(numberSpeed.Value.ToString())); + _messageCore.NodeMonitorService[DevKey.ToString()].PtzContrl(PTZCommand.Up, int.Parse(numberSpeed.Value.ToString())); } //下 private void btnDown_Click(object sender, EventArgs e) { - _messageCore.NodeMonitorService[DevKey].PtzContrl(PTZCommand.Down, int.Parse(numberSpeed.Value.ToString())); + _messageCore.NodeMonitorService[DevKey.ToString()].PtzContrl(PTZCommand.Down, int.Parse(numberSpeed.Value.ToString())); } //左 private void btnLeft_Click(object sender, EventArgs e) { - _messageCore.NodeMonitorService[DevKey].PtzContrl(PTZCommand.Left, int.Parse(numberSpeed.Value.ToString())); + _messageCore.NodeMonitorService[DevKey.ToString()].PtzContrl(PTZCommand.Left, int.Parse(numberSpeed.Value.ToString())); } //右 private void btnRight_Click(object sender, EventArgs e) { - _messageCore.NodeMonitorService[DevKey].PtzContrl(PTZCommand.Right, int.Parse(numberSpeed.Value.ToString())); + _messageCore.NodeMonitorService[DevKey.ToString()].PtzContrl(PTZCommand.Right, int.Parse(numberSpeed.Value.ToString())); } //左上 private void btnLeftUP_Click(object sender, EventArgs e) { - _messageCore.NodeMonitorService[DevKey].PtzContrl(PTZCommand.UpLeft, int.Parse(numberSpeed.Value.ToString())); + _messageCore.NodeMonitorService[DevKey.ToString()].PtzContrl(PTZCommand.UpLeft, int.Parse(numberSpeed.Value.ToString())); } //右上 private void btnRightUP_Click(object sender, EventArgs e) { - _messageCore.NodeMonitorService[DevKey].PtzContrl(PTZCommand.UpRight, int.Parse(numberSpeed.Value.ToString())); + _messageCore.NodeMonitorService[DevKey.ToString()].PtzContrl(PTZCommand.UpRight, int.Parse(numberSpeed.Value.ToString())); } //左下 private void btnLeftDown_Click(object sender, EventArgs e) { - _messageCore.NodeMonitorService[DevKey].PtzContrl(PTZCommand.DownLeft, int.Parse(numberSpeed.Value.ToString())); + _messageCore.NodeMonitorService[DevKey.ToString()].PtzContrl(PTZCommand.DownLeft, int.Parse(numberSpeed.Value.ToString())); } //右下 private void btnRightDown_Click(object sender, EventArgs e) { - _messageCore.NodeMonitorService[DevKey].PtzContrl(PTZCommand.DownRight, int.Parse(numberSpeed.Value.ToString())); + _messageCore.NodeMonitorService[DevKey.ToString()].PtzContrl(PTZCommand.DownRight, int.Parse(numberSpeed.Value.ToString())); } //停止 private void btnPTZStop_Click(object sender, EventArgs e) { - _messageCore.NodeMonitorService[DevKey].PtzContrl(PTZCommand.Stop, int.Parse(numberSpeed.Value.ToString())); + _messageCore.NodeMonitorService[DevKey.ToString()].PtzContrl(PTZCommand.Stop, int.Parse(numberSpeed.Value.ToString())); } #endregion @@ -809,14 +871,14 @@ namespace Win.GB28181.Client //设置预置位 private void btnSetPreset_Click(object sender, EventArgs e) { - _messageCore.NodeMonitorService[DevKey].PtzContrl(PTZCommand.SetPreset, int.Parse(numberSpeed.Value.ToString())); + _messageCore.NodeMonitorService[DevKey.ToString()].PtzContrl(PTZCommand.SetPreset, int.Parse(numberSpeed.Value.ToString())); } //查询预置位 private void btnSearchPreset_Click(object sender, EventArgs e) { cbxPreset.Items.Clear(); - _messageCore.NodeMonitorService[DevKey].DevicePresetQuery(); + _messageCore.NodeMonitorService[DevKey.ToString()].DevicePresetQuery(); } //private Dictionary presetList = new Dictionary(); @@ -854,7 +916,7 @@ namespace Win.GB28181.Client /// 调用预置位 private void btnGetPreset_Click(object sender, EventArgs e) { - _messageCore.NodeMonitorService[DevKey].PtzContrl(PTZCommand.GetPreset, int.Parse(numberSpeed.Value.ToString())); + _messageCore.NodeMonitorService[DevKey.ToString()].PtzContrl(PTZCommand.GetPreset, int.Parse(numberSpeed.Value.ToString())); } //删除预置位 @@ -862,7 +924,7 @@ namespace Win.GB28181.Client { if (cbxPreset.SelectedItem != null) { - _messageCore.NodeMonitorService[DevKey].PtzContrl(PTZCommand.RemovePreset, int.Parse(cbxPreset.SelectedItem.ToString())); + _messageCore.NodeMonitorService[DevKey.ToString()].PtzContrl(PTZCommand.RemovePreset, int.Parse(cbxPreset.SelectedItem.ToString())); cbxPreset.Items.Remove(cbxPreset.SelectedItem); //presetList.Remove(cbxPreset.SelectedText.ToString()); //reloadPreset(); @@ -873,39 +935,39 @@ namespace Win.GB28181.Client #region 变倍/聚焦/光圈 //变倍+ - private void BtnZoom1_Click(object sender, EventArgs e) + private void btnZoom1_Click(object sender, EventArgs e) { - _messageCore.NodeMonitorService[DevKey].PtzContrl(PTZCommand.Zoom1, int.Parse(numberSpeed.Value.ToString())); + _messageCore.NodeMonitorService[DevKey.ToString()].PtzContrl(PTZCommand.Zoom1, int.Parse(numberSpeed.Value.ToString())); } //变倍- private void btnZoom2_Click(object sender, EventArgs e) { - _messageCore.NodeMonitorService[DevKey].PtzContrl(PTZCommand.Zoom2, int.Parse(numberSpeed.Value.ToString())); + _messageCore.NodeMonitorService[DevKey.ToString()].PtzContrl(PTZCommand.Zoom2, int.Parse(numberSpeed.Value.ToString())); } //聚焦+ - private void BtnFocus1_Click(object sender, EventArgs e) + private void btnFocus1_Click(object sender, EventArgs e) { - _messageCore.NodeMonitorService[DevKey].PtzContrl(PTZCommand.Focus1, int.Parse(numberSpeed.Value.ToString())); + _messageCore.NodeMonitorService[DevKey.ToString()].PtzContrl(PTZCommand.Focus1, int.Parse(numberSpeed.Value.ToString())); } //聚焦- private void btnFocus2_Click(object sender, EventArgs e) { - _messageCore.NodeMonitorService[DevKey].PtzContrl(PTZCommand.Focus2, int.Parse(numberSpeed.Value.ToString())); + _messageCore.NodeMonitorService[DevKey.ToString()].PtzContrl(PTZCommand.Focus2, int.Parse(numberSpeed.Value.ToString())); } //光圈开 private void btnIris1_Click(object sender, EventArgs e) { - _messageCore.NodeMonitorService[DevKey].PtzContrl(PTZCommand.Iris1, int.Parse(numberSpeed.Value.ToString())); + _messageCore.NodeMonitorService[DevKey.ToString()].PtzContrl(PTZCommand.Iris1, int.Parse(numberSpeed.Value.ToString())); } //光圈关 private void btnIris2_Click(object sender, EventArgs e) { - _messageCore.NodeMonitorService[DevKey].PtzContrl(PTZCommand.Iris2, int.Parse(numberSpeed.Value.ToString())); + _messageCore.NodeMonitorService[DevKey.ToString()].PtzContrl(PTZCommand.Iris2, int.Parse(numberSpeed.Value.ToString())); } #endregion @@ -934,14 +996,14 @@ namespace Win.GB28181.Client private void btnZoomIn_Click(object sender, EventArgs e) { var zoom = DragZoomValue(); - _messageCore.NodeMonitorService[DevKey].DragZoomContrl(zoom, true); + _messageCore.NodeMonitorService[DevKey.ToString()].DragZoomContrl(zoom, true); } //拉框缩小 private void btnZoomOut_Click(object sender, EventArgs e) { var zoom = DragZoomValue(); - _messageCore.NodeMonitorService[DevKey].DragZoomContrl(zoom, false); + _messageCore.NodeMonitorService[DevKey.ToString()].DragZoomContrl(zoom, false); } #endregion @@ -949,13 +1011,13 @@ namespace Win.GB28181.Client //看守位开 private void btnPositionOpen_Click(object sender, EventArgs e) { - _messageCore.NodeMonitorService[DevKey].HomePositionControl(true); + _messageCore.NodeMonitorService[DevKey.ToString()].HomePositionControl(true); } //看守位关 private void btnPositionClose_Click(object sender, EventArgs e) { - _messageCore.NodeMonitorService[DevKey].HomePositionControl(false); + _messageCore.NodeMonitorService[DevKey.ToString()].HomePositionControl(false); } #endregion #endregion @@ -1082,7 +1144,7 @@ namespace Win.GB28181.Client }; playerWin.Play(frame); } - catch (Exception) + catch (Exception ex) { } } @@ -1224,22 +1286,22 @@ a=rtpmap:97 MPEG4/90000"; /// private void BtnAudioNotify_Click(object sender, EventArgs e) { - _messageCore.NodeMonitorService[DevKey].AudioPublishNotify(); + _messageCore.NodeMonitorService[DevKey.ToString()].AudioPublishNotify(); } - private void BtnSubPositionInfo_Click(object sender, EventArgs e) + private void btnSubPositionInfo_Click(object sender, EventArgs e) { int interval = (int)numInterval.Value; - _messageCore.NodeMonitorService[DevKey].MobilePositionQueryRequest(interval, true); + _messageCore.NodeMonitorService[DevKey.ToString()].MobilePositionQueryRequest(interval, true); } #endregion - private void BtnSubscribeCancel_Click(object sender, EventArgs e) + private void btnSubscribeCancel_Click(object sender, EventArgs e) { int interval = (int)numInterval.Value; - _messageCore.NodeMonitorService[DevKey].MobilePositionQueryRequest(interval, false); + _messageCore.NodeMonitorService[DevKey.ToString()].MobilePositionQueryRequest(interval, false); } #region 移动设备位置数据订阅/通知 @@ -1272,7 +1334,7 @@ a=rtpmap:97 MPEG4/90000"; /// private void btnKeyFrame_Click(object sender, EventArgs e) { - _messageCore.NodeMonitorService[DevKey].MakeKeyFrameRequest(); + _messageCore.NodeMonitorService[DevKey.ToString()].MakeKeyFrameRequest(); } private void tvCalatog_AfterSelect(object sender, TreeViewEventArgs e) @@ -1293,7 +1355,7 @@ a=rtpmap:97 MPEG4/90000"; private void button2_Click_1(object sender, EventArgs e) { - _messageCore.NodeMonitorService[DevKey].DeviceCatalogSubscribe(false); + _messageCore.NodeMonitorService[DevKey.ToString()].DeviceCatalogSubscribe(false); } } @@ -1313,3 +1375,4 @@ a=rtpmap:97 MPEG4/90000"; public KeepAlive Heart { get; set; } } } + diff --git a/Win.GB28181.Client/Message/SIPMessageDaemon.cs b/Win.GB28181.Client/Message/SIPMessageDaemon.cs index cc8578fc00011b0af9dc8673ea842337717d86e8..96950a3a304f96e6633f058bdb29e54e29efd216 100644 --- a/Win.GB28181.Client/Message/SIPMessageDaemon.cs +++ b/Win.GB28181.Client/Message/SIPMessageDaemon.cs @@ -34,24 +34,18 @@ // POSSIBILITY OF SUCH DAMAGE. // ============================================================================ -using System; -using System.Collections.Generic; -using System.IO; -using System.Linq; -using System.Net; -using System.Net.Sockets; -using System.Text; -using System.Xml; -using GB28181.SIPSorcery.Persistence; +using GB28181.Logger4Net; +using GB28181.SIPSorcery.Servers; +using GB28181.SIPSorcery.Servers.SIPMessage; using GB28181.SIPSorcery.SIP; using GB28181.SIPSorcery.SIP.App; -using GB28181.SIPSorcery.Servers; using GB28181.SIPSorcery.Sys; -using GB28181.Logger4Net; -using GB28181.SIPSorcery.Servers.SIPMessage; using GB28181.SIPSorcery.Sys.Config; +using System; +using System.Collections.Generic; +using System.Linq; -namespace Win.GB28181.Client.Message +namespace Gb28181_Client.Message { public class SIPMessageDaemon { @@ -59,7 +53,7 @@ namespace Win.GB28181.Client.Message private SIPTransport m_sipTransport; - private SIPAssetGetDelegate GetSIPAccount_External; + // private SIPAssetGetDelegate GetSIPAccount_External; private SIPAuthenticateRequestDelegate SIPAuthenticateRequest_External; private Dictionary _platformList; private SIPAccount _account; @@ -86,14 +80,12 @@ namespace Win.GB28181.Client.Message m_sipTransport = new SIPTransport(SIPDNSManager.ResolveSIPService, new SIPTransactionEngine(), false); m_sipTransport.PerformanceMonitorPrefix = SIPSorceryPerformanceMonitor.REGISTRAR_PREFIX; SIPAccount account = SipAccountStorage.Instance.Accounts.FirstOrDefault(); - var sipChannels = SIPTransportConfig.ParseSIPChannelsNode(account.LocalIP, account.LocalPort); m_sipTransport.AddSIPChannel(sipChannels); + MessageCore = new SIPMessageCore(m_sipTransport, SIPConstants.SIP_SERVER_STRING); - - MessageCore.Initialize(SIPAuthenticateRequest_External, _platformList,_account); - + MessageCore.Initialize(SIPAuthenticateRequest_External, _platformList, _account); GB28181Catalog.Instance.MessageCore = MessageCore; m_sipTransport.SIPTransportRequestReceived += MessageCore.AddMessageRequest; m_sipTransport.SIPTransportResponseReceived += MessageCore.AddMessageResponse; diff --git a/Win.GB28181.Client/Message/SIPMessagetate.cs b/Win.GB28181.Client/Message/SIPMessagetate.cs index 298226bac2fab6d05a939e8e29bc9dc92e109464..bb8ddee3af83b703acdd497184d21f146f2ca8bd 100644 --- a/Win.GB28181.Client/Message/SIPMessagetate.cs +++ b/Win.GB28181.Client/Message/SIPMessagetate.cs @@ -34,17 +34,11 @@ // POSSIBILITY OF SUCH DAMAGE. // ============================================================================ +using GB28181.Logger4Net; using System; -using System.Collections.Generic; -using System.Linq; -using System.Net; -using System.Text; using System.Xml; -using GB28181.Logger4Net; -using GB28181.SIPSorcery.Sys; -using System.Configuration; -namespace Win.GB28181.Client.Message +namespace Gb28181_Client.Message { /// /// Retrieves application conifguration settings from App.Config. @@ -78,7 +72,7 @@ namespace Win.GB28181.Client.Message try { - // GB28181.Logger4Net.Config.XmlConfigurator.Configure(); + // log4net.Config.XmlConfigurator.Configure(); logger = LogManager.GetLogger(LOGGER_NAME); } catch (Exception logExcp) diff --git a/Win.GB28181.Client/Player/Codec/AVCodecCfg.cs b/Win.GB28181.Client/Player/Codec/AVCodecCfg.cs index ab9dc5c00dd098f8196ef61a2a86a550e4edbbbe..053253355a274b30839216d8a673b2ec2764ae21 100644 --- a/Win.GB28181.Client/Player/Codec/AVCodecCfg.cs +++ b/Win.GB28181.Client/Player/Codec/AVCodecCfg.cs @@ -3,10 +3,10 @@ using System.Collections.Generic; using System.Linq; using System.Text; using System.Runtime.InteropServices; -using Win.Media; +using SS.Media; using System.IO; -namespace Win.ClientBase.Codec +namespace SS.ClientBase.Codec { /// /// 音视频编码参数设置 @@ -80,7 +80,7 @@ namespace Win.ClientBase.Codec // encodeName = name; // encoder = GetGeneralEncoder(name); // } - + // // 获取通用编码代号 // public static int GetGeneralEncoder(String name) { @@ -96,14 +96,12 @@ namespace Win.ClientBase.Codec //} - public class VideoEncodeCfg : Win.Media.Codec.VideoEncodeCfg - { - + public class VideoEncodeCfg : SS.Media.Codec.VideoEncodeCfg { + public IYUVDraw Draw; + - - public static VideoEncodeCfg GetDefaule(IYUVDraw _Draw = null) - { + public static VideoEncodeCfg GetDefaule(IYUVDraw _Draw = null) { VideoEncodeCfg encCfg = new VideoEncodeCfg(); encCfg.SetEncoder("H264"); @@ -120,8 +118,7 @@ namespace Win.ClientBase.Codec - public class AudioEncodeCfg : Win.Media.Codec.AudioEncodeCfg - { + public class AudioEncodeCfg : SS.Media.Codec.AudioEncodeCfg { public int micId = 0; public int frequency = 8000;// 采样 public int format = 16;// 位元 @@ -132,8 +129,7 @@ namespace Win.ClientBase.Codec - public static AudioEncodeCfg GetDefault() - { + public static AudioEncodeCfg GetDefault() { AudioEncodeCfg r = new AudioEncodeCfg(); r.SetEncoder("AAC_"); r.frequency = 32000; diff --git a/Win.GB28181.Client/Player/Codec/CameraEncoder.cs b/Win.GB28181.Client/Player/Codec/CameraEncoder.cs index 382aad5310c27dece78c3b3ce160333663b5c1b6..b025a3181e4a2cd21c1db2add2d8feae14efa45d 100644 --- a/Win.GB28181.Client/Player/Codec/CameraEncoder.cs +++ b/Win.GB28181.Client/Player/Codec/CameraEncoder.cs @@ -2,10 +2,10 @@ using GLib.AXLib.Utility; using GLib.Extension; using GLib.GeneralModel; -using Win.ClientBase.Mixer.Video; -using Win.Comm; -using Win.Media; -using Win.WPFClient.DShow; +using SS.ClientBase.Mixer.Video; +using SS.Comm; +using SS.Media; +using SS.WPFClient.DShow; using System; using System.Collections.Generic; using System.Drawing; @@ -14,7 +14,7 @@ using System.Drawing.Imaging; using System.Runtime.InteropServices; using System.Threading; -namespace Win.ClientBase.Codec +namespace SS.ClientBase.Codec { public class CameraCapturer : IDisposable { @@ -29,12 +29,12 @@ namespace Win.ClientBase.Codec private bool _isworking = false; private bool _isDisoseing = false; private bool _isDisosed = false; - private readonly int _camera; - private readonly int _width; - private readonly int _height; + private int _camera; + private int _width; + private int _height; private FFScale _ffscale = null; - private readonly Action _callBack = null; + private Action _callBack = null; public CameraCapturer() { } @@ -173,7 +173,8 @@ namespace Win.ClientBase.Codec buf = _ffscale.Convert(buf); - _callBack?.Invoke(buf); + if (_callBack != null) + _callBack(buf); } public void Dispose() @@ -219,10 +220,10 @@ namespace Win.ClientBase.Codec public class CameraAForge : CameraCapturer { - private readonly AForge.Video.DirectShow.VideoCaptureDevice videoDevice; - private readonly AForge.Video.DirectShow.FilterInfoCollection videoDevices; - private readonly FFScale _ffscale = null; - private readonly Action _callBack = null; + private AForge.Video.DirectShow.VideoCaptureDevice videoDevice; + private AForge.Video.DirectShow.FilterInfoCollection videoDevices; + private FFScale _ffscale = null; + private Action _callBack = null; public CameraAForge(int camera, int width, int height, Action callBack) { _callBack = callBack; @@ -261,7 +262,8 @@ namespace Win.ClientBase.Codec byte[] buffer = FunctionEx.IntPtrToBytes(e.Buffer, 0, e.Len); buffer = _ffscale.Convert(buffer); - _callBack?.Invoke(buffer); + if (_callBack != null) + _callBack(buffer); } @@ -690,7 +692,7 @@ namespace Win.ClientBase.Codec } public class CameraEncoder : IDisposable { - public static int CameraCapturerMode = System.Configuration.ConfigurationManager.AppSettings["CameraCapturerMode"] == "1" ? 1 : 0; + public static int CameraCapturerMode = System.Configuration.ConfigurationSettings.AppSettings["CameraCapturerMode"] == "1" ? 1 : 0; protected bool _isworking = false; protected CameraCapturer _capturer = null; protected X264Native _x264; @@ -811,7 +813,7 @@ namespace Win.ClientBase.Codec if (mf.nIsKeyFrame == 1) { - var sps_pps = Win.ClientBase.Media.MediaSteamConverter.GetSPS_PPS(enc); + var sps_pps = SS.ClientBase.Media.MediaSteamConverter.GetSPS_PPS(enc); mf.nSPSLen = (short)sps_pps[0].Length; mf.nPPSLen = (short)sps_pps[1].Length; } @@ -823,7 +825,8 @@ namespace Win.ClientBase.Codec { _needClearVideoTransportBuffer = false; var frame = CreateClearVideoTransportBufferMediaFrame(mf); - _callBack?.Invoke(frame); + if (_callBack != null) + _callBack(frame); } if (_isFirstKeyFrame) @@ -838,23 +841,24 @@ namespace Win.ClientBase.Codec _callBack(frame); } - _callBack?.Invoke(mf); + if (_callBack != null) + _callBack(mf); } - catch (Exception) + catch (Exception e) { if (_isworking) throw; } } - protected static MediaFrame CreateClearVideoTransportBufferMediaFrame(MediaFrame mf) + protected MediaFrame CreateClearVideoTransportBufferMediaFrame(MediaFrame mf) { var frame = MediaFrame.CreateCommandMediaFrame(false, MediaFrameCommandType.ClearVideoTransportBuffer); return frame; } - protected static MediaFrame CreateResetCodecMediaFrame(MediaFrame mf) + protected MediaFrame CreateResetCodecMediaFrame(MediaFrame mf) { var infoMediaFrame = new MediaFrame() { @@ -868,7 +872,7 @@ namespace Win.ClientBase.Codec nPPSLen = mf.nPPSLen, nSPSLen = mf.nSPSLen, nTimetick = mf.nTimetick, - Data = Array.Empty(), + Data = new byte[0], nSize = 0, }; @@ -881,7 +885,7 @@ namespace Win.ClientBase.Codec _draw.Draw(yuv); } - protected virtual void Dispose(bool all) + public void Dispose() { try { @@ -892,18 +896,12 @@ namespace Win.ClientBase.Codec _x264.Release(); _draw.Release(); } - catch (Exception) + catch (Exception e) { throw; } } - public void Dispose() - { - Dispose(true); - GC.SuppressFinalize(this); - } - } diff --git a/Win.GB28181.Client/Player/Codec/FFImp.cs b/Win.GB28181.Client/Player/Codec/FFImp.cs index d96b499410a97d396f54753c3ae0677e5dde3599..1447ec0aba3f1c7ca3779983a50b30b18f2ac42c 100644 --- a/Win.GB28181.Client/Player/Codec/FFImp.cs +++ b/Win.GB28181.Client/Player/Codec/FFImp.cs @@ -5,11 +5,11 @@ using System.Linq; using System.Text; using System.Runtime.InteropServices; using GLib.Extension; -//using Win.Base; +//using SS.Base; using System.Threading; -namespace Win.ClientBase.Codec { +namespace SS.ClientBase.Codec { public partial class FFImp { diff --git a/Win.GB28181.Client/Player/Codec/FaacImp.cs b/Win.GB28181.Client/Player/Codec/FaacImp.cs index 988ddb403299d70f486139f2ff7023d48464e641..7f500d0e3b8dbc40f7765fdfba1d7b04e750f80d 100644 --- a/Win.GB28181.Client/Player/Codec/FaacImp.cs +++ b/Win.GB28181.Client/Player/Codec/FaacImp.cs @@ -7,7 +7,7 @@ using GLib.Extension; using System.IO; using System.Threading; -namespace Win.ClientBase.Codec { +namespace SS.ClientBase.Codec { public class FaacImp : IDisposable { private IntPtr _handle = IntPtr.Zero; private int _channel = 0; diff --git a/Win.GB28181.Client/Player/Codec/FaadImp.cs b/Win.GB28181.Client/Player/Codec/FaadImp.cs index 7fc144bd9c160bf98e8c68451b12efe81f1c80aa..2e2b6d3aea226ae3ec7de8f0ebaca9651a6b9639 100644 --- a/Win.GB28181.Client/Player/Codec/FaadImp.cs +++ b/Win.GB28181.Client/Player/Codec/FaadImp.cs @@ -6,7 +6,7 @@ using System.Text; using GLib.Extension; using System.IO; -namespace Win.ClientBase.Codec { +namespace SS.ClientBase.Codec { public class FaadImp : IDisposable { private IntPtr _handle = IntPtr.Zero; private Boolean _inited = false; diff --git a/Win.GB28181.Client/Player/Codec/MicEncoder.cs b/Win.GB28181.Client/Player/Codec/MicEncoder.cs index 413afcde5d06432ca4a3999fe25d669cb20c07d6..bf6e1f7d051db588c146d74a0ea32970156950c4 100644 --- a/Win.GB28181.Client/Player/Codec/MicEncoder.cs +++ b/Win.GB28181.Client/Player/Codec/MicEncoder.cs @@ -11,11 +11,11 @@ using System.Runtime.InteropServices; using System.Threading; using System.IO; -using Win.Media; -using Win.Media.Wave.Wave; +using SS.Media; +using SS.Media.Wave.Wave; -namespace Win.ClientBase.Codec +namespace SS.ClientBase.Codec { @@ -151,7 +151,7 @@ namespace Win.ClientBase.Codec if (buf.Length == 0) return; //生成媒体帧 - var mf = new Win.Media.MediaFrame() + var mf = new SS.Media.MediaFrame() { nFrequency = _frequency, nSamples = (short)_audioCfg.samples, diff --git a/Win.GB28181.Client/Player/Codec/Speex.cs b/Win.GB28181.Client/Player/Codec/Speex.cs index 3b335b0a34b49da59887486b7ec4c3ac50708cd7..10ecda13a3aeead91b63e5ff1e8f96bd007dfe43 100644 --- a/Win.GB28181.Client/Player/Codec/Speex.cs +++ b/Win.GB28181.Client/Player/Codec/Speex.cs @@ -7,7 +7,7 @@ using GLib.Extension; using System.Threading; -namespace Win.ClientBase.Codec +namespace SS.ClientBase.Codec { /// /// SPEEX编码器 diff --git a/Win.GB28181.Client/Player/Codec/StreamFileHelper.cs b/Win.GB28181.Client/Player/Codec/StreamFileHelper.cs index 2ab698cc9ceffe9ebb6f488fbfca4dd963f3f999..6440c639510eb7bddf3189a98ad87556ba1c5a94 100644 --- a/Win.GB28181.Client/Player/Codec/StreamFileHelper.cs +++ b/Win.GB28181.Client/Player/Codec/StreamFileHelper.cs @@ -3,9 +3,9 @@ //using System.IO; //using System.Linq; //using System.Text; -//using Win.MediaNetEngine; +//using SS.Media; -//namespace Win.ClientBase.Codec { +//namespace SS.ClientBase.Codec { // public class ReadFile { // public static List GetBuffByFile1(string file) { // var q = GetBuffByFile(file); diff --git a/Win.GB28181.Client/Player/Codec/SwsScale.cs b/Win.GB28181.Client/Player/Codec/SwsScale.cs index 78fb002374a599b941c82732c4749e49da44ac9d..ed67b74c8fb8cffead9408b2979238007c3db589 100644 --- a/Win.GB28181.Client/Player/Codec/SwsScale.cs +++ b/Win.GB28181.Client/Player/Codec/SwsScale.cs @@ -6,7 +6,7 @@ using System.Runtime.InteropServices; using GLib.Extension; -namespace Win.ClientBase.Codec { +namespace SS.ClientBase.Codec { public class FFScale { private int _handle = -1; diff --git a/Win.GB28181.Client/Player/Codec/x264.cs b/Win.GB28181.Client/Player/Codec/x264.cs index 022095b49aa8f746c8ededae6299e7acb4190eeb..512ac5928e19298c532b68632b15339a066a1629 100644 --- a/Win.GB28181.Client/Player/Codec/x264.cs +++ b/Win.GB28181.Client/Player/Codec/x264.cs @@ -1,12 +1,14 @@ using System; +using System.Collections.Generic; +using System.Linq; +using System.Text; using System.Runtime.InteropServices; +using System.Linq; using GLib.Extension; using System.IO; -using Win.Media; -namespace Win.ClientBase.Codec -{ - public partial class X264Native { +namespace SS.ClientBase.Codec { + public partial class X264Native { private static BinaryWriter w = null; public static void Test() { int width = 320, height = 240; @@ -16,7 +18,7 @@ namespace Win.ClientBase.Codec x264.Init(); var ls = MediaServer.Media.ReadFile.GetBuffByFile1(@"D:\video_monitor\v2v_super_exchange\branch\branch_V3.16.0.0(dongtaifuyong)\bin\Debug\1237.yuv"); - AVCodecCfg cf = AVCodecCfg.CreateVideo(width, height, (int)AVCode.CODEC_ID_H264, 100000); + AVCodecCfg cf = AVCodecCfg.CreateVideo(width, height, (int)SS.Media.AVCode.CODEC_ID_H264, 100000); FFImp ffimp = new FFImp(cf, true); //FFScale ffscale = new FFScale(width, height, 26, 12, width, height, 12, 12); FFScale ffscale = new FFScale(width, height, 0, 12,width,height, 3, 24); diff --git a/Win.GB28181.Client/Player/Controls/PlayerControl.Designer.cs b/Win.GB28181.Client/Player/Controls/PlayerControl.Designer.cs index 22a62eff8789d09ebb678ea47a1c8262d541d916..ca3f196caa2e76900bd04fb4621cf6bea58a9ff2 100644 --- a/Win.GB28181.Client/Player/Controls/PlayerControl.Designer.cs +++ b/Win.GB28181.Client/Player/Controls/PlayerControl.Designer.cs @@ -1,4 +1,4 @@ -namespace Win.ClientBase +namespace SS.ClientBase { partial class PlayerControl { diff --git a/Win.GB28181.Client/Player/Controls/PlayerControl.cs b/Win.GB28181.Client/Player/Controls/PlayerControl.cs index 1fc271152290d49fb5176e3e4335fa51e1a15270..27d02aa05ade2f9343b5bcbebf8b8f131e353752 100644 --- a/Win.GB28181.Client/Player/Controls/PlayerControl.cs +++ b/Win.GB28181.Client/Player/Controls/PlayerControl.cs @@ -7,11 +7,11 @@ using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; -using Win.ClientBase.Codec; -using Win.ClientBase.Media; -using Win.Media; +using SS.ClientBase.Codec; +using SS.ClientBase.Media; +using SS.Media; -namespace Win.ClientBase +namespace SS.ClientBase { public partial class PlayerControl : UserControl { diff --git a/Win.GB28181.Client/Player/DShow/BaseFilterEx.cs b/Win.GB28181.Client/Player/DShow/BaseFilterEx.cs index e34f9ffa21785bff489052bf0252724f9fb3a8b4..e86ae6e8082a23099348eb2f95b9c7134ddcdea6 100644 --- a/Win.GB28181.Client/Player/DShow/BaseFilterEx.cs +++ b/Win.GB28181.Client/Player/DShow/BaseFilterEx.cs @@ -5,7 +5,7 @@ using System.Text; using DirectShowLib; using System.Runtime.InteropServices; -namespace Win.WPFClient.DShow +namespace SS.WPFClient.DShow { /// /// DShow过滤器扩展 diff --git a/Win.GB28181.Client/Player/DShow/DShowHelper.cs b/Win.GB28181.Client/Player/DShow/DShowHelper.cs index 7b9bd0bd39173c00712cb0bba6551796bef79c1f..3dbee07aa8112738879632918765850191d9c899 100644 --- a/Win.GB28181.Client/Player/DShow/DShowHelper.cs +++ b/Win.GB28181.Client/Player/DShow/DShowHelper.cs @@ -9,7 +9,7 @@ using GLib.Extension; using GLib; using System.Drawing; -namespace Win.WPFClient.DShow +namespace SS.WPFClient.DShow { public class DShowHelper { diff --git a/Win.GB28181.Client/Player/DShow/FilterGrap.cs b/Win.GB28181.Client/Player/DShow/FilterGrap.cs index 30304e2a1a0ca13761d79dc5757d2e29d058fc0d..2351afe070841298d0b83bbbcfee095d163c3c7b 100644 --- a/Win.GB28181.Client/Player/DShow/FilterGrap.cs +++ b/Win.GB28181.Client/Player/DShow/FilterGrap.cs @@ -7,7 +7,7 @@ using DirectShowLib; using System.Runtime.InteropServices; using GLib.Extension; using System.Diagnostics; -namespace Win.WPFClient.DShow +namespace SS.WPFClient.DShow { /// /// 过滤器--图表基类 diff --git a/Win.GB28181.Client/Player/DShow/IDSMutualFilter.cs b/Win.GB28181.Client/Player/DShow/IDSMutualFilter.cs index 86f2853af2d2c764bb0d7f27064efcf1019d59e5..1adb86f7e19b3ba27a824f831bac9ff49ecc1a0a 100644 --- a/Win.GB28181.Client/Player/DShow/IDSMutualFilter.cs +++ b/Win.GB28181.Client/Player/DShow/IDSMutualFilter.cs @@ -8,7 +8,7 @@ using DirectShowLib; using GLib.Extension; using System.Diagnostics; -namespace Win.WPFClient.DShow +namespace SS.WPFClient.DShow { [UnmanagedFunctionPointer(CallingConvention.Cdecl)] public delegate long JSSourceFilter_FillBufferCallBack(ref IntPtr pData); diff --git a/Win.GB28181.Client/Player/DShow/IffdshowBase.cs b/Win.GB28181.Client/Player/DShow/IffdshowBase.cs index 0f4ebf6b7821b039adeecfbf75cb4a434cbcb011..86a1888735dbe6e4b557098db67bfcd36f27eb88 100644 --- a/Win.GB28181.Client/Player/DShow/IffdshowBase.cs +++ b/Win.GB28181.Client/Player/DShow/IffdshowBase.cs @@ -5,7 +5,7 @@ using System.Text; using System.Runtime.InteropServices; using System.Security; -namespace Win.WPFClient.DShow +namespace SS.WPFClient.DShow { #region [Guid("FC5BCCF4-FD62-45ee-B022-3840EAEA77B2"), SuppressUnmanagedCodeSecurity, diff --git a/Win.GB28181.Client/Player/DShow/PinEx.cs b/Win.GB28181.Client/Player/DShow/PinEx.cs index e9c447829ed94aa5773c3cd64eb90284a36fe91c..d62d57b7c1872edf195a39db10ad89778b5aced2 100644 --- a/Win.GB28181.Client/Player/DShow/PinEx.cs +++ b/Win.GB28181.Client/Player/DShow/PinEx.cs @@ -6,7 +6,7 @@ using DirectShowLib; using System.Runtime.InteropServices; using System.Diagnostics; using GLib.GeneralModel; -namespace Win.WPFClient.DShow +namespace SS.WPFClient.DShow { public class PinConnectEventArg : EventArgs { diff --git a/Win.GB28181.Client/Player/DShow/SampleGrabberCB.cs b/Win.GB28181.Client/Player/DShow/SampleGrabberCB.cs index fd3abcf3ec04af51aa1707aa4ea732fd04866aa2..de26630a4fa2a66e2750ea3ff6cd2bc35b3a142a 100644 --- a/Win.GB28181.Client/Player/DShow/SampleGrabberCB.cs +++ b/Win.GB28181.Client/Player/DShow/SampleGrabberCB.cs @@ -5,7 +5,7 @@ using System.Text; using System.Runtime.InteropServices; using DirectShowLib; -namespace Win.WPFClient.DShow +namespace SS.WPFClient.DShow { //directshow 数据回调 [System.Security.SuppressUnmanagedCodeSecurity] diff --git a/Win.GB28181.Client/Player/Media/AudioPlayer.cs b/Win.GB28181.Client/Player/Media/AudioPlayer.cs index d4f4f0f83187ff7911ca34254f569a39efe60d55..6c131c090c10f91e2a2fffae1e158c2cab0de298 100644 --- a/Win.GB28181.Client/Player/Media/AudioPlayer.cs +++ b/Win.GB28181.Client/Player/Media/AudioPlayer.cs @@ -14,13 +14,13 @@ using System.Threading; using System.Runtime.InteropServices; using System.Drawing; using System.IO; -using Win.Media; -using Win.Media.Wave.Wave; -using Win.ClientBase.Codec; +using SS.Media; +using SS.Media.Wave.Wave; +using SS.ClientBase.Codec; using GLib.AXLib.Utility; -using Win.MediaServer.Media; +using SS.MediaServer.Media; -namespace Win.ClientBase.Media +namespace SS.ClientBase.Media { /// /// 音频播放器 diff --git a/Win.GB28181.Client/Player/Media/MediaCapturer.cs b/Win.GB28181.Client/Player/Media/MediaCapturer.cs index e8fe3a36e5ed7922c977db6f0b8eb86532f5e915..8d84fadc8d9bd93af63f36aa16aeb9891cc07ef4 100644 --- a/Win.GB28181.Client/Player/Media/MediaCapturer.cs +++ b/Win.GB28181.Client/Player/Media/MediaCapturer.cs @@ -15,13 +15,13 @@ using System.Threading; using System.IO; -using Win.Comm; -using Win.Media; -using Win.ClientBase.Codec; -using Win.MediaServer.Media.TS; +using SS.Comm; +using SS.Media; +using SS.ClientBase.Codec; +using SS.MediaServer.Media.TS; -namespace Win.ClientBase.Media +namespace SS.ClientBase.Media { public class MediaCapturer : IDisposable diff --git a/Win.GB28181.Client/Player/Media/MediaPlayer.cs b/Win.GB28181.Client/Player/Media/MediaPlayer.cs index ff6214c4a1485b212f9a1575c00356a51bdb9dcf..e4fbe1ef9ce4cb326e551c26cafdd1b3cd4c2826 100644 --- a/Win.GB28181.Client/Player/Media/MediaPlayer.cs +++ b/Win.GB28181.Client/Player/Media/MediaPlayer.cs @@ -6,11 +6,11 @@ using System.Threading; using System.Windows.Forms; using GLib.AXLib.Utility; using GLib.GeneralModel; -using Win.ClientBase.Codec; -using Win.ClientBase.Media; -using Win.Media; +using SS.ClientBase.Codec; +using SS.ClientBase.Media; +using SS.Media; -namespace Win.ClientBase.Media { +namespace SS.ClientBase.Media { public class MediaPlayer : IDisposable { private WaveAudioPlayer _ap; diff --git a/Win.GB28181.Client/Player/Media/MediaSteamConverter.cs b/Win.GB28181.Client/Player/Media/MediaSteamConverter.cs index 5a2b2fd190108152f3b4cdcef1cb61aec2cbe604..ecb7b3f1141cf22ac02bef02fff0ddaaef8c4deb 100644 --- a/Win.GB28181.Client/Player/Media/MediaSteamConverter.cs +++ b/Win.GB28181.Client/Player/Media/MediaSteamConverter.cs @@ -5,11 +5,11 @@ using BoxMatrix.Media; using GLib.AXLib.Utility; using GLib.Extension; -using Win.Media; +using SS.Media; using System; using System.IO; -namespace Win.ClientBase.Media +namespace SS.ClientBase.Media { diff --git a/Win.GB28181.Client/Player/Media/SDLPlay.cs b/Win.GB28181.Client/Player/Media/SDLPlay.cs index 447ee77f5b12fa70ccd607696ad979ed08955aec..e916e4d3b60608cbd7e990e43d7cab4e4e7b0888 100644 --- a/Win.GB28181.Client/Player/Media/SDLPlay.cs +++ b/Win.GB28181.Client/Player/Media/SDLPlay.cs @@ -8,7 +8,7 @@ using GLib.Extension; using Tao.Sdl; -namespace Win.ClientBase.Media +namespace SS.ClientBase.Media { public class SDLPlay { diff --git a/Win.GB28181.Client/Player/Media/VideoPlayer.cs b/Win.GB28181.Client/Player/Media/VideoPlayer.cs index 7ecd494af29b955e91e844f38a2de89042f3ee72..2b5f4c1acc06d0e46efea4c6682a3a7641bb8464 100644 --- a/Win.GB28181.Client/Player/Media/VideoPlayer.cs +++ b/Win.GB28181.Client/Player/Media/VideoPlayer.cs @@ -3,13 +3,13 @@ using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows.Forms; -using Win.Media; -using Win.ClientBase.Codec; +using SS.Media; +using SS.ClientBase.Codec; using System.Threading; using GLib.AXLib.Utility; using GLib.GeneralModel; -namespace Win.ClientBase.Media { +namespace SS.ClientBase.Media { public class VideoPlayer : IDisposable { private IYUVDraw _yuvDraw = null; private FFImp _ffimp = null; diff --git a/Win.GB28181.Client/Player/Media/Wave/WavInDevice.cs b/Win.GB28181.Client/Player/Media/Wave/WavInDevice.cs index 7048f767a228f8a789694291cd66f618a443b788..10518d777b4c87abd7d831b9080cf8c62790c580 100644 --- a/Win.GB28181.Client/Player/Media/Wave/WavInDevice.cs +++ b/Win.GB28181.Client/Player/Media/Wave/WavInDevice.cs @@ -2,7 +2,7 @@ using System; using System.Collections.Generic; using System.Text; -namespace Win.Media.Wave.Wave +namespace SS.Media.Wave.Wave { /// /// This class represents wav input device. diff --git a/Win.GB28181.Client/Player/Media/Wave/WavOutDevice.cs b/Win.GB28181.Client/Player/Media/Wave/WavOutDevice.cs index a1b2b1e87f4ca7434571fc699566eabd8531a2fe..9a6e16e9a270feb8207a967a8d9e47be5f551cb9 100644 --- a/Win.GB28181.Client/Player/Media/Wave/WavOutDevice.cs +++ b/Win.GB28181.Client/Player/Media/Wave/WavOutDevice.cs @@ -2,7 +2,7 @@ using System; using System.Collections.Generic; using System.Text; -namespace Win.Media.Wave.Wave +namespace SS.Media.Wave.Wave { /// /// This class represents wav output device. diff --git a/Win.GB28181.Client/Player/Media/Wave/WaveIn.cs b/Win.GB28181.Client/Player/Media/Wave/WaveIn.cs index a473708ff667d7ba00427c939f335d80ce07a943..759834bc912b0954d193dc2ade8d1085ab950892 100644 --- a/Win.GB28181.Client/Player/Media/Wave/WaveIn.cs +++ b/Win.GB28181.Client/Player/Media/Wave/WaveIn.cs @@ -4,9 +4,9 @@ using System.Text; using System.Threading; using System.Runtime.InteropServices; -using Win.Media.Wave.Wave.Native; +using SS.Media.Wave.Wave.Native; -namespace Win.Media.Wave.Wave { +namespace SS.Media.Wave.Wave { #region Delegates Implementation /// diff --git a/Win.GB28181.Client/Player/Media/Wave/WaveOut.cs b/Win.GB28181.Client/Player/Media/Wave/WaveOut.cs index d78934ae6ee65b6bedb369ad5a0942ebb6004b5f..5862c23a8fcd968919655e5f9f0f2eb8b0c6049a 100644 --- a/Win.GB28181.Client/Player/Media/Wave/WaveOut.cs +++ b/Win.GB28181.Client/Player/Media/Wave/WaveOut.cs @@ -5,9 +5,9 @@ using System.Text; using System.Threading; using System.Runtime.InteropServices; -using Win.Media.Wave.Wave.Native; +using SS.Media.Wave.Wave.Native; -namespace Win.Media.Wave.Wave +namespace SS.Media.Wave.Wave { /// /// This class implements streaming wav data player. diff --git a/Win.GB28181.Client/Player/Media/Wave/native/MMSYSERR.cs b/Win.GB28181.Client/Player/Media/Wave/native/MMSYSERR.cs index bfde803f1a5829a29ede4befd20d6154530c9026..d522d58c5949f67b7b1a90d8e08c47dd5b0bb3a7 100644 --- a/Win.GB28181.Client/Player/Media/Wave/native/MMSYSERR.cs +++ b/Win.GB28181.Client/Player/Media/Wave/native/MMSYSERR.cs @@ -2,7 +2,7 @@ using System; using System.Collections.Generic; using System.Text; -namespace Win.Media.Wave.Wave.Native +namespace SS.Media.Wave.Wave.Native { /// /// This class holds MMSYSERR errors. diff --git a/Win.GB28181.Client/Player/Media/Wave/native/WAVEFORMATEX.cs b/Win.GB28181.Client/Player/Media/Wave/native/WAVEFORMATEX.cs index 9f4b8442528d9cf1e16fac28f37f18f409b21731..6de3b9b276d09df03948d76b15d937fa85cb9ef0 100644 --- a/Win.GB28181.Client/Player/Media/Wave/native/WAVEFORMATEX.cs +++ b/Win.GB28181.Client/Player/Media/Wave/native/WAVEFORMATEX.cs @@ -3,7 +3,7 @@ using System.Collections.Generic; using System.Text; using System.Runtime.InteropServices; -namespace Win.Media.Wave.Wave.Native +namespace SS.Media.Wave.Wave.Native { // Why this must be class ? otherwise in win XP won't work. diff --git a/Win.GB28181.Client/Player/Media/Wave/native/WAVEHDR.cs b/Win.GB28181.Client/Player/Media/Wave/native/WAVEHDR.cs index b13087a4b49c145fa0ea6ff2c5aa2c0a7b6c0147..5bb3b20adc46d98afbe1f2661d61dae2e11c23ea 100644 --- a/Win.GB28181.Client/Player/Media/Wave/native/WAVEHDR.cs +++ b/Win.GB28181.Client/Player/Media/Wave/native/WAVEHDR.cs @@ -3,7 +3,7 @@ using System.Collections.Generic; using System.Text; using System.Runtime.InteropServices; -namespace Win.Media.Wave.Wave.Native +namespace SS.Media.Wave.Wave.Native { /// /// This class represents WAVEHDR structure. diff --git a/Win.GB28181.Client/Player/Media/Wave/native/WAVEOUTCAPS.cs b/Win.GB28181.Client/Player/Media/Wave/native/WAVEOUTCAPS.cs index 00e281a59eb9173065deed576ec9914ff4b0eca5..59b55fb050d5f50495ee6d9eb47b9af44cc7ed2e 100644 --- a/Win.GB28181.Client/Player/Media/Wave/native/WAVEOUTCAPS.cs +++ b/Win.GB28181.Client/Player/Media/Wave/native/WAVEOUTCAPS.cs @@ -3,7 +3,7 @@ using System.Collections.Generic; using System.Text; using System.Runtime.InteropServices; -namespace Win.Media.Wave.Wave.Native +namespace SS.Media.Wave.Wave.Native { /// /// This class represents WAVEOUTCAPS structure. diff --git a/Win.GB28181.Client/Player/Media/Wave/native/WavConstants.cs b/Win.GB28181.Client/Player/Media/Wave/native/WavConstants.cs index a4d9664373d17abfcbbd303a8c45bd3b97ffb538..ca19e855174ed5765bbb0cebdb20b256b7699314 100644 --- a/Win.GB28181.Client/Player/Media/Wave/native/WavConstants.cs +++ b/Win.GB28181.Client/Player/Media/Wave/native/WavConstants.cs @@ -2,7 +2,7 @@ using System; using System.Collections.Generic; using System.Text; -namespace Win.Media.Wave.Wave.Native +namespace SS.Media.Wave.Wave.Native { /// /// This class provides most used wav constants. diff --git a/Win.GB28181.Client/Player/Media/Wave/native/WavFormat.cs b/Win.GB28181.Client/Player/Media/Wave/native/WavFormat.cs index 7385ca5e779b4110655ebf673b5cfc1e5eb32370..b3f64c823cb25fb57ade81f563463dbb0d5f84c1 100644 --- a/Win.GB28181.Client/Player/Media/Wave/native/WavFormat.cs +++ b/Win.GB28181.Client/Player/Media/Wave/native/WavFormat.cs @@ -2,7 +2,7 @@ using System; using System.Collections.Generic; using System.Text; -namespace Win.Media.Wave.Wave.Native +namespace SS.Media.Wave.Wave.Native { /// /// This class holds most known wav compression formats. diff --git a/Win.GB28181.Client/Player/Media/Wave/native/WavMethods.cs b/Win.GB28181.Client/Player/Media/Wave/native/WavMethods.cs index e8fa6c3463faf60d6ec99adb2f8d172f220e4457..89c86850d8f43f9faf1c83437206e5256cb13b23 100644 --- a/Win.GB28181.Client/Player/Media/Wave/native/WavMethods.cs +++ b/Win.GB28181.Client/Player/Media/Wave/native/WavMethods.cs @@ -3,7 +3,7 @@ using System.Collections.Generic; using System.Text; using System.Runtime.InteropServices; -namespace Win.Media.Wave.Wave.Native +namespace SS.Media.Wave.Wave.Native { /// /// The waveOutProc function is the callback function used with the waveform-audio output device. diff --git a/Win.GB28181.Client/Player/Media/YUVDraw.cs b/Win.GB28181.Client/Player/Media/YUVDraw.cs index de62eb29678422b1559706261bc7a89f2a9ff50d..00f5e1fb8a8db7d538c4c04db5c048383c35a413 100644 --- a/Win.GB28181.Client/Player/Media/YUVDraw.cs +++ b/Win.GB28181.Client/Player/Media/YUVDraw.cs @@ -10,7 +10,7 @@ using System.Drawing; using System.Drawing.Imaging; using System.Threading; -namespace Win.ClientBase.Codec { +namespace SS.ClientBase.Codec { public interface IYUVDraw { void Start(); diff --git a/Win.GB28181.Client/Player/Mixer/Audio/AAC_ADTS.cs b/Win.GB28181.Client/Player/Mixer/Audio/AAC_ADTS.cs index 9d70d46bbad36bb8cd8551e726c58087d2bc180e..14e955bfc1800283a1e3c4432bd7360937b1eaa4 100644 --- a/Win.GB28181.Client/Player/Mixer/Audio/AAC_ADTS.cs +++ b/Win.GB28181.Client/Player/Mixer/Audio/AAC_ADTS.cs @@ -3,7 +3,7 @@ using System; using System.Collections.Generic; using System.IO; -namespace Win.ClientBase.Mixer.Audio +namespace SS.ClientBase.Mixer.Audio { public class AAC_ADTS { diff --git a/Win.GB28181.Client/Player/Mixer/Audio/AacDec.cs b/Win.GB28181.Client/Player/Mixer/Audio/AacDec.cs index e98ce8829b7bfa525ad0a7e72893be9fdd1c082f..fab4e83cc422c29c9298b4abf28d4cafed6f0178 100644 --- a/Win.GB28181.Client/Player/Mixer/Audio/AacDec.cs +++ b/Win.GB28181.Client/Player/Mixer/Audio/AacDec.cs @@ -1,6 +1,6 @@ -using Win.ClientBase.Codec; -using Win.Media; -using Win.MediaServer.Media; +using SS.ClientBase.Codec; +using SS.Media; +using SS.MediaServer.Media; using System; using System.Collections.Generic; using System.IO; @@ -8,7 +8,7 @@ using System.Linq; using System.Text; using System.Threading.Tasks; -namespace Win.ClientBase.Mixer.Audio +namespace SS.ClientBase.Mixer.Audio { internal class AacDec : DecoderLine { diff --git a/Win.GB28181.Client/Player/Mixer/Audio/AacEnc.cs b/Win.GB28181.Client/Player/Mixer/Audio/AacEnc.cs index bbe05db6d1077afc661a5f8dd1d5222dc354a221..1b42060f3637fc06ec13db5c982f4bb678078216 100644 --- a/Win.GB28181.Client/Player/Mixer/Audio/AacEnc.cs +++ b/Win.GB28181.Client/Player/Mixer/Audio/AacEnc.cs @@ -1,11 +1,11 @@ -using Win.ClientBase.Codec; +using SS.ClientBase.Codec; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; -namespace Win.ClientBase.Mixer.Audio +namespace SS.ClientBase.Mixer.Audio { public class AacEnc : IDisposable diff --git a/Win.GB28181.Client/Player/Mixer/Audio/ByteArrayExtensions.cs b/Win.GB28181.Client/Player/Mixer/Audio/ByteArrayExtensions.cs index dc202ef02e158e53ceffaee245c99df7d8777a80..712eeb2d28118cfdd38b6fe3bfd80d367985026f 100644 --- a/Win.GB28181.Client/Player/Mixer/Audio/ByteArrayExtensions.cs +++ b/Win.GB28181.Client/Player/Mixer/Audio/ByteArrayExtensions.cs @@ -4,7 +4,7 @@ using System.Globalization; using System.Linq; using System.Net; using System.Text; -namespace Win.ClientBase.Mixer.Audio +namespace SS.ClientBase.Mixer.Audio { /// /// Extension methods for byte[]. diff --git a/Win.GB28181.Client/Player/Mixer/Audio/DecoderBase.cs b/Win.GB28181.Client/Player/Mixer/Audio/DecoderBase.cs index f59b181f2a91656aca0d443eb702f57422609fb9..2026b92537e8fb3b862e644c302a50355ef77d87 100644 --- a/Win.GB28181.Client/Player/Mixer/Audio/DecoderBase.cs +++ b/Win.GB28181.Client/Player/Mixer/Audio/DecoderBase.cs @@ -1,21 +1,46 @@ using System; using System.Collections.Generic; +using System.Linq; +using System.Text; +using System.Threading.Tasks; -namespace Win.ClientBase.Mixer.Audio +namespace SS.ClientBase.Mixer.Audio { internal abstract class DecoderLine { - private byte[] _Buffer = Array.Empty(); + + public int ID; + /// + /// + /// + public int AudioType; + private byte[] _Buffer = new byte[0]; public byte[] Buffer { get { return _Buffer; } - set => _Buffer = value ?? Array.Empty(); + set + { + if (value == null) + _Buffer = new byte[0]; + else + _Buffer = value; + } } - public Queue QueueBuffer { get; set; } = new Queue(); + public Queue QueueBuffer + { + get + { + return queueBuffer; + } + + set + { + queueBuffer = value; + } + } - public int AudioType { get; set; } - public int ID { get; set; } + private Queue queueBuffer = new Queue(); public abstract void Dec(byte[] src); diff --git a/Win.GB28181.Client/Player/Mixer/Audio/EncorderBase.cs b/Win.GB28181.Client/Player/Mixer/Audio/EncorderBase.cs index a37018d25140c1d16c04e0d844c786ff3da3008f..64156dcd27f05c1123af0018650538c47af0a906 100644 --- a/Win.GB28181.Client/Player/Mixer/Audio/EncorderBase.cs +++ b/Win.GB28181.Client/Player/Mixer/Audio/EncorderBase.cs @@ -4,7 +4,7 @@ using System.Linq; using System.Text; using System.Threading.Tasks; -namespace Win.ClientBase.Mixer.Audio +namespace SS.ClientBase.Mixer.Audio { public class EncorderBase { diff --git a/Win.GB28181.Client/Player/Mixer/Audio/Mixer.cs b/Win.GB28181.Client/Player/Mixer/Audio/Mixer.cs index 02a25361d9ce5993c43f8b0dd052ba7d8c23c5db..16e3890a76931555c862eb0f05cb7af2d454be5c 100644 --- a/Win.GB28181.Client/Player/Mixer/Audio/Mixer.cs +++ b/Win.GB28181.Client/Player/Mixer/Audio/Mixer.cs @@ -4,7 +4,7 @@ using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; -namespace Win.ClientBase.Mixer.Audio +namespace SS.ClientBase.Mixer.Audio { public partial class MixerAudio:IDisposable { diff --git a/Win.GB28181.Client/Player/Mixer/MediaCanvas.cs b/Win.GB28181.Client/Player/Mixer/MediaCanvas.cs index 5dce9e237a9276c7c51b9001a9d8b4424cc2d72b..39493df159179ca0d04dc589a6be2b3f48877ae4 100644 --- a/Win.GB28181.Client/Player/Mixer/MediaCanvas.cs +++ b/Win.GB28181.Client/Player/Mixer/MediaCanvas.cs @@ -3,17 +3,17 @@ using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; -using Win.ClientBase.Mixer.Video; +using SS.ClientBase.Mixer.Video; using System.Drawing; using System.Collections; using System.Windows.Forms; using System.Runtime.InteropServices; using System.Threading; -using Win.ClientBase.Codec; +using SS.ClientBase.Codec; using System.Drawing.Imaging; -using Win.ClientBase.Media; +using SS.ClientBase.Media; -namespace Win.ClientBase.Mixer +namespace SS.ClientBase.Mixer { public sealed class MediaMixerCanvas { @@ -368,7 +368,7 @@ namespace Win.ClientBase.Mixer if (count < 0 || count > MAXVIDEO_NUM) return; - Image image = Image.FromFile(@"D:\Mixer\SlWClient\Win.WPFClient\Images\bg_module_call.png"); + Image image = Image.FromFile(@"D:\Mixer\SlWClient\SS.WPFClient\Images\bg_module_call.png"); mapRects.Clear(); CreateRect(count); System.Drawing.Font logFont = new System.Drawing.Font("宋体", 22.5F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(134))); @@ -424,7 +424,7 @@ namespace Win.ClientBase.Mixer item.StreamID = StreamID; } } - public void Play(Win.Media.MediaFrame frame) + public void Play(SS.Media.MediaFrame frame) { //if(frame.StreamID) monitor[0].Play(frame); diff --git a/Win.GB28181.Client/Player/Mixer/Video/Canvas.cs b/Win.GB28181.Client/Player/Mixer/Video/Canvas.cs index c2744a651f74d5575600edad101b593c0edc7e00..36523cb08859ce3242f363360d442686c033ccfa 100644 --- a/Win.GB28181.Client/Player/Mixer/Video/Canvas.cs +++ b/Win.GB28181.Client/Player/Mixer/Video/Canvas.cs @@ -2,7 +2,7 @@ using System.Collections.Generic; using System.Drawing; -namespace Win.ClientBase.Mixer.Video +namespace SS.ClientBase.Mixer.Video { public class Canvas : IDisposable { diff --git a/Win.GB28181.Client/Player/Mixer/Video/CanvasStyle.cs b/Win.GB28181.Client/Player/Mixer/Video/CanvasStyle.cs index 8209ca847e733ffd4647fdeb4ea3c4de15e5296a..1e06db0a4980f51350463a31a8fffad43051eedb 100644 --- a/Win.GB28181.Client/Player/Mixer/Video/CanvasStyle.cs +++ b/Win.GB28181.Client/Player/Mixer/Video/CanvasStyle.cs @@ -1,4 +1,4 @@ -namespace Win.ClientBase.Mixer.Video +namespace SS.ClientBase.Mixer.Video { public enum CanvasStyle : byte { diff --git a/Win.GB28181.Client/Player/Mixer/Video/GraphicsBase.cs b/Win.GB28181.Client/Player/Mixer/Video/GraphicsBase.cs index 1c677f76c75c2c8c0cdef205cac3a2ca9bb508fd..95eed984288b238d13a3c2a43e6e3933b82a929c 100644 --- a/Win.GB28181.Client/Player/Mixer/Video/GraphicsBase.cs +++ b/Win.GB28181.Client/Player/Mixer/Video/GraphicsBase.cs @@ -2,7 +2,7 @@ using System.Drawing; using System.Drawing.Drawing2D; -namespace Win.ClientBase.Mixer.Video +namespace SS.ClientBase.Mixer.Video { public abstract class GraphicsBase : IDisposable { diff --git a/Win.GB28181.Client/Player/Mixer/Video/ImageCanvas.cs b/Win.GB28181.Client/Player/Mixer/Video/ImageCanvas.cs index 7e3d9b02d8dd232d0df42b9e9e2141e49a49fa8e..74bf21d490eb10403677a02d8798c99f3816cd64 100644 --- a/Win.GB28181.Client/Player/Mixer/Video/ImageCanvas.cs +++ b/Win.GB28181.Client/Player/Mixer/Video/ImageCanvas.cs @@ -1,7 +1,7 @@ using System.Drawing; using System.Drawing.Drawing2D; -namespace Win.ClientBase.Mixer.Video +namespace SS.ClientBase.Mixer.Video { public class ImageCanvas : Canvas { diff --git a/Win.GB28181.Client/Player/Mixer/Video/MarqueeCanvas.cs b/Win.GB28181.Client/Player/Mixer/Video/MarqueeCanvas.cs index 60b7b815357c8df08d5dafd593ab6d067411795d..4a3c16f8ee77c36aa1bec4076834ddaf4adf63ed 100644 --- a/Win.GB28181.Client/Player/Mixer/Video/MarqueeCanvas.cs +++ b/Win.GB28181.Client/Player/Mixer/Video/MarqueeCanvas.cs @@ -1,7 +1,7 @@ using System; using System.Drawing; -namespace Win.ClientBase.Mixer.Video +namespace SS.ClientBase.Mixer.Video { public class MarqueeCanvas : StringCanvas { diff --git a/Win.GB28181.Client/Player/Mixer/Video/StringCanvas.cs b/Win.GB28181.Client/Player/Mixer/Video/StringCanvas.cs index 78736a45965b56e0d5f587b1ba478dbf0de27c15..c91c0c9f694d4b41aaf0655e8882033ef2fcdc44 100644 --- a/Win.GB28181.Client/Player/Mixer/Video/StringCanvas.cs +++ b/Win.GB28181.Client/Player/Mixer/Video/StringCanvas.cs @@ -1,6 +1,6 @@ using System.Drawing; -namespace Win.ClientBase.Mixer.Video +namespace SS.ClientBase.Mixer.Video { public class StringCanvas : Canvas { diff --git a/Win.GB28181.Client/Player/Mixer/Video/TimeCanvas.cs b/Win.GB28181.Client/Player/Mixer/Video/TimeCanvas.cs index b0fde61d781b2ae0b1aaa75d2752b4d69a98201f..9f82bfdbaf99ef1381bb1efaed09bec1be4e047a 100644 --- a/Win.GB28181.Client/Player/Mixer/Video/TimeCanvas.cs +++ b/Win.GB28181.Client/Player/Mixer/Video/TimeCanvas.cs @@ -1,7 +1,7 @@ using System; using System.Drawing; -namespace Win.ClientBase.Mixer.Video +namespace SS.ClientBase.Mixer.Video { public class TimeCanvas : StringCanvas { diff --git a/Win.GB28181.Client/Player/Mixer/Video/VideoCanvas.cs b/Win.GB28181.Client/Player/Mixer/Video/VideoCanvas.cs index 100dd55afc368c94c213bc02bc184b273b7bafd7..0cc84864edaf3316d0b573100ff0c507646efc9b 100644 --- a/Win.GB28181.Client/Player/Mixer/Video/VideoCanvas.cs +++ b/Win.GB28181.Client/Player/Mixer/Video/VideoCanvas.cs @@ -1,14 +1,14 @@ -using Win.ClientBase.Codec; -using System.Drawing; +using SS.ClientBase.Codec; using System; -using System.Runtime.InteropServices; +using System.Drawing; using System.Drawing.Imaging; +using System.Runtime.InteropServices; -namespace Win.ClientBase.Mixer.Video +namespace SS.ClientBase.Mixer.Video { public class VideoCanvas : Canvas, IYUVDraw { - public System.Drawing.Bitmap Background; + public Bitmap Background; public int srcWidth; diff --git a/Win.GB28181.Client/Program.cs b/Win.GB28181.Client/Program.cs index 52822a962ea2c36439bb347cd33e36a95846a1cc..ada221362d45a5f6af859b773f98b21a7ce4e525 100644 --- a/Win.GB28181.Client/Program.cs +++ b/Win.GB28181.Client/Program.cs @@ -1,16 +1,24 @@ -using System; +using Autofac; +using GB28181.SIPSorcery.Servers; +using GB28181.SIPSorcery.Servers.SIPMessage; +using System; +using System.Reflection; using System.Windows.Forms; namespace Win.GB28181.Client { static class Program - { + { /// /// 应用程序的主入口点。 /// [STAThread] static void Main() { + + + + // ISIPRegistrarCore aa = new SIPRegistrarCore(); Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Form1()); diff --git a/Win.GB28181.Client/Win.GB28181.Client.csproj b/Win.GB28181.Client/Win.GB28181.Client.csproj index 99414cfee8bfb8a75fa3384a88f76ae0692a71d3..c8c3ec7bf5da05d77dd77b4b84a5c47b6033f006 100644 --- a/Win.GB28181.Client/Win.GB28181.Client.csproj +++ b/Win.GB28181.Client/Win.GB28181.Client.csproj @@ -2,19 +2,16 @@ Debug AnyCPU - {3E2F1C35-7354-4F55-ABA4-44CBCE2E18B5} WinExe - netcoreapp3.1 + netcoreapp3.1 true false - Properties Win.GB28181.Client Win.GB28181.Client - 512 true - x86 + AnyCPU @@ -23,14 +20,15 @@ - + - + + - - + + @@ -48,27 +46,8 @@ ..\Win.GB28181.Libs\DirectShowLib-2005.dll - - ..\Win.GB28181.Libs\GLib.dll - - - ..\Win.GB28181.Libs\StarEye.VideoConver.dll - ..\Win.GB28181.Libs\Tao.Sdl.dll - - - True - True - Settings.settings - - - - - SettingsSingleFileGenerator - Settings.Designer.cs - - \ No newline at end of file diff --git a/Win.GB28181.Libs/GLib.dll b/Win.GB28181.Libs/GLib.dll deleted file mode 100644 index 2cec2d41e551d08cd248ee9a1e23c7e8e3910671..0000000000000000000000000000000000000000 Binary files a/Win.GB28181.Libs/GLib.dll and /dev/null differ diff --git a/Win.MeidaNetEngine/Win.MediaNetEngine.csproj b/Win.MeidaNetEngine/Win.MediaNetEngine.csproj deleted file mode 100644 index 66d61ca5bb5c44fd2994b579368bcbb158c93ab9..0000000000000000000000000000000000000000 --- a/Win.MeidaNetEngine/Win.MediaNetEngine.csproj +++ /dev/null @@ -1,19 +0,0 @@ - - - {8332828E-DA9A-4813-9569-9DBA95DF8FF8} - Library - Properties - Win.MediaNetEngine - Win.MediaNetEngine - netcoreapp3.1 - true - - - - - - - ..\Win.GB28181.Libs\GLib.dll - - - \ No newline at end of file diff --git a/docs/Video/Flow/Video-Session-Cascade.png b/docs/Video/Flow/Video-Session-Cascade.png new file mode 100644 index 0000000000000000000000000000000000000000..70a27fae77ad36e839e9642fc4c5ceacd80d9bfa Binary files /dev/null and b/docs/Video/Flow/Video-Session-Cascade.png differ diff --git a/docs/Video/Flow/Video-Session-Flow.png b/docs/Video/Flow/Video-Session-Flow.png new file mode 100644 index 0000000000000000000000000000000000000000..70c5cae2e93c71fecf76f100cc422a60d6d050af Binary files /dev/null and b/docs/Video/Flow/Video-Session-Flow.png differ diff --git a/docs/Video/Format/Video-Data-Package-Format.png b/docs/Video/Format/Video-Data-Package-Format.png new file mode 100644 index 0000000000000000000000000000000000000000..644da4c4cf1db3eac2d3b7b2202849d6181f1b08 Binary files /dev/null and b/docs/Video/Format/Video-Data-Package-Format.png differ diff --git a/docs/Video/Format/Video-Data-Package-RFC.png b/docs/Video/Format/Video-Data-Package-RFC.png new file mode 100644 index 0000000000000000000000000000000000000000..b17552e729d1b1db5f6706769577c2e7ae57d33a Binary files /dev/null and b/docs/Video/Format/Video-Data-Package-RFC.png differ