Compare commits

103 Commits
1_0_0 ... Main

Author SHA1 Message Date
e59d6e3f39 ProxyCmdExecutor: Add Enable and Disable buttons. 2025-11-28 16:52:14 +01:00
0499ac5bb9 WorkLog: Allow usage of stats forms even without worklog selected 2025-10-02 15:04:18 +02:00
15c77a14ec Update submodules URLs 2023-04-10 02:10:10 +02:00
4e8ce63ed9 VAR.Toolbox: Remove bogus self-reference 2022-05-15 13:49:55 +02:00
6575eb3139 VirtualMouse: Allow mouse actions using global keybindings (WIP) 2022-04-10 03:39:51 +02:00
807fa0ee54 Apply Rider recommendations 2022-04-09 16:47:17 +02:00
f6d8b2c988 Remove duplicated Mouse class 2022-04-09 16:32:34 +02:00
635aa484a7 Remove duplicated Screenshoter 2022-04-09 16:29:28 +02:00
9206ede6eb FrmScreenAutomation: Use VAR.Toolbox controls 2022-04-09 16:12:16 +02:00
1881974311 WindowHandling: Use existing User32 DllImports 2022-04-09 16:11:50 +02:00
050ad1ad9c Move IConfiguration to current namespace 2022-04-09 03:29:48 +02:00
d0fc1235a9 Replace AutomationBotFactory with one using BaseFactory<> 2022-04-09 03:25:25 +02:00
44d6531bda Remove duplicated CtrImageViewer 2022-04-09 02:53:12 +02:00
ef30383abb Remove duplicated CtrOutput and IOutputHandler 2022-04-09 02:49:55 +02:00
4a3ae05f39 Integrate code of VAR.ScreenAutomation in VAR.Toolbox 2022-04-09 02:31:02 +02:00
3ac5b5f081 Merge VAR.VAR.ScreenAutomation 2022-04-09 01:05:30 +02:00
fc5b81014b Changes recommended by Rider/Resharper 2022-04-09 00:55:02 +02:00
827f68b0c6 Changes recommended by Rider/Resharper 2022-04-08 22:43:39 +02:00
1a11a67248 Update VAR.Json and VAR.HttpServer 2022-04-08 02:14:54 +02:00
95a5e83b73 WorkLog: If there is matching overlap, try to keep Activity, description or tags 2022-03-03 19:47:31 +01:00
070ce10fae FrmWorkLog: Easier date adjusting with plus and minus buttons. 2021-12-01 07:25:07 +01:00
7ceabb226b Redraw full control rectangle on custom controls:
This fixes graphics issues with custom controls; CButton CComboBox and CGroupBox.
2021-12-01 07:15:47 +01:00
a3e4ca9ea1 CGroupBox: Reduce GC pressure OnPaint 2021-12-01 07:13:57 +01:00
2de11e8560 CButton: Reduce GC pressure OnPaint. 2021-12-01 06:55:51 +01:00
f9273193d2 FrmWorkLog: New Search button for tags. 2021-12-01 06:54:37 +01:00
16ce7cefb4 FrmWorkLog Stats and Sumary: 1 month radius 2021-12-01 06:42:03 +01:00
b8c77aba7b FrmWorkLog: Tags field 2021-10-20 09:01:16 +02:00
729ae1604e FrmWorkLog: Allow merging of WorkLogItems while importing 2021-09-08 07:22:34 +02:00
72c0450d40 FrmProxyCmd: Replace TextBox with CtrOutput. 2021-05-13 21:38:58 +02:00
92e5ce837a ListBoxNormal and ListBoxMonospace: Remove smooth scrolling. 2021-05-13 20:38:44 +02:00
fb898e4bde FrmWorkLog: Fix NRE changing start date of a work log. 2021-05-13 19:01:19 +02:00
2e8f8c6c8d Dark style 2021-04-11 06:39:57 +02:00
98ced01b0f WorkLog: Usability fixes. 2020-12-01 08:48:37 +01:00
ed27887c08 FrmWorkLogStats: Show week numbers. 2020-11-30 08:09:58 +01:00
88e70cee26 FrmWorkLog: Disable modal dialogs on Stats and Summay. Ask before closing if there are unsaved changes. 2020-11-30 02:40:05 +01:00
f5c6fcd75f PnlSuspension: Remove Init event handler. 2020-08-21 14:16:11 +02:00
e24be59878 Move WorkLogItem code to VAR.Toolbox.Code.WorkLog. 2020-07-21 12:48:35 +02:00
8e957dc054 ControlsUtils.SetControlPropertyThreadSafeDelegate: Method to change properties of controls in a thread safe way. 2020-07-20 20:50:27 +02:00
b9902f4847 WebServicesUtils: New implementations of generic service calling. 2020-07-16 03:58:15 +02:00
a4fd7eb05c Force 96dpi, and generalize Frame, SubFrame, ListBox and TextBox controls. 2020-07-16 03:57:30 +02:00
873d32518c Upgrade to .Net Framework 4.8. 2020-07-16 03:51:48 +02:00
6d80a5d553 FrmWorkLogSumary: Form to sumarice a date range. 2020-07-08 00:55:34 +02:00
2fe83f1202 FrmWorkLogStats: Misc changes.
Adjust dates to start and end of day.
Show hours as decimal numbers.
Fix alignment of total label.
2020-07-08 00:55:00 +02:00
640bed074a FrmWorkLog: Search button for fast selection of activities. 2020-06-19 01:51:16 +02:00
8deb5a449f VARTextWorkLogImporter: Fix exportation ordering. 2020-06-19 01:50:40 +02:00
67207b15dd FrmListBoxDialog 2020-06-19 01:50:19 +02:00
ea5a8a8f8d FrmWorkLogStats 2020-06-16 01:48:50 +02:00
2059053a03 WorkLog: Show times. 2020-06-15 22:45:31 +02:00
81210f77b1 FrmWorkLog: Rename button. 2020-06-15 22:29:30 +02:00
5244b2f3fb FrmDialogString 2020-06-15 22:28:59 +02:00
62ef1b0613 FrmWorkLog: Export VARText. 2020-06-10 03:07:49 +02:00
a7053d8104 FrmWorkLog: Remove unnecessary refresh code. 2020-06-10 02:15:15 +02:00
0af7d299c9 FrmWorkLog: Better worklog viewer 2020-06-10 02:07:05 +02:00
5cd2983fe4 FrmWorkLog: Adjust DateTimePickers. 2020-06-09 07:57:44 +02:00
e1d859ea48 FrmWorkLog: Importing data marks dirty. 2020-06-09 07:55:24 +02:00
e3cbfca06a Update VAR.Json. 2020-06-08 08:34:56 +02:00
72a4f58bb7 FrmWorkLog: Import VARText. 2020-06-08 03:38:41 +02:00
7634feebb9 BaseFactory: Generic base factory. 2020-06-08 01:13:36 +02:00
db7df7123f WorkLog: Save and Load. 2020-06-07 19:18:42 +02:00
523ec9b7f5 FrmWorkLog. 2020-06-07 12:08:52 +02:00
47e26eda7d Update submodules. 2020-06-06 04:57:32 +02:00
eeb58c27bd FrmCoder: Update style. 2020-06-06 03:36:21 +02:00
c38aa902fe EventDispatcher and IEventListener. 2019-11-18 18:23:26 +01:00
73e7fe89f1 FrmScreenAutomation: Remove TopLevel when showing a FrmAutomationBotParams. 2019-11-10 19:56:27 +01:00
7660b9ce88 TetrisBot: Make ShotCooldownFrames configurable. 2019-11-10 18:36:08 +01:00
089500fcb4 TetrisGrid: Put default weights on Evaluate method parameters. 2019-11-10 18:33:24 +01:00
0385c04136 TetrisBot: Rename Cell value constants. 2019-11-10 18:32:39 +01:00
7b97e3249e TetrisBot: Better search shape and search best move algorithm. 2019-11-10 18:23:03 +01:00
7379b52334 TetrisBot.TetrisGrid: Expose Width and Height. 2019-11-08 02:10:28 +01:00
c3c9bb88ab TetrisBot: Split DefaultShapes from IsValid method. 2019-11-08 02:09:44 +01:00
87c5878ec9 TetrisBot: Remove maxHeightWeigth from evaluation function. 2019-11-08 02:09:04 +01:00
64d7c9531b TetrisBot: Better shot heuristics. 2019-11-08 02:07:33 +01:00
629ad33767 FrmScreenAutomation: Add checks for keeping window on top level and click on start. 2019-11-08 02:06:32 +01:00
f32b4e4f03 TetriBot: Adjust cell values. 2019-11-08 02:05:41 +01:00
e43ef3dca5 TetrisBot: Remove extra "I" shape. 2019-11-07 19:50:45 +01:00
0457466bd0 Allow configuration on AutomationBots. 2019-11-05 17:34:50 +01:00
474757af5e Screenshoter: Avoid exception while copy screen when there is no desktop. 2019-11-05 17:34:26 +01:00
4da5466de9 FrmScreenAutomation: Only top level while running. 2019-11-05 17:32:14 +01:00
2f8f4492ea TetrisBot: Better visualization. 2019-11-05 02:36:22 +01:00
2fb562de19 Save configuration between executions. 2019-11-05 02:20:19 +01:00
9bc7a542b4 TetrisBot: Better heuristics. Clearer representation of internal state. 2019-11-03 18:34:36 +01:00
923d889a8f TetrisBot 2019-11-02 22:34:07 +01:00
d7116687f5 FrmScreenAutomation: Variable FPS selector. 2019-11-02 22:33:31 +01:00
71ab81e11a FrmScreenAutomation: Adjust timer to 10FPS. 2019-11-02 00:55:10 +01:00
1a46040210 DummyBot: Even more dummy. 2019-11-01 02:38:28 +01:00
d3e4e53c1b FrmScreenAutomation: Process bots always. 2019-11-01 02:37:36 +01:00
437366fd67 Implement AutomationBotFactory and UI for Bot selection. 2019-11-01 00:29:46 +01:00
3531b72793 Initial commit 2019-11-01 00:18:01 +01:00
856396a031 FrmToolbox: Order panels by type name. 2019-05-30 07:21:24 +02:00
11afa74e58 PnlActivity: Log user activity. 2019-05-30 07:21:00 +02:00
8847f3f9b7 Add plug-in support 2019-05-29 09:48:49 +02:00
1f1cbfd1e5 More warning fixes 2019-05-27 07:34:45 +02:00
c5b76ee077 New dynamic factories for TextCoders and ProxyCmdExecutors. 2019-05-26 18:53:32 +02:00
e72b3ca600 Remove rest of build messages 2019-05-26 18:10:57 +02:00
14353a0ef8 FrmToolbox: Dynamic tools initialization. 2019-05-26 17:53:53 +02:00
eac18b2e78 Remove all build messages. 2019-05-24 07:41:30 +02:00
b49c70a039 Replace IFromWithIcon with IToolForm.HasIcon. 2019-05-24 07:29:02 +02:00
4c90dc1661 IToolForm and IToolPanel to mark tool forms and panels. 2019-05-23 20:50:23 +02:00
8b918a57de Replace usages of "String" with "string". 2019-05-23 08:32:35 +02:00
dcb9c65267 FrmCover: Uncover with keypress.
FrmCover: Copy active window title, before covering.
2019-05-23 08:31:43 +02:00
2a8e876c60 Add VAR.HttpServer SubModule. 2019-04-28 17:28:23 +02:00
4958b8404a Add VAR.Json SubModule 2019-04-27 14:15:11 +02:00
a4d45e03e0 FrmNetworkInfo: Network information on realtime. 2019-03-18 23:04:33 +01:00
158 changed files with 8744 additions and 2070 deletions

6
.gitignore vendored
View File

