Changes recommended by Rider/Resharper

This commit is contained in:
2022-04-08 02:20:17 +02:00
parent 1a11a67248
commit 827f68b0c6
122 changed files with 1598 additions and 1201 deletions

1
.gitignore vendored
View File

@@ -4,5 +4,6 @@
*/bin/*
*/obj/*
*.csproj.user
*.DotSettings.user
*.suo
.vs

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>

View File

@@ -10,8 +10,8 @@ namespace VAR.Toolbox.TestPlugin
InitializeComponent();
}
public string ToolName { get { return "Test"; } }
public string ToolName => "Test";
public bool HasIcon { get { return false; } }
public bool HasIcon => false;
}
}

View File

@@ -10,4 +10,5 @@
## Usage
Put the generated assembly near ```VAR.Toolbox.exe``` it will load as plug-ins any assembly that starts with ```VAR.Toolbox```
Put the generated assembly near ```VAR.Toolbox.exe``` it will load as plug-ins any assembly that starts
with ```VAR.Toolbox```

View File

@@ -9,9 +9,10 @@
<AppDesignerFolder>Properties</AppDesignerFolder>
<RootNamespace>VAR.Toolbox.TestPlugin</RootNamespace>
<AssemblyName>VAR.Toolbox.TestPlugin</AssemblyName>
<TargetFrameworkVersion>v4.7.2</TargetFrameworkVersion>
<TargetFrameworkVersion>v4.8</TargetFrameworkVersion>
<FileAlignment>512</FileAlignment>
<Deterministic>true</Deterministic>
<TargetFrameworkProfile />
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DebugSymbols>true</DebugSymbols>

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

@@ -6,7 +6,8 @@ namespace VAR.Toolbox.Code
{
public abstract class BaseFactory<T> where T : INamed
{
private static Dictionary<string, Type> _dictTypes = null;
// ReSharper disable once StaticMemberInGenericType
private static Dictionary<string, Type> _dictTypes;
private static Dictionary<string, Type> GetDict()
{
@@ -37,8 +38,10 @@ namespace VAR.Toolbox.Code
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));
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);
@@ -55,10 +58,13 @@ namespace VAR.Toolbox.Code
{
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));
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 });

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,6 +1,5 @@
#pragma warning disable IDE1006
using System;
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,6 +1,5 @@
#pragma warning disable IDE1006
using System;
using System.Runtime.InteropServices;
namespace VAR.Toolbox.Code.DirectShow
@@ -47,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>
///
@@ -87,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.
@@ -99,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

@@ -95,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>
///
@@ -257,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>
@@ -268,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>
@@ -360,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>
@@ -368,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

@@ -20,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)
{
@@ -55,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

@@ -5,7 +5,7 @@ namespace VAR.Toolbox.Code
{
public static class EventDispatcher
{
private static List<IEventListener> _eventListeners = null;
private static List<IEventListener> _eventListeners;
private static IEnumerable<IEventListener> GetEventListeners()
{
@@ -19,8 +19,7 @@ namespace VAR.Toolbox.Code
_eventListeners = new List<IEventListener>();
foreach (Type eventListener in eventListeners)
{
IEventListener eventListenerInstance = Activator.CreateInstance(eventListener) as IEventListener;
if (eventListenerInstance != null)
if (Activator.CreateInstance(eventListener) is IEventListener eventListenerInstance)
{
_eventListeners.Add(eventListenerInstance);
}
@@ -37,6 +36,5 @@ namespace VAR.Toolbox.Code
eventListener.ProcessEvent(eventName, eventData);
}
}
}
}

View File

@@ -7,13 +7,16 @@ namespace VAR.Toolbox.Code
{
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

@@ -1,10 +1,4 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace VAR.Toolbox.Code
namespace VAR.Toolbox.Code
{
public interface IEventListener
{

View File

@@ -6,19 +6,18 @@ namespace VAR.Toolbox.Code
public 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);
}
@@ -61,14 +61,17 @@ namespace VAR.Toolbox.Code
{
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>
@@ -79,38 +82,45 @@ namespace VAR.Toolbox.Code
{
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

@@ -39,14 +39,17 @@ namespace VAR.Toolbox.Code
{
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 };
if (User32.SendInput(1, inputs, Marshal.SizeOf(typeof(User32.INPUT))) == 0)
throw new Exception();

View File

@@ -2,7 +2,8 @@
{
public class ProxyCmdExecutorDummy : IProxyCmdExecutor
{
public string Name { get { return "Dummy"; } }
private readonly string _config;
public string Name => "Dummy";
public ProxyCmdExecutorDummy(string config)
{
@@ -10,11 +11,13 @@
{
throw new System.ArgumentNullException(nameof(config));
}
_config = config;
}
public bool ExecuteCmd(string cmdString, IOutputHandler outputHandler)
{
outputHandler.OutputLine(string.Format("DummyExecution: {0}", cmdString));
outputHandler.OutputLine($"DummyExecution: {cmdString} | {_config}");
return true;
}
}

View File

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

View File

@@ -5,9 +5,9 @@ namespace VAR.Toolbox.Code.ProxyCmdExecutors
{
public class ProxyCmdExecutorThroughSQLServer : IProxyCmdExecutor
{
public string Name { get { return "SqlServer"; } }
public string Name => "SqlServer";
private readonly string _connectionString = null;
private readonly string _connectionString;
public ProxyCmdExecutorThroughSQLServer(string connectionString)
{
@@ -27,6 +27,7 @@ namespace VAR.Toolbox.Code.ProxyCmdExecutors
string output = Convert.ToString(reader[0]);
outputHandler.OutputLine(output);
}
cnx.Close();
return true;
}

View File

@@ -4,7 +4,7 @@ namespace VAR.Toolbox.Code.ProxyCmdExecutors
{
public class ProxyCmdExecutorWMIC : IProxyCmdExecutor
{
public string Name { get { return "WMIC"; } }
public string Name => "WMIC";
private readonly string _configWMIC;
@@ -15,7 +15,8 @@ namespace VAR.Toolbox.Code.ProxyCmdExecutors
public 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 = string.Format(" /node:\"{0}\" process call create \"cmd.exe /c \\\"{1}\\\"\"",
_configWMIC.Replace("\"", "\\\""), cmd.Replace("\"", "\\\""));
Process process = new Process();
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardOutput = true;

View File

@@ -17,6 +17,5 @@ namespace VAR.Toolbox.Code
interfaceType.IsAssignableFrom(x) &&
true);
}
}
}

View File

@@ -6,7 +6,7 @@ using VAR.Toolbox.Code.Windows;
namespace VAR.Toolbox.Code
{
public class Screenshooter
public static class Screenshoter
{
public static Bitmap CaptureScreen(Bitmap bmp = null)
{
@@ -17,7 +17,7 @@ namespace VAR.Toolbox.Code
int screenHeight = SystemInformation.VirtualScreen.Height;
// Create a bitmap of the appropriate size to receive the screenshot.
if (bmp == null || bmp?.Width != screenWidth || bmp?.Height != screenHeight)
if (bmp == null || bmp.Width != screenWidth || bmp.Height != screenHeight)
{
bmp = new Bitmap(screenWidth, screenHeight);
}
@@ -27,6 +27,7 @@ namespace VAR.Toolbox.Code
{
g.CopyFromScreen(screenLeft, screenTop, 0, 0, bmp.Size);
}
return bmp;
}
@@ -76,8 +77,5 @@ namespace VAR.Toolbox.Code
return img;
}
}
}

View File

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

View File

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

View File

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

View File

@@ -4,9 +4,9 @@ namespace VAR.Toolbox.Code.TextCoders
{
public class TextCoderHexToAscii : ITextCoder
{
public string Name { get { return "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.TextCoders
byte[] toEncodeAsBytes = Encoding.ASCII.GetBytes(input);
return HexUtils.BytesToHexString(toEncodeAsBytes);
}
}
}

View File

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

View File

@@ -7,11 +7,14 @@ using System.Threading.Tasks;
namespace VAR.Toolbox.Code
{
public class WebServicesUtils
public static class WebServicesUtils
{
private static readonly CookieContainer _cookieJar = new CookieContainer();
public static string CallApi(string urlService, string urlApiMethod, Dictionary<string, string> prms, object content, CookieContainer cookieJar = null, string stringContent = null, Dictionary<string, string> customHeaders = null, string verb = "POST", bool disableCertificateValidation = false)
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)
{
@@ -20,11 +23,12 @@ namespace VAR.Toolbox.Code
}
if (cookieJar == null) { cookieJar = _cookieJar; }
try
{
var sbRequestUrl = new StringBuilder();
sbRequestUrl.Append(urlService);
if (urlService.EndsWith("/") && urlApiMethod.StartsWith("/"))
if (urlService != null && urlService.EndsWith("/") && urlApiMethod.StartsWith("/"))
{
sbRequestUrl.Append(urlApiMethod.Substring(1));
}
@@ -32,23 +36,19 @@ namespace VAR.Toolbox.Code
{
sbRequestUrl.Append(urlApiMethod);
}
if (prms != null)
if (parameters != null)
{
foreach (KeyValuePair<string, string> pair in prms)
foreach (KeyValuePair<string, string> pair in parameters)
{
if (pair.Value == null)
{
sbRequestUrl.AppendFormat("&{0}={1}", pair.Key, string.Empty);
}
else
{
sbRequestUrl.AppendFormat("&{0}={1}", pair.Key, HttpServer.HttpUtility.UrlEncode(pair.Value));
}
sbRequestUrl.AppendFormat("&{0}={1}", pair.Key,
pair.Value == null ? string.Empty : HttpServer.HttpUtility.UrlEncode(pair.Value));
}
}
if (sbRequestUrl.Length > 2048)
{
throw new Exception(string.Format("CallApi: Request URL longer than 2048: url: \"{0}\"", sbRequestUrl.ToString()));
throw new Exception($"CallApi: Request URL longer than 2048: url: \"{sbRequestUrl}\"");
}
var http = (HttpWebRequest)WebRequest.Create(new Uri(sbRequestUrl.ToString()));
@@ -56,7 +56,8 @@ namespace VAR.Toolbox.Code
#if UNIFIKAS_COMMONS
if (disableCertificateValidation)
{
http.ServerCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) => { return true; };
http.ServerCertificateValidationCallback =
(sender, certificate, chain, sslPolicyErrors) => { return true; };
}
#else
if (disableCertificateValidation)
@@ -83,6 +84,7 @@ namespace VAR.Toolbox.Code
{
parsedContent = stringContent;
}
UTF8Encoding encoding = new UTF8Encoding();
byte[] bytes = encoding.GetBytes(parsedContent);
@@ -97,40 +99,47 @@ namespace VAR.Toolbox.Code
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> parms, string namespaceUrl = "http://tempuri.org", ICredentials credentials = null)
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 = string.Format("http://{0}", url.Substring("https://".Length));
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: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> parm in parms)
foreach (KeyValuePair<string, object> parameter in parameters)
{
if (parm.Value != null && !(parm.Value is DBNull))
if (parameter.Value != null && !(parameter.Value is DBNull))
{
sbData.AppendFormat("<{0}>{1}</{0}>", parm.Key, parm.Value);
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\" />", parm.Key);
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>");
@@ -138,22 +147,20 @@ namespace VAR.Toolbox.Code
byte[] postData = Encoding.UTF8.GetBytes(sbData.ToString());
// Realizar petición
var client = new System.Net.WebClient();
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");
if (namespaceUrl.ToLower().StartsWith("http"))
{
client.Headers.Add("SOAPAction", string.Format("\"{0}/{1}\"", namespaceUrl, method));
}
else
{
client.Headers.Add("SOAPAction", string.Format("\"{0}:{1}\"", namespaceUrl, method));
}
client.Headers.Add("SOAPAction",
namespaceUrl.ToLower().StartsWith("http")
? $"\"{namespaceUrl}/{method}\""
: $"\"{namespaceUrl}:{method}\"");
byte[] data;
try
{
@@ -161,11 +168,11 @@ namespace VAR.Toolbox.Code
}
catch (Exception ex)
{
throw new Exception(string.Format("Failure calling SoapService: URL: {0}", url), ex);
}
string strData = System.Text.Encoding.UTF8.GetString(data);
return strData;
throw new Exception($"Failure calling SoapService: URL: {url}", ex);
}
string strData = Encoding.UTF8.GetString(data);
return strData;
}
}
}

View File

@@ -1,5 +1,7 @@
#pragma warning disable IDE0018
#pragma warning disable IDE0059
// ReSharper disable SuspiciousTypeConversion.Global
// ReSharper disable ConvertToAutoProperty
using System;
using System.Collections.Generic;
@@ -10,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 readonly IFilterGraph2 graph;
private readonly ICaptureGraphBuilder2 capture;
private readonly IMediaControl control;
private readonly IBaseFilter sourceFilter;
private readonly IBaseFilter samplegrabberfilter;
private readonly IBaseFilter nullrenderer;
private readonly IMediaControl _control;
private readonly IBaseFilter _sourceFilter;
private readonly IBaseFilter _sampleGrabberFilter;
private readonly IBaseFilter _nullRenderer;
private readonly Grabber grabber;
private readonly int _width;
private readonly int _height;
private readonly int _bpp;
private readonly int width = 0;
private readonly int height = 0;
private readonly int bpp = 0;
private bool active = false;
private bool _active;
private static Dictionary<string, string> _deviceDescriptions;
@@ -37,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
@@ -49,33 +50,29 @@ 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
@@ -85,15 +82,16 @@ namespace VAR.Toolbox.Code
};
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();
@@ -102,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();
}
@@ -119,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");
@@ -175,6 +170,7 @@ namespace VAR.Toolbox.Code
Marshal.ReleaseComObject(devMoniker[0]);
devMoniker[0] = null;
}
_deviceDescriptions = devices;
Marshal.ReleaseComObject(devEnum);
@@ -202,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;
}
@@ -213,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 = "";
@@ -242,11 +236,9 @@ namespace VAR.Toolbox.Code
finally
{
// release all COM objects
bag = null;
if (bagObj != null)
{
Marshal.ReleaseComObject(bagObj);
bagObj = null;
}
}
}
@@ -267,7 +259,7 @@ namespace VAR.Toolbox.Code
{
private readonly Webcam _parent;
private readonly Bitmap[] _frames = null;
private readonly Bitmap[] _frames;
private readonly int _numFrames = 10;
private int _currentFrameIndex = -1;
@@ -281,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;
}
@@ -299,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);
@@ -314,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;
@@ -326,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

@@ -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

@@ -2,6 +2,11 @@
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
{
public static class User32
@@ -23,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>
@@ -93,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)]
@@ -111,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")]
@@ -139,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();
@@ -177,14 +177,15 @@ namespace VAR.Toolbox.Code.Windows
public static string GetActiveWindowTitle()
{
const int nChars = 256;
StringBuilder Buff = new StringBuilder(nChars);
const int NChars = 256;
StringBuilder buff = new StringBuilder(NChars);
IntPtr handle = GetForegroundWindow();
if (GetWindowText(handle, Buff, nChars) > 0)
if (GetWindowText(handle, buff, NChars) > 0)
{
return Buff.ToString();
return buff.ToString();
}
return null;
}
}

View File

@@ -4,6 +4,10 @@ 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
@@ -51,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);
@@ -90,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()
{
@@ -104,6 +109,7 @@ namespace VAR.Toolbox.Code.Windows
uint lastInputTick = lastInputInfo.dwTime;
idleTime = envTicks - lastInputTick;
}
return ((idleTime > 0) ? (idleTime / 1000) : 0);
}
}

View File

@@ -10,7 +10,7 @@ namespace VAR.Toolbox.Code.WorkLog
{
public class VARTextWorkLogImporter : IWorkLogImporter
{
public string Name { get { return "VARText"; } }
public string Name => "VARText";
//TODO: VARTextWorkLogImporter: Export WorkLigItem.Tags
public bool Export(List<WorkLogItem> items, Form form)
@@ -23,6 +23,7 @@ namespace VAR.Toolbox.Code.WorkLog
{
File.Delete(saveFileDialog.FileName);
}
using (StreamWriter streamWriter = new StreamWriter(saveFileDialog.FileName))
{
DateTime lastDateTime = DateTime.MinValue;
@@ -30,30 +31,33 @@ namespace VAR.Toolbox.Code.WorkLog
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);
int weekOfYear = CultureInfo.InvariantCulture.Calendar.GetWeekOfYear(item.DateStart,
CalendarWeekRule.FirstFourDayWeek, DayOfWeek.Monday);
if (weekOfYear != lastWeekOfYear)
{
streamWriter.WriteLine();
streamWriter.WriteLine();
streamWriter.WriteLine(string.Format("--- {0:0000}-{1:00}-{2:00}", item.DateStart.Year, item.DateStart.Month, item.DateStart.Day));
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(string.Format("{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));
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(string.Format(" {0}", item.Description));
streamWriter.WriteLine($" {item.Description}");
}
}
}
return true;
}
@@ -82,14 +86,13 @@ namespace VAR.Toolbox.Code.WorkLog
{
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)
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
{
continue;
currentDateStart = new DateTime(Convert.ToInt32(strDateParts[0]),
Convert.ToInt32(strDateParts[1]), Convert.ToInt32(strDateParts[2]), 0, 0, 0);
}
else { }
}
else if (lineAux.StartsWith("--"))
{
@@ -97,7 +100,6 @@ namespace VAR.Toolbox.Code.WorkLog
{
currentWorkLog.Description += lineAux + "\n";
}
continue;
}
else
{
@@ -108,8 +110,10 @@ namespace VAR.Toolbox.Code.WorkLog
{
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);

View File

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

View File

@@ -12,7 +12,7 @@ namespace VAR.Toolbox.Code.WorkLog
public bool Overlaps(WorkLogItem other)
{
return (other.DateEnd < this.DateStart || other.DateStart > this.DateEnd) == false;
return (other.DateEnd < DateStart || other.DateStart > DateEnd) == false;
}
}
}

View File

@@ -4,16 +4,16 @@ using System.Windows.Forms;
namespace VAR.Toolbox.Controls
{
public class CButton : System.Windows.Forms.Button
public class CButton : Button
{
private Brush _foreColorBrush;
private Brush _foreColorDisableBrush;
private Brush _backColorBrush;
private Brush _backColorOverBrush;
private Brush _backColorDownBrush;
private readonly Brush _foreColorBrush;
private readonly Brush _foreColorDisableBrush;
private readonly Brush _backColorBrush;
private readonly Brush _backColorOverBrush;
private readonly Brush _backColorDownBrush;
private bool _mouseIsDown = false;
private bool _mouseIsOver = false;
private bool _mouseIsDown;
private bool _mouseIsOver;
public CButton()
{
@@ -47,15 +47,9 @@ namespace VAR.Toolbox.Controls
if (mevent.Button != MouseButtons.None)
{
Rectangle r = ClientRectangle;
if (!r.Contains(mevent.X, mevent.Y))
{
_mouseIsDown = false;
}
else
{
_mouseIsDown = true;
}
_mouseIsDown = r.Contains(mevent.X, mevent.Y);
}
base.OnMouseMove(mevent);
}
@@ -71,7 +65,8 @@ namespace VAR.Toolbox.Controls
base.OnMouseUp(mevent);
}
private StringFormat _stringFormat = new StringFormat { Alignment = StringAlignment.Center, LineAlignment = StringAlignment.Center };
private readonly StringFormat _stringFormat = new StringFormat
{ Alignment = StringAlignment.Center, LineAlignment = StringAlignment.Center };
protected override void OnPaint(PaintEventArgs pevent)
{
@@ -84,14 +79,7 @@ namespace VAR.Toolbox.Controls
}
else
{
if (_mouseIsOver)
{
pevent.Graphics.FillRectangle(_backColorOverBrush, rectangle);
}
else
{
pevent.Graphics.FillRectangle(_backColorBrush, rectangle);
}
pevent.Graphics.FillRectangle(_mouseIsOver ? _backColorOverBrush : _backColorBrush, rectangle);
}
}
else
@@ -99,8 +87,8 @@ namespace VAR.Toolbox.Controls
pevent.Graphics.FillRectangle(_backColorBrush, rectangle);
}
pevent.Graphics.DrawString(Text, Font, Enabled ? _foreColorBrush : _foreColorDisableBrush, rectangle, _stringFormat);
}
pevent.Graphics.DrawString(Text, Font, Enabled ? _foreColorBrush : _foreColorDisableBrush, rectangle,
_stringFormat);
}
}
}

View File

@@ -3,14 +3,19 @@ using System.Windows.Forms;
namespace VAR.Toolbox.Controls
{
public class CComboBox : System.Windows.Forms.ComboBox
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 = System.Windows.Forms.FlatStyle.Flat;
FlatStyle = FlatStyle.Flat;
}
protected override void OnPaint(PaintEventArgs pevent)

View File

@@ -5,6 +5,11 @@ 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

@@ -3,26 +3,31 @@ using System.Windows.Forms;
namespace VAR.Toolbox.Controls
{
public class CGroupBox : System.Windows.Forms.GroupBox
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 = System.Windows.Forms.FlatStyle.Flat;
FlatStyle = FlatStyle.Flat;
}
private Color _borderColor = Color.Black;
public Color BorderColor
{
get { return this._borderColor; }
set { this._borderColor = value; }
get => _borderColor;
set => _borderColor = value;
}
private SolidBrush _brushBackColor = null;
private SolidBrush _brushForeColor = null;
private SolidBrush _brushBackColor;
private SolidBrush _brushForeColor;
protected override void OnPaint(PaintEventArgs e)
{
@@ -30,6 +35,7 @@ namespace VAR.Toolbox.Controls
{
_brushBackColor = new SolidBrush(BackColor);
}
if (_brushForeColor == null || _brushForeColor.Color != ForeColor)
{
_brushForeColor = new SolidBrush(ForeColor);

View File

@@ -5,6 +5,11 @@ 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

@@ -24,7 +24,7 @@ namespace VAR.Toolbox.Controls
{
control.Invoke(new SetControlPropertyThreadSafeDelegate
(SetControlPropertyThreadSafe),
new object[] { control, propertyName, propertyValue });
new[] { control, propertyName, propertyValue });
}
else
{
@@ -33,7 +33,7 @@ namespace VAR.Toolbox.Controls
BindingFlags.SetProperty,
null,
control,
new object[] { propertyValue });
new[] { propertyValue });
}
}
}

View File

@@ -8,7 +8,7 @@ namespace VAR.Toolbox.Controls
{
#region Declarations
private Image _imageShow = null;
private Image _imageShow;
#endregion
@@ -16,7 +16,8 @@ namespace VAR.Toolbox.Controls
public Image ImageShow
{
get { return _imageShow; }
// ReSharper disable once InconsistentlySynchronizedField
get => _imageShow;
set
{
lock (this)
@@ -32,6 +33,11 @@ namespace VAR.Toolbox.Controls
#region Control life cycle
public CtrImageViewer()
{
InitializeComponent();
}
private void InitializeComponent()
{
BackColor = Color.Black;
}
@@ -46,7 +52,7 @@ namespace VAR.Toolbox.Controls
{
base.OnResize(e);
//Redraw(null);
this.Invalidate();
Invalidate();
}
#endregion
@@ -59,11 +65,12 @@ namespace VAR.Toolbox.Controls
{
return;
}
lock (_imageShow)
{
if (graph == null)
{
graph = this.CreateGraphics();
graph = CreateGraphics();
}
// Calcular dimensiones a dibujar y centrar
@@ -71,7 +78,7 @@ 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
@@ -110,6 +117,5 @@ namespace VAR.Toolbox.Controls
}
#endregion
}
}

View File

@@ -16,6 +16,7 @@ namespace VAR.Toolbox.Controls
{
public string Text { get; set; }
public object Data { get; set; }
public override string ToString()
{
return Text;
@@ -62,6 +63,7 @@ namespace VAR.Toolbox.Controls
CopyToClipboard();
return true;
}
return base.ProcessCmdKey(ref msg, keyData);
}
@@ -80,6 +82,7 @@ namespace VAR.Toolbox.Controls
{
sbText.AppendLine(item.Text);
}
if (sbText.Length > 0)
{
Clipboard.SetText(sbText.ToString());
@@ -99,7 +102,7 @@ namespace VAR.Toolbox.Controls
}
}
private bool _updated = false;
private bool _updated;
private readonly List<OutputItem> _pendingOutput = new List<OutputItem>();
private void UpdatePosition()
@@ -112,6 +115,7 @@ namespace VAR.Toolbox.Controls
{
_listBox.Items.Add(item);
}
_pendingOutput.Clear();
_listBox.ResumeLayout();
@@ -124,10 +128,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);
}
@@ -161,6 +167,7 @@ namespace VAR.Toolbox.Controls
public string GetCurrentText()
{
if (_listBox.SelectedItems.Count == 0) { return null; }
OutputItem item = (OutputItem)_listBox.SelectedItems[0];
return item?.Text;
}
@@ -168,6 +175,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

@@ -6,7 +6,13 @@ namespace VAR.Toolbox.Controls
{
public Frame()
{
Font = new System.Drawing.Font(Font.Name, ControlsUtils.GetFontSize(this, 8.25f), Font.Style, Font.Unit, Font.GdiCharSet, Font.GdiVerticalFont);
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

@@ -6,6 +6,11 @@ namespace VAR.Toolbox.Controls
public class ListBoxMonospace : ListBox
{
public ListBoxMonospace()
{
InitializeComponent();
}
private void InitializeComponent()
{
FormattingEnabled = true;
Font = new Font("Consolas", ControlsUtils.GetFontSize(this, 9));
@@ -17,16 +22,16 @@ namespace VAR.Toolbox.Controls
protected override void OnMouseWheel(MouseEventArgs e)
{
(e as HandledMouseEventArgs).Handled = true;
const int rows = 5;
((HandledMouseEventArgs)e).Handled = true;
const int Rows = 5;
if (e.Delta > 0)
{
if (TopIndex < rows) { TopIndex = 0; }
else { TopIndex -= rows; }
if (TopIndex < Rows) { TopIndex = 0; }
else { TopIndex -= Rows; }
}
else
{
TopIndex += rows;
TopIndex += Rows;
}
}
}

View File

@@ -6,6 +6,11 @@ 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));
@@ -16,16 +21,16 @@ namespace VAR.Toolbox.Controls
protected override void OnMouseWheel(MouseEventArgs e)
{
(e as HandledMouseEventArgs).Handled = true;
const int rows = 5;
((HandledMouseEventArgs)e).Handled = true;
const int Rows = 5;
if (e.Delta > 0)
{
if (TopIndex < rows) { TopIndex = 0; }
else { TopIndex -= rows; }
if (TopIndex < Rows) { TopIndex = 0; }
else { TopIndex -= Rows; }
}
else
{
TopIndex += rows;
TopIndex += Rows;
}
}
}

View File

@@ -6,7 +6,13 @@ namespace VAR.Toolbox.Controls
{
public SubFrame()
{
Font = new System.Drawing.Font(Font.Name, ControlsUtils.GetFontSize(this, 8.25f), Font.Style, Font.Unit, Font.GdiCharSet, Font.GdiVerticalFont);
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

@@ -6,6 +6,11 @@ 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);

View File

@@ -6,6 +6,11 @@ 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);

View File

@@ -23,8 +23,11 @@ namespace VAR.Toolbox
string executingAssemblyPath = Assembly.GetExecutingAssembly().Location;
string dirName = Path.GetDirectoryName(executingAssemblyPath);
string execName = Path.GetFileNameWithoutExtension(executingAssemblyPath);
string[] assemblyPaths = Directory.GetFiles(dirName, string.Format("{0}*.dll", execName));
if (dirName != null)
{
string[] assemblyPaths = Directory.GetFiles(dirName, $"{execName}*.dll");
foreach (string assemblyPath in assemblyPaths) { AssemblyLoadFull(assemblyPath); }
}
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
@@ -45,19 +48,25 @@ namespace VAR.Toolbox
Application.Exit();
}
private static Assembly AssemblyLoadFull(string fullPath, List<string> allAssemblyNames = null)
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) { }
if (asm == null) { return null; }
catch (Exception)
{
// ignored
}
if (asm == null) { return; }
allAssemblyNames.Add(asm.GetName().Name);
// Load dependencies
@@ -67,13 +76,10 @@ namespace VAR.Toolbox
{
if (allAssemblyNames.Contains(asmName.Name) == false)
{
string fullPathAux = string.Format("{0}/{1}.dll", dirPath, asmName.Name);
Assembly asmAux = AssemblyLoadFull(fullPathAux, allAssemblyNames);
string fullPathAux = $"{dirPath}/{asmName.Name}.dll";
AssemblyLoadFull(fullPathAux, allAssemblyNames);
}
}
}
return asm;
}
}
}

View File

@@ -11,20 +11,20 @@ namespace VAR.Toolbox.UI
public string Title
{
get { return base.Text; }
set { Text = value; }
get => base.Text;
set => Text = value;
}
public string Description
{
get { return lblDescription.Text; }
set { lblDescription.Text = value; }
get => lblDescription.Text;
set => lblDescription.Text = value;
}
public string Value
{
get { return txtValue.Text; }
set { txtValue.Text = value; }
get => txtValue.Text;
set => txtValue.Text = value;
}
}
}

View File

@@ -1,4 +1,5 @@
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using VAR.Toolbox.Controls;
@@ -13,20 +14,17 @@ namespace VAR.Toolbox.UI
public string Title
{
get { return base.Text; }
set { Text = value; }
get => base.Text;
set => Text = value;
}
public void LoadItems(List<string> items)
{
lsbItems.Items.Clear();
lsbItems.Items.AddRange(items.ToArray());
lsbItems.Items.AddRange(items.ToArray<object>());
}
public string Value
{
get { return (lsbItems.SelectedItem as string) ?? string.Empty; }
}
public string Value => (lsbItems.SelectedItem as string) ?? string.Empty;
private void lsbItems_SelectedIndexChanged(object sender, System.EventArgs e)
{

View File

@@ -5,7 +5,6 @@ using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Windows.Forms;
using VAR.Toolbox.Code;
using VAR.Toolbox.Code.Windows;
using VAR.Toolbox.Controls;
@@ -16,14 +15,14 @@ namespace VAR.Toolbox.UI
{
#region Declarations
private bool _closing = false;
private bool _closing;
private Label lblToolbox;
private CButton btnExit;
private Label _lblToolbox;
private CButton _btnExit;
private NotifyIcon niTray = null;
private NotifyIcon _niTray;
private static FrmToolbox _currentInstance = null;
private static FrmToolbox _currentInstance;
#endregion Declarations
@@ -39,7 +38,7 @@ namespace VAR.Toolbox.UI
{
Icon ico = Icon.ExtractAssociatedIcon(Application.ExecutablePath);
Icon = ico;
niTray.Icon = ico;
_niTray.Icon = ico;
}
protected override void OnFormClosing(FormClosingEventArgs e)
@@ -74,7 +73,7 @@ namespace VAR.Toolbox.UI
if (dialogResult == DialogResult.Yes)
{
_closing = true;
niTray.Visible = false;
_niTray.Visible = false;
CloseChildWindows();
Close();
}
@@ -102,18 +101,18 @@ namespace VAR.Toolbox.UI
private void InitializeDynamicComponents()
{
SuspendLayout();
const int toolSpacing = 5;
const int toolWidth = 200;
const int windowSpacing = 10;
int nextYLocation = 0;
const int ToolSpacing = 5;
const int ToolWidth = 200;
const int WindowSpacing = 10;
// Get list of ToolForms
Type iToolForm = typeof(IToolForm);
IEnumerable<Type> toolFormTypes = ReflectionUtils.GetTypesOfInterface(iToolForm);
Dictionary<string, Type> dictToolFormTypes = toolFormTypes.ToDictionary(t =>
{
IToolForm toolForm = System.Runtime.Serialization.FormatterServices.GetUninitializedObject(t) as IToolForm;
return toolForm.ToolName;
IToolForm toolForm =
System.Runtime.Serialization.FormatterServices.GetUninitializedObject(t) as IToolForm;
return toolForm?.ToolName ?? t.Name;
});
// Get list of ToolPanels
@@ -121,27 +120,28 @@ namespace VAR.Toolbox.UI
IEnumerable<Type> toolPanelTypes = ReflectionUtils.GetTypesOfInterface(iToolPanel).OrderBy(t => t.Name);
// lblToolbox
lblToolbox = new Label
_lblToolbox = new Label
{
Anchor = (AnchorStyles.Top | AnchorStyles.Left | AnchorStyles.Right),
Font = new Font(Font.FontFamily, ControlsUtils.GetFontSize(this, 27.75F), FontStyle.Bold, GraphicsUnit.Point, 0),
Location = new Point(windowSpacing, windowSpacing),
Font = new Font(Font.FontFamily, ControlsUtils.GetFontSize(this, 27.75F), FontStyle.Bold,
GraphicsUnit.Point, 0),
Location = new Point(WindowSpacing, WindowSpacing),
Margin = new Padding(0, 0, 0, 0),
Name = "lblToolbox",
Size = new Size(toolWidth * 2 + toolSpacing, 50),
Size = new Size(ToolWidth * 2 + ToolSpacing, 50),
TabIndex = 6,
Text = "Toolbox",
TextAlign = ContentAlignment.MiddleCenter
};
lblToolbox.MouseDown += DragWindow_MouseDown;
nextYLocation = lblToolbox.Location.Y + lblToolbox.Size.Height + windowSpacing;
_lblToolbox.MouseDown += DragWindow_MouseDown;
int nextYLocation = _lblToolbox.Location.Y + _lblToolbox.Size.Height + WindowSpacing;
// Tool buttons
int idxButton = 0;
int xStartButtons = windowSpacing;
int xStepButtons = toolWidth + toolSpacing;
int xStartButtons = WindowSpacing;
int xStepButtons = ToolWidth + ToolSpacing;
int yStartButtons = nextYLocation;
int yStepButtons = 40 + toolSpacing;
int yStepButtons = 40 + ToolSpacing;
IEnumerable<KeyValuePair<string, Type>> sortedToolForms = dictToolFormTypes.OrderBy(p => p.Key);
foreach (KeyValuePair<string, Type> p in sortedToolForms)
{
@@ -150,15 +150,15 @@ namespace VAR.Toolbox.UI
CButton btn = new CButton
{
Location = new Point(x, y),
Name = string.Format("btn{0}", p.Key),
Size = new Size(toolWidth, 40),
Name = $"btn{p.Key}",
Size = new Size(ToolWidth, 40),
TabIndex = idxButton,
Text = p.Key,
};
btn.Click += (s, e) => { CreateWindow(p.Value); };
Controls.Add(btn);
nextYLocation = btn.Location.Y + btn.Size.Height + windowSpacing;
nextYLocation = btn.Location.Y + btn.Size.Height + WindowSpacing;
idxButton++;
}
@@ -166,48 +166,51 @@ namespace VAR.Toolbox.UI
// Tool panels
int idxPanel = 0;
int yStartPanels = nextYLocation;
int xStartPanels = windowSpacing;
int xStartPanels = WindowSpacing;
int xNextPanels = xStartPanels;
foreach (Type t in toolPanelTypes)
{
ContainerControl pnl = Activator.CreateInstance(t) as ContainerControl;
if (pnl == null) { continue; }
pnl.Location = new Point(xNextPanels, yStartPanels);
Controls.Add(pnl);
int tempNextYLocation = pnl.Location.Y + pnl.Size.Height + windowSpacing;
int tempNextYLocation = pnl.Location.Y + pnl.Size.Height + WindowSpacing;
if (nextYLocation < tempNextYLocation)
{
nextYLocation = tempNextYLocation;
}
xNextPanels = pnl.Location.X + pnl.Size.Width + toolSpacing;
xNextPanels = pnl.Location.X + pnl.Size.Width + ToolSpacing;
if ((idxPanel % 2) == 1)
{
yStartPanels = nextYLocation;
xNextPanels = xStartPanels;
}
idxPanel++;
}
// btnExit
btnExit = new CButton
_btnExit = new CButton
{
Anchor = ((AnchorStyles.Bottom | AnchorStyles.Left)
| AnchorStyles.Right),
Location = new Point(windowSpacing, nextYLocation),
Location = new Point(WindowSpacing, nextYLocation),
Name = "btnExit",
Size = new Size(toolWidth * 2 + toolSpacing, 40),
Size = new Size(ToolWidth * 2 + ToolSpacing, 40),
TabIndex = 7,
Text = "Exit",
};
btnExit.Click += BtnExit_Click;
nextYLocation = btnExit.Location.Y + btnExit.Size.Height + windowSpacing;
_btnExit.Click += BtnExit_Click;
nextYLocation = _btnExit.Location.Y + _btnExit.Size.Height + WindowSpacing;
// FrmToolbox
ClientSize = new Size(425, nextYLocation);
Controls.Add(btnExit);
Controls.Add(lblToolbox);
Controls.Add(_btnExit);
Controls.Add(_lblToolbox);
FormBorderStyle = FormBorderStyle.Fixed3D;
MaximizeBox = false;
Name = "FrmToolbox";
@@ -219,12 +222,12 @@ namespace VAR.Toolbox.UI
ResumeLayout(false);
// niTray
niTray = new NotifyIcon
_niTray = new NotifyIcon
{
Text = "VAR.Toolbox",
Visible = true
};
niTray.MouseClick += NiTray_MouseClick;
_niTray.MouseClick += NiTray_MouseClick;
ResumeLayout();
@@ -234,21 +237,22 @@ namespace VAR.Toolbox.UI
#region Window handling
private Form CreateWindow(Type type)
private void CreateWindow(Type type)
{
var frm = Activator.CreateInstance(type) as Form;
if (frm == null)
{
return null;
return;
}
_forms.Add(frm);
frm.FormClosing += FrmChild_FormClosing;
if ((frm as IToolForm)?.HasIcon == false)
{
frm.Icon = Icon;
}
frm.Show();
return frm;
}
private readonly List<Form> _forms = new List<Form>();
@@ -263,7 +267,7 @@ namespace VAR.Toolbox.UI
CloseChildWindows();
}
private bool _wasMinimized = false;
private bool _wasMinimized;
private void FrmToolbox_Resize(object sender, EventArgs e)
{
@@ -272,6 +276,7 @@ namespace VAR.Toolbox.UI
_wasMinimized = true;
HideChildWindows();
}
if (FormWindowState.Normal == WindowState && _wasMinimized)
{
_wasMinimized = false;
@@ -312,6 +317,7 @@ namespace VAR.Toolbox.UI
{
List<T> list = new List<T>();
if (_currentInstance == null) { return list; }
foreach (Form frm in _currentInstance._forms)
{
if (frm is T)
@@ -319,10 +325,10 @@ namespace VAR.Toolbox.UI
list.Add((T)(object)frm);
}
}
return list;
}
#endregion Window handling
}
}

View File

@@ -1,6 +1,4 @@
namespace VAR.Toolbox.UI
{
public interface IToolPanel
{
}
public interface IToolPanel { }
}

View File

@@ -1,4 +1,4 @@
namespace VAR.Toolbox.UI
namespace VAR.Toolbox.UI.Tools
{
partial class FrmCoder
{

View File

@@ -1,25 +1,26 @@
using System;
using System.Linq;
using System.Windows.Forms;
using VAR.Toolbox.Code.TextCoders;
using VAR.Toolbox.Controls;
namespace VAR.Toolbox.UI
namespace VAR.Toolbox.UI.Tools
{
public partial class FrmCoder : Frame, IToolForm
{
public string ToolName { get { return "Coder"; } }
public string ToolName => "Coder";
public bool HasIcon { get { return false; } }
public bool HasIcon => false;
public FrmCoder()
{
InitializeComponent();
cboCode.Items.AddRange(TextCoderFactory.GetNames());
cboCode.Items.AddRange(TextCoderFactory.GetNames().ToArray<object>());
cboCode.SelectedIndex = 1;
}
private ITextCoder _coder = null;
private ITextCoder _coder;
private void BtnDecode_Click(object sender, EventArgs e)
{
@@ -32,6 +33,7 @@ namespace VAR.Toolbox.UI
{
MessageBox.Show(ex.Message);
}
txtOutput.Text = output;
}
@@ -46,14 +48,13 @@ namespace VAR.Toolbox.UI
{
MessageBox.Show(ex.Message);
}
txtOutput.Text = output;
}
private void BtnSwap_Click(object sender, EventArgs e)
{
string temp = txtOutput.Text;
txtOutput.Text = txtInput.Text;
txtInput.Text = temp;
(txtOutput.Text, txtInput.Text) = (txtInput.Text, txtOutput.Text);
}
private void CboCode_SelectedIndexChanged(object sender, EventArgs e)

View File

@@ -5,7 +5,7 @@ using VAR.Toolbox.Code;
using VAR.Toolbox.Code.Windows;
using VAR.Toolbox.Controls;
namespace VAR.Toolbox.UI
namespace VAR.Toolbox.UI.Tools
{
public class FrmCover : Frame
{
@@ -14,14 +14,19 @@ namespace VAR.Toolbox.UI
private readonly Random _rnd = new Random();
private readonly Timer _timer = new Timer();
private readonly uint _mouseX = 0;
private readonly uint _mouseY = 0;
private uint _mouseX;
private uint _mouseY;
#endregion Declarations
#region Form life cycle
public FrmCover()
{
InitializeComponent();
}
private void InitializeComponent()
{
Mouse.GetPosition(out _mouseX, out _mouseY);
@@ -47,6 +52,7 @@ namespace VAR.Toolbox.UI
{
r = Rectangle.Union(r, s.Bounds);
}
Top = r.Top;
Left = r.Left;
Width = r.Width;
@@ -91,7 +97,11 @@ namespace VAR.Toolbox.UI
(_rnd.Next() % 11) - 5,
(_rnd.Next() % 11) - 5);
}
catch (Exception) { } // ignore exceptions moving mouse
catch (Exception)
{
// ignored exceptions moving mouse
}
_timer.Stop();
_timer.Start();
}

View File

@@ -1,4 +1,4 @@
namespace VAR.Toolbox.UI
namespace VAR.Toolbox.UI.Tools
{
partial class FrmIPScan
{

View File

@@ -6,13 +6,13 @@ using System.Threading;
using System.Windows.Forms;
using VAR.Toolbox.Controls;
namespace VAR.Toolbox.UI
namespace VAR.Toolbox.UI.Tools
{
public partial class FrmIPScan : Frame, IToolForm
{
public string ToolName { get { return "IPScan"; } }
public string ToolName => "IPScan";
public bool HasIcon { get { return false; } }
public bool HasIcon => false;
public FrmIPScan()
{
@@ -24,19 +24,20 @@ namespace VAR.Toolbox.UI
private void FrmIPScan_Disposed(object sender, EventArgs e)
{
running = false;
_running = false;
}
private void PrintStatus(string status)
{
if (lblStatus.IsDisposed) { return; }
if (lblStatus.InvokeRequired)
{
lblStatus.Invoke((MethodInvoker)(() => { lblStatus.Text = string.Format("Status: {0}", status); }));
lblStatus.Invoke((MethodInvoker)(() => { lblStatus.Text = $"Status: {status}"; }));
}
else
{
lblStatus.Text = string.Format("Status: {0}", status);
lblStatus.Text = $"Status: {status}";
Application.DoEvents();
}
}
@@ -44,6 +45,7 @@ namespace VAR.Toolbox.UI
private void Control_SetEnabled(Control ctrl, bool enabled)
{
if (ctrl.IsDisposed) { return; }
if (ctrl.InvokeRequired)
{
ctrl.Invoke((MethodInvoker)(() => { ctrl.Enabled = enabled; }));
@@ -63,23 +65,23 @@ namespace VAR.Toolbox.UI
private void BtnStop_Click(object sender, EventArgs e)
{
running = false;
_running = false;
}
private bool running = false;
private bool _running;
private void IPScan(string ipBase)
{
Control_SetEnabled(btnScan, false);
running = true;
ctrOutput.AddLine(string.Format("IPScan started at {0}", DateTime.UtcNow.ToString("s")));
for (int i = 1; i < 255 && running; i++)
_running = true;
ctrOutput.AddLine($"IPScan started at {DateTime.UtcNow:s}");
for (int i = 1; i < 255 && _running; i++)
{
string ip = ipBase + i.ToString();
PrintStatus(string.Format("Scanning {0}", ip));
PrintStatus($"Scanning {ip}");
Ping p = new Ping();
PingReply pingReply = p.Send(ip, 100);
if (pingReply.Status == IPStatus.Success)
if (pingReply != null && pingReply.Status == IPStatus.Success)
{
string name = "?";
try
@@ -88,14 +90,16 @@ namespace VAR.Toolbox.UI
name = hostEntry.HostName;
}
catch (SocketException) { }
ctrOutput.AddLine(string.Format("{0} ({1}) is up: ({2} ms)", ip, name, pingReply.RoundtripTime));
}
Application.DoEvents();
}
PrintStatus("Idle");
ctrOutput.AddLine(string.Format("IPScan ended at {0}", DateTime.UtcNow.ToString("s")));
Control_SetEnabled(btnScan, true);
ctrOutput.AddLine($"{ip} ({name}) is up: ({pingReply.RoundtripTime} ms)");
}
Application.DoEvents();
}
PrintStatus("Idle");
ctrOutput.AddLine($"IPScan ended at {DateTime.UtcNow:s}");
Control_SetEnabled(btnScan, true);
}
}
}

View File

@@ -1,4 +1,4 @@
namespace VAR.Toolbox.UI
namespace VAR.Toolbox.UI.Tools
{
partial class FrmNetworkInfo
{

View File

@@ -7,13 +7,13 @@ using System.Text;
using System.Windows.Forms;
using VAR.Toolbox.Controls;
namespace VAR.Toolbox.UI
namespace VAR.Toolbox.UI.Tools
{
public partial class FrmNetworkInfo : Frame, IToolForm
{
public string ToolName { get { return "NetworkInfo"; } }
public string ToolName => "NetworkInfo";
public bool HasIcon { get { return false; } }
public bool HasIcon => false;
public FrmNetworkInfo()
{
@@ -39,6 +39,7 @@ namespace VAR.Toolbox.UI
{
var listItem = ddlNetworkInterfaces.SelectedItem as ListItem;
if (listItem == null) { return; }
RefreshInterface(listItem.ID);
}
@@ -59,9 +60,11 @@ namespace VAR.Toolbox.UI
{
found = true;
if (it.Text != nic.Description) { it.Text = nic.Description; }
break;
}
}
if (found == false)
{
ddlNetworkInterfaces.Items.Add(new ListItem { ID = nic.Id, Text = nic.Description });
@@ -69,7 +72,7 @@ namespace VAR.Toolbox.UI
}
}
private string _networkInterfaceId = null;
private string _networkInterfaceId;
private void RefreshInterface()
{
@@ -92,16 +95,23 @@ namespace VAR.Toolbox.UI
private void RefreshInterface(NetworkInterface nic)
{
if (txtID.Text != nic.Id) { txtID.Text = nic.Id; }
if (txtName.Text != nic.Name) { txtName.Text = nic.Name; }
string status = nic.OperationalStatus.ToString();
if (txtStatus.Text != status) { txtStatus.Text = status; }
string speed = FormatNetworkSpeedUnits(nic.Speed);
if (txtSpeed.Text != speed) { txtSpeed.Text = speed; }
if (txtDescription.Text != nic.Description) { txtDescription.Text = nic.Description; }
string strInterface = nic.NetworkInterfaceType.ToString();
if (txtInterface.Text != strInterface) { txtInterface.Text = strInterface; }
string strMac = FormatPhysicalAddress(nic.GetPhysicalAddress().GetAddressBytes());
if (txtMAC.Text != strMac) { txtMAC.Text = strMac; }
StringBuilder sbIPs = new StringBuilder();
IPInterfaceProperties ipInterfaceProperties = nic.GetIPProperties();
sbIPs.AppendLine("****** IPs *****");
@@ -109,18 +119,21 @@ namespace VAR.Toolbox.UI
{
sbIPs.AppendLine(uniAddress.Address.ToString());
}
sbIPs.AppendLine();
sbIPs.AppendLine("****** Gateways *****");
foreach (GatewayIPAddressInformation gwAddress in ipInterfaceProperties.GatewayAddresses)
{
sbIPs.AppendLine(gwAddress.Address.ToString());
}
sbIPs.AppendLine();
sbIPs.AppendLine("****** DNSs *****");
foreach (IPAddress dnsAddress in ipInterfaceProperties.DnsAddresses)
{
sbIPs.AppendLine(dnsAddress.ToString());
}
string strIPs = sbIPs.ToString();
if (txtIPs.Text != strIPs) { txtIPs.Text = strIPs; }
}
@@ -128,39 +141,44 @@ namespace VAR.Toolbox.UI
private static string FormatNetworkSpeedUnits(long speed)
{
decimal dSpeed;
if (speed < 1000)
{
return string.Format("{0}bps", speed);
return $"{speed}bps";
}
dSpeed = speed / (decimal)1000;
decimal dSpeed = speed / (decimal)1000;
if (dSpeed < 1000)
{
return string.Format("{0}kbps", Math.Round(dSpeed, 2));
return $"{Math.Round(dSpeed, 2)}kbps";
}
dSpeed /= 1000;
if (dSpeed < 1000)
{
return string.Format("{0}mbps", Math.Round(dSpeed, 2));
return $"{Math.Round(dSpeed, 2)}mbps";
}
dSpeed /= 1000;
if (dSpeed < 1000)
{
return string.Format("{0}gbps", Math.Round(dSpeed, 2));
return $"{Math.Round(dSpeed, 2)}gbps";
}
dSpeed /= 1000;
return string.Format("{0}tbps", Math.Round(dSpeed, 2));
return $"{Math.Round(dSpeed, 2)}tbps";
}
private static string FormatPhysicalAddress(byte[] address)
{
StringBuilder sbAddres = new StringBuilder();
StringBuilder sbAddress = new StringBuilder();
foreach (byte b in address)
{
if (sbAddres.Length > 0) { sbAddres.Append(":"); }
sbAddres.AppendFormat("{0:X2}", b);
if (sbAddress.Length > 0) { sbAddress.Append(":"); }
sbAddress.AppendFormat("{0:X2}", b);
}
return sbAddres.ToString();
return sbAddress.ToString();
}
}
@@ -169,8 +187,9 @@ namespace VAR.Toolbox.UI
public string Text { get; set; }
public string ID { get; set; }
public override string ToString() { return Text; }
public override string ToString()
{
return Text;
}
}
}

View File

@@ -1,4 +1,4 @@
namespace VAR.Toolbox.UI
namespace VAR.Toolbox.UI.Tools
{
partial class FrmProxyCmd
{

View File

@@ -2,19 +2,20 @@
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Windows.Forms;
using VAR.Toolbox.Code;
using VAR.Toolbox.Code.ProxyCmdExecutors;
using VAR.Toolbox.Controls;
namespace VAR.Toolbox.UI
namespace VAR.Toolbox.UI.Tools
{
public partial class FrmProxyCmd : Frame, IOutputHandler, IToolForm
{
public string ToolName { get { return "ProxyCmd"; } }
public string ToolName => "ProxyCmd";
public bool HasIcon { get { return false; } }
public bool HasIcon => false;
#region Declarations
@@ -45,6 +46,7 @@ namespace VAR.Toolbox.UI
Application.DoEvents();
return;
}
if (e.KeyCode == Keys.Return)
{
e.Handled = true;
@@ -58,35 +60,43 @@ namespace VAR.Toolbox.UI
PrepareProxyCmdExecutor();
new Thread(() => ExecuteCmd(cmd)).Start();
}
return;
}
if (e.KeyCode == Keys.Enter)
{
e.Handled = true;
return;
}
if (e.KeyCode == Keys.LineFeed)
{
e.Handled = true;
return;
}
if (e.KeyCode == Keys.Up)
{
e.Handled = true;
if (_currentHistoryIndex == -1) { _currentHistoryIndex = _cmdHistory.Count; }
_currentHistoryIndex--;
if (_currentHistoryIndex < 0)
{
_currentHistoryIndex = 0;
}
if (_currentHistoryIndex >= 0 && _currentHistoryIndex < _cmdHistory.Count)
{
txtInput.Text = _cmdHistory[_currentHistoryIndex];
txtInput.SelectionStart = txtInput.Text.Length;
txtInput.SelectionLength = 0;
}
return;
}
if (e.KeyCode == Keys.Down)
{
e.Handled = true;
@@ -105,7 +115,6 @@ namespace VAR.Toolbox.UI
txtInput.SelectionLength = 0;
}
}
return;
}
}
@@ -123,25 +132,25 @@ namespace VAR.Toolbox.UI
#region ProxyCmdExecutor
private IProxyCmdExecutor _proxyCmdExecutor = null;
private IProxyCmdExecutor _proxyCmdExecutor;
private void PrepareProxyCmdExecutor()
{
if (_proxyCmdExecutor == null)
{
_proxyCmdExecutor = ProxyCmdExecutorFactory.CreateFromConfig(GetCurrentConfig());
if (_proxyCmdExecutor == null)
{
_proxyCmdExecutor = new ProxyCmdExecutorDummy(string.Empty);
}
_proxyCmdExecutor = ProxyCmdExecutorFactory.CreateFromConfig(GetCurrentConfig()) ??
new ProxyCmdExecutorDummy(string.Empty);
}
}
private void CleanProxyCmdExecutor()
{
// ReSharper disable once SuspiciousTypeConversion.Global
if (_proxyCmdExecutor is IDisposable disposableProxyCmdExecutor)
{
disposableProxyCmdExecutor.Dispose();
}
_proxyCmdExecutor = null;
}
@@ -163,6 +172,7 @@ namespace VAR.Toolbox.UI
Logger.Log(ex);
OutputLine(ex.Message);
}
Monitor.Exit(_executionLock);
}
@@ -190,8 +200,9 @@ namespace VAR.Toolbox.UI
{
previousSelectedName = selectedConfig.Name;
}
ddlCurrentConfig.Items.Clear();
ddlCurrentConfig.Items.AddRange(configItems.ToArray());
ddlCurrentConfig.Items.AddRange(configItems.ToArray<object>());
ddlCurrentConfig.SelectedIndex = 0;
if (string.IsNullOrEmpty(previousSelectedName) == false)
{
@@ -210,6 +221,7 @@ namespace VAR.Toolbox.UI
{
var selectedConfig = ddlCurrentConfig.SelectedItem as ProxyCmdConfigItem;
if (selectedConfig == null) { return null; }
return selectedConfig.Config;
}

View File

@@ -1,4 +1,4 @@
namespace VAR.Toolbox.UI
namespace VAR.Toolbox.UI.Tools
{
partial class FrmProxyCmdConfig
{

View File

@@ -3,10 +3,11 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using VAR.Toolbox.Controls;
namespace VAR.Toolbox.UI
namespace VAR.Toolbox.UI.Tools
{
public partial class FrmProxyCmdConfig : Frame
{
@@ -21,7 +22,12 @@ namespace VAR.Toolbox.UI
private void LsvCmdProxyConfigs_SelectedIndexChanged(object sender, EventArgs e)
{
ProxyCmdConfigItem selectedConfig = lsvCmdProxyConfigs.SelectedItem as ProxyCmdConfigItem;
if (selectedConfig == null) { CleanConfig(); return; }
if (selectedConfig == null)
{
CleanConfig();
return;
}
ShowConfig(selectedConfig);
}
@@ -43,8 +49,8 @@ namespace VAR.Toolbox.UI
private void LoadData()
{
lsvCmdProxyConfigs.Items.Clear();
List<ProxyCmdConfigItem> configItems = FrmProxyCmdConfig.GetConfigurationItems();
lsvCmdProxyConfigs.Items.AddRange(configItems.ToArray());
List<ProxyCmdConfigItem> configItems = GetConfigurationItems();
lsvCmdProxyConfigs.Items.AddRange(configItems.ToArray<object>());
}
private void SaveData()
@@ -54,8 +60,10 @@ namespace VAR.Toolbox.UI
{
ProxyCmdConfigItem config = o as ProxyCmdConfigItem;
if (config == null) { continue; }
sbConfig.AppendFormat("{0}|{1}\n", config.Name, config.Config);
}
string configFileName = GetConfigFileName();
File.WriteAllText(configFileName, sbConfig.ToString());
@@ -95,6 +103,7 @@ namespace VAR.Toolbox.UI
selectedConfig.Name = txtCmdProxyConfigName.Text;
selectedConfig.Config = txtCmdProxyConfigContent.Text;
}
SaveData();
}
@@ -102,16 +111,20 @@ namespace VAR.Toolbox.UI
{
ProxyCmdConfigItem selectedConfig = lsvCmdProxyConfigs.SelectedItem as ProxyCmdConfigItem;
if (selectedConfig == null) { return; }
List<ProxyCmdConfigItem> configItems = new List<ProxyCmdConfigItem>();
foreach (object o in lsvCmdProxyConfigs.Items)
{
ProxyCmdConfigItem config = o as ProxyCmdConfigItem;
if (config == null) { continue; }
if (config.Name == selectedConfig.Name) { continue; }
configItems.Add(config);
}
lsvCmdProxyConfigs.Items.Clear();
lsvCmdProxyConfigs.Items.AddRange(configItems.ToArray());
lsvCmdProxyConfigs.Items.AddRange(configItems.ToArray<object>());
SaveData();
CleanConfig();
}
@@ -122,28 +135,23 @@ namespace VAR.Toolbox.UI
CleanConfig();
}
public static string GetConfigFileName()
private static string GetConfigFileName()
{
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 configFile = string.Format("{0}/{1}.ProxyCmd.cfg", path, filenameWithoutExtension);
string configFile = $"{path}/{filenameWithoutExtension}.ProxyCmd.cfg";
return configFile;
}
public static string[] GetConfigurationLines()
private static string[] GetConfigurationLines()
{
string configFile = GetConfigFileName();
string[] config;
if (File.Exists(configFile) == false)
{
config = new string[] { "Dummy|Dummy:" };
}
else
{
config = File.ReadAllLines(configFile);
}
string[] config = File.Exists(configFile) == false
? new[] { "Dummy|Dummy:" }
: File.ReadAllLines(configFile);
return config;
}
@@ -155,11 +163,13 @@ namespace VAR.Toolbox.UI
{
int idxSplit = configLine.IndexOf('|');
if (idxSplit < 0) { continue; }
string configName = configLine.Substring(0, idxSplit);
string configData = configLine.Substring(idxSplit + 1);
configItems.Add(new ProxyCmdConfigItem { Name = configName, Config = configData, });
}
return configItems;
}
}
@@ -168,6 +178,10 @@ namespace VAR.Toolbox.UI
{
public string Name { get; set; }
public string Config { get; set; }
public override string ToString() { return Name; }
public override string ToString()
{
return Name;
}
}
}

View File

@@ -1,4 +1,4 @@
namespace VAR.Toolbox.UI
namespace VAR.Toolbox.UI.Tools
{
partial class FrmScreenshooter
{
@@ -43,7 +43,7 @@
this.btnScreenshoot.TabIndex = 1;
this.btnScreenshoot.Text = "Screenshoot";
this.btnScreenshoot.UseVisualStyleBackColor = true;
this.btnScreenshoot.Click += new System.EventHandler(this.BtnScreenshoot_Click);
this.btnScreenshoot.Click += new System.EventHandler(this.BtnScreenshot_Click);
//
// picViewer
//

View File

@@ -5,43 +5,44 @@ using System.Windows.Forms;
using VAR.Toolbox.Code;
using VAR.Toolbox.Controls;
namespace VAR.Toolbox.UI
namespace VAR.Toolbox.UI.Tools
{
public partial class FrmScreenshooter : Frame, IToolForm
{
public string ToolName { get { return "Screenshooter"; } }
public string ToolName => "Screenshooter";
public bool HasIcon { get { return false; } }
public bool HasIcon => false;
private bool _repetitiveScreenshots = false;
private readonly Timer timTicker;
private Bitmap bmpScreen = null;
private bool _repetitiveScreenshots;
private readonly Timer _timTicker;
private Bitmap _bmpScreen;
public FrmScreenshooter()
{
InitializeComponent();
if (components == null) { components = new Container(); }
timTicker = new Timer(components)
_timTicker = new Timer(components)
{
Interval = 16,
Enabled = false
};
timTicker.Tick += TimTicker_Tick;
_timTicker.Tick += TimTicker_Tick;
}
private void BtnScreenshoot_Click(object sender, EventArgs e)
private void BtnScreenshot_Click(object sender, EventArgs e)
{
bmpScreen = Screenshooter.CaptureScreen(bmpScreen);
picViewer.ImageShow = bmpScreen;
_bmpScreen = Screenshoter.CaptureScreen(_bmpScreen);
picViewer.ImageShow = _bmpScreen;
}
private void TimTicker_Tick(object sender, EventArgs e)
{
timTicker.Stop();
bmpScreen = Screenshooter.CaptureScreen(bmpScreen);
picViewer.ImageShow = bmpScreen;
timTicker.Start();
_timTicker.Stop();
_bmpScreen = Screenshoter.CaptureScreen(_bmpScreen);
picViewer.ImageShow = _bmpScreen;
_timTicker.Start();
}
private void BtnStartStop_Click(object sender, EventArgs e)
@@ -51,15 +52,15 @@ namespace VAR.Toolbox.UI
{
_repetitiveScreenshots = false;
btnStartStop.Text = "Start";
timTicker.Stop();
timTicker.Enabled = false;
_timTicker.Stop();
_timTicker.Enabled = false;
}
else
{
_repetitiveScreenshots = true;
btnStartStop.Text = "Stop";
timTicker.Enabled = true;
timTicker.Start();
_timTicker.Enabled = true;
_timTicker.Start();
}
}
}

View File

@@ -1,4 +1,4 @@
namespace VAR.Toolbox.UI
namespace VAR.Toolbox.UI.Tools
{
partial class FrmTestWebService
{

View File

@@ -5,13 +5,13 @@ using System.Text;
using VAR.Toolbox.Code;
using VAR.Toolbox.Controls;
namespace VAR.Toolbox.UI
namespace VAR.Toolbox.UI.Tools
{
public partial class FrmTestWebService : Frame, IToolForm
{
public string ToolName { get { return "TestWebService"; } }
public string ToolName => "TestWebService";
public bool HasIcon { get { return false; } }
public bool HasIcon => false;
public FrmTestWebService()
{
@@ -25,9 +25,10 @@ namespace VAR.Toolbox.UI
string url = txtUrlSoap.Text;
string namespaceUrl = txtNamespaceUrlSoap.Text;
string method = txtMethodSoap.Text;
Dictionary<string, object> parms = StringToDictionary(txtParametersSoap.Text).ToDictionary(p => p.Key, p => (object)p.Value);
Dictionary<string, object> parameters = StringToDictionary(txtParametersSoap.Text)
.ToDictionary(p => p.Key, p => (object)p.Value);
string result = WebServicesUtils.CallSoapMethod(url, method, parms, namespaceUrl);
string result = WebServicesUtils.CallSoapMethod(url, method, parameters, namespaceUrl);
txtResultSoap.Text = result;
}
@@ -39,6 +40,7 @@ namespace VAR.Toolbox.UI
sbException.AppendFormat("{0}\r\n{1}\r\n\r\n", ex.Message, ex.StackTrace);
ex = ex.InnerException;
}
txtResultSoap.Text = sbException.ToString();
}
}
@@ -49,10 +51,10 @@ namespace VAR.Toolbox.UI
{
string url = txtUrlRest.Text;
string urlApiMethod = txtUrlApiMethodRest.Text;
Dictionary<string, string> parms = StringToDictionary(txtParametersRest.Text);
Dictionary<string, string> parameters = StringToDictionary(txtParametersRest.Text);
string body = txtBodyRest.Text;
string result = WebServicesUtils.CallApi(url, urlApiMethod, parms, null, stringContent: body);
string result = WebServicesUtils.CallApi(url, urlApiMethod, parameters, null, stringContent: body);
txtResultRest.Text = result;
}
@@ -64,42 +66,44 @@ namespace VAR.Toolbox.UI
sbException.AppendFormat("{0}\r\n{1}\r\n\r\n", ex.Message, ex.StackTrace);
ex = ex.InnerException;
}
txtResultRest.Text = sbException.ToString();
}
}
/// <summary>
/// Deseria una cadena a un diccionario string,string
/// Deserializa una cadena a un diccionario string,string
/// </summary>
/// <param name="str">The STR.</param>
/// <returns></returns>
/// <author>VAR</author>
public static Dictionary<string, string> StringToDictionary(string str)
private static Dictionary<string, string> StringToDictionary(string str)
{
var dic = new Dictionary<string, string>();
List<string> pairs = SplitUnscaped(str, ',');
List<string> pairs = SplitUnescaped(str, ',');
foreach (string pair in pairs)
{
List<string> values = SplitUnscaped(pair, ':');
List<string> values = SplitUnescaped(pair, ':');
if (values.Count < 2) continue;
string key = values[0].Replace("\\:", ":").Replace("\\,", ",");
string val = values[1].Replace("\\:", ":").Replace("\\,", ",");
dic.Add(key, val);
}
return dic;
}
/// <summary>
/// Parte una cadena usando un caracter, evitando usar las ocurrencias escapadas con '\\'
/// Parte una cadena usando un carácter, evitando usar las ocurrencias escapadas con '\\'
/// </summary>
/// <param name="str">The STR.</param>
/// <param name="splitter">The splitter.</param>
/// <returns></returns>
/// <author>VAR</author>
public static List<string> SplitUnscaped(string str, char splitter)
private static List<string> SplitUnescaped(string str, char splitter)
{
var strs = new List<string>();
var strings = new List<string>();
int j, i;
int n = str.Length;
@@ -108,15 +112,14 @@ namespace VAR.Toolbox.UI
if (str[i] == '\\') i++;
else if (str[i] == splitter)
{
strs.Add(str.Substring(j, i - j));
strings.Add(str.Substring(j, i - j));
j = i + 1;
}
}
if (i >= j) strs.Add(str.Substring(j, n - j));
return strs;
}
if (i >= j) strings.Add(str.Substring(j, n - j));
return strings;
}
}
}

View File

@@ -1,4 +1,4 @@
namespace VAR.Toolbox.UI
namespace VAR.Toolbox.UI.Tools
{
partial class FrmTunnelTCP
{

View File

@@ -4,21 +4,21 @@ using System.Net.Sockets;
using System.Threading;
using VAR.Toolbox.Controls;
namespace VAR.Toolbox.UI
namespace VAR.Toolbox.UI.Tools
{
public partial class FrmTunnelTCP : Frame, IToolForm
{
public string ToolName { get { return "TunnelTCP"; } }
public string ToolName => "TunnelTCP";
public bool HasIcon { get { return false; } }
public bool HasIcon => false;
private bool _running = false;
private bool _running;
private class ConnectedClient
{
public string hostRemoto = null;
public int puertoRemoto = 0;
public Socket socketCliente = null;
public string RemoteHost;
public int RemotePort;
public Socket ClientSocket;
}
public FrmTunnelTCP()
@@ -43,7 +43,7 @@ namespace VAR.Toolbox.UI
private void BtnRun_Click(object sender, EventArgs e)
{
if (_running == true) { return; }
if (_running) { return; }
_running = true;
btnStop.Enabled = true;
@@ -65,9 +65,7 @@ namespace VAR.Toolbox.UI
{
try
{
Socket sock;
sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
Socket sock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
sock.Bind(new IPEndPoint(IPAddress.Any, localPort));
sock.Listen(1000);
@@ -81,9 +79,9 @@ namespace VAR.Toolbox.UI
ConnectedClient client = new ConnectedClient
{
hostRemoto = remoteHost,
puertoRemoto = remotePort,
socketCliente = sockCliente,
RemoteHost = remoteHost,
RemotePort = remotePort,
ClientSocket = sockCliente,
};
Thread thread = new Thread(() =>
{
@@ -97,7 +95,7 @@ namespace VAR.Toolbox.UI
}
catch (Exception ex)
{
ctrOutput.AddLine("Excepcion: " + ex.Message);
ctrOutput.AddLine("Exception: " + ex.Message);
ctrOutput.AddLine("Backtrace:");
ctrOutput.AddLine(ex.StackTrace);
}
@@ -107,45 +105,47 @@ namespace VAR.Toolbox.UI
{
try
{
Socket remoteSock = null;
Socket clientSock = client.socketCliente;
bool threadRunning;
Socket clientSock = client.ClientSocket;
byte[] buffer = new byte[4096];
int len;
long totalSent = 0;
long totalRecv = 0;
long totalReceived = 0;
// Info
ctrOutput.AddLine(
DateTime.Now.ToString() +
DateTime.Now.ToString("s") +
" Nuevo Cliente: " +
((IPEndPoint)clientSock.RemoteEndPoint).Address);
// Conectar al host remoto
IPHostEntry EntryHostRemoto = Dns.GetHostEntry(client.hostRemoto);
IPAddress ipHostRemoto = null;
foreach (IPAddress addr in EntryHostRemoto.AddressList)
IPHostEntry entryHostRemoto = Dns.GetHostEntry(client.RemoteHost);
IPAddress ipRemoteHost = null;
foreach (IPAddress address in entryHostRemoto.AddressList)
{
if (addr.AddressFamily == AddressFamily.InterNetwork)
if (address.AddressFamily == AddressFamily.InterNetwork)
{
ipHostRemoto = addr;
ipRemoteHost = address;
break;
}
}
IPEndPoint endpHostRemoto = new IPEndPoint(ipHostRemoto, client.puertoRemoto);
remoteSock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
remoteSock.Connect(endpHostRemoto);
// Bucle de recepcion y envio entre el cliente y el servidor remoto
threadRunning = true;
if (ipRemoteHost == null) { return; }
IPEndPoint endPointRemoteHost = new IPEndPoint(ipRemoteHost, client.RemotePort);
Socket remoteSock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
remoteSock.Connect(endPointRemoteHost);
// Bucle de recepción y envío entre el cliente y el servidor remoto
bool threadRunning = true;
while (threadRunning && _running)
{
// Comprobar recepcion del cliente
// Comprobar recepción del cliente
int len;
if (clientSock.Poll(100, SelectMode.SelectRead))
{
if (clientSock.Available == 0)
{
// Cliente cierra conexion
// Cliente cierra conexión
threadRunning = false;
}
else
@@ -163,17 +163,18 @@ namespace VAR.Toolbox.UI
{
ctrOutput.AddLine("No se pudo enviar... (" + ex.Message + ")");
}
totalRecv += enviado;
totalReceived += enviado;
} while (enviado <= 0 && remoteSock.Connected);
}
}
// Comprobar recepcion del remoto
// Comprobar recepción del remoto
if (remoteSock.Poll(100, SelectMode.SelectRead))
{
if (remoteSock.Available == 0)
{
// Remoto cierra conexion
// Remoto cierra conexión
threadRunning = false;
}
else
@@ -192,6 +193,7 @@ namespace VAR.Toolbox.UI
ctrOutput.AddLine("No se pudo enviar... (" + ex.Message + ")");
Thread.Sleep(10);
}
totalSent += enviado;
} while (enviado <= 0 && clientSock.Connected);
}
@@ -200,10 +202,10 @@ namespace VAR.Toolbox.UI
// Info
ctrOutput.AddLine(
DateTime.Now.ToString() +
" Desconexion de cliente: " +
DateTime.Now.ToString("s") +
" Client disconnection: " +
((IPEndPoint)clientSock.RemoteEndPoint).Address +
" IN/OUT: " + UnidadesBytes(totalRecv) + "/" + UnidadesBytes(totalSent));
" IN/OUT: " + UnidadesBytes(totalReceived) + "/" + UnidadesBytes(totalSent));
// Cerrar conexiones
remoteSock.Close();
@@ -211,7 +213,7 @@ namespace VAR.Toolbox.UI
}
catch (Exception ex)
{
ctrOutput.AddLine("Excepcion: " + ex.Message);
ctrOutput.AddLine("Exception: " + ex.Message);
ctrOutput.AddLine("Backtrace:");
ctrOutput.AddLine(ex.StackTrace);
}
@@ -228,31 +230,30 @@ namespace VAR.Toolbox.UI
double number = n;
if (number < 1024)
{
return string.Format("{0} B", number);
return $"{number} B";
}
number /= 1024.0;
if (number < 1024)
{
return string.Format("{0:#.00} KiB", number);
return $"{number:#.00} KiB";
}
number /= 1024.0;
if (number < 1024)
{
return string.Format("{0:#.00} MiB", number);
return $"{number:#.00} MiB";
}
number /= 1024.0;
if (number < 1024)
{
return string.Format("{0:#.00} GiB", number);
return $"{number:#.00} GiB";
}
number /= 1024.0;
return string.Format("{0:#.00} TiB", number);
}
return $"{number:#.00} TiB";
}
}
}

View File

@@ -1,4 +1,4 @@
namespace VAR.Toolbox.UI
namespace VAR.Toolbox.UI.Tools
{
partial class FrmWebcam
{

View File

@@ -5,15 +5,15 @@ using System.Windows.Forms;
using VAR.Toolbox.Code;
using VAR.Toolbox.Controls;
namespace VAR.Toolbox.UI
namespace VAR.Toolbox.UI.Tools
{
public partial class FrmWebcam : Frame, IToolForm
{
public string ToolName { get { return "Webcam"; } }
public string ToolName => "Webcam";
public bool HasIcon { get { return false; } }
public bool HasIcon => false;
private Webcam webcam = null;
private Webcam _webcam;
public FrmWebcam()
{
@@ -32,30 +32,31 @@ namespace VAR.Toolbox.UI
private void FrmWebcam_FormClosed(object sender, FormClosedEventArgs e)
{
if (webcam != null)
if (_webcam != null)
{
webcam.Stop();
_webcam.Stop();
}
}
private void BtnStartStop_Click(object sender, EventArgs e)
{
if (webcam == null)
if (_webcam == null)
{
InitWebcam();
}
if (webcam != null)
if (_webcam != null)
{
if (webcam.Active)
if (_webcam.Active)
{
webcam.Stop();
_webcam.Stop();
btnStartStop.Text = "Start";
picWebcam.ImageShow = null;
webcam = null;
_webcam = null;
}
else
{
webcam.Start();
_webcam.Start();
btnStartStop.Text = "Stop";
}
}
@@ -64,9 +65,10 @@ namespace VAR.Toolbox.UI
private void InitWebcam()
{
if (cboWebcams.SelectedIndex < 0) { return; }
WebcamObject webcamObject = (WebcamObject)cboWebcams.SelectedItem;
webcam = new Webcam(webcamObject.Moniker);
webcam.NewFrame += Webcam_NewFrame;
_webcam = new Webcam(webcamObject.Moniker);
_webcam.NewFrame += Webcam_NewFrame;
}
private class WebcamObject
@@ -89,6 +91,7 @@ namespace VAR.Toolbox.UI
{
cboWebcams.Items.Add(new WebcamObject { Name = pair.Key, Moniker = pair.Value });
}
if (cboWebcams.Items.Count > 0)
{
cboWebcams.SelectedIndex = 0;

View File

@@ -6,6 +6,8 @@ using VAR.Json;
using VAR.Toolbox.Code.Windows;
using VAR.Toolbox.Controls;
// ReSharper disable UnusedAutoPropertyAccessor.Local
namespace VAR.Toolbox.UI.Tools
{
public partial class PnlActivity : SubFrame, IToolPanel
@@ -18,6 +20,7 @@ namespace VAR.Toolbox.UI.Tools
private void TimTicker_Tick(object sender, EventArgs e)
{
if (DesignMode) { return; }
timTicker.Stop();
string activeWindowTitle = User32.GetActiveWindowTitle();
@@ -90,26 +93,28 @@ namespace VAR.Toolbox.UI.Tools
};
// Write frame
JsonWriter jsonWriter = new Json.JsonWriter();
JsonWriter jsonWriter = new JsonWriter();
string line = jsonWriter.Write(frame);
try
{
StreamWriter outStream = GetOutputStreamWritter();
StreamWriter outStream = GetOutputStreamWriter();
outStream.WriteLine(line);
CloseOutputStreamWritter(outStream);
CloseOutputStreamWriter(outStream);
}
catch (Exception)
{
/* Nom Nom Nom */
}
catch (Exception) { /* Nom Nom Nom */}
}
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 fileOut = string.Format("{0}/Activity.{1}.txt", path,
DateTime.UtcNow.ToString("yyyy-MM-dd"));
string fileOut = $"{path}/Activity.{DateTime.UtcNow:yyyy-MM-dd}.txt";
return File.AppendText(fileOut);
}
catch (Exception)
@@ -118,14 +123,12 @@ namespace VAR.Toolbox.UI.Tools
}
}
private static void CloseOutputStreamWritter(StreamWriter stream)
private static void CloseOutputStreamWriter(StreamWriter stream)
{
if (stream != null)
{
stream.Close();
}
}
}
}