@@ -1,8 +1,8 @@
*.exe
*.dll
*.pdb
*/bin/*
*/obj/*
*.csproj.user
**/bin/**
**/obj/**
*.suo
.vs
*.user

8
.gitmodules vendored Normal file
View File

@@ -0,0 +1,8 @@
[submodule "VAR.Json"]
path = VAR.Json
url = https://datacube.duckdns.org/git/VAR/VAR.Json.git
branch = master
[submodule "VAR.HttpServer"]
path = VAR.HttpServer
url = https://datacube.duckdns.org/git/VAR/VAR.HttpServer.git
branch = master

13
.idea/.idea.VAR.Toolbox/.idea/.gitignore generated vendored Normal file
View File

@@ -0,0 +1,13 @@
# Default ignored files
/shelf/
/workspace.xml
# Rider ignored files
/contentModel.xml
/.idea.VAR.Json.iml
/modules.xml
/projectSettingsUpdater.xml
# Editor-based HTTP Client requests
/httpRequests/
# Datasource local storage ignored files
/dataSources/
/dataSources.local.xml

View File

@@ -0,0 +1,3 @@
<component name="ProjectDictionaryState">
<dictionary name="VAR" />
</component>

View File

@@ -0,0 +1,4 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="Encoding" addBOMForNewFiles="with BOM under Windows, with no BOM otherwise" />
</project>

View File

@@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="UserContentModel">
<attachedFolders />
<explicitIncludes />
<explicitExcludes />
</component>
</project>

8
.idea/.idea.VAR.Toolbox/.idea/vcs.xml generated Normal file
View File

@@ -0,0 +1,8 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="$PROJECT_DIR$" vcs="Git" />
<mapping directory="$PROJECT_DIR$/VAR.HttpServer" vcs="Git" />
<mapping directory="$PROJECT_DIR$/VAR.Json" vcs="Git" />
</component>
</project>

1
VAR.HttpServer Submodule

Submodule VAR.HttpServer added at f7c1a581e7

1
VAR.Json Submodule

Submodule VAR.Json added at 0332af453a

View File

@@ -0,0 +1,39 @@
namespace VAR.Toolbox.TestPlugin
{
partial class FrmTestPlugin
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(800, 450);
this.Text = "FrmTestPlugin";
}
#endregion
}
}

View File

@@ -0,0 +1,17 @@
using System.Windows.Forms;
using VAR.Toolbox.UI;
namespace VAR.Toolbox.TestPlugin
{
public partial class FrmTestPlugin : Form, IToolForm
{
public FrmTestPlugin()
{
InitializeComponent();
}
public string ToolName => "Test";
public bool HasIcon => false;
}
}

View File

@@ -0,0 +1,14 @@
## Preparation
* Build as class library.
* Add reference to ```VAR.Toolbox``` for interface declarations and utilities.
* Use the interfaces to extend functionality:
* ```IToolForm```: Tool window.
* ```IToolPanel```: Tool panels in the main window. Try to fit all on 200px width.
* ```ITextCoder```: Text codification clases.
* ```IProxyCmdExecutor```: Proxy command executors, mainly for remote executions.
## Usage
Put the generated assembly near ```VAR.Toolbox.exe``` it will load as plug-ins any assembly that starts
with ```VAR.Toolbox```

View File

@@ -0,0 +1,35 @@
using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("VAR.Toolbox.TestPlugin")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("VAR.Toolbox.TestPlugin")]
[assembly: AssemblyCopyright("Copyright © 2019")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("74fe172a-d63c-460e-b15f-debf4150bab1")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]

View File

@@ -0,0 +1,65 @@
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="15.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<Import Project="$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props" Condition="Exists('$(MSBuildExtensionsPath)\$(MSBuildToolsVersion)\Microsoft.Common.props')" />
<PropertyGroup>
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
<ProjectGuid>{74FE172A-D63C-460E-B15F-DEBF4150BAB1}</ProjectGuid>
<OutputType>Library</OutputType>
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>VAR.Toolbox.TestPlugin</RootNamespace>
<AssemblyName>VAR.Toolbox.TestPlugin</AssemblyName>
<TargetFrameworkVersion>v4.8</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<Deterministic>true</Deterministic>
<TargetFrameworkProfile />
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
<OutputPath>bin\Debug\</OutputPath>
<DefineConstants>DEBUG;TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.Core" />
<Reference Include="System.Drawing" />
<Reference Include="System.Windows.Forms" />
<Reference Include="System.Xml.Linq" />
<Reference Include="System.Data.DataSetExtensions" />
<Reference Include="Microsoft.CSharp" />
<Reference Include="System.Data" />
<Reference Include="System.Net.Http" />
<Reference Include="System.Xml" />
</ItemGroup>
<ItemGroup>
<Compile Include="FrmTestPlugin.cs">
<SubType>Form</SubType>
</Compile>
<Compile Include="FrmTestPlugin.Designer.cs">
<DependentUpon>FrmTestPlugin.cs</DependentUpon>
</Compile>
<Compile Include="Properties\AssemblyInfo.cs" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\VAR.Toolbox\VAR.Toolbox.csproj">
<Project>{e8dab98d-4fd0-4d40-b29a-62b4c2fca4d7}</Project>
<Name>VAR.Toolbox</Name>
</ProjectReference>
</ItemGroup>
<ItemGroup>
<None Include="Notes.md" />
</ItemGroup>
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
</Project>

View File

@@ -1,10 +1,12 @@
Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio 14
VisualStudioVersion = 14.0.25420.1
# Visual Studio Version 16
VisualStudioVersion = 16.0.28917.181
MinimumVisualStudioVersion = 10.0.40219.1
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "VAR.Toolbox", "VAR.Toolbox\VAR.Toolbox.csproj", "{E8DAB98D-4FD0-4D40-B29A-62B4C2FCA4D7}"
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "VAR.Toolbox.TestPlugin", "VAR.Toolbox.TestPlugin\VAR.Toolbox.TestPlugin.csproj", "{74FE172A-D63C-460E-B15F-DEBF4150BAB1}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
@@ -15,8 +17,15 @@ Global
{E8DAB98D-4FD0-4D40-B29A-62B4C2FCA4D7}.Debug|Any CPU.Build.0 = Debug|Any CPU
{E8DAB98D-4FD0-4D40-B29A-62B4C2FCA4D7}.Release|Any CPU.ActiveCfg = Release|Any CPU
{E8DAB98D-4FD0-4D40-B29A-62B4C2FCA4D7}.Release|Any CPU.Build.0 = Release|Any CPU
{74FE172A-D63C-460E-B15F-DEBF4150BAB1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{74FE172A-D63C-460E-B15F-DEBF4150BAB1}.Debug|Any CPU.Build.0 = Debug|Any CPU
{74FE172A-D63C-460E-B15F-DEBF4150BAB1}.Release|Any CPU.ActiveCfg = Release|Any CPU
{74FE172A-D63C-460E-B15F-DEBF4150BAB1}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
EndGlobalSection
GlobalSection(ExtensibilityGlobals) = postSolution
SolutionGuid = {08F0DAFF-33C5-4164-9454-62623789F7EB}
EndGlobalSection
EndGlobal

View File

@@ -0,0 +1,63 @@
<wpf:ResourceDictionary xml:space="preserve" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:s="clr-namespace:System;assembly=mscorlib" xmlns:ss="urn:shemas-jetbrains-com:settings-storage-xaml" xmlns:wpf="http://schemas.microsoft.com/winfx/2006/xaml/presentation">
<s:String x:Key="/Default/CodeStyle/CodeFormatting/CSharpCodeStyle/BRACES_FOR_IFELSE/@EntryValue">NotRequired</s:String>
<s:Boolean x:Key="/Default/CodeStyle/CodeFormatting/CSharpCodeStyle/TRAILING_COMMA_IN_MULTILINE_LISTS/@EntryValue">True</s:Boolean>
<s:Boolean x:Key="/Default/CodeStyle/CodeFormatting/CSharpCodeStyle/TRAILING_COMMA_IN_SINGLELINE_LISTS/@EntryValue">True</s:Boolean>
<s:String x:Key="/Default/CodeStyle/CodeFormatting/CSharpFormat/EMPTY_BLOCK_STYLE/@EntryValue">TOGETHER_SAME_LINE</s:String>
<s:Boolean x:Key="/Default/CodeStyle/CodeFormatting/CSharpFormat/KEEP_EXISTING_EMBEDDED_BLOCK_ARRANGEMENT/@EntryValue">True</s:Boolean>
<s:Boolean x:Key="/Default/CodeStyle/CodeFormatting/CSharpFormat/PLACE_SIMPLE_EMBEDDED_BLOCK_ON_SAME_LINE/@EntryValue">True</s:Boolean>
<s:Boolean x:Key="/Default/CodeStyle/CodeFormatting/CSharpFormat/SPACE_AFTER_TYPECAST_PARENTHESES/@EntryValue">False</s:Boolean>
<s:Boolean x:Key="/Default/CodeStyle/CodeFormatting/CSharpFormat/SPACE_WITHIN_SINGLE_LINE_ARRAY_INITIALIZER_BRACES/@EntryValue">True</s:Boolean>
<s:Boolean x:Key="/Default/CodeStyle/CodeFormatting/HtmlFormatter/ALLOW_FAR_ALIGNMENT/@EntryValue">True</s:Boolean>
<s:Boolean x:Key="/Default/CodeStyle/CodeFormatting/HtmlFormatter/NormalizeTagNames/@EntryValue">True</s:Boolean>
<s:String x:Key="/Default/CodeStyle/CodeFormatting/HtmlFormatter/ProcessingInstructionAttributeIndenting/@EntryValue">OneStep</s:String>
<s:String x:Key="/Default/CodeStyle/CodeFormatting/HtmlFormatter/TagAttributeIndenting/@EntryValue">OneStep</s:String>
<s:Boolean x:Key="/Default/CodeStyle/CodeFormatting/HtmlFormatter/TagSpaceBeforeHeaderEnd1/@EntryValue">True</s:Boolean>
<s:String x:Key="/Default/CodeStyle/CSharpVarKeywordUsage/ForBuiltInTypes/@EntryValue">UseVarWhenEvident</s:String>
<s:String x:Key="/Default/CodeStyle/CSharpVarKeywordUsage/ForOtherTypes/@EntryValue">UseVarWhenEvident</s:String>
<s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/Abbreviations/=AES/@EntryIndexedValue">AES</s:String>
<s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/Abbreviations/=AM/@EntryIndexedValue">AM</s:String>
<s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/Abbreviations/=AUX/@EntryIndexedValue">AUX</s:String>
<s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/Abbreviations/=BPP/@EntryIndexedValue">BPP</s:String>
<s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/Abbreviations/=DC/@EntryIndexedValue">DC</s:String>
<s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/Abbreviations/=DES/@EntryIndexedValue">DES</s:String>
<s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/Abbreviations/=EPM/@EntryIndexedValue">EPM</s:String>
<s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/Abbreviations/=GDI/@EntryIndexedValue">GDI</s:String>
<s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/Abbreviations/=ID/@EntryIndexedValue">ID</s:String>
<s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/Abbreviations/=IP/@EntryIndexedValue">IP</s:String>
<s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/Abbreviations/=RECT/@EntryIndexedValue">RECT</s:String>
<s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/Abbreviations/=RGB/@EntryIndexedValue">RGB</s:String>
<s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/Abbreviations/=SCART/@EntryIndexedValue">SCART</s:String>
<s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/Abbreviations/=SPDIF/@EntryIndexedValue">SPDIF</s:String>
<s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/Abbreviations/=SQL/@EntryIndexedValue">SQL</s:String>
<s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/Abbreviations/=SRCCOPY/@EntryIndexedValue">SRCCOPY</s:String>
<s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/Abbreviations/=TCP/@EntryIndexedValue">TCP</s:String>
<s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/Abbreviations/=URL/@EntryIndexedValue">URL</s:String>
<s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/Abbreviations/=USB/@EntryIndexedValue">USB</s:String>
<s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/Abbreviations/=VAR/@EntryIndexedValue">VAR</s:String>
<s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/Abbreviations/=WMIC/@EntryIndexedValue">WMIC</s:String>
<s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/Abbreviations/=YRYBY/@EntryIndexedValue">YRYBY</s:String>
<s:Boolean x:Key="/Default/CodeStyle/Naming/CSharpNaming/ApplyAutoDetectedRules/@EntryValue">False</s:Boolean>
<s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/PredefinedNamingRules/=Constants/@EntryIndexedValue">&lt;Policy Inspect="True" Prefix="" Suffix="" Style="AaBb_AaBb" /&gt;</s:String>
<s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/PredefinedNamingRules/=EnumMember/@EntryIndexedValue">&lt;Policy Inspect="True" Prefix="" Suffix="" Style="AaBb_AaBb"&gt;&lt;ExtraRule Prefix="T" Suffix="" Style="AaBb_AaBb" /&gt;&lt;/Policy&gt;</s:String>
<s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/PredefinedNamingRules/=Interfaces/@EntryIndexedValue">&lt;Policy Inspect="True" Prefix="I" Suffix="" Style="AaBb_AaBb" /&gt;</s:String>
<s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/PredefinedNamingRules/=LocalConstants/@EntryIndexedValue">&lt;Policy Inspect="True" Prefix="" Suffix="" Style="AaBb_AaBb" /&gt;</s:String>
<s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/PredefinedNamingRules/=Locals/@EntryIndexedValue">&lt;Policy Inspect="True" Prefix="" Suffix="" Style="aaBb_AaBb" /&gt;</s:String>
<s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/PredefinedNamingRules/=Method/@EntryIndexedValue">&lt;Policy Inspect="True" Prefix="" Suffix="" Style="AaBb_AaBb" /&gt;</s:String>
<s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/PredefinedNamingRules/=Parameters/@EntryIndexedValue">&lt;Policy Inspect="True" Prefix="" Suffix="" Style="aaBb_AaBb" /&gt;</s:String>
<s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/PredefinedNamingRules/=PrivateConstants/@EntryIndexedValue">&lt;Policy Inspect="True" Prefix="" Suffix="" Style="AaBb_AaBb" /&gt;</s:String>
<s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/PredefinedNamingRules/=PrivateInstanceFields/@EntryIndexedValue">&lt;Policy Inspect="True" Prefix="_" Suffix="" Style="aaBb_AaBb" /&gt;</s:String>
<s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/PredefinedNamingRules/=PrivateStaticFields/@EntryIndexedValue">&lt;Policy Inspect="True" Prefix="_" Suffix="" Style="aaBb_AaBb" /&gt;</s:String>
<s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/PredefinedNamingRules/=PrivateStaticReadonly/@EntryIndexedValue">&lt;Policy Inspect="True" Prefix="_" Suffix="" Style="aaBb_AaBb" /&gt;</s:String>
<s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/PredefinedNamingRules/=Property/@EntryIndexedValue">&lt;Policy Inspect="True" Prefix="" Suffix="" Style="AaBb_AaBb" /&gt;</s:String>
<s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/PredefinedNamingRules/=PublicFields/@EntryIndexedValue">&lt;Policy Inspect="True" Prefix="" Suffix="" Style="AaBb_AaBb" /&gt;</s:String>
<s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/PredefinedNamingRules/=StaticReadonly/@EntryIndexedValue">&lt;Policy Inspect="True" Prefix="" Suffix="" Style="AaBb" /&gt;</s:String>
<s:String x:Key="/Default/CodeStyle/Naming/CSharpNaming/PredefinedNamingRules/=TypesAndNamespaces/@EntryIndexedValue">&lt;Policy Inspect="True" Prefix="" Suffix="" Style="AaBb_AaBb" /&gt;</s:String>
<s:Boolean x:Key="/Default/Environment/SettingsMigration/IsMigratorApplied/=JetBrains_002EReSharper_002EPsi_002ECSharp_002ECodeStyle_002ECSharpKeepExistingMigration/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/Environment/SettingsMigration/IsMigratorApplied/=JetBrains_002EReSharper_002EPsi_002ECSharp_002ECodeStyle_002ECSharpPlaceEmbeddedOnSameLineMigration/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/Environment/SettingsMigration/IsMigratorApplied/=JetBrains_002EReSharper_002EPsi_002ECSharp_002ECodeStyle_002ECSharpUseContinuousIndentInsideBracesMigration/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/Environment/SettingsMigration/IsMigratorApplied/=JetBrains_002EReSharper_002EPsi_002ECSharp_002ECodeStyle_002ESettingsUpgrade_002EMigrateBlankLinesAroundFieldToBlankLinesAroundProperty/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/UserDictionary/Words/=bitblt/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/UserDictionary/Words/=Deserializa/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/UserDictionary/Words/=Screenshooter/@EntryIndexedValue">True</s:Boolean>
<s:Boolean x:Key="/Default/UserDictionary/Words/=tbps/@EntryIndexedValue">True</s:Boolean>
</wpf:ResourceDictionary>

View File

@@ -0,0 +1,79 @@
using System;
using System.Collections.Generic;
using System.Linq;
namespace VAR.Toolbox.Code
{
public abstract class BaseFactory<T> where T : INamed
{
// ReSharper disable once StaticMemberInGenericType
private static Dictionary<string, Type> _dictTypes;
private static Dictionary<string, Type> GetDict()
{
if (_dictTypes != null)
{
return _dictTypes;
}
Type iType = typeof(T);
IEnumerable<Type> types = ReflectionUtils.GetTypesOfInterface(iType);
_dictTypes = types.ToDictionary(t =>
{
T type = (T)System.Runtime.Serialization.FormatterServices.GetUninitializedObject(t);
return type.Name;
});
return _dictTypes;
}
public static string[] GetNames()
{
Dictionary<string, Type> dict = GetDict();
return dict.Select(p => p.Key).ToArray();
}
public static T CreateFromName(string name)
{
Dictionary<string, Type> dict = GetDict();
if (dict.ContainsKey(name) == false)
{
throw new NotImplementedException(string.Format("Cant create {1} with this name: {0}", name,
typeof(T).Name));
}
Type type = dict[name];
T instance = (T)Activator.CreateInstance(type);
return instance;
}
public static T CreateFromConfig(string config)
{
Dictionary<string, Type> dict = GetDict();
int indexOfColon = config.IndexOf(':');
string name = config.Substring(0, indexOfColon < 0 ? config.Length : indexOfColon);
string nextConfig = config.Substring(indexOfColon + 1);
if (string.IsNullOrEmpty(name))
{
return (T)(object)null;
}
if (dict.ContainsKey(name) == false)
{
throw new NotImplementedException(string.Format("Cant create {1} with this config: {0}", config,
typeof(T).Name));
}
Type type = dict[name];
T instance = (T)Activator.CreateInstance(type, new object[] { nextConfig });
return instance;
}
}
public interface INamed
{
string Name { get; }
}
}

View File

@@ -0,0 +1,6 @@
namespace VAR.Toolbox.Code.Bots
{
public abstract class AutomationBotFactory: BaseFactory<IAutomationBot>
{
}
}

View File

@@ -0,0 +1,32 @@
using System.Drawing;
using VAR.Toolbox.Code.Configuration;
namespace VAR.Toolbox.Code.Bots
{
public class DummyBot : IAutomationBot
{
public string Name => "Dummy";
public IConfiguration GetDefaultConfiguration()
{
return null;
}
public void Init(IOutputHandler output, IConfiguration config)
{
output.Clean();
}
public Bitmap Process(Bitmap bmpInput, IOutputHandler output)
{
return bmpInput;
}
public string ResponseKeys()
{
// https://docs.microsoft.com/en-us/dotnet/api/system.windows.forms.sendkeys?view=netframework-4.8
//return "{UP}";
return string.Empty;
}
}
}

View File

@@ -0,0 +1,13 @@
using System.Drawing;
using VAR.Toolbox.Code.Configuration;
namespace VAR.Toolbox.Code.Bots
{
public interface IAutomationBot: INamed
{
IConfiguration GetDefaultConfiguration();
void Init(IOutputHandler output, IConfiguration config);
Bitmap Process(Bitmap bmpInput, IOutputHandler output);
string ResponseKeys();
}
}

View File

@@ -0,0 +1,894 @@
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using VAR.Toolbox.Code.Configuration;
namespace VAR.Toolbox.Code.Bots
{
public class TetrisBot : IAutomationBot
{
private TetrisGrid _grid;
private List<TetrisShape> _currentShape;
private TetrisGrid _workGrid0;
private TetrisGrid _workGrid1;
private double[] _columnEvaluation;
private bool _shapeFound;
private int _shapeX;
private int _shapeY;
private double _bestEvaluation = double.MinValue;
private int _bestXOffset;
private int _bestRotation;
public string Name => "Tetris";
private const int DefaultGridWidth = 10;
private const int DefaultGridHeight = 20;
private const int DefaultShotCooldownFrames = 2;
public IConfiguration GetDefaultConfiguration()
{
var defaultConfiguration = new MemoryBackedConfiguration();
defaultConfiguration.Set("GridWidth", DefaultGridWidth);
defaultConfiguration.Set("GridHeight", DefaultGridHeight);
defaultConfiguration.Set("ShotCooldownFrames", DefaultShotCooldownFrames);
return defaultConfiguration;
}
public void Init(IOutputHandler output, IConfiguration config)
{
int gridWidth = config.Get("GridWidth", DefaultGridWidth);
int gridHeight = config.Get("GridHeight", DefaultGridHeight);
_shotCooldownFrames = config.Get("ShotCooldownFrames", DefaultShotCooldownFrames);
_grid = new TetrisGrid(gridWidth, gridHeight);
_workGrid0 = new TetrisGrid(gridWidth, gridHeight);
_workGrid1 = new TetrisGrid(gridWidth, gridHeight);
_columnEvaluation = new double[gridWidth];
_currentShape = new List<TetrisShape>
{
new TetrisShape(),
new TetrisShape(),
new TetrisShape(),
new TetrisShape(),
};
output.Clean();
output.AddLine($"TetrisBot: Starting {DateTime.UtcNow:s}");
}
public Bitmap Process(Bitmap bmpInput, IOutputHandler output)
{
_grid.SampleFromBitmap(bmpInput);
SearchShape();
SearchBestAction();
// Show information
_workGrid0.SampleOther(_grid, TetrisGrid.CellSolid, TetrisGrid.CellSolid);
if (_shapeFound)
{
_currentShape[0].PutOnGrid(_workGrid0, _shapeX, _shapeY, TetrisGrid.CellEmpty);
_currentShape[_bestRotation].Drop(_workGrid0, _shapeX + _bestXOffset, _shapeY, TetrisGrid.CellShapeA);
_currentShape[0].PutOnGrid(_workGrid0, _shapeX, _shapeY, TetrisGrid.CellShapeB);
}
_workGrid0.Draw(bmpInput, 0.75f);
_workGrid0.SampleOther(_grid, TetrisGrid.CellSolid, TetrisGrid.CellSolid);
_workGrid0.RemoveGround();
_workGrid0.Draw(bmpInput, 0.25f);
return bmpInput;
}
private void SearchShape()
{
_workGrid0.SampleOther(_grid, TetrisGrid.CellSolid, TetrisGrid.CellSolid);
_workGrid0.RemoveGround();
_shapeFound = false;
for (int y = 0; y < _grid.Height; y++)
{
for (int x = 0; x < _grid.Width; x++)
{
TetrisShape matchedShape =
TetrisShape.DefaultShapes.FirstOrDefault(s => s.MatchOnGrid(_workGrid0, x, y));
if (matchedShape != null)
{
_workGrid1.SampleOther(_workGrid0, TetrisGrid.CellSolid, TetrisGrid.CellSolid);
matchedShape.PutOnGrid(_workGrid1, x, y, TetrisGrid.CellEmpty);
if (matchedShape.CheckIntersection(_workGrid1, x, y + 1)) { continue; }
// Shape found
_currentShape[0].Copy(matchedShape);
for (int i = 1; i < 4; i++)
{
_currentShape[i].RotateClockWise(_currentShape[i - 1]);
}
_shapeX = x;
_shapeY = y;
_shapeFound = true;
break;
}
}
if (_shapeFound) { break; }
}
}
private void SearchBestAction()
{
_bestEvaluation = double.MinValue;
_bestXOffset = 0;
_bestRotation = 0;
if (!_shapeFound)
{
_workGrid0.SampleOther(_grid, TetrisGrid.CellSolid, TetrisGrid.CellSolid);
return;
}
for (int rotation = 0; rotation < 4; rotation++)
{
for (int x = 0; x < _grid.Width; x++)
{
_workGrid0.SampleOther(_grid, TetrisGrid.CellSolid, TetrisGrid.CellSolid);
_currentShape[0].PutOnGrid(_workGrid0, _shapeX, _shapeY, TetrisGrid.CellEmpty);
if (_currentShape[rotation].Drop(_workGrid0, x, _shapeY, TetrisGrid.CellShapeA))
{
double newEvaluation = _workGrid0.Evaluate();
_columnEvaluation[x] = newEvaluation;
}
else
{
_columnEvaluation[x] = double.MinValue;
}
}
// Search valid X range
int minX = _shapeX;
while (minX >= 0 && _columnEvaluation[minX] > double.MinValue) { minX--; }
minX++;
int maxX = _shapeX;
while (maxX < _grid.Width && _columnEvaluation[maxX] > double.MinValue) { maxX++; }
maxX--;
// Apply best value inside valid X range
for (int x = minX; x <= maxX; x++)
{
if (_columnEvaluation[x] > _bestEvaluation)
{
_bestEvaluation = _columnEvaluation[x];
_bestXOffset = x - _shapeX;
_bestRotation = rotation;
}
}
}
}
private int _shotCooldownFrames;
private int _shotCooldown;
public string ResponseKeys()
{
if (_shapeFound == false) { return string.Empty; }
if (_bestRotation == 0 && _bestXOffset == 0 && _bestEvaluation > double.MinValue)
{
if (_shotCooldown <= 0)
{
_shotCooldown = _shotCooldownFrames;
return " ";
}
else
{
_shotCooldown--;
return string.Empty;
}
}
_shotCooldown = _shotCooldownFrames;
if (_bestRotation != 0 && _bestXOffset < 0) { return "{UP}{LEFT}"; }
if (_bestRotation != 0 && _bestXOffset > 0) { return "{UP}{RIGHT}"; }
if (_bestRotation != 0) { return "{UP}"; }
if (_bestXOffset < 0) { return "{LEFT}"; }
if (_bestXOffset > 0) { return "{RIGHT}"; }
return string.Empty;
}
}
public class TetrisShape
{
private const int ShapeSize = 4;
private readonly byte[][] _cells;
private int _count;
public TetrisShape(byte[][] cells = null)
{
_cells = new byte[ShapeSize][];
for (int y = 0; y < ShapeSize; y++)
{
_cells[y] = new byte[ShapeSize];
}
_count = 0;
if (cells != null)
{
for (int j = 0; j < ShapeSize; j++)
{
if (j >= cells.Length) { break; }
for (int i = 0; i < ShapeSize; i++)
{
if (i >= cells[j].Length) { break; }
_cells[j][i] = cells[j][i];
if (_cells[j][i] != 0) { _count++; }
}
}
}
}
public int GetCount()
{
return _count;
}
private static List<TetrisShape> _defaultShapes;
public static List<TetrisShape> DefaultShapes
{
get
{
return _defaultShapes ?? (_defaultShapes = new List<TetrisShape>
{
// I
new TetrisShape(new[]
{
new byte[] { 1, 1, 1, 1, },
}),
new TetrisShape(new[]
{
new byte[] { 1, },
new byte[] { 1, },
new byte[] { 1, },
new byte[] { 1, },
}),
// J
new TetrisShape(new[]
{
new byte[] { 1, },
new byte[] { 1, 1, 1, },
}),
new TetrisShape(new[]
{
new byte[] { 1, 1, },
new byte[] { 1, },
new byte[] { 1, },
}),
new TetrisShape(new[]
{
new byte[] { 1, 1, 1, },
new byte[] { 0, 0, 1, },
}),
new TetrisShape(new[]
{
new byte[] { 0, 1, },
new byte[] { 0, 1, },
new byte[] { 1, 1, },
}),
// L
new TetrisShape(new[]
{
new byte[] { 0, 0, 1, },
new byte[] { 1, 1, 1, },
}),
new TetrisShape(new[]
{
new byte[] { 1, },
new byte[] { 1, },
new byte[] { 1, 1, },
}),
new TetrisShape(new[]
{
new byte[] { 1, 1, 1, },
new byte[] { 1, },
}),
new TetrisShape(new[]
{
new byte[] { 1, 1, },
new byte[] { 0, 1, },
new byte[] { 0, 1, },
}),
// S
new TetrisShape(new[]
{
new byte[] { 0, 1, 1, },
new byte[] { 1, 1, },
}),
new TetrisShape(new[]
{
new byte[] { 1, },
new byte[] { 1, 1, },
new byte[] { 0, 1, },
}),
// T
new TetrisShape(new[]
{
new byte[] { 0, 1, },
new byte[] { 1, 1, 1, },
}),
new TetrisShape(new[]
{
new byte[] { 1, },
new byte[] { 1, 1, },
new byte[] { 1, },
}),
new TetrisShape(new[]
{
new byte[] { 1, 1, 1, },
new byte[] { 0, 1, },
}),
new TetrisShape(new[]
{
new byte[] { 0, 1, },
new byte[] { 1, 1, },
new byte[] { 0, 1, },
}),
// Z
new TetrisShape(new[]
{
new byte[] { 1, 1, },
new byte[] { 0, 1, 1, },
}),
new TetrisShape(new[]
{
new byte[] { 0, 1, },
new byte[] { 1, 1, },
new byte[] { 1, },
}),
// O
new TetrisShape(new[]
{
new byte[] { 1, 1, },
new byte[] { 1, 1, },
})
});
}
}
public bool IsValid()
{
if (_count != 4) { return false; }
bool matchesAnyDefault = DefaultShapes.Any(CompareShape);
return matchesAnyDefault;
}
public void Copy(TetrisShape shape)
{
for (int j = 0; j < ShapeSize; j++)
{
for (int i = 0; i < ShapeSize; i++)
{
_cells[j][i] = shape._cells[j][i];
_count = shape._count;
}
}
}
private bool CompareShape(TetrisShape shape)
{
for (int j = 0; j < ShapeSize; j++)
{
for (int i = 0; i < ShapeSize; i++)
{
if (_cells[j][i] != shape._cells[j][i])
{
return false;
}
}
}
return true;
}
public void SampleFromGrid(TetrisGrid grid, int x, int y, byte value)
{
_count = 0;
for (int j = 0; j < ShapeSize; j++)
{
for (int i = 0; i < ShapeSize; i++)
{
if (grid.Get(x + i, y + j) == value)
{
_cells[j][i] = 1;
_count++;
}
else
{
_cells[j][i] = 0;
}
}
}
}
public void PutOnGrid(TetrisGrid grid, int x, int y, byte value)
{
for (int j = 0; j < ShapeSize; j++)
{
for (int i = 0; i < ShapeSize; i++)
{
if (_cells[j][i] == 0) { continue; }
grid.Set(x + i, y + j, value);
}
}
}
public bool CheckIntersection(TetrisGrid grid, int x, int y)
{
for (int j = 0; j < ShapeSize; j++)
{
for (int i = 0; i < ShapeSize; i++)
{
if (_cells[j][i] == 0) { continue; }
if (grid.Get(x + i, y + j) != 0)
{
return true;
}
}
}
return false;
}
public bool Drop(TetrisGrid grid, int x, int y, byte value)
{
if (CheckIntersection(grid, x, y)) { return false; }
while (CheckIntersection(grid, x, y + 1) == false)
{
y++;
}
PutOnGrid(grid, x, y, value);
return true;
}
private bool SearchFirstCell(byte value, out int x, out int y)
{
x = -1;
y = -1;
for (int j = 0; j < ShapeSize && y == -1; j++)
{
for (int i = 0; i < ShapeSize && y == -1; i++)
{
if (_cells[j][i] == value)
{
y = j;
}
}
}
if (y == -1) { return false; }
for (int i = 0; i < ShapeSize && x == -1; i++)
{
for (int j = 0; j < ShapeSize && x == -1; j++)
{
if (_cells[j][i] == value)
{
x = i;
}
}
}
if (x == -1) { return false; }
return true;
}
private void Offset(int x, int y)
{
_count = 0;
for (int j = 0; j < ShapeSize; j++)
{
for (int i = 0; i < ShapeSize; i++)
{
if ((j + y) < ShapeSize && (i + x) < ShapeSize)
{
_cells[j][i] = _cells[j + y][i + x];
if (_cells[j][i] != 0)
{
_count++;
}
}
else
{
_cells[j][i] = 0;
}
}
}
}
public void RotateClockWise(TetrisShape shape)
{
for (int j = 0; j < ShapeSize; j++)
{
for (int i = 0; i < ShapeSize; i++)
{
_cells[i][ShapeSize - (j + 1)] = shape._cells[j][i];
}
}
_count = shape._count;
if (SearchFirstCell(1, out int offsetX, out int offsetY))
{
Offset(offsetX, offsetY);
}
}
public void Print(IOutputHandler output)
{
for (int y = 0; y < ShapeSize; y++)
{
StringBuilder sbLine = new StringBuilder();
for (int x = 0; x < ShapeSize; x++)
{
sbLine.Append(_cells[y][x] == 0 ? ".." : "[]");
}
output.AddLine(sbLine.ToString());
}
}
public bool MatchOnGrid(TetrisGrid grid, int x, int y)
{
for (int j = 0; j < ShapeSize; j++)
{
for (int i = 0; i < ShapeSize; i++)
{
int currentCell = grid.Get(x + i, y + j);
if (_cells[j][i] == 0)
{
if (currentCell != 0 && currentCell != 0xFF)
{
return false;
}
}
else
{
if (currentCell == 0 || currentCell == 0xFF)
{
return false;
}
}
}
}
return true;
}
}
public class TetrisGrid
{
public const byte CellEmpty = 0;
public const byte CellSolid = 1;
public const byte CellShapeA = 2;
public const byte CellShapeB = 3;
private readonly int _gridWidth;
private readonly int _gridHeight;
public int Width => _gridWidth;
public int Height => _gridHeight;
private readonly byte[][] _grid;
private readonly int[] _heights;
public TetrisGrid(int gridWidth, int gridHeight)
{
_gridWidth = gridWidth;
_gridHeight = gridHeight;
_grid = new byte[_gridHeight][];
for (int y = 0; y < _gridHeight; y++)
{
_grid[y] = new byte[_gridWidth];
}
_heights = new int[_gridWidth];
}
public byte Get(int x, int y)
{
if (x >= _gridWidth || x < 0) { return 0xFF; }
if (y >= _gridHeight || y < 0) { return 0xFF; }
return _grid[y][x];
}
public void Set(int x, int y, byte value)
{
if (x >= _gridWidth || x < 0) { return; }
if (y >= _gridHeight || y < 0) { return; }
_grid[y][x] = value;
}
public void SampleFromBitmap(Bitmap bmp)
{
float xStep = bmp.Width / (float)_gridWidth;
float yStep = bmp.Height / (float)_gridHeight;
float xOff0 = xStep / 2;
float xOff1 = xOff0 / 2;
float xOff2 = xOff0 + xOff1;
float yOff0 = yStep / 2;
float yOff1 = yOff0 / 2;
float yOff2 = yOff0 + yOff1;
for (int y = 0; y < _gridHeight; y++)
{
for (int x = 0; x < _gridWidth; x++)
{
Color color = bmp.GetPixel(
x: (int)((x * xStep) + xOff0),
y: (int)((y * yStep) + yOff0));
if (color.R > 128 || color.G > 128 || color.B > 128)
{
Color color0 = bmp.GetPixel(
x: (int)((x * xStep) + xOff1),
y: (int)((y * yStep) + yOff1));
Color color1 = bmp.GetPixel(
x: (int)((x * xStep) + xOff1),
y: (int)((y * yStep) + yOff2));
Color color2 = bmp.GetPixel(
x: (int)((x * xStep) + xOff2),
y: (int)((y * yStep) + yOff1));
Color color3 = bmp.GetPixel(
x: (int)((x * xStep) + xOff2),
y: (int)((y * yStep) + yOff2));
if (
(color0.R > 128 || color0.G > 128 || color0.B > 128) &&
(color1.R > 128 || color1.G > 128 || color1.B > 128) &&
(color2.R > 128 || color2.G > 128 || color2.B > 128) &&
(color3.R > 128 || color3.G > 128 || color3.B > 128) &&
true)
{
_grid[y][x] = 1;
}
else
{
_grid[y][x] = 0;
}
}
else
{
_grid[y][x] = 0;
}
}
}
}
public void RemoveGround()
{
for (int i = 0; i < _gridWidth; i++)
{
if (_grid[_gridHeight - 1][i] == 1)
{
FloodFill(i, _gridHeight - 1, CellSolid, CellEmpty);
}
}
}
private void FloodFill(int x, int y, byte expectedValue, byte fillValue)
{
if (x >= _gridWidth || x < 0) { return; }
if (y >= _gridHeight || y < 0) { return; }
if (_grid[y][x] != expectedValue) { return; }
_grid[y][x] = fillValue;
FloodFill(x - 1, y - 1, expectedValue, fillValue);
FloodFill(x - 1, y + 0, expectedValue, fillValue);
FloodFill(x - 1, y + 1, expectedValue, fillValue);
FloodFill(x + 0, y - 1, expectedValue, fillValue);
FloodFill(x + 0, y + 1, expectedValue, fillValue);
FloodFill(x + 1, y - 1, expectedValue, fillValue);
FloodFill(x + 1, y + 0, expectedValue, fillValue);
FloodFill(x + 1, y + 1, expectedValue, fillValue);
}
public void SampleOther(TetrisGrid grid, byte value, byte setValue)
{
for (int y = 0; y < _gridHeight; y++)
{
for (int x = 0; x < _gridWidth; x++)
{
if (grid._grid[y][x] == value)
{
_grid[y][x] = setValue;
}
else
{
_grid[y][x] = 0;
}
}
}
}
public bool SearchFirstCell(byte value, out int x, out int y)
{
x = -1;
y = -1;
for (int j = 0; j < _gridHeight && y == -1; j++)
{
for (int i = 0; i < _gridWidth && y == -1; i++)
{
if (_grid[j][i] == value)
{
y = j;
}
}
}
if (y == -1) { return false; }
for (int i = 0; i < _gridWidth && x == -1; i++)
{
for (int j = 0; j < _gridHeight && x == -1; j++)
{
if (_grid[j][i] == value)
{
x = i;
}
}
}
if (x == -1) { return false; }
return true;
}
private bool IsCompleteLine(int y)
{
bool complete = true;
for (int x = 0; x < _gridWidth; x++)
{
if (_grid[y][x] == 0)
{
complete = false;
break;
}
}
return complete;
}
public double Evaluate(
double aggregateHeightWeight = -0.510066,
double completeLinesWeight = 0.760666,
double holesWeight = -0.35663,
double bumpinessWeight = -0.184483)
{
// Calculate aggregate height
for (int i = 0; i < _gridWidth; i++)
{
int j = 0;
while (j < _gridHeight && _grid[j][i] == CellEmpty) { j++; }
_heights[i] = _gridHeight - j;
}
double aggregateHeight = _heights.Sum();
// Calculate complete lines
int completeLines = 0;
for (int y = 0; y < _gridHeight; y++)
{
if (IsCompleteLine(y)) { completeLines++; }
}
// Calculate holes
int holes = 0;
for (int x = 0; x < _gridWidth; x++)
{
bool block = false;
for (int y = 1; y < _gridHeight; y++)
{
if (_grid[y][x] != CellEmpty && IsCompleteLine(y) == false)
{
block = true;
}
else if (_grid[y][x] == CellEmpty && block)
{
holes++;
}
}
}
// Calculate bumpiness
int bumpiness = 0;
for (int i = 1; i < _gridWidth; i++)
{
bumpiness += Math.Abs(_heights[i] - _heights[i - 1]);
}
// Evaluate formula
double evaluationValue =
aggregateHeightWeight * aggregateHeight +
completeLinesWeight * completeLines +
holesWeight * holes +
bumpinessWeight * bumpiness +
0;
return evaluationValue;
}
public void Draw(Bitmap bmp, float dotWith = 0.5f)
{
float xStep = bmp.Width / (float)_gridWidth;
float yStep = bmp.Height / (float)_gridHeight;
float halfXStep = xStep * dotWith;
float halfYStep = yStep * dotWith;
float offX = (xStep - halfXStep) / 2;
float offY = (yStep - halfYStep) / 2;
using (Pen borderPen = new Pen(Color.DarkGray))
using (Graphics g = Graphics.FromImage(bmp))
{
for (int y = 0; y < _gridHeight; y++)
{
for (int x = 0; x < _gridWidth; x++)
{
Brush br = null;
if (_grid[y][x] == CellEmpty)
{
br = Brushes.Black;
}
else if (_grid[y][x] == CellSolid)
{
br = Brushes.Blue;
}
else if (_grid[y][x] == CellShapeA)
{
br = Brushes.Red;
}
else if (_grid[y][x] == CellShapeB)
{
br = Brushes.Green;
}
if (br == null) { continue; }
g.DrawRectangle(borderPen, (xStep * x) + offX - 1, (yStep * y) + offY - 1, halfXStep + 2,
halfYStep + 2);
g.FillRectangle(br, (xStep * x) + offX, (yStep * y) + offY, halfXStep, halfYStep);
}
}
}
}
}
}

View File

@@ -0,0 +1,116 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
namespace VAR.Toolbox.Code.Configuration
{
public class FileBackedConfiguration : IConfiguration
{
private readonly MemoryBackedConfiguration _config = new MemoryBackedConfiguration();
private readonly string _name;
public FileBackedConfiguration(string name = null)
{
_name = name;
}
private static string GetConfigFileName(string name = null)
{
string location = System.Reflection.Assembly.GetEntryAssembly()?.Location;
string path = Path.GetDirectoryName(location);
string filenameWithoutExtension = Path.GetFileNameWithoutExtension(location);
string configFile = string.IsNullOrEmpty(name)
? $"{path}/{filenameWithoutExtension}.cfg"
: $"{path}/{filenameWithoutExtension}_{name}.cfg";
return configFile;
}
private static string[] GetConfigurationLines(string name = null)
{
string configFile = GetConfigFileName(name);
string[] config = File.Exists(configFile) == false
? Array.Empty<string>()
: File.ReadAllLines(configFile);
return config;
}
public void Load(IConfiguration other = null)
{
_config.Clear();
if (other != null)
{
foreach (string key in other.GetKeys())
{
_config.Set(key, other.Get(key, null));
}
}
string[] configLines = GetConfigurationLines(_name);
foreach (string configLine in configLines)
{
int idxSplit = configLine.IndexOf('|');
if (idxSplit < 0) { continue; }
string configName = configLine.Substring(0, idxSplit);
string configData = configLine.Substring(idxSplit + 1);
_config.Set(configName, configData);
}
}
public void Save()
{
StringBuilder sbConfig = new StringBuilder();
foreach (string key in _config.GetKeys())
{
sbConfig.AppendFormat("{0}|{1}\n", key, _config.Get(key, string.Empty));
}
string configFileName = GetConfigFileName(_name);
File.WriteAllText(configFileName, sbConfig.ToString());
}
public IEnumerable<string> GetKeys()
{
return _config.GetKeys();
}
public void Clear()
{
_config.Clear();
}
public string Get(string key, string defaultValue)
{
return _config.Get(key, defaultValue);
}
public int Get(string key, int defaultValue)
{
return _config.Get(key, defaultValue);
}
public bool Get(string key, bool defaultValue)
{
return _config.Get(key, defaultValue);
}
public void Set(string key, string value)
{
_config.Set(key, value);
}
public void Set(string key, int value)
{
_config.Set(key, value);
}
public void Set(string key, bool value)
{
_config.Set(key, value);
}
}
}

View File

@@ -0,0 +1,16 @@
using System.Collections.Generic;
namespace VAR.Toolbox.Code.Configuration
{
public interface IConfiguration
{
IEnumerable<string> GetKeys();
void Clear();
bool Get(string key, bool defaultValue);
int Get(string key, int defaultValue);
string Get(string key, string defaultValue);
void Set(string key, bool value);
void Set(string key, int value);
void Set(string key, string value);
}
}

View File

@@ -0,0 +1,102 @@
using System;
using System.Collections.Generic;
using System.Linq;
namespace VAR.Toolbox.Code.Configuration
{
public class MemoryBackedConfiguration : IConfiguration
{
private readonly Dictionary<string, string> _configItems = new Dictionary<string, string>();
public IEnumerable<string> GetKeys()
{
return _configItems == null
? new List<string>()
: _configItems.Select(p => p.Key);
}
public void Clear()
{
_configItems.Clear();
}
public string Get(string key, string defaultValue)
{
if (_configItems == null) { return defaultValue; }
return _configItems.ContainsKey(key) ? _configItems[key] : defaultValue;
}
public int Get(string key, int defaultValue)
{
if (_configItems == null) { return defaultValue; }
if (_configItems.ContainsKey(key))
{
if (int.TryParse(_configItems[key], out int value))
{
return value;
}
return defaultValue;
}
return defaultValue;
}
public bool Get(string key, bool defaultValue)
{
if (_configItems == null) { return defaultValue; }
if (_configItems.ContainsKey(key))
{
string value = _configItems[key];
return (value == "true");
}
return defaultValue;
}
public void Set(string key, string value)
{
if (_configItems == null) { return; }
if (_configItems.ContainsKey(key))
{
_configItems[key] = value;
}
else
{
_configItems.Add(key, value);
}
}
public void Set(string key, int value)
{
if (_configItems == null) { return; }
if (_configItems.ContainsKey(key))
{
_configItems[key] = Convert.ToString(value);
}
else
{
_configItems.Add(key, Convert.ToString(value));
}
}
public void Set(string key, bool value)
{
if (_configItems == null) { return; }
if (_configItems.ContainsKey(key))
{
_configItems[key] = value ? "true" : "false";
}
else
{
_configItems.Add(key, value ? "true" : "false");
}
}
}
}

View File

@@ -11,26 +11,32 @@
/// Pan control.
/// </summary>
Pan = 0,
/// <summary>
/// Tilt control.
/// </summary>
Tilt,
/// <summary>
/// Roll control.
/// </summary>
Roll,
/// <summary>
/// Zoom control.
/// </summary>
Zoom,
/// <summary>
/// Exposure control.
/// </summary>
Exposure,
/// <summary>
/// Iris control.
/// </summary>
Iris,
/// <summary>
/// Focus control.
/// </summary>
@@ -47,10 +53,12 @@
/// No control flag.
/// </summary>
None = 0x0,
/// <summary>
/// Auto control Flag.
/// </summary>
Auto = 0x0001,
/// <summary>
/// Manual control Flag.
/// </summary>

View File

@@ -1,6 +1,5 @@
namespace VAR.Toolbox.Code.DirectShow
{
using System;
using System.Runtime.InteropServices;
/// <summary>
@@ -16,7 +15,7 @@
/// Gets the range and default value of a specified camera property.
/// </summary>
///
/// <param name="Property">Specifies the property to query.</param>
/// <param name="property">Specifies the property to query.</param>
/// <param name="pMin">Receives the minimum value of the property.</param>
/// <param name="pMax">Receives the maximum value of the property.</param>
/// <param name="pSteppingDelta">Receives the step size for the property.</param>
@@ -27,7 +26,7 @@
///
[PreserveSig]
int GetRange(
[In] CameraControlProperty Property,
[In] CameraControlProperty property,
[Out] out int pMin,
[Out] out int pMax,
[Out] out int pSteppingDelta,
@@ -39,35 +38,35 @@
/// Sets a specified property on the camera.
/// </summary>
///
/// <param name="Property">Specifies the property to set.</param>
/// <param name="property">Specifies the property to set.</param>
/// <param name="lValue">Specifies the new value of the property.</param>
/// <param name="Flags">Specifies the desired control setting, as a member of the CameraControlFlags enumeration.</param>
/// <param name="flags">Specifies the desired control setting, as a member of the CameraControlFlags enumeration.</param>
///
/// <returns>Return's <b>HRESULT</b> error code.</returns>
///
[PreserveSig]
int Set(
[In] CameraControlProperty Property,
[In] CameraControlProperty property,
[In] int lValue,
[In] CameraControlFlags Flags
[In] CameraControlFlags flags
);
/// <summary>
/// Gets the current setting of a camera property.
/// </summary>
///
/// <param name="Property">Specifies the property to retrieve.</param>
/// <param name="property">Specifies the property to retrieve.</param>
/// <param name="lValue">Receives the value of the property.</param>
/// <param name="Flags">Receives a member of the CameraControlFlags enumeration.
/// <param name="flags">Receives a member of the CameraControlFlags enumeration.
/// The returned value indicates whether the setting is controlled manually or automatically.</param>
///
/// <returns>Return's <b>HRESULT</b> error code.</returns>
///
[PreserveSig]
int Get(
[In] CameraControlProperty Property,
[In] CameraControlProperty property,
[Out] out int lValue,
[Out] out CameraControlFlags Flags
[Out] out CameraControlFlags flags
);
}
}

View File

@@ -1,4 +1,5 @@
using System;
#pragma warning disable IDE1006
using System.Runtime.InteropServices;
namespace VAR.Toolbox.Code.DirectShow

View File

@@ -1,6 +1,5 @@
namespace VAR.Toolbox.Code.DirectShow
{
using System;
using System.Runtime.InteropServices;
/// <summary>
@@ -60,8 +59,10 @@ namespace VAR.Toolbox.Code.DirectShow
[PreserveSig]
int GetStreamCaps(
[In] int index,
[Out, MarshalAs(UnmanagedType.LPStruct)] out AMMediaType mediaType,
[In, MarshalAs(UnmanagedType.LPStruct)] VideoStreamConfigCaps streamConfigCaps
[Out, MarshalAs(UnmanagedType.LPStruct)]
out AMMediaType mediaType,
[In, MarshalAs(UnmanagedType.LPStruct)]
VideoStreamConfigCaps streamConfigCaps
);
}
}

View File

@@ -19,12 +19,12 @@ namespace VAR.Toolbox.Code.DirectShow
/// Returns the class identifier (CLSID) for the component object.
/// </summary>
///
/// <param name="ClassID">Points to the location of the CLSID on return.</param>
/// <param name="classID">Points to the location of the CLSID on return.</param>
///
/// <returns>Return's <b>HRESULT</b> error code.</returns>
///
[PreserveSig]
int GetClassID([Out] out Guid ClassID);
int GetClassID([Out] out Guid classID);
// --- IMediaFilter Methods

View File

@@ -1,3 +1,5 @@
// ReSharper disable IdentifierTypo
namespace VAR.Toolbox.Code.DirectShow
{
using System;
@@ -48,14 +50,15 @@ namespace VAR.Toolbox.Code.DirectShow
///
[PreserveSig]
int SetOutputFileName(
[In, MarshalAs(UnmanagedType.LPStruct)] Guid type,
[In, MarshalAs(UnmanagedType.LPStruct)]
Guid type,
[In, MarshalAs(UnmanagedType.LPWStr)] string fileName,
[Out] out IBaseFilter baseFilter,
[Out] out IntPtr fileSinkFilter
);
/// <summary>
/// Searche the graph for a specified interface, starting from a specified filter.
/// Search the graph for a specified interface, starting from a specified filter.
/// </summary>
///
/// <param name="category">GUID that specifies the search criteria.</param>
@@ -68,11 +71,15 @@ namespace VAR.Toolbox.Code.DirectShow
///
[PreserveSig]
int FindInterface(
[In, MarshalAs(UnmanagedType.LPStruct)] Guid category,
[In, MarshalAs(UnmanagedType.LPStruct)] Guid type,
[In, MarshalAs(UnmanagedType.LPStruct)]
Guid category,
[In, MarshalAs(UnmanagedType.LPStruct)]
Guid type,
[In] IBaseFilter baseFilter,
[In, MarshalAs(UnmanagedType.LPStruct)] Guid interfaceID,
[Out, MarshalAs(UnmanagedType.IUnknown)] out object retInterface
[In, MarshalAs(UnmanagedType.LPStruct)]
Guid interfaceID,
[Out, MarshalAs(UnmanagedType.IUnknown)]
out object retInterface
);
/// <summary>
@@ -89,9 +96,12 @@ namespace VAR.Toolbox.Code.DirectShow
///
[PreserveSig]
int RenderStream(
[In, MarshalAs(UnmanagedType.LPStruct)] Guid category,
[In, MarshalAs(UnmanagedType.LPStruct)] Guid mediaType,
[In, MarshalAs(UnmanagedType.IUnknown)] object source,
[In, MarshalAs(UnmanagedType.LPStruct)]
Guid category,
[In, MarshalAs(UnmanagedType.LPStruct)]
Guid mediaType,
[In, MarshalAs(UnmanagedType.IUnknown)]
object source,
[In] IBaseFilter compressor,
[In] IBaseFilter renderer
);
@@ -114,9 +124,12 @@ namespace VAR.Toolbox.Code.DirectShow
///
[PreserveSig]
int ControlStream(
[In, MarshalAs(UnmanagedType.LPStruct)] Guid category,
[In, MarshalAs(UnmanagedType.LPStruct)] Guid mediaType,
[In, MarshalAs(UnmanagedType.Interface)] IBaseFilter filter,
[In, MarshalAs(UnmanagedType.LPStruct)]
Guid category,
[In, MarshalAs(UnmanagedType.LPStruct)]
Guid mediaType,
[In, MarshalAs(UnmanagedType.Interface)]
IBaseFilter filter,
[In] long start,
[In] long stop,
[In] short startCookie,
@@ -173,13 +186,17 @@ namespace VAR.Toolbox.Code.DirectShow
///
[PreserveSig]
int FindPin(
[In, MarshalAs(UnmanagedType.IUnknown)] object source,
[In, MarshalAs(UnmanagedType.IUnknown)]
object source,
[In] PinDirection pinDirection,
[In, MarshalAs(UnmanagedType.LPStruct)] Guid category,
[In, MarshalAs(UnmanagedType.LPStruct)] Guid mediaType,
[In, MarshalAs(UnmanagedType.LPStruct)]
Guid category,
[In, MarshalAs(UnmanagedType.LPStruct)]
Guid mediaType,
[In, MarshalAs(UnmanagedType.Bool)] bool unconnected,
[In] int index,
[Out, MarshalAs(UnmanagedType.Interface)] out IPin pin
[Out, MarshalAs(UnmanagedType.Interface)]
out IPin pin
);
}
}

View File

@@ -1,6 +1,5 @@
namespace VAR.Toolbox.Code.DirectShow
{
using System;
using System.Runtime.InteropServices;
/// <summary>
@@ -25,7 +24,8 @@ namespace VAR.Toolbox.Code.DirectShow
///
[PreserveSig]
int Next([In] int cFilters,
[Out, MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 0)] IBaseFilter[] filters,
[Out, MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 0)]
IBaseFilter[] filters,
[Out] out int filtersFetched);
/// <summary>

View File

@@ -1,6 +1,5 @@
namespace VAR.Toolbox.Code.DirectShow
{
using System;
using System.Runtime.InteropServices;
/// <summary>
@@ -24,7 +23,8 @@ namespace VAR.Toolbox.Code.DirectShow
///
[PreserveSig]
int Next([In] int cPins,
[Out, MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 0)] IPin[] pins,
[Out, MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 0)]
IPin[] pins,
[Out] out int pinsFetched);
/// <summary>

View File

@@ -1,6 +1,5 @@
namespace VAR.Toolbox.Code.DirectShow
{
using System;
using System.Runtime.InteropServices;
/// <summary>
@@ -23,7 +22,8 @@ namespace VAR.Toolbox.Code.DirectShow
///
[PreserveSig]
int Load([In, MarshalAs(UnmanagedType.LPWStr)] string fileName,
[In, MarshalAs(UnmanagedType.LPStruct)] AMMediaType mediaType);
[In, MarshalAs(UnmanagedType.LPStruct)]
AMMediaType mediaType);
/// <summary>
/// Retrieves the current file.
@@ -36,6 +36,7 @@ namespace VAR.Toolbox.Code.DirectShow
///
[PreserveSig]
int GetCurFile([Out, MarshalAs(UnmanagedType.LPWStr)] out string fileName,
[Out, MarshalAs(UnmanagedType.LPStruct)] AMMediaType mediaType);
[Out, MarshalAs(UnmanagedType.LPStruct)]
AMMediaType mediaType);
}
}

View File

@@ -70,7 +70,9 @@ namespace VAR.Toolbox.Code.DirectShow
/// <returns>Return's <b>HRESULT</b> error code.</returns>
///
[PreserveSig]
int ConnectDirect([In] IPin pinOut, [In] IPin pinIn, [In, MarshalAs(UnmanagedType.LPStruct)] AMMediaType mediaType);
int ConnectDirect([In] IPin pinOut, [In] IPin pinIn,
[In, MarshalAs(UnmanagedType.LPStruct)]
AMMediaType mediaType);
/// <summary>
/// Breaks the existing pin connection and reconnects it to the same pin.

View File

@@ -73,7 +73,9 @@ namespace VAR.Toolbox.Code.DirectShow
/// <returns>Return's <b>HRESULT</b> error code.</returns>
///
[PreserveSig]
int ConnectDirect([In] IPin pinOut, [In] IPin pinIn, [In, MarshalAs(UnmanagedType.LPStruct)] AMMediaType mediaType);
int ConnectDirect([In] IPin pinOut, [In] IPin pinIn,
[In, MarshalAs(UnmanagedType.LPStruct)]
AMMediaType mediaType);
/// <summary>
/// Breaks the existing pin connection and reconnects it to the same pin.
@@ -226,7 +228,8 @@ namespace VAR.Toolbox.Code.DirectShow
[PreserveSig]
int ReconnectEx(
[In] IPin pin,
[In, MarshalAs(UnmanagedType.LPStruct)] AMMediaType mediaType
[In, MarshalAs(UnmanagedType.LPStruct)]
AMMediaType mediaType
);
/// <summary>
@@ -245,6 +248,5 @@ namespace VAR.Toolbox.Code.DirectShow
[In] int flags,
[In] IntPtr context
);
}
}

View File

@@ -71,7 +71,9 @@ namespace VAR.Toolbox.Code.DirectShow
/// <returns>Return's <b>HRESULT</b> error code.</returns>
///
[PreserveSig]
int ConnectDirect([In] IPin pinOut, [In] IPin pinIn, [In, MarshalAs(UnmanagedType.LPStruct)] AMMediaType mediaType);
int ConnectDirect([In] IPin pinOut, [In] IPin pinIn,
[In, MarshalAs(UnmanagedType.LPStruct)]
AMMediaType mediaType);
/// <summary>
/// Breaks the existing pin connection and reconnects it to the same pin.

View File

@@ -1,8 +1,9 @@
#pragma warning disable IDE1006
using System.Runtime.InteropServices;
namespace VAR.Toolbox.Code.DirectShow
{
using System;
using System.Runtime.InteropServices;
/// <summary>
/// The interface provides methods for controlling the flow of data through the filter graph.
/// It includes methods for running, pausing, and stopping the graph.
@@ -45,7 +46,7 @@ namespace VAR.Toolbox.Code.DirectShow
/// </summary>
///
/// <param name="timeout">Duration of the time-out, in milliseconds, or INFINITE to specify an infinite time-out.</param>
/// <param name="filterState">Ìariable that receives a member of the <b>FILTER_STATE</b> enumeration.</param>
/// <param name="filterState">Variable that receives a member of the <b>FILTER_STATE</b> enumeration.</param>
///
/// <returns>Return's <b>HRESULT</b> error code.</returns>
///
@@ -85,7 +86,8 @@ namespace VAR.Toolbox.Code.DirectShow
///
[PreserveSig]
int get_FilterCollection(
[Out, MarshalAs(UnmanagedType.IDispatch)] out object collection);
[Out, MarshalAs(UnmanagedType.IDispatch)]
out object collection);
/// <summary>
/// Retrieves a collection of all the filters listed in the registry.
@@ -97,7 +99,8 @@ namespace VAR.Toolbox.Code.DirectShow
///
[PreserveSig]
int get_RegFilterCollection(
[Out, MarshalAs(UnmanagedType.IDispatch)] out object collection);
[Out, MarshalAs(UnmanagedType.IDispatch)]
out object collection);
/// <summary>
/// Pauses the filter graph, allowing filters to queue data, and then stops the filter graph.

View File

@@ -34,7 +34,8 @@
/// <returns>Return's <b>HRESULT</b> error code.</returns>
///
[PreserveSig]
int GetEvent([Out, MarshalAs(UnmanagedType.I4)] out DsEvCode lEventCode, [Out] out IntPtr lParam1, [Out] out IntPtr lParam2, int msTimeout);
int GetEvent([Out, MarshalAs(UnmanagedType.I4)] out DsEvCode lEventCode, [Out] out IntPtr lParam1,
[Out] out IntPtr lParam2, int msTimeout);
/// <summary>
/// Waits for the filter graph to render all available data.
@@ -85,14 +86,14 @@
/// Registers a window to process event notifications.
/// </summary>
///
/// <param name="hwnd">Handle to the window, or <see cref="IntPtr.Zero"/> to stop receiving event messages.</param>
/// <param name="hWnd">Handle to the window, or <see cref="IntPtr.Zero"/> to stop receiving event messages.</param>
/// <param name="lMsg">Window message to be passed as the notification.</param>
/// <param name="lInstanceData">Value to be passed as the <i>lParam</i> parameter for the <i>lMsg</i> message.</param>
///
/// <returns>Return's <b>HRESULT</b> error code.</returns>
///
[PreserveSig]
int SetNotifyWindow(IntPtr hwnd, int lMsg, IntPtr lInstanceData);
int SetNotifyWindow(IntPtr hWnd, int lMsg, IntPtr lInstanceData);
/// <summary>
/// Enables or disables event notifications.

View File

@@ -1,3 +1,5 @@
// ReSharper disable IdentifierTypo
namespace VAR.Toolbox.Code.DirectShow
{
using System;
@@ -88,4 +90,3 @@ namespace VAR.Toolbox.Code.DirectShow
int GetSyncSource([Out] out IReferenceClock pClock);
}
}

View File

@@ -26,7 +26,8 @@ namespace VAR.Toolbox.Code.DirectShow
[PreserveSig]
int Read(
[In, MarshalAs(UnmanagedType.LPWStr)] string propertyName,
[In, Out, MarshalAs(UnmanagedType.Struct)] ref object pVar,
[In, Out, MarshalAs(UnmanagedType.Struct)]
ref object pVar,
[In] IntPtr pErrorLog);
/// <summary>

View File

@@ -1,3 +1,6 @@
// ReSharper disable CommentTypo
// ReSharper disable IdentifierTypo
namespace VAR.Toolbox.Code.DirectShow
{
using System;

View File

@@ -25,7 +25,7 @@ namespace VAR.Toolbox.Code.DirectShow
int SampleCB(double sampleTime, IntPtr sample);
/// <summary>
/// Callback method that receives a pointer to the sample bufferþ
/// Callback method that receives a pointer to the sample buffer
/// </summary>
///
/// <param name="sampleTime">Starting time of the sample, in seconds.</param>

View File

@@ -1,6 +1,7 @@
// ReSharper disable CommentTypo
namespace VAR.Toolbox.Code.DirectShow
{
using System;
using System.Runtime.InteropServices;
/// <summary>

View File

@@ -1,8 +1,10 @@
#pragma warning disable IDE1006
using System;
using System.Runtime.InteropServices;
namespace VAR.Toolbox.Code.DirectShow
{
using System;
using System.Runtime.InteropServices;
/// <summary>
/// The interface sets properties on the video window.
/// </summary>
@@ -93,7 +95,7 @@ namespace VAR.Toolbox.Code.DirectShow
/// Queries whether the video renderer automatically shows the video window when it receives video data.
/// </summary>
///
/// <param name="autoShow">REceives window auto show flag.</param>
/// <param name="autoShow">Receives window auto show flag.</param>
///
/// <returns>Return's <b>HRESULT</b> error code.</returns>
///
@@ -255,7 +257,7 @@ namespace VAR.Toolbox.Code.DirectShow
int get_Height(out int height);
/// <summary>
/// Specifies a parent window for the video windowþ
/// Specifies a parent window for the video window
/// </summary>
///
/// <param name="owner">Specifies a handle to the parent window.</param>
@@ -266,7 +268,7 @@ namespace VAR.Toolbox.Code.DirectShow
int put_Owner(IntPtr owner);
/// <summary>
/// Retrieves the video window's parent window, if anyþ
/// Retrieves the video window's parent window, if any
/// </summary>
///
/// <param name="owner">Parent window's handle.</param>
@@ -358,7 +360,7 @@ namespace VAR.Toolbox.Code.DirectShow
/// Forwards a message to the video window.
/// </summary>
///
/// <param name="hwnd">Handle to the window.</param>
/// <param name="hWnd">Handle to the window.</param>
/// <param name="msg">Specifies the message.</param>
/// <param name="wParam">Message parameter.</param>
/// <param name="lParam">Message parameter.</param>
@@ -366,10 +368,10 @@ namespace VAR.Toolbox.Code.DirectShow
/// <returns>Return's <b>HRESULT</b> error code.</returns>
///
[PreserveSig]
int NotifyOwnerMessage(IntPtr hwnd, int msg, IntPtr wParam, IntPtr lParam);
int NotifyOwnerMessage(IntPtr hWnd, int msg, IntPtr wParam, IntPtr lParam);
/// <summary>
/// Sets the position of the video windowþ
/// Sets the position of the video window
/// </summary>
///
/// <param name="left">Specifies the x-coordinate, in pixels.</param>

View File

@@ -1,4 +1,6 @@
namespace VAR.Toolbox.Code.DirectShow
// ReSharper disable CommentTypo
namespace VAR.Toolbox.Code.DirectShow
{
/// <summary>
/// Specifies the physical type of pin (audio or video).
@@ -10,62 +12,77 @@
/// connection type should not be changed (input) or was not determined (output).
/// </summary>
Default = 0,
/// <summary>
/// Specifies a tuner pin for video.
/// </summary>
VideoTuner = 1,
/// <summary>
/// Specifies a composite pin for video.
/// </summary>
VideoComposite,
/// <summary>
/// Specifies an S-Video (Y/C video) pin.
/// </summary>
VideoSVideo,
/// <summary>
/// Specifies an RGB pin for video.
/// </summary>
VideoRGB,
/// <summary>
/// Specifies a YRYBY (Y, RY, BY) pin for video.
/// </summary>
VideoYRYBY,
/// <summary>
/// Specifies a serial digital pin for video.
/// </summary>
VideoSerialDigital,
/// <summary>
/// Specifies a parallel digital pin for video.
/// </summary>
VideoParallelDigital,
/// <summary>
/// Specifies a SCSI (Small Computer System Interface) pin for video.
/// </summary>
VideoSCSI,
/// <summary>
/// Specifies an AUX (auxiliary) pin for video.
/// </summary>
VideoAUX,
/// <summary>
/// Specifies an IEEE 1394 pin for video.
/// </summary>
Video1394,
/// <summary>
/// Specifies a USB (Universal Serial Bus) pin for video.
/// </summary>
VideoUSB,
/// <summary>
/// Specifies a video decoder pin.
/// </summary>
VideoDecoder,
/// <summary>
/// Specifies a video encoder pin.
/// </summary>
VideoEncoder,
/// <summary>
/// Specifies a SCART (Peritel) pin for video.
/// </summary>
VideoSCART,
/// <summary>
/// Not used.
/// </summary>
@@ -75,38 +92,47 @@
/// Specifies a tuner pin for audio.
/// </summary>
AudioTuner = 4096,
/// <summary>
/// Specifies a line pin for audio.
/// </summary>
AudioLine,
/// <summary>
/// Specifies a microphone pin.
/// </summary>
AudioMic,
/// <summary>
/// Specifies an AES/EBU (Audio Engineering Society/European Broadcast Union) digital pin for audio.
/// </summary>
AudioAESDigital,
/// <summary>
/// Specifies an S/PDIF (Sony/Philips Digital Interface Format) digital pin for audio.
/// </summary>
AudioSPDIFDigital,
/// <summary>
/// Specifies a SCSI pin for audio.
/// </summary>
AudioSCSI,
/// <summary>
/// Specifies an AUX pin for audio.
/// </summary>
AudioAUX,
/// <summary>
/// Specifies an IEEE 1394 pin for audio.
/// </summary>
Audio1394,
/// <summary>
/// Specifies a USB pin for audio.
/// </summary>
AudioUSB,
/// <summary>
/// Specifies an audio decoder pin.
/// </summary>

View File

@@ -1,3 +1,7 @@
// ReSharper disable IdentifierTypo
// ReSharper disable CommentTypo
// ReSharper disable InconsistentNaming
namespace VAR.Toolbox.Code.DirectShow
{
using System;
@@ -47,14 +51,12 @@ namespace VAR.Toolbox.Code.DirectShow
/// <summary>
/// If <b>true</b>, samples are of a fixed size.
/// </summary>
[MarshalAs(UnmanagedType.Bool)]
public bool FixedSizeSamples = true;
[MarshalAs(UnmanagedType.Bool)] public bool FixedSizeSamples = true;
/// <summary>
/// If <b>true</b>, samples are compressed using temporal (interframe) compression.
/// </summary>
[MarshalAs(UnmanagedType.Bool)]
public bool TemporalCompression;
[MarshalAs(UnmanagedType.Bool)] public bool TemporalCompression;
/// <summary>
/// Size of the sample in bytes. For compressed data, the value can be zero.
@@ -429,6 +431,7 @@ namespace VAR.Toolbox.Code.DirectShow
[Flags, ComVisible(false)]
internal enum AnalogVideoStandard
{
// ReSharper disable InconsistentNaming
None = 0x00000000, // This is a digital sensor
NTSC_M = 0x00000001, // 75 IRE Setup
NTSC_M_J = 0x00000002, // Japan, 0 IRE Setup
@@ -449,7 +452,9 @@ namespace VAR.Toolbox.Code.DirectShow
SECAM_K1 = 0x00020000,
SECAM_L = 0x00040000,
SECAM_L1 = 0x00080000,
PAL_N_COMBO = 0x00100000 // Argentina
// ReSharper restore InconsistentNaming
}
[Flags, ComVisible(false)]

View File

@@ -1,7 +1,9 @@
#pragma warning disable IDE0018
using System.Runtime.InteropServices;
namespace VAR.Toolbox.Code.DirectShow
{
using System.Runtime.InteropServices;
/// <summary>
/// Some miscellaneous functions.
/// </summary>
@@ -18,24 +20,20 @@ namespace VAR.Toolbox.Code.DirectShow
///
/// <returns>Returns filter's pin.</returns>
///
public static IPin GetPin(IBaseFilter filter, PinDirection dir, int num)
private static IPin GetPin(IBaseFilter filter, PinDirection dir, int num)
{
IPin[] pin = new IPin[1];
IEnumPins pinsEnum = null;
// enum filter pins
if (filter.EnumPins(out pinsEnum) == 0)
if (filter.EnumPins(out IEnumPins pinsEnum) == 0)
{
PinDirection pinDir;
int n;
try
{
// get next pin
while (pinsEnum.Next(1, pin, out n) == 0)
while (pinsEnum.Next(1, pin, out int _) == 0)
{
// query pin`s direction
pin[0].QueryDirection(out pinDir);
pin[0].QueryDirection(out PinDirection pinDir);
if (pinDir == dir)
{
@@ -53,6 +51,7 @@ namespace VAR.Toolbox.Code.DirectShow
Marshal.ReleaseComObject(pinsEnum);
}
}
return null;
}

View File

@@ -1,3 +1,8 @@
// ReSharper disable CommentTypo
// ReSharper disable IdentifierTypo
// ReSharper disable InconsistentNaming
namespace VAR.Toolbox.Code.DirectShow
{
using System;
@@ -7,7 +12,7 @@ namespace VAR.Toolbox.Code.DirectShow
/// DirectShow class IDs.
/// </summary>
[ComVisible(false)]
static internal class Clsid
internal static class Clsid
{
/// <summary>
/// System device enumerator.
@@ -57,7 +62,6 @@ namespace VAR.Toolbox.Code.DirectShow
public static readonly Guid NullRenderer =
new Guid(0xC1F400A4, 0x3F08, 0x11d3, 0x9F, 0x0B, 0x00, 0x60, 0x08, 0x03, 0x9E, 0x37);
}
/// <summary>
@@ -65,7 +69,7 @@ namespace VAR.Toolbox.Code.DirectShow
/// </summary>
///
[ComVisible(false)]
static internal class FormatType
internal static class FormatType
{
/// <summary>
/// VideoInfo.
@@ -91,7 +95,7 @@ namespace VAR.Toolbox.Code.DirectShow
/// </summary>
///
[ComVisible(false)]
static internal class MediaType
internal static class MediaType
{
/// <summary>
/// Video.
@@ -144,7 +148,7 @@ namespace VAR.Toolbox.Code.DirectShow
/// </summary>
///
[ComVisible(false)]
static internal class MediaSubType
internal static class MediaSubType
{
/// <summary>
/// YUY2 (packed 4:2:2).
@@ -260,7 +264,7 @@ namespace VAR.Toolbox.Code.DirectShow
/// </summary>
///
[ComVisible(false)]
static internal class PinCategory
internal static class PinCategory
{
/// <summary>
/// Capture pin.
@@ -279,7 +283,6 @@ namespace VAR.Toolbox.Code.DirectShow
///
public static readonly Guid Preview =
new Guid(0xfb6c4282, 0x0353, 0x11d1, 0x90, 0x5f, 0x00, 0x00, 0xc0, 0xcc, 0x16, 0xba);
}
/// <summary>

View File

@@ -0,0 +1,40 @@
using System;
using System.Collections.Generic;
namespace VAR.Toolbox.Code
{
public static class EventDispatcher
{
private static List<IEventListener> _eventListeners;
private static IEnumerable<IEventListener> GetEventListeners()
{
if (_eventListeners != null)
{
return _eventListeners;
}
Type iEventListener = typeof(IEventListener);
IEnumerable<Type> eventListeners = ReflectionUtils.GetTypesOfInterface(iEventListener);
_eventListeners = new List<IEventListener>();
foreach (Type eventListener in eventListeners)
{
if (Activator.CreateInstance(eventListener) is IEventListener eventListenerInstance)
{
_eventListeners.Add(eventListenerInstance);
}
}
return _eventListeners;
}
public static void EmitEvent(string eventName, object eventData)
{
IEnumerable<IEventListener> eventListeners = GetEventListeners();
foreach (IEventListener eventListener in eventListeners)
{
eventListener.ProcessEvent(eventName, eventData);
}
}
}
}

View File

@@ -0,0 +1,121 @@
using System;
using System.Collections.Generic;
using System.Security.Cryptography;
using System.Windows.Forms;
using VAR.Toolbox.Code.Windows;
namespace VAR.Toolbox.Code
{
public class GlobalKeyboardHook
{
#region Declarations
private bool _capturing = false;
private bool _captureAll = false;
/// <summary>
/// The collections of keys to watch for
/// </summary>
private readonly List<Keys> _hookedKeys = new List<Keys>();
/// <summary>
/// Handle to the hook, need this to unhook and call the next hook
/// </summary>
private IntPtr _hHook = IntPtr.Zero;
#endregion Declarations
#region Private methods
/// <summary>
/// The callback for the keyboard hook
/// </summary>
/// <param name="code">The hook code, if it isn't >= 0, the function shouldn't do anyting</param>
/// <param name="wParam">The event type</param>
/// <param name="lParam">The keyhook event information</param>
/// <returns></returns>
private int HookProc(int code, int wParam, ref User32.keyboardHookStruct lParam) {
try
{
if (code >= 0)
{
Keys key = (Keys)lParam.vkCode;
if (_hookedKeys.Contains(key) || _captureAll)
{
KeyEventArgs kea = new KeyEventArgs(key);
if ((wParam == User32.WM_KEYDOWN || wParam == User32.WM_SYSKEYDOWN) && (KeyDown != null))
{
KeyDown(this, kea);
}
else if ((wParam == User32.WM_KEYUP || wParam == User32.WM_SYSKEYUP) && (KeyUp != null))
{
KeyUp(this, kea);
}
if (kea.Handled)
return 1;
}
}
}
catch (Exception)
{
// ignored
}
return User32.CallNextHookEx(_hHook, code, wParam, ref lParam);
}
#endregion Private methods
#region Public events
/// <summary>
/// Occurs when one of the hooked keys is pressed
/// </summary>
public event KeyEventHandler KeyDown;
/// <summary>
/// Occurs when one of the hooked keys is released
/// </summary>
public event KeyEventHandler KeyUp;
#endregion Public events
#region Public methods
public void Start(bool all = false)
{
if (_capturing) { return; }
_captureAll = all;
//IntPtr hInstance = User32.LoadLibrary("User32");
//_hHook = User32.SetWindowsHookEx(User32.WH_KEYBOARD_LL, HookProc, hInstance, 0);
IntPtr iModule = System.Runtime.InteropServices.Marshal.GetHINSTANCE(
System.Reflection.Assembly.GetExecutingAssembly().GetModules()[0]);
_hHook = User32.SetWindowsHookEx(User32.WH_KEYBOARD_LL, HookProc, iModule, 0);
_capturing = true;
}
public void Stop()
{
if (_capturing == false) { return; }
User32.UnhookWindowsHookEx(_hHook);
_capturing = false;
}
public bool IsCapturing()
{
return _capturing;
}
public void AddHook(Keys key)
{
_hookedKeys.Add(key);
}
#endregion Public methods
}
}

View File

@@ -3,17 +3,20 @@ using System.Text;
namespace VAR.Toolbox.Code
{
public class HexUtils
public static class HexUtils
{
public static byte[] HexStringToBytes(string input)
{
int[] hexValues = new int[] {
int[] hexValues = new int[]
{
0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x00,
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F };
0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F
};
if (input.Length % 2 == 1)
{
throw new Exception("Unenven number of hex digits");
throw new Exception("Uneven number of hex digits");
}
byte[] bytes = new byte[input.Length / 2];
int count = input.Length;
for (int x = 0, i = 0; i < count; i += 2, x += 1)
@@ -38,6 +41,7 @@ namespace VAR.Toolbox.Code
sbOutput.Append(HexAlphabet[(b >> 4)]);
sbOutput.Append(HexAlphabet[(b & 0xF)]);
}
return sbOutput.ToString();
}
}

View File

@@ -0,0 +1,7 @@
namespace VAR.Toolbox.Code
{
public interface IEventListener
{
void ProcessEvent(string eventName, object eventData);
}
}

View File

@@ -2,6 +2,7 @@
{
public interface IOutputHandler
{
void OutputLine(string line);
void Clean();
void AddLine(string line, object data = null);
}
}

View File

@@ -1,7 +0,0 @@
namespace VAR.Toolbox.Code
{
public interface IProxyCmdExecutor
{
bool ExecuteCmd(string cmd, IOutputHandler outputHandler);
}
}

View File

@@ -3,22 +3,21 @@ using System.IO;
namespace VAR.Toolbox.Code
{
public class Logger
public static class Logger
{
/// <summary>
/// Obtiene el StreamWritter de salida
/// Obtiene el StreamWriter de salida
/// </summary>
/// <returns></returns>
private static StreamWriter GetOutputStreamWritter()
private static StreamWriter GetOutputStreamWriter()
{
try
{
string location = System.Reflection.Assembly.GetEntryAssembly().Location;
string location = System.Reflection.Assembly.GetEntryAssembly()?.Location;
string path = Path.GetDirectoryName(location);
string filenameWithoutExtension = Path.GetFileNameWithoutExtension(location);
string fileOut = string.Format("{0}/{1}.{2}.txt", path, filenameWithoutExtension,
DateTime.UtcNow.ToString("yyyy-MM"));
string fileOut = $"{path}/{filenameWithoutExtension}.{DateTime.UtcNow:yyyy-MM}.txt";
return File.AppendText(fileOut);
}
catch (Exception)
@@ -28,10 +27,10 @@ namespace VAR.Toolbox.Code
}
/// <summary>
/// Cierra el StreamWritter de salida
/// Cierra el StreamWriter de salida
/// </summary>
/// <param name="stream">The stream.</param>
private static void CloseOutputStreamWritter(StreamWriter stream)
private static void CloseOutputStreamWriter(StreamWriter stream)
{
if (stream != null)
{
@@ -50,6 +49,7 @@ namespace VAR.Toolbox.Code
{
stream.WriteLine(line);
}
Console.Out.WriteLine(line);
}
@@ -57,60 +57,70 @@ namespace VAR.Toolbox.Code
/// Logea el marcador
/// </summary>
/// <param name="text">The text.</param>
public static void Marker(String text)
public static void Marker(string text)
{
try
{
StreamWriter outStream = GetOutputStreamWritter();
StreamWriter outStream = GetOutputStreamWriter();
WriteLine(outStream, string.Empty);
WriteLine(outStream, String.Format("---------------------------- {0} -----------------------", text));
WriteLine(outStream, String.Format("\\- Date: {0}", DateTime.UtcNow.ToString("s")));
WriteLine(outStream, $"---------------------------- {text} -----------------------");
WriteLine(outStream, $"\\- Date: {DateTime.UtcNow:s}");
WriteLine(outStream, string.Empty);
CloseOutputStreamWritter(outStream);
CloseOutputStreamWriter(outStream);
}
catch (Exception)
{
/* Nom Nom Nom */
}
catch (Exception) { /* Nom Nom Nom */}
}
/// <summary>
/// Logea el texto especificado
/// </summary>
/// <param name="text">The text.</param>
public static void Log(String text)
public static void Log(string text)
{
try
{
StreamWriter outStream = GetOutputStreamWritter();
WriteLine(outStream, String.Format("{0} -- {1}", DateTime.UtcNow.ToString("s"), text));
CloseOutputStreamWritter(outStream);
StreamWriter outStream = GetOutputStreamWriter();
WriteLine(outStream, $"{DateTime.UtcNow:s} -- {text}");
CloseOutputStreamWriter(outStream);
}
catch (Exception)
{
/* Nom Nom Nom */
}
catch (Exception) { /* Nom Nom Nom */}
}
/// <summary>
/// Logea una excepcion
/// Logea una excepción
/// </summary>
/// <param name="ex">The Exception.</param>
public static void Log(Exception ex)
{
try
{
StreamWriter outStream = GetOutputStreamWritter();
StreamWriter outStream = GetOutputStreamWriter();
WriteLine(outStream, string.Empty);
WriteLine(outStream, String.Format("!!!!!!!!!!!!!!!!!!!!!!!!!!!! {0} !!!!!!!!!!!!!!!!!!!!!!!", "Exception"));
WriteLine(outStream, String.Format("\\- Date: {0}", DateTime.UtcNow.ToString("s")));
WriteLine(outStream,
"!!!!!!!!!!!!!!!!!!!!!!!!!!!! Exception !!!!!!!!!!!!!!!!!!!!!!!");
WriteLine(outStream, $"\\- Date: {DateTime.UtcNow:s}");
WriteLine(outStream, string.Empty);
Exception exAux = ex;
while (exAux != null)
{
WriteLine(outStream, String.Format("Message: {0}", exAux.Message));
WriteLine(outStream, String.Format("Stacktrace: {0}", exAux.StackTrace));
WriteLine(outStream, $"Message: {exAux.Message}");
WriteLine(outStream, $"Stacktrace: {exAux.StackTrace}");
exAux = exAux.InnerException;
}
CloseOutputStreamWritter(outStream);
}
catch (Exception) { /* Nom Nom Nom */}
}
CloseOutputStreamWriter(outStream);
}
catch (Exception)
{
/* Nom Nom Nom */
}
}
}
}

View File

@@ -4,16 +4,18 @@ using VAR.Toolbox.Code.Windows;
namespace VAR.Toolbox.Code
{
public class Mouse
public static class Mouse
{
public static void Move(int dx, int dy)
{
User32.INPUT input = new User32.INPUT();
input.Type = User32.INPUT_MOUSE;
User32.INPUT input = new User32.INPUT
{
Type = User32.INPUT_MOUSE
};
input.Data.Mouse.X = dx;
input.Data.Mouse.Y = dy;
input.Data.Mouse.Flags = User32.MOUSEEVENTF_MOVE;
User32.INPUT[] inputs = new User32.INPUT[] { input };
User32.INPUT[] inputs = new[] { input };
if (User32.SendInput(1, inputs, Marshal.SizeOf(typeof(User32.INPUT))) == 0)
throw new Exception();
}
@@ -27,23 +29,28 @@ namespace VAR.Toolbox.Code
public static void SetButton(MouseButtons button, bool down)
{
User32.INPUT input = new User32.INPUT();
input.Type = User32.INPUT_MOUSE;
User32.INPUT input = new User32.INPUT
{
Type = User32.INPUT_MOUSE
};
input.Data.Mouse.X = 0;
input.Data.Mouse.Y = 0;
if (button == MouseButtons.Left)
{
input.Data.Mouse.Flags = down ? User32.MOUSEEVENTF_LEFTDOWN : User32.MOUSEEVENTF_LEFTUP;
}
if (button == MouseButtons.Middle)
{
input.Data.Mouse.Flags = down ? User32.MOUSEEVENTF_MIDDLEDOWN : User32.MOUSEEVENTF_MIDDLEUP;
}
if (button == MouseButtons.Right)
{
input.Data.Mouse.Flags = down ? User32.MOUSEEVENTF_RIGHTDOWN : User32.MOUSEEVENTF_RIGHTUP;
}
User32.INPUT[] inputs = new User32.INPUT[] { input };
User32.INPUT[] inputs = new[] { input };
if (User32.SendInput(1, inputs, Marshal.SizeOf(typeof(User32.INPUT))) == 0)
throw new Exception();
}
@@ -57,8 +64,7 @@ namespace VAR.Toolbox.Code
public static void GetPosition(out UInt32 x, out UInt32 y)
{
User32.POINT lpPoint;
User32.GetCursorPos(out lpPoint);
User32.GetCursorPos(out User32.POINT lpPoint);
x = lpPoint.X;
y = lpPoint.Y;
}

View File

@@ -1,11 +0,0 @@
namespace VAR.Toolbox.Code
{
public class ProxyCmdExecutorDummy : IProxyCmdExecutor
{
public bool ExecuteCmd(string cmdString, IOutputHandler outputHandler)
{
outputHandler.OutputLine(string.Format("DummyExecution: {0}", cmdString));
return true;
}
}
}

View File

@@ -1,26 +0,0 @@
using System;
namespace VAR.Toolbox.Code
{
public class ProxyCmdExecutorFactory
{
public static IProxyCmdExecutor CreateFromConfig(string config)
{
if (string.IsNullOrEmpty(config) || config.StartsWith("Dummy:"))
{
return new ProxyCmdExecutorDummy();
}
if (config.StartsWith("SqlServer:"))
{
string configSqlServer = config.Substring("SqlServer:".Length);
return new ProxyCmdExecutorThroughSQLServer(configSqlServer);
}
if (config.StartsWith("WMIC:"))
{
string configWMIC = config.Substring("WMIC:".Length);
return new ProxyCmdExecutorWMIC(configWMIC);
}
throw new NotImplementedException(string.Format("Cant create IProxyCmdExecutor with this config: {0}", config));
}
}
}

View File

@@ -1,32 +0,0 @@
using System;
using System.Data.SqlClient;
namespace VAR.Toolbox.Code
{
public class ProxyCmdExecutorThroughSQLServer : IProxyCmdExecutor
{
private string _connectionString = null;
public ProxyCmdExecutorThroughSQLServer(string connectionString)
{
_connectionString = connectionString;
}
public bool ExecuteCmd(string cmdString, IOutputHandler outputHandler)
{
SqlConnection cnx = new SqlConnection(_connectionString);
SqlCommand cmd = cnx.CreateCommand();
cmd.CommandText = "exec master.dbo.xp_cmdshell @cmd";
cmd.Parameters.Add(new SqlParameter("cmd", cmdString));
cnx.Open();
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
string output = Convert.ToString(reader[0]);
outputHandler.OutputLine(output);
}
cnx.Close();
return true;
}
}
}

View File

@@ -0,0 +1,21 @@
using System;
namespace VAR.Toolbox.Code.ProxyCmdExecutors
{
public abstract class BaseProxyCmdExecutor : IProxyCmdExecutor
{
public abstract string Name { get; }
public virtual bool Disable()
{
throw new NotImplementedException();
}
public virtual bool Enable()
{
return true;
}
public abstract bool ExecuteCmd(string cmd, IOutputHandler outputHandler);
}
}

View File

@@ -0,0 +1,11 @@
namespace VAR.Toolbox.Code.ProxyCmdExecutors
{
public interface IProxyCmdExecutor : INamed
{
bool ExecuteCmd(string cmd, IOutputHandler outputHandler);
bool Enable();
bool Disable();
}
}

View File

@@ -0,0 +1,24 @@
namespace VAR.Toolbox.Code.ProxyCmdExecutors
{
public class ProxyCmdExecutorDummy : BaseProxyCmdExecutor
{
private readonly string _config;
public override string Name => "Dummy";
public ProxyCmdExecutorDummy(string config)
{
if (config == null)
{
throw new System.ArgumentNullException(nameof(config));
}
_config = config;
}
public override bool ExecuteCmd(string cmdString, IOutputHandler outputHandler)
{
outputHandler.AddLine($"DummyExecution: {cmdString} | {_config}");
return true;
}
}
}

View File

@@ -0,0 +1,4 @@
namespace VAR.Toolbox.Code.ProxyCmdExecutors
{
public abstract class ProxyCmdExecutorFactory : BaseFactory<IProxyCmdExecutor> { }
}

View File

@@ -0,0 +1,83 @@
using System;
using System.Data.SqlClient;
namespace VAR.Toolbox.Code.ProxyCmdExecutors
{
public class ProxyCmdExecutorThroughSQLServer : BaseProxyCmdExecutor
{
public override string Name => "SqlServer";
private readonly string _connectionString;
public ProxyCmdExecutorThroughSQLServer(string connectionString)
{
_connectionString = connectionString;
}
public override bool ExecuteCmd(string cmdString, IOutputHandler outputHandler)
{
SqlConnection cnx = new SqlConnection(_connectionString);
SqlCommand cmd = cnx.CreateCommand();
cmd.CommandText = "exec master.dbo.xp_cmdshell @cmd";
cmd.Parameters.Add(new SqlParameter("cmd", cmdString));
cnx.Open();
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
string output = Convert.ToString(reader[0]);
outputHandler.AddLine(output);
}
cnx.Close();
return true;
}
public override bool Enable()
{
try
{
SqlConnection cnx = new SqlConnection(_connectionString);
SqlCommand cmd = cnx.CreateCommand();
cmd.CommandText = @"
EXEC sp_configure 'show advanced options', '1'
RECONFIGURE
EXEC sp_configure 'xp_cmdshell', '1'
RECONFIGURE
";
cnx.Open();
cmd.ExecuteNonQuery();
cnx.Close();
return true;
}
catch (Exception ex)
{
Logger.Log(ex);
return false;
}
}
public override bool Disable()
{
try
{
SqlConnection cnx = new SqlConnection(_connectionString);
SqlCommand cmd = cnx.CreateCommand();
cmd.CommandText = @"
EXEC sp_configure 'show advanced options', '1'
RECONFIGURE
EXEC sp_configure 'xp_cmdshell', '0'
RECONFIGURE
";
cnx.Open();
cmd.ExecuteNonQuery();
cnx.Close();
return true;
}
catch (Exception ex)
{
Logger.Log(ex);
return false;
}
}
}
}