View File

@@ -1,4 +1,4 @@
namespace VAR.Toolbox.UI
namespace VAR.Toolbox.UI.Tools
{
partial class PnlCover
{

View File

@@ -4,7 +4,7 @@ using VAR.Toolbox.Code;
using VAR.Toolbox.Code.Windows;
using VAR.Toolbox.Controls;
namespace VAR.Toolbox.UI
namespace VAR.Toolbox.UI.Tools
{
public partial class PnlCover : SubFrame, IToolPanel
{
@@ -19,10 +19,11 @@ namespace VAR.Toolbox.UI
private void TimTicker_Tick(object sender, EventArgs e)
{
if (DesignMode) { return; }
timTicker.Stop();
uint inactiveTime = Win32.GetLastInputTime();
lblInactive.Text = string.Format("Inactive by {0} seconds", inactiveTime);
lblInactive.Text = $"Inactive by {inactiveTime} seconds";
if (chkAutoCover.Checked)
{
@@ -31,6 +32,7 @@ namespace VAR.Toolbox.UI
CoverScreen();
}
}
timTicker.Start();
}
@@ -39,7 +41,7 @@ namespace VAR.Toolbox.UI
CoverScreen();
}
private FrmCover _frmCover = null;
private FrmCover _frmCover;
private void CoverScreen()
{
@@ -52,6 +54,7 @@ namespace VAR.Toolbox.UI
_frmCover.Show();
return;
}
_frmCover = new FrmCover();
_frmCover.FormClosing += (sender, e) => { _frmCover = null; };
_frmCover.Show();
@@ -61,6 +64,5 @@ namespace VAR.Toolbox.UI
frmParent.WindowState = FormWindowState.Minimized;
}
}
}
}

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