View File

@@ -1,19 +1,22 @@
using System.Diagnostics;
namespace VAR.Toolbox.Code
namespace VAR.Toolbox.Code.ProxyCmdExecutors
{
public class ProxyCmdExecutorWMIC : IProxyCmdExecutor
public class ProxyCmdExecutorWMIC : BaseProxyCmdExecutor
{
private string _configWMIC;
public override string Name => "WMIC";
private readonly string _configWMIC;
public ProxyCmdExecutorWMIC(string configWMIC)
{
_configWMIC = configWMIC;
}
public bool ExecuteCmd(string cmd, IOutputHandler outputHandler)
public override bool ExecuteCmd(string cmd, IOutputHandler outputHandler)
{
string parameters = string.Format(" /node:\"{0}\" process call create \"cmd.exe /c \\\"{1}\\\"\"", _configWMIC.Replace("\"", "\\\""), cmd.Replace("\"", "\\\""));
string parameters =
$" /node:\"{_configWMIC.Replace("\"", "\\\"")}\" process call create \"cmd.exe /c \\\"{cmd.Replace("\"", "\\\"")}\\\"\"";
Process process = new Process();
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardOutput = true;

View File

@@ -0,0 +1,21 @@
using System;
using System.Collections.Generic;
using System.Linq;
namespace VAR.Toolbox.Code
{
public static class ReflectionUtils
{
public static IEnumerable<Type> GetTypesOfInterface(Type interfaceType)
{
return AppDomain.CurrentDomain
.GetAssemblies()
.SelectMany(x => x.GetTypes())
.Where(x =>
x.IsAbstract == false &&
x.IsInterface == false &&
interfaceType.IsAssignableFrom(x) &&
true);
}
}
}

View File

@@ -6,27 +6,47 @@ using VAR.Toolbox.Code.Windows;
namespace VAR.Toolbox.Code
{
public class Screenshooter
public static class Screenshoter
{
public static Bitmap CaptureScreen(Bitmap bmp = null)
public static Bitmap CaptureControl(Control ctrl, Bitmap bmp = null)
{
// Determine the size of the "virtual screen", which includes all monitors.
int screenLeft = SystemInformation.VirtualScreen.Left;
int screenTop = SystemInformation.VirtualScreen.Top;
int screenWidth = SystemInformation.VirtualScreen.Width;
int screenHeight = SystemInformation.VirtualScreen.Height;
if (ctrl == null) { return bmp; }
// Create a bitmap of the appropriate size to receive the screenshot.
if (bmp == null || bmp?.Width != screenWidth || bmp?.Height != screenHeight)
{
bmp = new Bitmap(screenWidth, screenHeight);
Point picCapturerOrigin = ctrl.PointToScreen(new Point(0, 0));
bmp = CaptureScreen(bmp, picCapturerOrigin.X, picCapturerOrigin.Y, ctrl.Width, ctrl.Height);
return bmp;
}
public static Bitmap CaptureScreen(Bitmap bmp = null, int? left = null, int? top = null, int? width = null,
int? height = null)
{
if (width <= 0 || height <= 0) { return bmp; }
// Determine the size of the "virtual screen", which includes all monitors.
left = left ?? SystemInformation.VirtualScreen.Left;
top = top ?? SystemInformation.VirtualScreen.Top;
width = width ?? SystemInformation.VirtualScreen.Width;
height = height ?? SystemInformation.VirtualScreen.Height;
// Create a bitmap of the appropriate size to receive the screenshot.
if (bmp == null || bmp.Width != width || bmp.Height != height)
{
bmp = new Bitmap((int)width, (int)height);
}
try
{
// Draw the screenshot into our bitmap.
using (Graphics g = Graphics.FromImage(bmp))
{
g.CopyFromScreen(screenLeft, screenTop, 0, 0, bmp.Size);
g.CopyFromScreen((int)left, (int)top, 0, 0, bmp.Size);
}
}
catch (Exception)
{
/* Nom Nom Nom */
}
return bmp;
}
@@ -52,8 +72,8 @@ namespace VAR.Toolbox.Code
User32.GetWindowRect(handle, ref windowRect);
int left = windowRect.left;
int top = windowRect.top;
int width = windowRect.right - windowRect.left;
int height = windowRect.bottom - windowRect.top;
int width = windowRect.right - left;
int height = windowRect.bottom - top;
// create a device context we can copy to
IntPtr hdcDest = GDI32.CreateCompatibleDC(hdcSrc);
// create a bitmap we can copy it to,
@@ -76,8 +96,5 @@ namespace VAR.Toolbox.Code
return img;
}
}
}

View File

@@ -1,38 +0,0 @@
using System;
namespace VAR.Toolbox.Code
{
public class TextCoderFactory
{
public static string[] GetSupportedCoders()
{
return new string[] {
TextCoderBase64ToAscii.Name,
TextCoderBase64ToUtf8.Name,
TextCoderHexToUtf8.Name,
TextCoderHexToAscii.Name,
};
}
public static ITextCoder CreateFromName(string name)
{
if (name == TextCoderBase64ToAscii.Name)
{
return new TextCoderBase64ToAscii();
}
if (name == TextCoderBase64ToUtf8.Name)
{
return new TextCoderBase64ToUtf8();
}
if (name == TextCoderHexToUtf8.Name)
{
return new TextCoderHexToUtf8();
}
if (name == TextCoderHexToAscii.Name)
{
return new TextCoderHexToAscii();
}
throw new NotImplementedException(string.Format("Cant create ITextCoder with this name: {0}", name));
}
}
}

View File

@@ -1,6 +1,6 @@
namespace VAR.Toolbox.Code
namespace VAR.Toolbox.Code.TextCoders
{
public interface ITextCoder
public interface ITextCoder : INamed
{
bool NeedsKey { get; }

View File

@@ -1,13 +1,13 @@
using System;
using System.Text;
namespace VAR.Toolbox.Code
namespace VAR.Toolbox.Code.TextCoders
{
public class TextCoderBase64ToAscii : ITextCoder
{
public const string Name = "Base64ToAscii";
public string Name => "Base64ToAscii";
public bool NeedsKey { get { return false; } }
public bool NeedsKey => false;
public string Decode(string input, string key)
{

View File

@@ -1,13 +1,13 @@
using System;
using System.Text;
namespace VAR.Toolbox.Code
namespace VAR.Toolbox.Code.TextCoders
{
public class TextCoderBase64ToUtf8 : ITextCoder
{
public const string Name = "Base64ToUtf8";
public string Name => "Base64ToUtf8";
public bool NeedsKey { get { return false; } }
public bool NeedsKey => false;
public string Decode(string input, string key)
{

View File

@@ -0,0 +1,4 @@
namespace VAR.Toolbox.Code.TextCoders
{
public abstract class TextCoderFactory : BaseFactory<ITextCoder> { }
}

View File

@@ -1,12 +1,12 @@
using System.Text;
namespace VAR.Toolbox.Code
namespace VAR.Toolbox.Code.TextCoders
{
public class TextCoderHexToAscii : ITextCoder
{
public const string Name = "HexToAscii";
public string Name => "HexToAscii";
public bool NeedsKey { get { return false; } }
public bool NeedsKey => false;
public string Decode(string input, string key)
{
@@ -20,6 +20,5 @@ namespace VAR.Toolbox.Code
byte[] toEncodeAsBytes = Encoding.ASCII.GetBytes(input);
return HexUtils.BytesToHexString(toEncodeAsBytes);
}
}
}

View File

@@ -1,12 +1,12 @@
using System.Text;
namespace VAR.Toolbox.Code
namespace VAR.Toolbox.Code.TextCoders
{
public class TextCoderHexToUtf8 : ITextCoder
{
public const string Name = "HexToUtf8";
public string Name => "HexToUtf8";
public bool NeedsKey { get { return false; } }
public bool NeedsKey => false;
public string Decode(string input, string key)
{

View File

@@ -0,0 +1,178 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;
using System.Threading.Tasks;
namespace VAR.Toolbox.Code
{
public static class WebServicesUtils
{
private static readonly CookieContainer _cookieJar = new CookieContainer();
public static string CallApi(string urlService, string urlApiMethod, Dictionary<string, string> parameters,
object content, CookieContainer cookieJar = null, string stringContent = null,
Dictionary<string, string> customHeaders = null, string verb = "POST",
bool disableCertificateValidation = false)
{
if (urlService?.StartsWith("!") == true)
{
urlService = urlService.Substring(1);
disableCertificateValidation = true;
}
if (cookieJar == null) { cookieJar = _cookieJar; }
try
{
var sbRequestUrl = new StringBuilder();
sbRequestUrl.Append(urlService);
if (urlService != null && urlService.EndsWith("/") && urlApiMethod.StartsWith("/"))
{
sbRequestUrl.Append(urlApiMethod.Substring(1));
}
else
{
sbRequestUrl.Append(urlApiMethod);
}
if (parameters != null)
{
foreach (KeyValuePair<string, string> pair in parameters)
{
sbRequestUrl.AppendFormat("&{0}={1}", pair.Key,
pair.Value == null ? string.Empty : HttpServer.HttpUtility.UrlEncode(pair.Value));
}
}
if (sbRequestUrl.Length > 2048)
{
throw new Exception($"CallApi: Request URL longer than 2048: url: \"{sbRequestUrl}\"");
}
var http = (HttpWebRequest)WebRequest.Create(new Uri(sbRequestUrl.ToString()));
#if UNIFIKAS_COMMONS
if (disableCertificateValidation)
{
http.ServerCertificateValidationCallback =
(sender, certificate, chain, sslPolicyErrors) => { return true; };
}
#else
if (disableCertificateValidation)
{
throw new NotImplementedException("ApiHelper.CallApi: Can't disable certificate validation");
}
#endif
http.CookieContainer = cookieJar;
http.Accept = "application/json";
http.ContentType = "application/json; charset=utf-8";
http.Method = verb;
if (customHeaders != null)
{
foreach (KeyValuePair<string, string> customHeader in customHeaders)
{
http.Headers[customHeader.Key] = customHeader.Value;
}
}
if (verb == "POST")
{
string parsedContent = Json.JsonWriter.WriteObject(content);
if (string.IsNullOrEmpty(stringContent) == false)
{
parsedContent = stringContent;
}
UTF8Encoding encoding = new UTF8Encoding();
byte[] bytes = encoding.GetBytes(parsedContent);
Task<Stream> requestStreamTask = http.GetRequestStreamAsync();
requestStreamTask.Wait();
Stream requestStream = requestStreamTask.Result;
requestStream.Write(bytes, 0, bytes.Length);
requestStream.Flush();
}
Task<WebResponse> responseTask = http.GetResponseAsync();
responseTask.Wait();
WebResponse response = responseTask.Result;
var stream = response.GetResponseStream();
if (stream == null) { return null; }
var sr = new StreamReader(stream);
return sr.ReadToEnd();
}
catch (Exception ex)
{
// ReSharper disable once PossibleIntendedRethrow
throw ex;
}
}
public static string CallSoapMethod(string url, string method, Dictionary<string, object> parameters,
string namespaceUrl = "http://tempuri.org", ICredentials credentials = null)
{
// Los servicios SOAP se llaman siempre a través de HTTP.
if (url.ToLower().StartsWith("https://"))
{
url = $"http://{url.Substring("https://".Length)}";
}
// Construir petición
var sbData = new StringBuilder();
sbData.AppendFormat("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>");
sbData.AppendFormat(
"<soap:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">");
sbData.AppendFormat("<soap:Body>");
sbData.AppendFormat("<{0} xmlns=\"{1}\">", method, namespaceUrl);
foreach (KeyValuePair<string, object> parameter in parameters)
{
if (parameter.Value != null && !(parameter.Value is DBNull))
{
sbData.AppendFormat("<{0}>{1}</{0}>", parameter.Key, parameter.Value);
}
else
{
sbData.AppendFormat("<{0} i:nil=\"true\" xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\" />",
parameter.Key);
}
}
sbData.AppendFormat("</{0}>", method);
sbData.AppendFormat("</soap:Body>");
sbData.AppendFormat("</soap:Envelope>");
Console.WriteLine(sbData.ToString());
byte[] postData = Encoding.UTF8.GetBytes(sbData.ToString());
// Realizar petición
var client = new WebClient();
if (credentials != null)
{
client.Credentials = credentials;
}
client.Headers.Add("Accept", "text/xml");
client.Headers.Add("Accept-Charset", "UTF-8");
client.Headers.Add("Content-Type", "text/xml; charset=UTF-8");
client.Headers.Add("SOAPAction",
namespaceUrl.ToLower().StartsWith("http")
? $"\"{namespaceUrl}/{method}\""
: $"\"{namespaceUrl}:{method}\"");
byte[] data;
try
{
data = client.UploadData(url, "POST", postData);
}
catch (Exception ex)
{
throw new Exception($"Failure calling SoapService: URL: {url}", ex);
}
string strData = Encoding.UTF8.GetString(data);
return strData;
}
}
}

View File

@@ -1,4 +1,9 @@
using System;
#pragma warning disable IDE0018
#pragma warning disable IDE0059
// ReSharper disable SuspiciousTypeConversion.Global
// ReSharper disable ConvertToAutoProperty
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Drawing.Imaging;
@@ -7,26 +12,23 @@ using System.Runtime.InteropServices.ComTypes;
using VAR.Toolbox.Code.DirectShow;
using VAR.Toolbox.Code.Windows;
namespace VAR.Toolbox.Code
{
public class Webcam
{
#region Declarations
private IFilterGraph2 graph;
private ICaptureGraphBuilder2 capture;
private IMediaControl control;
private IBaseFilter sourceFilter;
private IBaseFilter samplegrabberfilter;
private IBaseFilter nullrenderer;
private readonly IMediaControl _control;
private readonly IBaseFilter _sourceFilter;
private readonly IBaseFilter _sampleGrabberFilter;
private readonly IBaseFilter _nullRenderer;
private Grabber grabber;
private readonly int _width;
private readonly int _height;
private readonly int _bpp;
private int width = 0;
private int height = 0;
private int bpp = 0;
private bool active = false;
private bool _active;
private static Dictionary<string, string> _deviceDescriptions;
@@ -34,11 +36,13 @@ namespace VAR.Toolbox.Code
#region Properties
public int Width { get { return width; } }
public int Height { get { return height; } }
public int BPP { get { return bpp; } }
public int Width => _width;
public bool Active { get { return active; } }
public int Height => _height;
public int BPP => _bpp;
public bool Active => _active;
#endregion Properties
@@ -46,49 +50,48 @@ namespace VAR.Toolbox.Code
public Webcam(string monikerString)
{
int result;
graph = CreateInstanceFromClsid<IFilterGraph2>(Clsid.FilterGraph);
capture = CreateInstanceFromClsid<ICaptureGraphBuilder2>(Clsid.CaptureGraphBuilder2);
control = (IMediaControl)graph;
IFilterGraph2 graph = CreateInstanceFromClsid<IFilterGraph2>(Clsid.FilterGraph);
ICaptureGraphBuilder2 capture = CreateInstanceFromClsid<ICaptureGraphBuilder2>(Clsid.CaptureGraphBuilder2);
_control = (IMediaControl)graph;
capture.SetFiltergraph((IGraphBuilder)graph);
IBindCtx bindCtx = null;
IMoniker moniker = null;
int n = 0;
if (Win32.CreateBindCtx(0, out bindCtx) != 0)
if (Win32.CreateBindCtx(0, out IBindCtx bindCtx) != 0)
{
throw new Exception("Failed to create binding context");
}
if (Win32.MkParseDisplayName(bindCtx, monikerString, ref n, out moniker) != 0)
if (Win32.MkParseDisplayName(bindCtx, monikerString, ref n, out IMoniker moniker) != 0)
{
throw new Exception("Failed to create binding moniker");
}
graph.AddSourceFilterForMoniker(moniker, bindCtx, monikerString, out sourceFilter);
graph.AddSourceFilterForMoniker(moniker, bindCtx, monikerString, out _sourceFilter);
samplegrabberfilter = CreateInstanceFromClsid<IBaseFilter>(Clsid.SampleGrabber);
graph.AddFilter(samplegrabberfilter, string.Format("SampleGrabber {0}", monikerString));
_sampleGrabberFilter = CreateInstanceFromClsid<IBaseFilter>(Clsid.SampleGrabber);
graph.AddFilter(_sampleGrabberFilter, $"SampleGrabber {monikerString}");
ISampleGrabber sampleGrabber = (ISampleGrabber)samplegrabberfilter;
ISampleGrabber sampleGrabber = (ISampleGrabber)_sampleGrabberFilter;
// Set media type
AMMediaType mediaType = new AMMediaType();
mediaType.MajorType = MediaType.Video;
mediaType.SubType = MediaSubType.RGB24;
AMMediaType mediaType = new AMMediaType
{
MajorType = MediaType.Video,
SubType = MediaSubType.RGB24
};
sampleGrabber.SetMediaType(mediaType);
grabber = new Grabber(this);
result = sampleGrabber.SetCallback(grabber, 1);
var grabber = new Grabber(this);
int result = sampleGrabber.SetCallback(grabber, 1);
if (result < 0) throw new Exception("Failure creating Webcam device");
//set the null renderer
nullrenderer = CreateInstanceFromClsid<IBaseFilter>(Clsid.NullRenderer);
graph.AddFilter(nullrenderer, string.Format("NullRenderer {0}", monikerString));
_nullRenderer = CreateInstanceFromClsid<IBaseFilter>(Clsid.NullRenderer);
graph.AddFilter(_nullRenderer, $"NullRenderer {monikerString}");
result = capture.RenderStream(PinCategory.Preview, MediaType.Video, sourceFilter, samplegrabberfilter, nullrenderer);
result = capture.RenderStream(PinCategory.Preview, MediaType.Video, _sourceFilter, _sampleGrabberFilter,
_nullRenderer);
if (result < 0) throw new Exception("Failure creating Webcam device");
AMMediaType queryMediaType = new AMMediaType();
@@ -97,14 +100,15 @@ namespace VAR.Toolbox.Code
{
if (queryMediaType.FormatType == FormatType.VideoInfo)
{
VideoInfoHeader videoInfo = (VideoInfoHeader)Marshal.PtrToStructure(queryMediaType.FormatPtr, typeof(VideoInfoHeader));
width = videoInfo.BmiHeader.Width;
height = videoInfo.BmiHeader.Height;
bpp = videoInfo.BmiHeader.BitCount;
VideoInfoHeader videoInfo =
(VideoInfoHeader)Marshal.PtrToStructure(queryMediaType.FormatPtr, typeof(VideoInfoHeader));
_width = videoInfo.BmiHeader.Width;
_height = videoInfo.BmiHeader.Height;
_bpp = videoInfo.BmiHeader.BitCount;
}
}
control.Run();
_control.Run();
Stop();
}
@@ -114,41 +118,37 @@ namespace VAR.Toolbox.Code
public void Start()
{
control.Run();
int result;
result = nullrenderer.Run(0);
_control.Run();
int result = _nullRenderer.Run(0);
if (result < 0) throw new Exception("Webcam Start failure");
result = samplegrabberfilter.Run(0);
result = _sampleGrabberFilter.Run(0);
if (result < 0) throw new Exception("Webcam Start failure");
result = sourceFilter.Run(0);
result = _sourceFilter.Run(0);
if (result < 0) throw new Exception("Webcam Start failure");
active = true;
_active = true;
}
public void Stop()
{
int result;
result = sourceFilter.Stop();
int result = _sourceFilter.Stop();
if (result < 0) throw new Exception("Webcam Stop failure");
result = samplegrabberfilter.Stop();
result = _sampleGrabberFilter.Stop();
if (result < 0) throw new Exception("Webcam Stop failure");
result = nullrenderer.Stop();
result = _nullRenderer.Stop();
if (result < 0) throw new Exception("Webcam Stop failure");
control.Stop();
active = false;
_control.Stop();
_active = false;
}
public static Dictionary<string, string> ListDevices()
{
if (_deviceDescriptions != null) { return _deviceDescriptions; }
int result;
Dictionary<string, string> devices = new Dictionary<string, string>();
ICreateDevEnum devEnum = CreateInstanceFromClsid<ICreateDevEnum>(Clsid.SystemDeviceEnum);
IEnumMoniker enumMon = null;
Guid category = FilterCategory.VideoInputDevice;
result = devEnum.CreateClassEnumerator(ref category, out enumMon, 0);
int result = devEnum.CreateClassEnumerator(ref category, out IEnumMoniker enumMon, 0);
if (result != 0)
throw new ApplicationException("No devices of the category");
@@ -162,14 +162,15 @@ namespace VAR.Toolbox.Code
break;
// Add device description
string deviceName = new String(GetMonikerName(devMoniker[0]).ToCharArray());
string deviceString = new String(GetMonikerString(devMoniker[0]).ToCharArray());
string deviceName = new string(GetMonikerName(devMoniker[0]).ToCharArray());
string deviceString = new string(GetMonikerString(devMoniker[0]).ToCharArray());
devices.Add(deviceName, deviceString);
// Release COM object
Marshal.ReleaseComObject(devMoniker[0]);
devMoniker[0] = null;
}
_deviceDescriptions = devices;
Marshal.ReleaseComObject(devEnum);
@@ -197,8 +198,7 @@ namespace VAR.Toolbox.Code
//
private static string GetMonikerString(IMoniker moniker)
{
string str;
moniker.GetDisplayName(null, null, out str);
moniker.GetDisplayName(null, null, out string str);
return str;
}
@@ -208,14 +208,13 @@ namespace VAR.Toolbox.Code
private static string GetMonikerName(IMoniker moniker)
{
Object bagObj = null;
IPropertyBag bag = null;
try
{
Guid bagId = typeof(IPropertyBag).GUID;
// get property bag of the moniker
moniker.BindToStorage(null, null, ref bagId, out bagObj);
bag = (IPropertyBag)bagObj;
IPropertyBag bag = (IPropertyBag)bagObj;
// read FriendlyName
object val = "";
@@ -237,11 +236,9 @@ namespace VAR.Toolbox.Code
finally
{
// release all COM objects
bag = null;
if (bagObj != null)
{
Marshal.ReleaseComObject(bagObj);
bagObj = null;
}
}
}
@@ -260,10 +257,10 @@ namespace VAR.Toolbox.Code
private class Grabber : ISampleGrabberCB
{
private Webcam _parent;
private readonly Webcam _parent;
private Bitmap[] _frames = null;
private int _numFrames = 10;
private readonly Bitmap[] _frames;
private readonly int _numFrames = 10;
private int _currentFrameIndex = -1;
public Grabber(Webcam parent)
@@ -276,11 +273,13 @@ namespace VAR.Toolbox.Code
{
_currentFrameIndex = (_currentFrameIndex + 1) % _numFrames;
Bitmap currentBitmap = _frames[_currentFrameIndex];
if (currentBitmap == null || currentBitmap?.Width != _parent.width || currentBitmap?.Height != _parent.height)
if (currentBitmap == null || currentBitmap.Width != _parent._width ||
currentBitmap.Height != _parent._height)
{
currentBitmap = new Bitmap(_parent.width, _parent.height, PixelFormat.Format24bppRgb);
currentBitmap = new Bitmap(_parent._width, _parent._height, PixelFormat.Format24bppRgb);
_frames[_currentFrameIndex] = currentBitmap;
}
return currentBitmap;
}
@@ -294,12 +293,12 @@ namespace VAR.Toolbox.Code
if (_parent.NewFrame != null)
{
// create new image
Bitmap _image = GetNextFrame();
Rectangle _imageRect = new Rectangle(0, 0, _parent.width, _parent.height);
Bitmap image = GetNextFrame();
Rectangle imageRect = new Rectangle(0, 0, _parent._width, _parent._height);
// lock bitmap data
BitmapData imageData = _image.LockBits(
_imageRect,
BitmapData imageData = image.LockBits(
imageRect,
ImageLockMode.ReadWrite,
PixelFormat.Format24bppRgb);
@@ -309,10 +308,10 @@ namespace VAR.Toolbox.Code
unsafe
{
byte* dst = (byte*)imageData.Scan0.ToPointer() + dstStride * (_parent.height - 1);
byte* dst = (byte*)imageData.Scan0.ToPointer() + dstStride * (_parent._height - 1);
byte* src = (byte*)buffer.ToPointer();
for (int y = 0; y < _parent.height; y++)
for (int y = 0; y < _parent._height; y++)
{
Win32.memcpy(dst, src, srcStride);
dst -= dstStride;
@@ -321,10 +320,10 @@ namespace VAR.Toolbox.Code
}
// unlock bitmap data
_image.UnlockBits(imageData);
image.UnlockBits(imageData);
// notify parent
_parent.NewFrame?.Invoke(this, _image);
_parent.NewFrame?.Invoke(this, image);
}
return 0;

View File

@@ -0,0 +1,33 @@
using System;
using System.Diagnostics;
using System.Windows.Forms;
using VAR.Toolbox.Code.Windows;
// ReSharper disable InconsistentNaming
namespace VAR.Toolbox.Code
{
public static class WindowHandling
{
public static void WindowSetTopLevel(Form form, bool top = true)
{
User32.SetWindowPos(form.Handle, top
? User32.HWND_TOPMOST
: User32.HWND_NOTOPMOST,
0, 0, 0, 0, User32.TOPMOST_FLAGS);
}
public static bool ApplicationIsActivated()
{
var activatedHandle = User32.GetForegroundWindow();
if (activatedHandle == IntPtr.Zero)
{
return false;
}
var procId = Process.GetCurrentProcess().Id;
User32.GetWindowThreadProcessId(activatedHandle, out int activeProcId);
return activeProcId == procId;
}
}
}

View File

@@ -11,15 +11,20 @@ namespace VAR.Toolbox.Code.Windows
public static extern bool BitBlt(IntPtr hObject, int nXDest, int nYDest,
int nWidth, int nHeight, IntPtr hObjectSource,
int nXSrc, int nYSrc, int dwRop);
[DllImport("gdi32.dll")]
public static extern IntPtr CreateCompatibleBitmap(IntPtr hDC, int nWidth,
int nHeight);
[DllImport("gdi32.dll")]
public static extern IntPtr CreateCompatibleDC(IntPtr hDC);
[DllImport("gdi32.dll")]
public static extern bool DeleteDC(IntPtr hDC);
[DllImport("gdi32.dll")]
public static extern bool DeleteObject(IntPtr hObject);
[DllImport("gdi32.dll")]
public static extern IntPtr SelectObject(IntPtr hDC, IntPtr hObject);
}

View File

@@ -1,5 +1,11 @@
using System;
using System.Runtime.InteropServices;
using System.Text;
// ReSharper disable InconsistentNaming
// ReSharper disable MemberCanBePrivate.Global
// ReSharper disable FieldCanBeMadeReadOnly.Global
// ReSharper disable IdentifierTypo
namespace VAR.Toolbox.Code.Windows
{
@@ -22,14 +28,11 @@ namespace VAR.Toolbox.Code.Windows
[StructLayout(LayoutKind.Explicit)]
public struct MOUSEKEYBDHARDWAREINPUT
{
[FieldOffset(0)]
public HARDWAREINPUT Hardware;
[FieldOffset(0)] public HARDWAREINPUT Hardware;
[FieldOffset(0)]
public KEYBDINPUT Keyboard;
[FieldOffset(0)] public KEYBDINPUT Keyboard;
[FieldOffset(0)]
public MOUSEINPUT Mouse;
[FieldOffset(0)] public MOUSEINPUT Mouse;
}
/// <summary>
@@ -92,7 +95,7 @@ namespace VAR.Toolbox.Code.Windows
[DllImport("User32.dll")]
public static extern int SendInput(int nInputs, INPUT[] pInputs, int cbSize);
// <summary>
/// <summary>
/// Struct representing a point.
/// </summary>
[StructLayout(LayoutKind.Sequential)]
@@ -110,18 +113,16 @@ namespace VAR.Toolbox.Code.Windows
public static extern bool GetCursorPos(out POINT lpPoint);
[DllImport("User32.dll")]
public static extern Boolean SetCursorPos(UInt32 X, UInt32 Y);
public static extern Boolean SetCursorPos(UInt32 x, UInt32 y);
[StructLayout(LayoutKind.Sequential)]
public struct LASTINPUTINFO
{
public static readonly int SizeOf = Marshal.SizeOf(typeof(LASTINPUTINFO));
[MarshalAs(UnmanagedType.U4)]
public UInt32 cbSize;
[MarshalAs(UnmanagedType.U4)] public UInt32 cbSize;
[MarshalAs(UnmanagedType.U4)]
public UInt32 dwTime;
[MarshalAs(UnmanagedType.U4)] public UInt32 dwTime;
}
[DllImport("user32.dll")]
@@ -138,7 +139,7 @@ namespace VAR.Toolbox.Code.Windows
public const int HT_CAPTION = 0x2;
[DllImport("user32.dll")]
public static extern int SendMessage(IntPtr hWnd, int Msg, int wParam, int lParam);
public static extern int SendMessage(IntPtr hWnd, int msg, int wParam, int lParam);
[DllImport("user32.dll")]
public static extern bool ReleaseCapture();
@@ -154,11 +155,111 @@ namespace VAR.Toolbox.Code.Windows
[DllImport("user32.dll")]
public static extern IntPtr GetDesktopWindow();
[DllImport("user32.dll")]
public static extern IntPtr GetWindowDC(IntPtr hWnd);
[DllImport("user32.dll")]
public static extern IntPtr ReleaseDC(IntPtr hWnd, IntPtr hDC);
[DllImport("user32.dll")]
public static extern IntPtr GetWindowRect(IntPtr hWnd, ref RECT rect);
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool SetForegroundWindow(IntPtr hWnd);
[DllImport("user32.dll")]
public static extern IntPtr GetForegroundWindow();
[DllImport("user32.dll")]
public static extern int GetWindowText(IntPtr hWnd, StringBuilder text, int count);
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
public static extern int GetWindowThreadProcessId(IntPtr handle, out int processId);
public static string GetActiveWindowTitle()
{
const int NChars = 256;
StringBuilder buff = new StringBuilder(NChars);
IntPtr handle = GetForegroundWindow();
if (GetWindowText(handle, buff, NChars) > 0)
{
return buff.ToString();
}
return null;
}
public static readonly IntPtr HWND_TOPMOST = new IntPtr(-1);
public static readonly IntPtr HWND_NOTOPMOST = new IntPtr(-2);
public const UInt32 SWP_NOSIZE = 0x0001;
public const UInt32 SWP_NOMOVE = 0x0002;
public const UInt32 TOPMOST_FLAGS = SWP_NOMOVE | SWP_NOSIZE;
[DllImport("user32.dll")]
[return: MarshalAs(UnmanagedType.Bool)]
public static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int x, int y, int cx, int cy,
uint uFlags);
/// <summary>
/// defines the callback type for the hook
/// </summary>
public delegate int keyboardHookProc(int code, int wParam, ref keyboardHookStruct lParam);
public struct keyboardHookStruct {
public int vkCode;
public int scanCode;
public int flags;
public int time;
public int dwExtraInfo;
}
public const int WH_KEYBOARD_LL = 13;
public const int WM_KEYDOWN = 0x100;
public const int WM_KEYUP = 0x101;
public const int WM_SYSKEYDOWN = 0x104;
public const int WM_SYSKEYUP = 0x105;
/// <summary>
/// Sets the windows hook, do the desired event, one of hInstance or threadId must be non-null
/// </summary>
/// <param name="idHook">The id of the event you want to hook</param>
/// <param name="callback">The callback.</param>
/// <param name="hInstance">The handle you want to attach the event to, can be null</param>
/// <param name="threadId">The thread you want to attach the event to, can be null</param>
/// <returns>a handle to the desired hook</returns>
[DllImport("user32.dll")]
public static extern IntPtr SetWindowsHookEx(int idHook, keyboardHookProc callback, IntPtr hInstance, uint threadId);
/// <summary>
/// Unhooks the windows hook.
/// </summary>
/// <param name="hInstance">The hook handle that was returned from SetWindowsHookEx</param>
/// <returns>True if successful, false otherwise</returns>
[DllImport("user32.dll")]
public static extern bool UnhookWindowsHookEx(IntPtr hInstance);
/// <summary>
/// Calls the next hook.
/// </summary>
/// <param name="idHook">The hook id</param>
/// <param name="nCode">The hook code</param>
/// <param name="wParam">The wparam.</param>
/// <param name="lParam">The lparam.</param>
/// <returns></returns>
[DllImport("user32.dll")]
public static extern int CallNextHookEx(IntPtr idHook, int nCode, int wParam, ref keyboardHookStruct lParam);
/// <summary>
/// Loads the library.
/// </summary>
/// <param name="lpFileName">Name of the library</param>
/// <returns>A handle to the library</returns>
[DllImport("kernel32.dll")]
public static extern IntPtr LoadLibrary(string lpFileName);
}
}

View File

@@ -1,7 +1,13 @@
using System;
#pragma warning disable IDE1006
using System;
using System.Runtime.InteropServices;
using System.Runtime.InteropServices.ComTypes;
// ReSharper disable IdentifierTypo
// ReSharper disable StringLiteralTypo
// ReSharper disable CommentTypo
namespace VAR.Toolbox.Code.Windows
{
public static class Win32
@@ -49,7 +55,7 @@ namespace VAR.Toolbox.Code.Windows
/// <returns>Return's the value of <b>dst</b> - pointer to destination.</returns>
///
[DllImport("ntdll.dll", CallingConvention = CallingConvention.Cdecl)]
public static unsafe extern int memcpy(
public static extern unsafe int memcpy(
byte* dst,
byte* src,
int count);
@@ -79,7 +85,7 @@ namespace VAR.Toolbox.Code.Windows
int y,
[MarshalAs(UnmanagedType.LPWStr)] string caption,
int cObjects,
[MarshalAs( UnmanagedType.Interface, ArraySubType = UnmanagedType.IUnknown )]
[MarshalAs(UnmanagedType.Interface, ArraySubType = UnmanagedType.IUnknown)]
ref object ppUnk,
int cPages,
IntPtr lpPageClsID,
@@ -88,7 +94,8 @@ namespace VAR.Toolbox.Code.Windows
IntPtr lpvReserved);
[DllImport("PowrProf.dll")]
public static extern Boolean SetSuspendState(Boolean Hibernate, Boolean ForceCritical, Boolean DisableWakeEvent);
public static extern Boolean
SetSuspendState(Boolean hibernate, Boolean forceCritical, Boolean disableWakeEvent);
public static uint GetLastInputTime()
{
@@ -102,6 +109,7 @@ namespace VAR.Toolbox.Code.Windows
uint lastInputTick = lastInputInfo.dwTime;
idleTime = envTicks - lastInputTick;
}
return ((idleTime > 0) ? (idleTime / 1000) : 0);
}
}

View File

@@ -0,0 +1,11 @@
using System.Collections.Generic;
using System.Windows.Forms;
namespace VAR.Toolbox.Code.WorkLog
{
public interface IWorkLogImporter : INamed
{
List<WorkLogItem> Import(Form form);
bool Export(List<WorkLogItem> items, Form form);
}
}

View File

@@ -0,0 +1,145 @@
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using System.Windows.Forms;
namespace VAR.Toolbox.Code.WorkLog
{
public class VARTextWorkLogImporter : IWorkLogImporter
{
public string Name => "VARText";
//TODO: VARTextWorkLogImporter: Export WorkLigItem.Tags
public bool Export(List<WorkLogItem> items, Form form)
{
SaveFileDialog saveFileDialog = new SaveFileDialog();
DialogResult dialogResult = saveFileDialog.ShowDialog(form);
if (dialogResult != DialogResult.OK) { return false; }
if (File.Exists(saveFileDialog.FileName) == false)
{
File.Delete(saveFileDialog.FileName);
}
using (StreamWriter streamWriter = new StreamWriter(saveFileDialog.FileName))
{
DateTime lastDateTime = DateTime.MinValue;
int lastWeekOfYear = -1;
List<WorkLogItem> itemsOrdered = items.OrderBy(x => x.DateStart).ToList();
foreach (WorkLogItem item in itemsOrdered)
{
int weekOfYear = CultureInfo.InvariantCulture.Calendar.GetWeekOfYear(item.DateStart,
CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday);
if (weekOfYear != lastWeekOfYear)
{
streamWriter.WriteLine();
streamWriter.WriteLine();
streamWriter.WriteLine("--- {0:0000}-{1:00}-{2:00}", item.DateStart.Year, item.DateStart.Month,
item.DateStart.Day);
lastWeekOfYear = weekOfYear;
}
if (lastDateTime.Day != item.DateStart.Day)
{
streamWriter.WriteLine();
lastDateTime = item.DateStart;
}
streamWriter.WriteLine("{0:00}_{1:00}_{2:00} - {3:00}_{4:00}_{5:00} {6}", item.DateStart.Day,
item.DateStart.Hour, item.DateStart.Minute, item.DateEnd.Day, item.DateEnd.Hour,
item.DateEnd.Minute, item.Activity);
if (string.IsNullOrEmpty(item.Description) == false)
{
streamWriter.WriteLine($" {item.Description}");
}
}
}
return true;
}
//TODO: VARTextWorkLogImporter: Import WorkLigItem.Tags
public List<WorkLogItem> Import(Form form)
{
OpenFileDialog openFileDialog = new OpenFileDialog();
DialogResult dialogResult = openFileDialog.ShowDialog(form);
if (dialogResult != DialogResult.OK) { return null; }
if (File.Exists(openFileDialog.FileName) == false) { return null; }
string[] allLines = File.ReadAllLines(openFileDialog.FileName);
Regex regex = new Regex(@"(\d\d)_(\d\d)_(\d\d)\s-\s(\d\d)_(\d\d)_(\d\d)\s(.*)");
DateTime currentDateStart = DateTime.MinValue;
WorkLogItem currentWorkLog = null;
List<WorkLogItem> workLog = new List<WorkLogItem>();
foreach (string line in allLines)
{
string lineAux = line.Trim();
if (string.IsNullOrEmpty(lineAux)) { continue; }
if (lineAux.StartsWith("--- "))
{
string strDate = lineAux.Substring(4);
string[] strDateParts = strDate.Split('-');
if (strDateParts.Length >= 3 && strDateParts[0].Length == 4 && strDateParts[1].Length == 2 &&
strDateParts[2].Length == 2)
{
currentDateStart = new DateTime(Convert.ToInt32(strDateParts[0]),
Convert.ToInt32(strDateParts[1]), Convert.ToInt32(strDateParts[2]), 0, 0, 0);
}
else { }
}
else if (lineAux.StartsWith("--"))
{
if (currentWorkLog != null)
{
currentWorkLog.Description += lineAux + "\n";
}
}
else
{
Match match = regex.Match(lineAux);
if (match.Groups.Count < 7)
{
if (currentWorkLog != null)
{
currentWorkLog.Description += lineAux + "\n";
}
continue;
}
int startDay = Convert.ToInt32(match.Groups[1].Value);
int startHour = Convert.ToInt32(match.Groups[2].Value);
int startMinute = Convert.ToInt32(match.Groups[3].Value);
int endDay = Convert.ToInt32(match.Groups[4].Value);
int endHour = Convert.ToInt32(match.Groups[5].Value);
int endMinute = Convert.ToInt32(match.Groups[6].Value);
string activity = match.Groups[7].Value;
DateTime dateTime = currentDateStart;
if (dateTime.Day > startDay)
{
dateTime = dateTime.AddMonths(1);
}
currentWorkLog = new WorkLogItem
{
DateStart = new DateTime(dateTime.Year, dateTime.Month, startDay, startHour, startMinute, 0),
DateEnd = new DateTime(dateTime.Year, dateTime.Month, endDay, endHour, endMinute, 0),
Activity = activity,
Description = string.Empty,
};
workLog.Add(currentWorkLog);
}
}
return workLog;
}
}
}

View File

@@ -0,0 +1,4 @@
namespace VAR.Toolbox.Code.WorkLog
{
public abstract class WorkLogImporterFactory : BaseFactory<IWorkLogImporter> { }
}

View File

@@ -0,0 +1,18 @@
using System;
namespace VAR.Toolbox.Code.WorkLog
{
public class WorkLogItem
{
public DateTime DateStart { get; set; }
public DateTime DateEnd { get; set; }
public string Activity { get; set; }
public string Description { get; set; }
public string Tags { get; set; }
public bool Overlaps(WorkLogItem other)
{
return (other.DateEnd < DateStart || other.DateStart > DateEnd) == false;
}
}
}

View File

@@ -0,0 +1,94 @@
using System;
using System.Drawing;
using System.Windows.Forms;
namespace VAR.Toolbox.Controls
{
public class CButton : Button
{
private readonly Brush _foreColorBrush;
private readonly Brush _foreColorDisableBrush;
private readonly Brush _backColorBrush;
private readonly Brush _backColorOverBrush;
private readonly Brush _backColorDownBrush;
private bool _mouseIsDown;
private bool _mouseIsOver;
public CButton()
{
_foreColorBrush = new SolidBrush(Color.FromArgb(255, 192, 192, 192));
_foreColorDisableBrush = new SolidBrush(Color.FromArgb(255, 96, 96, 96));
_backColorBrush = new SolidBrush(Color.FromArgb(255, 64, 64, 64));
_backColorOverBrush = new SolidBrush(Color.FromArgb(255, 128, 0, 0));
_backColorDownBrush = new SolidBrush(Color.FromArgb(255, 192, 64, 64));
}
protected override void OnLostFocus(EventArgs e)
{
_mouseIsDown = false;
base.OnLostFocus(e);
}
protected override void OnMouseEnter(EventArgs eventargs)
{
_mouseIsOver = true;
base.OnMouseEnter(eventargs);
}
protected override void OnMouseLeave(EventArgs eventargs)
{
_mouseIsOver = false;
base.OnMouseLeave(eventargs);
}
protected override void OnMouseMove(MouseEventArgs mevent)
{
if (mevent.Button != MouseButtons.None)
{
Rectangle r = ClientRectangle;
_mouseIsDown = r.Contains(mevent.X, mevent.Y);
}
base.OnMouseMove(mevent);
}
protected override void OnMouseDown(MouseEventArgs mevent)
{
_mouseIsDown = true;
base.OnMouseDown(mevent);
}
protected override void OnMouseUp(MouseEventArgs mevent)
{
_mouseIsDown = false;
base.OnMouseUp(mevent);
}
private readonly StringFormat _stringFormat = new StringFormat
{ Alignment = StringAlignment.Center, LineAlignment = StringAlignment.Center };
protected override void OnPaint(PaintEventArgs pevent)
{
Rectangle rectangle = new Rectangle(0, 0, Width, Height);
if (Enabled)
{
if (_mouseIsDown)
{
pevent.Graphics.FillRectangle(_backColorDownBrush, rectangle);
}
else
{
pevent.Graphics.FillRectangle(_mouseIsOver ? _backColorOverBrush : _backColorBrush, rectangle);
}
}
else
{
pevent.Graphics.FillRectangle(_backColorBrush, rectangle);
}
pevent.Graphics.DrawString(Text, Font, Enabled ? _foreColorBrush : _foreColorDisableBrush, rectangle,
_stringFormat);
}
}
}

View File

@@ -0,0 +1,27 @@
using System.Drawing;
using System.Windows.Forms;
namespace VAR.Toolbox.Controls
{
public class CComboBox : ComboBox
{
public CComboBox()
{
InitializeComponent();
}
private void InitializeComponent()
{
BackColor = Color.FromArgb(255, 0, 0, 0);
ForeColor = Color.FromArgb(255, 192, 192, 192);
FlatStyle = FlatStyle.Flat;
}
protected override void OnPaint(PaintEventArgs pevent)
{
Rectangle rectangle = new Rectangle(0, 0, Width, Height);
pevent.Graphics.FillRectangle(Brushes.CadetBlue, rectangle);
}
}
}

View File

@@ -0,0 +1,18 @@
using System.Drawing;
namespace VAR.Toolbox.Controls
{
public class CDateTimePicker : System.Windows.Forms.DateTimePicker
{
public CDateTimePicker()
{
InitializeComponent();
}
private void InitializeComponent()
{
BackColor = Color.DarkSlateGray;
ForeColor = Color.Gray;
}
}
}

View File

@@ -0,0 +1,59 @@
using System.Drawing;
using System.Windows.Forms;
namespace VAR.Toolbox.Controls
{
public class CGroupBox : GroupBox
{
public CGroupBox()
{
InitializeComponent();
}
private void InitializeComponent()
{
BackColor = Color.FromArgb(255, 32, 32, 32);
ForeColor = Color.FromArgb(255, 192, 192, 192);
BorderColor = Color.FromArgb(255, 64, 64, 64);
FlatStyle = FlatStyle.Flat;
}
private Color _borderColor = Color.Black;
public Color BorderColor
{
get => _borderColor;
set => _borderColor = value;
}
private SolidBrush _brushBackColor;
private SolidBrush _brushForeColor;
protected override void OnPaint(PaintEventArgs e)
{
if (_brushBackColor == null || _brushBackColor.Color != BackColor)
{
_brushBackColor = new SolidBrush(BackColor);
}
if (_brushForeColor == null || _brushForeColor.Color != ForeColor)
{
_brushForeColor = new SolidBrush(ForeColor);
}
Size tSize = TextRenderer.MeasureText(Text, Font);
Rectangle borderRect = new Rectangle(0, 0, Width, Height);
borderRect.Y = (borderRect.Y + (tSize.Height / 2));
borderRect.Height = (borderRect.Height - (tSize.Height / 2));
ControlPaint.DrawBorder(e.Graphics, borderRect, _borderColor, ButtonBorderStyle.Solid);
Rectangle textRect = new Rectangle(0, 0, Width, Height);
textRect.X = (textRect.X + 6);
textRect.Width = tSize.Width;
textRect.Height = tSize.Height;
e.Graphics.FillRectangle(_brushBackColor, textRect);
e.Graphics.DrawString(Text, Font, _brushForeColor, textRect);
}
}
}

View File

@@ -0,0 +1,18 @@
using System.Drawing;
namespace VAR.Toolbox.Controls
{
public class CSplitContainer : System.Windows.Forms.SplitContainer
{
public CSplitContainer()
{
InitializeComponent();
}
private void InitializeComponent()
{
BackColor = Color.FromArgb(255, 32, 32, 32);
ForeColor = Color.FromArgb(255, 192, 192, 192);
}
}
}

View File

@@ -0,0 +1,40 @@
using System.Reflection;
using System.Windows.Forms;
namespace VAR.Toolbox.Controls
{
public static class ControlsUtils
{
public static float GetFontSize(Control ctrl, float size)
{
return size * 96f / ctrl.CreateGraphics().DpiX;
}
private delegate void SetControlPropertyThreadSafeDelegate(
Control control,
string propertyName,
object propertyValue);
public static void SetControlPropertyThreadSafe(
Control control,
string propertyName,
object propertyValue)
{
if (control.InvokeRequired)
{
control.Invoke(new SetControlPropertyThreadSafeDelegate
(SetControlPropertyThreadSafe),
new[] { control, propertyName, propertyValue });
}
else
{
control.GetType().InvokeMember(
propertyName,
BindingFlags.SetProperty,
null,
control,
new[] { propertyValue });
}
}
}
}

View File

@@ -8,13 +8,7 @@ namespace VAR.Toolbox.Controls
{
#region Declarations
private Image _imageShow = null;
// Image projection
private double offsetX = 0;
private double offsetY = 0;
private double scaleX = 1.0f;
private double scaleY = 1.0f;
private Image _imageShow;
#endregion
@@ -22,13 +16,14 @@ namespace VAR.Toolbox.Controls
public Image ImageShow
{
get { return _imageShow; }
// ReSharper disable once InconsistentlySynchronizedField
get => _imageShow;
set
{
lock (this)
{
_imageShow = value;
this.Invalidate();
Invalidate();
}
}
}
@@ -38,6 +33,11 @@ namespace VAR.Toolbox.Controls
#region Control life cycle
public CtrImageViewer()
{
InitializeComponent();
}
private void InitializeComponent()
{
BackColor = Color.Black;
}
@@ -52,7 +52,7 @@ namespace VAR.Toolbox.Controls
{
base.OnResize(e);
//Redraw(null);
this.Invalidate();
Invalidate();
}
#endregion
@@ -65,11 +65,12 @@ namespace VAR.Toolbox.Controls
{
return;
}
lock (_imageShow)
{
if (graph == null)
{
graph = this.CreateGraphics();
graph = CreateGraphics();
}
// Calcular dimensiones a dibujar y centrar
@@ -77,49 +78,44 @@ namespace VAR.Toolbox.Controls
int imgDrawHeight;
float imgDrawX = 0;
float imgDrawY = 0;
float relation = (float)_imageShow.Width / (float)_imageShow.Height;
float relation = _imageShow.Width / (float)_imageShow.Height;
if (relation > 0)
{
// Imagen mas ancha que alta
imgDrawHeight = (int)(this.Width / relation);
if (imgDrawHeight > this.Height)
imgDrawHeight = (int)(Width / relation);
if (imgDrawHeight > Height)
{
imgDrawHeight = this.Height;
imgDrawWidth = (int)(this.Height * relation);
imgDrawX = ((this.Width - imgDrawWidth) / 2.0f);
imgDrawHeight = Height;
imgDrawWidth = (int)(Height * relation);
imgDrawX = ((Width - imgDrawWidth) / 2.0f);
}
else
{
imgDrawWidth = this.Width;
imgDrawY = ((this.Height - imgDrawHeight) / 2.0f);
imgDrawWidth = Width;
imgDrawY = ((Height - imgDrawHeight) / 2.0f);
}
}
else
{
// Imagen mas alta que ancha
imgDrawWidth = (int)(this.Width * relation);
if (imgDrawWidth > this.Width)
imgDrawWidth = (int)(Width * relation);
if (imgDrawWidth > Width)
{
imgDrawWidth = this.Width;
imgDrawHeight = (int)(this.Height / relation);
imgDrawY = ((this.Height - imgDrawHeight) / 2.0f);
imgDrawWidth = Width;
imgDrawHeight = (int)(Height / relation);
imgDrawY = ((Height - imgDrawHeight) / 2.0f);
}
else
{
imgDrawHeight = this.Height;
imgDrawX = ((this.Width - imgDrawWidth) / 2.0f);
imgDrawHeight = Height;
imgDrawX = ((Width - imgDrawWidth) / 2.0f);
}
}
graph.DrawImage(_imageShow, imgDrawX, imgDrawY, imgDrawWidth, imgDrawHeight);
offsetX = imgDrawX;
offsetY = imgDrawY;
scaleX = (double)imgDrawWidth / (double)_imageShow.Width;
scaleY = (double)imgDrawHeight / (double)_imageShow.Height;
}
}
#endregion
}
}

View File

@@ -1,15 +1,15 @@
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Runtime.InteropServices;
using System.Text;
using System.Windows.Forms;
using VAR.Toolbox.Code;
namespace VAR.Toolbox.Controls
{
public class CtrOutput : Control
public class CtrOutput : Control, IOutputHandler
{
private ListBox _listBox;
private ListBoxMonospace _listBox;
private Timer _timer;
@@ -17,6 +17,7 @@ namespace VAR.Toolbox.Controls
{
public string Text { get; set; }
public object Data { get; set; }
public override string ToString()
{
return Text;
@@ -32,17 +33,12 @@ namespace VAR.Toolbox.Controls
private void InitializeControls()
{
_listBox = new ListBox
_listBox = new ListBoxMonospace
{
Dock = DockStyle.Fill,
FormattingEnabled = true,
Font = new System.Drawing.Font("Consolas", 9),
BackColor = Color.Black,
ForeColor = Color.Gray,
SelectionMode = SelectionMode.MultiExtended,
};
_listBox.MouseDoubleClick += _listBox_MouseDoubleClick;
_listBox.KeyDown += _listBox_KeyDown;
_listBox.MouseDoubleClick += ListBox_MouseDoubleClick;
_listBox.KeyDown += ListBox_KeyDown;
Controls.Add(_listBox);
_timer = new Timer
@@ -50,7 +46,7 @@ namespace VAR.Toolbox.Controls
Interval = 100,
Enabled = true
};
_timer.Tick += _timer_Tick;
_timer.Tick += Timer_Tick;
Disposed += CtrOutput_Disposed;
}
@@ -68,10 +64,11 @@ namespace VAR.Toolbox.Controls
CopyToClipboard();
return true;
}
return base.ProcessCmdKey(ref msg, keyData);
}
private void _listBox_KeyDown(object sender, KeyEventArgs e)
private void ListBox_KeyDown(object sender, KeyEventArgs e)
{
if (e.Control && e.KeyCode == Keys.C)
{
@@ -86,18 +83,19 @@ namespace VAR.Toolbox.Controls
{
sbText.AppendLine(item.Text);
}
if (sbText.Length > 0)
{
Clipboard.SetText(sbText.ToString());
}
}
private void _listBox_MouseDoubleClick(object sender, MouseEventArgs e)
private void ListBox_MouseDoubleClick(object sender, MouseEventArgs e)
{
DoubleClick?.Invoke(sender, e);
}
private void _timer_Tick(object sender, EventArgs e)
private void Timer_Tick(object sender, EventArgs e)
{
if (_updated)
{
@@ -105,8 +103,8 @@ namespace VAR.Toolbox.Controls
}
}
private bool _updated = false;
private List<OutputItem> _pendingOutput = new List<OutputItem>();
private bool _updated;
private readonly List<OutputItem> _pendingOutput = new List<OutputItem>();
private void UpdatePosition()
{
@@ -118,6 +116,7 @@ namespace VAR.Toolbox.Controls
{
_listBox.Items.Add(item);
}
_pendingOutput.Clear();
_listBox.ResumeLayout();
@@ -130,10 +129,12 @@ namespace VAR.Toolbox.Controls
}
[DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = false)]
private static extern IntPtr SendMessage(HandleRef hWnd, Int32 Msg, IntPtr wParam, IntPtr lParam);
private static extern IntPtr SendMessage(HandleRef hWnd, Int32 msg, IntPtr wParam, IntPtr lParam);
private static void EnableRepaint(HandleRef handle, bool enable)
{
// ReSharper disable once InconsistentNaming
// ReSharper disable once IdentifierTypo
const int WM_SETREDRAW = 0x000B;
SendMessage(handle, WM_SETREDRAW, new IntPtr(enable ? 1 : 0), IntPtr.Zero);
}
@@ -167,6 +168,7 @@ namespace VAR.Toolbox.Controls
public string GetCurrentText()
{
if (_listBox.SelectedItems.Count == 0) { return null; }
OutputItem item = (OutputItem)_listBox.SelectedItems[0];
return item?.Text;
}
@@ -174,6 +176,7 @@ namespace VAR.Toolbox.Controls
public object GetCurrentData()
{
if (_listBox.SelectedItems.Count == 0) { return null; }
OutputItem item = (OutputItem)_listBox.SelectedItems[0];
return item?.Data;
}

View File

@@ -0,0 +1,21 @@
using System.Drawing;
namespace VAR.Toolbox.Controls
{
public class Frame : System.Windows.Forms.Form
{
public Frame()
{
InitializeComponent();
}
private void InitializeComponent()
{
Font = new Font(Font.Name, ControlsUtils.GetFontSize(this, 8.25f), Font.Style, Font.Unit,
Font.GdiCharSet, Font.GdiVerticalFont);
AutoScaleMode = System.Windows.Forms.AutoScaleMode.None;
BackColor = Color.FromArgb(255, 32, 32, 32);
ForeColor = Color.FromArgb(255, 192, 192, 192);
}
}
}

View File

@@ -0,0 +1,38 @@
using System.Drawing;
using System.Windows.Forms;
namespace VAR.Toolbox.Controls
{
public class ListBoxMonospace : ListBox
{
public ListBoxMonospace()
{
InitializeComponent();
}
private void InitializeComponent()
{
FormattingEnabled = true;
Font = new Font("Consolas", ControlsUtils.GetFontSize(this, 9));
BackColor = Color.Black;
ForeColor = Color.Gray;
BorderStyle = BorderStyle.FixedSingle;
SelectionMode = SelectionMode.MultiExtended;
}
protected override void OnMouseWheel(MouseEventArgs e)
{
((HandledMouseEventArgs)e).Handled = true;
const int Rows = 5;
if (e.Delta > 0)
{
if (TopIndex < Rows) { TopIndex = 0; }
else { TopIndex -= Rows; }
}
else
{
TopIndex += Rows;
}
}
}
}

View File

@@ -0,0 +1,37 @@
using System.Drawing;
using System.Windows.Forms;
namespace VAR.Toolbox.Controls
{
public class ListBoxNormal : ListBox
{
public ListBoxNormal()
{
InitializeComponent();
}
private void InitializeComponent()
{
FormattingEnabled = true;
Font = new Font("Microsoft Sans Serif", ControlsUtils.GetFontSize(this, 8.25f));
BackColor = Color.Black;
ForeColor = Color.Gray;
BorderStyle = BorderStyle.FixedSingle;
}
protected override void OnMouseWheel(MouseEventArgs e)
{
((HandledMouseEventArgs)e).Handled = true;
const int Rows = 5;
if (e.Delta > 0)
{
if (TopIndex < Rows) { TopIndex = 0; }
else { TopIndex -= Rows; }
}
else
{
TopIndex += Rows;
}
}
}
}

View File

@@ -0,0 +1,21 @@
using System.Drawing;
namespace VAR.Toolbox.Controls
{
public class SubFrame : System.Windows.Forms.UserControl
{
public SubFrame()
{
InitializeComponent();
}
private void InitializeComponent()
{
Font = new Font(Font.Name, ControlsUtils.GetFontSize(this, 8.25f), Font.Style, Font.Unit,
Font.GdiCharSet, Font.GdiVerticalFont);
AutoScaleMode = System.Windows.Forms.AutoScaleMode.None;
BackColor = Color.FromArgb(255, 32, 32, 32);
ForeColor = Color.FromArgb(255, 192, 192, 192);
}
}
}

View File

@@ -0,0 +1,21 @@
using System.Drawing;
using System.Windows.Forms;
namespace VAR.Toolbox.Controls
{
public class TextBoxMonospace : TextBox
{
public TextBoxMonospace()
{
InitializeComponent();
}
private void InitializeComponent()
{
Font = new Font("Consolas", ControlsUtils.GetFontSize(this, 9.0f));
BackColor = Color.FromArgb(255, 0, 0, 0);
ForeColor = Color.FromArgb(255, 192, 192, 192);
BorderStyle = BorderStyle.FixedSingle;
}
}
}

View File

@@ -0,0 +1,21 @@
using System.Drawing;
using System.Windows.Forms;
namespace VAR.Toolbox.Controls
{
public class TextBoxNormal : TextBox
{
public TextBoxNormal()
{
InitializeComponent();
}
private void InitializeComponent()
{
Font = new Font("Microsoft Sans Serif", ControlsUtils.GetFontSize(this, 8.25f));
BackColor = Color.FromArgb(255, 0, 0, 0);
ForeColor = Color.FromArgb(255, 192, 192, 192);
BorderStyle = BorderStyle.FixedSingle;
}
}
}

View File

@@ -28,11 +28,11 @@
<stop
style="stop-color:#8d0000;stop-opacity:1"
offset="0"
id="stop4841" />
id="stop4841"/>
<stop
style="stop-color:#ff0400;stop-opacity:1"
offset="1"
id="stop4843" />
id="stop4843"/>
</linearGradient>
<linearGradient
inkscape:collect="always"
@@ -40,11 +40,11 @@
<stop
style="stop-color:#8f0000;stop-opacity:1"
offset="0"
id="stop4835" />
id="stop4835"/>
<stop
style="stop-color:#fc0000;stop-opacity:1"
offset="1"
id="stop4837" />
id="stop4837"/>
</linearGradient>
<linearGradient
inkscape:collect="always"
@@ -54,7 +54,7 @@
y1="293.95728"
x2="10.583333"
y2="282.84479"
gradientUnits="userSpaceOnUse" />
gradientUnits="userSpaceOnUse"/>
<linearGradient
inkscape:collect="always"
xlink:href="#linearGradient4845"
@@ -63,7 +63,7 @@
y1="294.03665"
x2="9.7895832"
y2="282.92416"
gradientUnits="userSpaceOnUse" />
gradientUnits="userSpaceOnUse"/>
</defs>
<sodipodi:namedview
id="base"
@@ -87,13 +87,13 @@
<inkscape:grid
type="xygrid"
id="grid4485"
originy="0" />
originy="0"/>
<inkscape:grid
type="xygrid"
id="grid4487"
originx="0.13229167"
originy="0.13229167"
units="in" />
units="in"/>
</sodipodi:namedview>
<metadata
id="metadata5">
@@ -102,7 +102,7 @@
rdf:about="">
<dc:format>image/svg+xml</dc:format>
<dc:type
rdf:resource="http://purl.org/dc/dcmitype/StillImage" />
rdf:resource="http://purl.org/dc/dcmitype/StillImage"/>
<dc:title></dc:title>
</cc:Work>
</rdf:RDF>
@@ -117,119 +117,119 @@
id="path4665-6"
d="m 11.641667,285.75519 c -0.07519,0 -0.132327,-0.055 -0.131923,-0.12982 l 0.01,-1.84881 c 4.07e-4,-0.0754 -0.06708,-0.13652 -0.142114,-0.13656 l -5.8221957,-0.003 c -0.075331,-4e-5 -0.127582,0.0629 -0.1276415,0.13802 l -0.00146,1.84724 c -5.91e-5,0.0747 -0.056695,0.13196 -0.1320265,0.13202 l -3.9709303,0.003 c -0.075186,6e-5 -0.1312438,0.0554 -0.1312438,0.13006 v 2.11525 c 0,0.0745 0.061225,0.13617 0.1364114,0.13612 l 6.3458527,-0.004 c 0.075331,-5e-5 0.1374335,-0.0575 0.1368477,-0.13199 l -0.00413,-0.52582 c -5.88e-4,-0.0748 0.05546,-0.13627 0.1306467,-0.13612 l 1.0559706,0.002 c 0.075331,1.5e-4 0.1346351,0.0531 0.1346351,0.12785 v 0.5279 c 0,0.0745 0.055461,0.13821 0.1305009,0.13818 l 6.3561867,-0.002 c 0.07533,-3e-5 0.127184,-0.0554 0.127111,-0.12992 l -0.0021,-2.11732 c -7.3e-5,-0.0747 -0.05488,-0.13114 -0.130211,-0.13124 l -3.835927,-0.001 z m -5.0288563,0.006 c -0.075331,1.6e-4 -0.1282891,-0.0616 -0.1281431,-0.13641 l 0.00207,-1.05897 c 1.472e-4,-0.0754 0.050745,-0.12793 0.126076,-0.12814 l 3.7139823,-0.0103 c 0.07519,-2.1e-4 0.130354,0.0549 0.130209,0.1302 l -0.0021,1.07344 c -1.43e-4,0.0747 -0.05296,0.12177 -0.128142,0.12194 z"
inkscape:connector-curvature="0"
sodipodi:nodetypes="csssssssssssssssssssssssccsssssssss" />
sodipodi:nodetypes="csssssssssssssssssssssssccsssssssss"/>
<path
style="fill:url(#linearGradient4847);stroke:#000006;stroke-width:0.26458332;stroke-miterlimit:4;stroke-dasharray:none;stroke-opacity:1;fill-opacity:1"
id="path4669-8"
d="m 9.128125,290.3854 c 0,0.0747 -0.088061,0.13409 -0.1632469,0.13394 l -1.0270319,-0.002 c -0.075309,-1.6e-4 -0.1284816,-0.0596 -0.1285795,-0.13434 l -0.00207,-1.57833 c -9.78e-5,-0.0747 -0.059594,-0.13424 -0.1347806,-0.13434 l -6.3458527,-0.008 c -0.075186,-10e-5 -0.1364114,0.0616 -0.1364114,0.13641 v 4.50463 c 0,0.0747 0.061225,0.13641 0.1364114,0.13641 H 15.596683 c 0.07533,0 0.136309,-0.0616 0.136412,-0.13641 l 0.0062,-4.50463 c 1.03e-4,-0.0747 -0.05178,-0.13015 -0.12711,-0.13021 l -6.3489103,-0.005 c -0.075186,-5e-5 -0.1352525,0.0558 -0.135241,0.13057 l 2.355e-4,1.5273 z"
inkscape:connector-curvature="0"
sodipodi:nodetypes="cssssssssssssssscc" />
sodipodi:nodetypes="cssssssssssssssscc"/>
<path
style="fill:none;fill-rule:evenodd;stroke:#000000;stroke-width:0.26458332px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:0.49032259"
d="m 1.4552083,286.15207 v 1.5875"
id="path4799"
inkscape:connector-curvature="0"
sodipodi:nodetypes="cc" />
sodipodi:nodetypes="cc"/>
<path
style="fill:none;fill-rule:evenodd;stroke:#ffffff;stroke-width:0.26458332px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:0.49516129"
d="M 5.5562499,283.90311 H 11.377083"
id="path4809"
inkscape:connector-curvature="0" />
inkscape:connector-curvature="0"/>
<path
style="fill:none;fill-rule:evenodd;stroke:#ffffff;stroke-width:0.26458332px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:0.4983871"
d="M 9.2604166,288.93019 H 15.610416"
id="path4815"
inkscape:connector-curvature="0" />
inkscape:connector-curvature="0"/>
<path
style="fill:none;fill-rule:evenodd;stroke:#000000;stroke-width:0.26458332px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:0.5032258"
d="m 15.478125,289.06248 v 3.96875"
id="path4817"
inkscape:connector-curvature="0" />
inkscape:connector-curvature="0"/>
<path
style="fill:none;fill-rule:evenodd;stroke:#000000;stroke-width:0.26458332px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:0.74354839"
d="M 15.610416,293.16352 H 1.3229166"
id="path4819"
inkscape:connector-curvature="0" />
inkscape:connector-curvature="0"/>
<path
style="fill:none;fill-rule:evenodd;stroke:#000000;stroke-width:0.26458332px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:0.5016129"
d="m 1.4552083,293.03123 v -3.96875"
id="path4821"
inkscape:connector-curvature="0" />
inkscape:connector-curvature="0"/>
<path
style="fill:none;fill-rule:evenodd;stroke:#000000;stroke-width:0.26458332px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:0.76129031"
d="m 1.3229166,287.87186 h 6.2177083 v -0.39688 c 0.046835,-0.19876 0.1523728,-0.35185 0.396875,-0.39687 h 1.0583333 c 0.203798,0.046 0.3525696,0.15839 0.396875,0.39687 v 0.39688 h 6.2177078"
id="path4823"
inkscape:connector-curvature="0"
sodipodi:nodetypes="cccccccc" />
sodipodi:nodetypes="cccccccc"/>
<path
style="fill:none;fill-rule:evenodd;stroke:#000000;stroke-width:0.26458332px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:0.47903225"
d="m 15.478125,286.15207 v 1.5875"
id="path4825"
inkscape:connector-curvature="0" />
inkscape:connector-curvature="0"/>
<path
style="fill:none;fill-rule:evenodd;stroke:#ffffff;stroke-width:0.26458332px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:0.52741933"
d="m 1.3229166,288.93019 h 6.35"
id="path4849"
inkscape:connector-curvature="0" />
inkscape:connector-curvature="0"/>
<path
style="fill:none;fill-rule:evenodd;stroke:#ffffff;stroke-width:0.26458332px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:0.5016129"
d="m 7.5406249,290.33248 c 0.053822,0.16463 0.1162818,0.32765 0.396875,0.44979 h 1.0583333 c 0.2656949,-0.11387 0.3463096,-0.27777 0.396875,-0.44979"
id="path4851"
inkscape:connector-curvature="0"
sodipodi:nodetypes="cccc" />
sodipodi:nodetypes="cccc"/>
<path
style="fill:none;fill-rule:evenodd;stroke:#000000;stroke-width:0.26458332px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:0.49354839"
d="m 7.5406249,289.06248 v 1.32292"
id="path4853"
inkscape:connector-curvature="0" />
inkscape:connector-curvature="0"/>
<path
style="fill:none;fill-rule:evenodd;stroke:#000000;stroke-width:0.26458332px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:0.50645161"
d="m 9.3927082,289.06248 v 1.32292"
id="path4855"
inkscape:connector-curvature="0" />
inkscape:connector-curvature="0"/>
<path
style="fill:none;fill-rule:evenodd;stroke:#ffffef;stroke-width:0.26458332px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:0.47903227"
d="m 1.3229166,286.01977 h 3.96875 c 0.3141845,-0.0698 0.3341114,-0.24069 0.396875,-0.39687"
id="path4857"
inkscape:connector-curvature="0"
sodipodi:nodetypes="ccc" />
sodipodi:nodetypes="ccc"/>
<path
style="fill:none;fill-rule:evenodd;stroke:#ffffff;stroke-width:0.26458332px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:0.49677423"
d="m 6.2177083,285.6229 c 0.072285,0.16809 0.1030371,0.34858 0.396875,0.39687 H 10.31875 c 0.179896,-0.0515 0.345856,-0.12665 0.396875,-0.39687"
id="path4859"
inkscape:connector-curvature="0"
sodipodi:nodetypes="cccc" />
sodipodi:nodetypes="cccc"/>
<path
style="fill:none;fill-rule:evenodd;stroke:#ffffff;stroke-width:0.26458332px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:0.5"
d="m 11.244792,285.6229 c 0.04778,0.19396 0.146343,0.35086 0.396875,0.39687 h 3.968749"
id="path4861"
inkscape:connector-curvature="0"
sodipodi:nodetypes="ccc" />
sodipodi:nodetypes="ccc"/>
<path
style="fill:none;fill-rule:evenodd;stroke:#000000;stroke-width:0.26458332px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:0.75"
d="m 6.2177083,284.56457 c 0.078702,-0.13995 0.033329,-0.29762 0.3968749,-0.39688 H 10.31875 c 0.244504,0.045 0.35004,0.19812 0.396875,0.39688"
id="path4863"
inkscape:connector-curvature="0"
sodipodi:nodetypes="cccc" />
sodipodi:nodetypes="cccc"/>
<path
style="fill:none;fill-rule:evenodd;stroke:#000000;stroke-width:0.26458332px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:0.49516129"
d="m 5.6885416,284.0354 v 1.5875"
id="path4865"
inkscape:connector-curvature="0" />
inkscape:connector-curvature="0"/>
<path
style="fill:none;fill-rule:evenodd;stroke:#000000;stroke-width:0.26458332px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:0.49516129"
d="m 6.2177083,284.56457 v 1.05833"
id="path4867"
inkscape:connector-curvature="0" />
inkscape:connector-curvature="0"/>
<path
style="fill:none;fill-rule:evenodd;stroke:#000000;stroke-width:0.26458332px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:0.49516129"
d="m 10.715625,284.56457 v 1.05833"
id="path4869"
inkscape:connector-curvature="0" />
inkscape:connector-curvature="0"/>
<path
style="fill:none;fill-rule:evenodd;stroke:#000000;stroke-width:0.26458332px;stroke-linecap:butt;stroke-linejoin:miter;stroke-opacity:0.48387095"
d="m 11.244792,284.0354 v 1.5875"
id="path4871"
inkscape:connector-curvature="0" />
inkscape:connector-curvature="0"/>
</g>
</svg>

Before

Width:  |  Height:  |  Size: 12 KiB

After

Width:  |  Height:  |  Size: 13 KiB

View File

@@ -1,4 +1,8 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Windows.Forms;
using VAR.Toolbox.Code;
using VAR.Toolbox.UI;
@@ -15,6 +19,16 @@ namespace VAR.Toolbox
{
Application.ThreadException += Application_ThreadException;
// Load plug-ins
string executingAssemblyPath = Assembly.GetExecutingAssembly().Location;
string dirName = Path.GetDirectoryName(executingAssemblyPath);
string execName = Path.GetFileNameWithoutExtension(executingAssemblyPath);
if (dirName != null)
{
string[] assemblyPaths = Directory.GetFiles(dirName, $"{execName}*.dll");
foreach (string assemblyPath in assemblyPaths) { AssemblyLoadFull(assemblyPath); }
}
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
try
@@ -33,5 +47,39 @@ namespace VAR.Toolbox
Logger.Log(e.Exception);
Application.Exit();
}
private static void AssemblyLoadFull(string fullPath, List<string> allAssemblyNames = null)
{
if (allAssemblyNames == null)
{
allAssemblyNames = AppDomain.CurrentDomain.GetAssemblies().Select(a => a.GetName().Name).ToList();
}
Assembly asm = null;
try
{
asm = Assembly.LoadFrom(fullPath);
}
catch (Exception)
{
// ignored
}
if (asm == null) { return; }
allAssemblyNames.Add(asm.GetName().Name);
// Load dependencies
string dirPath = Path.GetDirectoryName(fullPath);
AssemblyName[] asmNames = asm.GetReferencedAssemblies();
foreach (AssemblyName asmName in asmNames)
{
if (allAssemblyNames.Contains(asmName.Name) == false)
{
string fullPathAux = $"{dirPath}/{asmName.Name}.dll";
AssemblyLoadFull(fullPathAux, allAssemblyNames);
}
}
}
}
}

Some files were not shown because too many files have changed in this diff Show More