diff --git a/.gitignore b/.gitignore index 839232a..d92ad33 100644 --- a/.gitignore +++ b/.gitignore @@ -5,3 +5,8 @@ /CSharpLibraryTools/.vs/CSharpLibraryTools/v16 /CSharpLibraryTools/CSharpLibraryTools/bin/Debug/netcoreapp3.1 /CSharpLibraryTools/CSharpLibraryTools/obj +/CSharpLibraryTools/.vs/CSharpLibraryTools/DesignTimeBuild +/CSharpLibraryTools/CoreActivities/bin/Debug/netcoreapp3.1 +/CSharpLibraryTools/CoreActivities/obj +/CSharpLibraryTools/.vs/CSharpLibraryTools/config +/CSharpLibraryTools/CoreActivities/bin/Debug diff --git a/CSharpLibraryTools/CSharpLibraryTools.sln b/CSharpLibraryTools/CSharpLibraryTools.sln index c3b3d17..fa2e605 100644 --- a/CSharpLibraryTools/CSharpLibraryTools.sln +++ b/CSharpLibraryTools/CSharpLibraryTools.sln @@ -3,7 +3,9 @@ Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio Version 16 VisualStudioVersion = 16.0.31129.286 MinimumVisualStudioVersion = 10.0.40219.1 -Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CSharpLibraryTools", "CSharpLibraryTools\CSharpLibraryTools.csproj", "{5C724B73-6CF8-4A5E-8114-EBC3D5AA832D}" +Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "CSharpLibraryTools", "CSharpLibraryTools\CSharpLibraryTools.csproj", "{5C724B73-6CF8-4A5E-8114-EBC3D5AA832D}" +EndProject +Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "CoreActivities", "CoreActivities\CoreActivities.csproj", "{E4431B92-3055-4E69-981F-DD1E4DA32179}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution @@ -15,6 +17,10 @@ Global {5C724B73-6CF8-4A5E-8114-EBC3D5AA832D}.Debug|Any CPU.Build.0 = Debug|Any CPU {5C724B73-6CF8-4A5E-8114-EBC3D5AA832D}.Release|Any CPU.ActiveCfg = Release|Any CPU {5C724B73-6CF8-4A5E-8114-EBC3D5AA832D}.Release|Any CPU.Build.0 = Release|Any CPU + {E4431B92-3055-4E69-981F-DD1E4DA32179}.Debug|Any CPU.ActiveCfg = Debug|Any CPU + {E4431B92-3055-4E69-981F-DD1E4DA32179}.Debug|Any CPU.Build.0 = Debug|Any CPU + {E4431B92-3055-4E69-981F-DD1E4DA32179}.Release|Any CPU.ActiveCfg = Release|Any CPU + {E4431B92-3055-4E69-981F-DD1E4DA32179}.Release|Any CPU.Build.0 = Release|Any CPU EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE diff --git a/CSharpLibraryTools/CSharpLibraryTools/AppSettingsInfo.cs b/CSharpLibraryTools/CSharpLibraryTools/AppSettingsInfo.cs new file mode 100644 index 0000000..79f04f5 --- /dev/null +++ b/CSharpLibraryTools/CSharpLibraryTools/AppSettingsInfo.cs @@ -0,0 +1,31 @@ +using Microsoft.Extensions.Configuration; +using System.IO; + +namespace CSharpLibraryTools +{ + /// + /// Note: While adding appsetting.json in console app, goto properties and select "Copy if newer" for "Copy to Output Directory" option. + /// Otherwise it will throw exception + /// + public static class AppSettingsInfo + { + public static string ConfigFileName { get; set; } = "appsettings.json"; + public static string CurrentDirectory = Directory.GetCurrentDirectory(); + + // Get a valued stored in the appsettings. + // Pass in a key like TestArea:TestKey to get Value + public static T GetCurrentValue(string Key) + { + var builder = new ConfigurationBuilder() + .SetBasePath(CurrentDirectory) + .AddJsonFile(ConfigFileName, optional: false, reloadOnChange: true) + .AddEnvironmentVariables(); + + IConfigurationRoot configuration = builder.Build(); + + return configuration.GetValue(Key); + } + + public static string CreateGoogleDriveAuthFile(string fileName) => $"{CurrentDirectory}\\{fileName}"; + } +} diff --git a/CSharpLibraryTools/CSharpLibraryTools/Application.cs b/CSharpLibraryTools/CSharpLibraryTools/Application.cs new file mode 100644 index 0000000..1650d15 --- /dev/null +++ b/CSharpLibraryTools/CSharpLibraryTools/Application.cs @@ -0,0 +1,81 @@ +using System; +using System.Linq; +using System.Threading.Tasks; + +namespace CSharpLibraryTools +{ + public class Application + { + private readonly ActiveProgramImp _activeProgramImp; + private readonly BrowseActivityImp _browseActivityImp; + private readonly DirectoryManagerImp _directoryManagerImp; + private readonly EgmaCvImp _egmaCv; + private readonly FileManagerImp _fileManagerImp; + private readonly RunningProgramImp _runningProgramImp; + private readonly ScreenCaptureImp _screenCaptureImp; + private readonly GoogleDriveApiImp _googleDriveApiImp; + + public Application(ActiveProgramImp activeProgramImp, + BrowseActivityImp browseActivityImp, + DirectoryManagerImp directoryManagerImp, + EgmaCvImp egmaCv, + FileManagerImp fileManagerImp, + RunningProgramImp runningProgramImp, + ScreenCaptureImp screenCaptureImp, + GoogleDriveApiImp googleDriveApiImp) + { + _activeProgramImp = activeProgramImp; + _browseActivityImp = browseActivityImp; + _directoryManagerImp = directoryManagerImp; + _egmaCv = egmaCv; + _fileManagerImp = fileManagerImp; + _runningProgramImp = runningProgramImp; + _screenCaptureImp = screenCaptureImp; + _googleDriveApiImp = googleDriveApiImp; + } + + public async Task Run() + { + TitlePrinter("Active Program Information"); + await _activeProgramImp.Run(); + PrintSeperator(20); + + TitlePrinter("Browser Activity"); + await _browseActivityImp.Run(); + PrintSeperator(20); + + TitlePrinter("Directory Manager"); + await _directoryManagerImp.Run(); + PrintSeperator(20); + + TitlePrinter("Webcam"); + await _egmaCv.Run(); + PrintSeperator(20); + + TitlePrinter("File Manager"); + await _fileManagerImp.Run(); + PrintSeperator(20); + + TitlePrinter("Running Programs"); + await _runningProgramImp.Run(); + PrintSeperator(20); + + TitlePrinter("Screen Capture"); + await _screenCaptureImp.Run(); + PrintSeperator(20); + + TitlePrinter("Google Drive Api"); + await _googleDriveApiImp.Run(); + PrintSeperator(20); + } + + public void TitlePrinter(string title) + => Console.WriteLine($"{title}\n{new string('-', title.Count())}"); + + public void PrintSeperator(int length) + { + var seperator = new string('=', length); + Console.WriteLine($"{seperator}\n{seperator}\n"); + } + } +} diff --git a/CSharpLibraryTools/CSharpLibraryTools/CSharpLibraryTools.csproj b/CSharpLibraryTools/CSharpLibraryTools/CSharpLibraryTools.csproj index c73e0d1..aa217a0 100644 --- a/CSharpLibraryTools/CSharpLibraryTools/CSharpLibraryTools.csproj +++ b/CSharpLibraryTools/CSharpLibraryTools/CSharpLibraryTools.csproj @@ -1,8 +1,30 @@ - + Exe netcoreapp3.1 + + + + + + + + + + + + + + + + Always + + + Always + + + diff --git a/CSharpLibraryTools/CSharpLibraryTools/Implementations/ActiveProgramImp.cs b/CSharpLibraryTools/CSharpLibraryTools/Implementations/ActiveProgramImp.cs new file mode 100644 index 0000000..1a9c1ec --- /dev/null +++ b/CSharpLibraryTools/CSharpLibraryTools/Implementations/ActiveProgramImp.cs @@ -0,0 +1,22 @@ +using CoreActivities.ActiveProgram; +using System; +using System.Threading.Tasks; + +namespace CSharpLibraryTools +{ + public class ActiveProgramImp + { + private readonly IActiveProgram _activeProgram; + + public ActiveProgramImp(IActiveProgram activeProgram) + => _activeProgram = activeProgram; + + public async Task Run() + { + await Task.Run(() => + { + Console.WriteLine($"Active Program: {_activeProgram.CaptureActiveProgramTitle()}"); + }); + } + } +} diff --git a/CSharpLibraryTools/CSharpLibraryTools/Implementations/BrowseActivityImp.cs b/CSharpLibraryTools/CSharpLibraryTools/Implementations/BrowseActivityImp.cs new file mode 100644 index 0000000..9a21d3a --- /dev/null +++ b/CSharpLibraryTools/CSharpLibraryTools/Implementations/BrowseActivityImp.cs @@ -0,0 +1,68 @@ +using CoreActivities.BrowserActivity; +using System; +using System.Threading.Tasks; + +namespace CSharpLibraryTools +{ + public class BrowseActivityImp + { + private readonly IBrowserActivity _browserActivity; + private readonly BrowserActivityEnumAdaptee _browserActivityEnumAdaptee; + + public BrowseActivityImp(IBrowserActivity browserActivity, + BrowserActivityEnumAdaptee browserActivityEnumAdaptee) + { + _browserActivity = browserActivity; + _browserActivityEnumAdaptee = browserActivityEnumAdaptee; + } + + public async Task Run() + { + await Task.Run(() => + { + //Check browser open or not + Console.WriteLine($"The browser {_browserActivityEnumAdaptee.ToDescriptionString(BrowserType.Chrome)} " + + $"{(_browserActivity.IsBrowserOpen(BrowserType.Chrome)?"is open": "is not open")}"); + + Console.WriteLine($"The browser {_browserActivityEnumAdaptee.ToDescriptionString(BrowserType.Edge)} " + + $"{(_browserActivity.IsBrowserOpen(BrowserType.Edge) ? "is open" : "is not open")}"); + + Console.WriteLine($"The browser {_browserActivityEnumAdaptee.ToDescriptionString(BrowserType.FireFox)} " + + $"{(_browserActivity.IsBrowserOpen(BrowserType.FireFox) ? "is open" : "is not open")}"); + + Console.WriteLine($"The browser {_browserActivityEnumAdaptee.ToDescriptionString(BrowserType.Opera)} " + + $"{(_browserActivity.IsBrowserOpen(BrowserType.Opera) ? "is open" : "is not open")}"); + + Console.WriteLine($"The browser {_browserActivityEnumAdaptee.ToDescriptionString(BrowserType.Safari)} " + + $"{(_browserActivity.IsBrowserOpen(BrowserType.Safari) ? "is open" : "is not open")}"); + + //Check open browser active url and tabs + if (_browserActivity.IsBrowserOpen(BrowserType.Chrome)) + { + var activeUrl = _browserActivity.EnlistActiveTabUrl(BrowserType.Chrome); + Console.WriteLine($"Active URL: {activeUrl}\n"); + + var activeTitle = _browserActivity.EnlistActiveTabTitle(BrowserType.Chrome); + Console.WriteLine($"Active Tab Title: {activeTitle}\n"); + + var tabs = _browserActivity.EnlistAllOpenTabs(BrowserType.Chrome); + foreach (var item in tabs) + Console.WriteLine($"Tab: {item}"); + } + + if (_browserActivity.IsBrowserOpen(BrowserType.Edge)) + { + var activeUrl = _browserActivity.EnlistActiveTabUrl(BrowserType.Edge); + Console.WriteLine($"Active URL: {activeUrl}\n"); + + var activeTitle = _browserActivity.EnlistActiveTabTitle(BrowserType.Chrome); + Console.WriteLine($"Active Tab Title: {activeTitle}\n"); + + var tabs = _browserActivity.EnlistAllOpenTabs(BrowserType.Edge); + foreach (var item in tabs) + Console.WriteLine($"Tab: {item}"); + } + }); + } + } +} diff --git a/CSharpLibraryTools/CSharpLibraryTools/Implementations/DirectoryManagerImp.cs b/CSharpLibraryTools/CSharpLibraryTools/Implementations/DirectoryManagerImp.cs new file mode 100644 index 0000000..6e09c46 --- /dev/null +++ b/CSharpLibraryTools/CSharpLibraryTools/Implementations/DirectoryManagerImp.cs @@ -0,0 +1,36 @@ +using CoreActivities.DirectoryManager; +using System; +using System.Threading.Tasks; + +namespace CSharpLibraryTools +{ + public class DirectoryManagerImp + { + private readonly IDirectoryManager _directoryManager; + + public DirectoryManagerImp(IDirectoryManager directoryManager) + { + _directoryManager = directoryManager; + } + + public async Task Run() + { + await Task.Run(() => + { + //The following prints the windows program data directorty path + Console.WriteLine($"ProgramData Directory: {_directoryManager.GetProgramDataDirectoryPath("Foobar")}"); + + //The following creates a directory under a drive and returns bool as created or not + var isCreated = _directoryManager.ChecknCreateDirectory("Foobar"); + if (isCreated) + Console.WriteLine("Has created Foobar under C:\\ProgramData"); + else + Console.WriteLine("The directory already exists. No need to create it."); + + //The following prints the file path of program data directory + var filePath = _directoryManager.CreateProgramDataFilePath("Foobar", "file.txt"); + Console.WriteLine($"File path: {filePath}\n"); + }); + } + } +} diff --git a/CSharpLibraryTools/CSharpLibraryTools/Implementations/EgmaCvImp.cs b/CSharpLibraryTools/CSharpLibraryTools/Implementations/EgmaCvImp.cs new file mode 100644 index 0000000..f8c7e2e --- /dev/null +++ b/CSharpLibraryTools/CSharpLibraryTools/Implementations/EgmaCvImp.cs @@ -0,0 +1,31 @@ +using CoreActivities.DirectoryManager; +using CoreActivities.EgmaCV; +using System; +using System.Collections.Generic; +using System.Text; +using System.Threading.Tasks; + +namespace CSharpLibraryTools +{ + public class EgmaCvImp + { + private readonly IDirectoryManager _directoryManager; + private readonly IEgmaCv _egmaCv; + + public EgmaCvImp(IDirectoryManager directoryManager, + IEgmaCv egmaCv) + { + _directoryManager = directoryManager; + _egmaCv = egmaCv; + } + + public async Task Run() + { + //The following capture image from webcam and store it on a file + var fileName = $"{Guid.NewGuid()}.jpg"; + var filePath = _directoryManager.CreateProgramDataFilePath("CSharpLib", fileName); + await _egmaCv.CaptureImageAsync(0, filePath); + Console.WriteLine($"Image Captured. FilePath: {filePath}"); + } + } +} diff --git a/CSharpLibraryTools/CSharpLibraryTools/Implementations/FileManagerImp.cs b/CSharpLibraryTools/CSharpLibraryTools/Implementations/FileManagerImp.cs new file mode 100644 index 0000000..3a44378 --- /dev/null +++ b/CSharpLibraryTools/CSharpLibraryTools/Implementations/FileManagerImp.cs @@ -0,0 +1,107 @@ +using CoreActivities.DirectoryManager; +using CoreActivities.EgmaCV; +using CoreActivities.FileManager; +using System; +using System.Collections.Generic; +using System.Threading.Tasks; + +namespace CSharpLibraryTools +{ + public class FileManagerImp + { + private readonly IDirectoryManager _directoryManager; + private readonly IFile _file; + private readonly IFileInfo _fileInfo; + private readonly IFileManager _fileManager; + private readonly IEgmaCv _egmaCv; + + public FileManagerImp(IDirectoryManager directoryManager, + IFile file, + IFileInfo fileInfo, + IFileManager fileManager, + IEgmaCv egmaCv) + { + _directoryManager = directoryManager; + _file = file; + _fileInfo = fileInfo; + _fileManager = fileManager; + _egmaCv = egmaCv; + } + + public async Task Run() + { + #region IFile implementation + var textList = new List + { + "This is me", + "I am the Dojo" + }; + + var singleText = "Hmm gots yoo"; + var folder = "CSharpLib"; + + //The following creates CSharpLib folder under C:\ProgramData and returns full path of specified file + var filePath = _directoryManager.CreateProgramDataFilePath(folder, "file.txt"); + var fileName = _file.FileName(filePath); + + Console.WriteLine($"FilePath: {filePath},\n FileName: {fileName}"); + + //Checks the file does exists. If not then create + if (!_file.DoesExists(filePath)) + _file.CreateFile(filePath); + + //Prints created file mime type + Console.WriteLine($"MimeType: {_file.GetMimeType(filePath)}\n"); + + //WriteAllTextAsync is same as WriteAllLineAsync but just write a string as text + //Note: Using WriteAllLineAsync and WriteAllTextAsync will override text of each other + await _file.WriteAllLineAsync(textList, filePath); + + //The following just add text on new line on a file + await _file.AppendAllLineAsync(textList, filePath); + await _file.AppendAllTextAsync(singleText, filePath); + + var allLines = await _file.ReadAllLineAsync(filePath); + var singleLine = await _file.ReadAllTextAsync(filePath); + + Console.WriteLine("ReadAllLineAsync"); + Console.WriteLine("----------------"); + foreach (var item in allLines) + Console.WriteLine(item); + Console.WriteLine(); + + Console.WriteLine("ReadAllTextAsync"); + Console.WriteLine("----------------"); + Console.WriteLine(singleLine); + Console.WriteLine(); + + Console.WriteLine("Printing base 64 string"); + Console.WriteLine("-----------------------"); + + var bytes = await _file.ReadFileAsByteAsync(filePath); + Console.WriteLine(_file.ConvertByteToBase64String(bytes)); + + var streanFilePath = _directoryManager.CreateProgramDataFilePath(folder, "streanFile.txt"); + await _file.WriteBytesStreamAsync(streanFilePath, bytes); + Console.WriteLine(); + + #endregion + + #region IFileInfo Implementation + Console.WriteLine($"Filesize: {_fileInfo.FileSize(filePath)} Bytes"); + Console.WriteLine($"IsReadonly: {_fileInfo.IsReadOnly(filePath)}"); + Console.WriteLine($"CreatedOn: {_fileInfo.CreatedOn(filePath)}"); + Console.WriteLine($"LastUpdateOn: {_fileInfo.LastUpdateOn(filePath)}"); + Console.WriteLine($"LastAccessOn: {_fileInfo.LastAccessOn(filePath)}"); + #endregion + + #region IFileManager Implementation + var writtenTextFilePath = _directoryManager.CreateProgramDataFilePath(folder, "written_text.txt"); + _fileManager.CreateFile(writtenTextFilePath); + + var readBytes = await _fileManager.ReadFileAsByteAsync(filePath); + await _fileManager.SaveByteStreamAsync(writtenTextFilePath, readBytes); + #endregion + } + } +} diff --git a/CSharpLibraryTools/CSharpLibraryTools/Implementations/GoogleDriveApiImp.cs b/CSharpLibraryTools/CSharpLibraryTools/Implementations/GoogleDriveApiImp.cs new file mode 100644 index 0000000..264ad76 --- /dev/null +++ b/CSharpLibraryTools/CSharpLibraryTools/Implementations/GoogleDriveApiImp.cs @@ -0,0 +1,99 @@ +using CoreActivities.DirectoryManager; +using CoreActivities.FileManager; +using CoreActivities.GoogleDriveApi; +using CoreActivities.GoogleDriveApi.Models; +using CoreActivities.RunningPrograms; +using System; +using System.Threading.Tasks; + +namespace CSharpLibraryTools +{ + public class GoogleDriveApiImp + { + private readonly IRunningPrograms _runningPrograms; + private readonly IDirectoryManager _directoryManager; + private readonly IFile _file; + private readonly IFileInfo _fileInfo; + private readonly IFileManager _fileManager; + private readonly IGoogleDriveApiManager _googleDriveApiManager; + + public GoogleDriveApiImp(IRunningPrograms runningPrograms, + IDirectoryManager directoryManager, + IFile file, + IFileInfo fileInfo, + IFileManager fileManager, + IGoogleDriveApiManager googleDriveApiManager) + { + _runningPrograms = runningPrograms; + _directoryManager = directoryManager; + _file = file; + _fileInfo = fileInfo; + _fileManager = fileManager; + _googleDriveApiManager = googleDriveApiManager; + } + + public async Task Run() + { + try + { + //Creating upload file path + var folder = "CSharpLib"; + var filePath = _directoryManager.CreateProgramDataFilePath(folder, $"google-drive-api-{Guid.NewGuid()}.txt"); + _fileManager.CreateFile(filePath); + + //Creating download file path + var downloadDir = $"{folder}Downlaod"; + var downloadFilePath = _directoryManager.CreateProgramDataFilePath(downloadDir, $"google-drive-api-download-{Guid.NewGuid()}.txt"); + _fileManager.CreateFile(downloadFilePath); + + //Gathering running program informations and writing info to upload file + var runningPrograms = _runningPrograms.GetRunningProgramsList(); + await _file.WriteAllLineAsync(runningPrograms, filePath); + + //Uploading the written file + Console.WriteLine("Uploading..."); + var file = await _googleDriveApiManager.UploadFileAsync(new UploadFileInfo + { + FileName = _file.FileName(filePath), + FilePath = filePath, + FileSize = _fileInfo.FileSize(filePath), + MimeType = _file.GetMimeType(filePath) + }); + + //Print present file information + Console.WriteLine("Printing..."); + await PrintFilesInAGoogleDirectory(); + Console.WriteLine(); + + //Downloading the uploaded file in download directory + Console.WriteLine("Downloading..."); + await _googleDriveApiManager.DownloadAsync(file, downloadFilePath); + + //Deleting the uploaded file + Console.WriteLine("Deleting..."); + await _googleDriveApiManager.DeleteAsync(file.Id); + + //Print present file information + Console.WriteLine("Printing..."); + await PrintFilesInAGoogleDirectory(); + Console.WriteLine(); + } + catch (Exception ex) + { + Console.WriteLine(ex.Message); + } + } + + private async Task PrintFilesInAGoogleDirectory() + { + var counter = 0; + var files = await _googleDriveApiManager.GetAllFilesAndFolders(); + + foreach (var item in files) + { + Console.WriteLine($"SL: {counter} Name: {item.Name}"); + counter++; + } + } + } +} diff --git a/CSharpLibraryTools/CSharpLibraryTools/Implementations/RunningProgramImp.cs b/CSharpLibraryTools/CSharpLibraryTools/Implementations/RunningProgramImp.cs new file mode 100644 index 0000000..5c863b3 --- /dev/null +++ b/CSharpLibraryTools/CSharpLibraryTools/Implementations/RunningProgramImp.cs @@ -0,0 +1,35 @@ +using CoreActivities.RunningPrograms; +using System; +using System.Threading.Tasks; + +namespace CSharpLibraryTools +{ + public class RunningProgramImp + { + private readonly IRunningPrograms _runningPrograms; + + public RunningProgramImp(IRunningPrograms runningPrograms) + { + _runningPrograms = runningPrograms; + } + + public async Task Run() + { + await Task.Run(() => + { + var runningProcesses = _runningPrograms.GetRunningProcessList(); + var runningPrograms = _runningPrograms.GetRunningProgramsList(); + + Console.WriteLine("Running Processes"); + foreach (var item in runningProcesses) + Console.WriteLine(item); + Console.WriteLine(); + + Console.WriteLine("Running Programs"); + foreach (var item in runningPrograms) + Console.WriteLine(item); + Console.WriteLine(); + }); + } + } +} diff --git a/CSharpLibraryTools/CSharpLibraryTools/Implementations/ScreenCaptureImp.cs b/CSharpLibraryTools/CSharpLibraryTools/Implementations/ScreenCaptureImp.cs new file mode 100644 index 0000000..005618b --- /dev/null +++ b/CSharpLibraryTools/CSharpLibraryTools/Implementations/ScreenCaptureImp.cs @@ -0,0 +1,42 @@ +using CoreActivities.DirectoryManager; +using CoreActivities.FileManager; +using CoreActivities.ScreenCapture; +using System; +using System.Threading.Tasks; + +namespace CSharpLibraryTools +{ + public class ScreenCaptureImp + { + private readonly IScreenCapture _screenCapture; + private readonly IDirectoryManager _directoryManager; + private readonly IFileManager _fileManager; + + public ScreenCaptureImp(IScreenCapture screenCapture, + IDirectoryManager directoryManager, + IFileManager fileManager) + { + _screenCapture = screenCapture; + _directoryManager = directoryManager; + _fileManager = fileManager; + } + + public async Task Run() + { + await Task.Run(() => + { + var folder = "CSharpLib"; + + Console.WriteLine("Capturing and storing image"); + + var filePath = _directoryManager.CreateProgramDataFilePath(folder, $"{Guid.NewGuid()}.jpg"); + _fileManager.CreateFile(filePath); + + var capturedScreen = _screenCapture.CaptureUserScreen(1920, 1080); + _fileManager.SaveBitmapImage(filePath, capturedScreen); + + Console.WriteLine($"Image Captured. FilePath: {filePath}"); + }); + } + } +} diff --git a/CSharpLibraryTools/CSharpLibraryTools/Program.cs b/CSharpLibraryTools/CSharpLibraryTools/Program.cs index ddec8b3..b394e2d 100644 --- a/CSharpLibraryTools/CSharpLibraryTools/Program.cs +++ b/CSharpLibraryTools/CSharpLibraryTools/Program.cs @@ -1,12 +1,60 @@ -using System; +using Autofac; +using CoreActivities.ActiveProgram; +using CoreActivities.BrowserActivity; +using CoreActivities.DirectoryManager; +using CoreActivities.EgmaCV; +using CoreActivities.FileManager; +using CoreActivities.GoogleDriveApi; +using CoreActivities.RunningPrograms; +using CoreActivities.ScreenCapture; +using System.Threading.Tasks; namespace CSharpLibraryTools { class Program { - static void Main(string[] args) + private static IContainer CompositionRoot() { - Console.WriteLine("Hello World!"); + var authFilePath = AppSettingsInfo.CreateGoogleDriveAuthFile(AppSettingsInfo.GetCurrentValue("AuthFileName")); + var directoryId = AppSettingsInfo.GetCurrentValue("DirectoryId"); + + var builder = new ContainerBuilder(); + + //Registering packages + builder.RegisterType(); + builder.RegisterModule(new ActiveProgramPackage()); + builder.RegisterModule(new BrowserActivityPackage()); + builder.RegisterModule(new DirectoryManagerPackage()); + builder.RegisterModule(new EgmaCvPackage()); + builder.RegisterModule(new FileManagerPackage()); + builder.RegisterModule(new GoogleDriveApiPackage(authFilePath, directoryId)); + builder.RegisterModule(new RunningProgramPackage()); + builder.RegisterModule(new ScreenCapturePackage()); + + //Registering implementations + builder.RegisterType() + .InstancePerLifetimeScope(); + builder.RegisterType() + .InstancePerLifetimeScope(); + builder.RegisterType() + .InstancePerLifetimeScope(); + builder.RegisterType() + .InstancePerLifetimeScope(); + builder.RegisterType() + .InstancePerLifetimeScope(); + builder.RegisterType() + .InstancePerLifetimeScope(); + builder.RegisterType() + .InstancePerLifetimeScope(); + builder.RegisterType() + .InstancePerLifetimeScope(); + + return builder.Build(); + } + + static async Task Main(string[] args) + { + await CompositionRoot().Resolve().Run(); } } } diff --git a/CSharpLibraryTools/CSharpLibraryTools/appsettings.json b/CSharpLibraryTools/CSharpLibraryTools/appsettings.json new file mode 100644 index 0000000..c41b33e --- /dev/null +++ b/CSharpLibraryTools/CSharpLibraryTools/appsettings.json @@ -0,0 +1,4 @@ +{ + "AuthFileName": "webcamsync.json", + "DirectoryId": "1UCNJUVNESqok8ziZUpsQB7ggtNj5nf3O" +} \ No newline at end of file diff --git a/CSharpLibraryTools/CSharpLibraryTools/webcamsync.json b/CSharpLibraryTools/CSharpLibraryTools/webcamsync.json new file mode 100644 index 0000000..fc39bb9 --- /dev/null +++ b/CSharpLibraryTools/CSharpLibraryTools/webcamsync.json @@ -0,0 +1,12 @@ +{ + "type": "service_account", + "project_id": "webcamsync", + "private_key_id": "a4fd4fb5c2719cedf20d7a98182616dd55dcb574", + "private_key": "-----BEGIN PRIVATE KEY-----\nMIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQC2D3MqeIoOEVo6\nJaoyEO+0BhaWdptYoWlT+wvGGO6U3sBJ1XNj0jB90+f9Kb6dGwBAueraV0+HZb6p\nOCzrUYa0rZm+AwbgAdXc+DwXfAFUspQUtRTf4zPfcDFSyHmMXr3XqL4sY/4CUmLC\nTdzm21uVClekSGjJcRRjfJQbjR6kZLzm6AVSsALjZxNXVtWlgbVnBrV/8Uo+Foji\nbM8OP3rRy751+Oy2ndSoBvplazxSqZDqr48tma2Fd7PJnuYOBBUz1cagAUOSCwlE\nMpMgAAIxYI9ynjf0KCbYofSzodOlTfMklWtMhHFwyI5UdGMONsbAROGBzL43G5Dx\ny6idUKDLAgMBAAECggEAHA5idYuQ3t0etfJC+acxgWEkzvglNXHebPI1nMgP0EJJ\niLdLqnjkPyfOSu3JcaWNEuxzvEUTPO7ZhHNjPLpaE3LjS+xkfVXbEsvwWsAh5l8E\nwfIr7tqxDkBYYYUCcjbRc7AN6oJYTRxMGtxr6+mnAd9PpUIBX/W8qh4zJtHHBJc8\nitfCYJEVqFbQxo8Vc9nLIlf5N9ITQisD+oLsqUBjbhAOac6YfubCmhr8LoEqrPnm\n5z5Q272y3sPvAlcgY/b7O1J3gBcCVFLvrGKu6YhUgaixML9Ui7b43RuchEwmuF50\n4CAyWuca3vFoBtSldCs2WapF3VveM5mjWtMqrXqUOQKBgQD1pz7SZjPMwLqh/C+1\nHIWhKDSgb38mvyTOxW6g9jf7RELcY4e81tPxes8so2IAsszAbrlavkA3EoirzqeH\nBqnmYIo+XX9LRDyRU9pQi7XUdBKyjyADbMH0TywrVxtU9/0n5R2PeS9Gj4jTX6b7\nVB7mW0HyF48KbCAaEbxo1moXSQKBgQC9uoOXA5C5jZDfyXHTpOykhYNMvvH9q7oS\nfNXY67uW9nmS2dpcKCZrX6upRSOAVrT1QptX1Oqm6jM1s2fyk21quihd4HmRtoYw\neauIXnHlzX8RFM58pGjH6NGxylCn2p7LqgDM9N5rOVnQXn+ODrZwbH+lRPYRY/KU\nwt78o7/TcwKBgQCz4qe/PLYb7tn8OobY8izsqVt4TI1o2znh7HOpjQPLjN4FMyE3\n6HzFbS/+uRnP9x62n5490+mEKp9IaIkG+Js7p2A0cRUBEdPke+n3Z4dcLy9t8B76\nQw74j22Bw0SxgPOx3jY6VPyIiB0i4/2MN7p050iwNg46DJmpXWmBv9lqeQKBgD0l\nG/2SP5UdQ6Brqox77WwEP1F/hDutmXUV2FFlf3piisHCBfaHVgJqvcb6qjtVNlKI\nmcnPq6QJfGGFJS3vR2cLAbFng6ZrPYnn3FlBntFhzd6yZu2SitZKeTIkMqQ199FJ\nQ6LKE9hYjlJx8gfVRAStYuHffLIUFPzOZNDk8RBzAoGAEbG9uLksc94qQxLbMOpi\nmbgCYCLLZ4z9npDLatQEMxBMy0JFG8vfoPyfD44fDCl2ubIzdZ8+P0twNxF2bEgg\nM5kg4uo7ZvHeCCEh0kPV78pGA6a1z5jqsVtv29CAx4Pa9C9ecAgCLH9POi9BIRWt\n2kUG0F6B7AesTnjXIVht8jE=\n-----END PRIVATE KEY-----\n", + "client_email": "webcamdatasnc@webcamsync.iam.gserviceaccount.com", + "client_id": "104904592306240427592", + "auth_uri": "https://accounts.google.com/o/oauth2/auth", + "token_uri": "https://oauth2.googleapis.com/token", + "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs", + "client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/webcamdatasnc%40webcamsync.iam.gserviceaccount.com" +} diff --git a/CSharpLibraryTools/CoreActivities/ActiveProgram/ActiveProgramAdaptee.cs b/CSharpLibraryTools/CoreActivities/ActiveProgram/ActiveProgramAdaptee.cs new file mode 100644 index 0000000..cf25655 --- /dev/null +++ b/CSharpLibraryTools/CoreActivities/ActiveProgram/ActiveProgramAdaptee.cs @@ -0,0 +1,26 @@ +using System; +using System.Runtime.InteropServices; +using System.Text; + +namespace CoreActivities.ActiveProgram +{ + public class ActiveProgramAdaptee + { + [DllImport("user32.dll")] + static extern IntPtr GetForegroundWindow(); + + [DllImport("user32.dll")] + static extern int GetWindowText(IntPtr hWnd, StringBuilder text, int count); + + public string GetActiveWindowTitle() + { + const int nChars = 256; + StringBuilder Buff = new StringBuilder(nChars); + IntPtr handle = GetForegroundWindow(); + if (GetWindowText(handle, Buff, nChars) > 0) + return Buff.ToString(); + + return null; + } + } +} diff --git a/CSharpLibraryTools/CoreActivities/ActiveProgram/ActiveProgramAdapter.cs b/CSharpLibraryTools/CoreActivities/ActiveProgram/ActiveProgramAdapter.cs new file mode 100644 index 0000000..d0a52ad --- /dev/null +++ b/CSharpLibraryTools/CoreActivities/ActiveProgram/ActiveProgramAdapter.cs @@ -0,0 +1,29 @@ +using System; + +namespace CoreActivities.ActiveProgram +{ + public interface IActiveProgram + { + string CaptureActiveProgramTitle(); + } + + public class ActiveProgramAdapter : IActiveProgram + { + private readonly ActiveProgramAdaptee _activeProgramAdaptee; + + public ActiveProgramAdapter(ActiveProgramAdaptee activeProgramAdaptee) + => _activeProgramAdaptee = activeProgramAdaptee; + + public string CaptureActiveProgramTitle() + { + var windowTitle = _activeProgramAdaptee.GetActiveWindowTitle(); + if (string.IsNullOrWhiteSpace(windowTitle)) + throw new Exception("No valid active program title has found"); + + if (windowTitle.Contains("\\")) + return windowTitle.Split("\\")[^1]; + else + return windowTitle; + } + } +} diff --git a/CSharpLibraryTools/CoreActivities/ActiveProgram/ActiveProgramPackage.cs b/CSharpLibraryTools/CoreActivities/ActiveProgram/ActiveProgramPackage.cs new file mode 100644 index 0000000..bfddab7 --- /dev/null +++ b/CSharpLibraryTools/CoreActivities/ActiveProgram/ActiveProgramPackage.cs @@ -0,0 +1,17 @@ +using Autofac; + +namespace CoreActivities.ActiveProgram +{ + public class ActiveProgramPackage : Module + { + protected override void Load(ContainerBuilder builder) + { + builder.RegisterType().As() + .InstancePerLifetimeScope(); + builder.RegisterType() + .InstancePerLifetimeScope(); + + base.Load(builder); + } + } +} diff --git a/CSharpLibraryTools/CoreActivities/BrowserActivity/BrowserActivityAdaptee.cs b/CSharpLibraryTools/CoreActivities/BrowserActivity/BrowserActivityAdaptee.cs new file mode 100644 index 0000000..82e38ab --- /dev/null +++ b/CSharpLibraryTools/CoreActivities/BrowserActivity/BrowserActivityAdaptee.cs @@ -0,0 +1,156 @@ +using System; +using System.Collections.Generic; +using System.Diagnostics; +using System.Linq; +using System.Windows.Automation; + +namespace CoreActivities.BrowserActivity +{ + public class BrowserActivityAdaptee + { + private readonly BrowserActivityEnumAdaptee _browserActivityEnumAdaptee; + + public BrowserActivityAdaptee(BrowserActivityEnumAdaptee browserActivityEnumAdaptee) + => _browserActivityEnumAdaptee = browserActivityEnumAdaptee; + + public string GetActiveTabTitle(BrowserType browserType) + { + try + { + // Find the automation element + var elm = GetAutomationElement(browserType); + if (elm != null) + return elm.Current.Name; + + return string.Empty; + } + catch (Exception ex) + { + throw new Exception(ex.Message); + } + } + + public string GetActiveTabUrl(BrowserType browserType) + { + try + { + // Find the automation element + var elm = GetAutomationElement(browserType); + if(elm != null) + { + var elmUrlBar = elm.FindFirst(TreeScope.Descendants, + new PropertyCondition(AutomationElement.NameProperty, "Address and search bar")); + + // If it can be found, get the value from the URL bar + if (elmUrlBar != null) + { + var patterns = elmUrlBar.GetSupportedPatterns(); + if (patterns.Length > 0) + { + var val = (ValuePattern)elmUrlBar.GetCurrentPattern(patterns[0]); + return val.Current.Value; + } + } + } + + return string.Empty; + } + catch (Exception ex) + { + throw new Exception(ex.Message); + } + } + + public IList GetOpenTabsInfos(BrowserType browserType) + { + try + { + var tabInfos = new List(); + + var browserName = _browserActivityEnumAdaptee.ToDescriptionString(browserType); + var processes = GetBrowserProcessByBrowserType(browserType); + + if (processes.Count <= 0) + return new List(); + else + { + foreach (var proc in processes) + { + if (proc.Process.MainWindowHandle != IntPtr.Zero) + { + var root = AutomationElement.FromHandle(proc.Process.MainWindowHandle); + var condition = new PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.TabItem); + var tabs = root.FindAll(TreeScope.Descendants, condition); + var enumerator = tabs.GetEnumerator(); + + while (enumerator.MoveNext()) + { + var info = (AutomationElement)enumerator.Current; + tabInfos.Add(info.Current.Name); + } + } + } + } + + return tabInfos; + } + catch (Exception ex) + { + throw new Exception(ex.Message); + } + } + + public IList GetBrowserProcessByBrowserType(BrowserType browserType) + { + var browser = _browserActivityEnumAdaptee.ToDescriptionString(browserType).ToLower(); + var processes = Process.GetProcesses(); + + return processes.Select(x => new ProcessAndTitle + { + MainWindowTitle = x.MainWindowTitle, + Process = x + }).Where(x => x.MainWindowTitle.ToLower().Contains(browser)) + .GroupBy(x => x.MainWindowTitle) + .Select(x => x.First()) + .ToList(); + } + + private AutomationElement GetAutomationElement(BrowserType browserType) + { + try + { + // There are always multiple chrome processes, so we have to loop through all of them to find the + // process with a Window Handle and an automation element of name "Address and search bar" + var browserProcess = GetBrowserProcessByBrowserType(browserType); + + if (browserProcess.Count > 0) + { + AutomationElement url = null; + foreach (var chrome in browserProcess) + { + // The browser process must have a window + if (chrome.Process.MainWindowHandle == IntPtr.Zero) + continue; + + // Find the automation element + return AutomationElement.FromHandle(chrome.Process.MainWindowHandle); + } + + return url; + } + else + return null; + } + catch (Exception ex) + { + throw new Exception(ex.Message); + } + } + } + + public class ProcessAndTitle + { + public string MainWindowTitle { get; set; } + public Process Process { get; set; } + } +} diff --git a/CSharpLibraryTools/CoreActivities/BrowserActivity/BrowserActivityAdapter.cs b/CSharpLibraryTools/CoreActivities/BrowserActivity/BrowserActivityAdapter.cs new file mode 100644 index 0000000..b1c5851 --- /dev/null +++ b/CSharpLibraryTools/CoreActivities/BrowserActivity/BrowserActivityAdapter.cs @@ -0,0 +1,63 @@ +using System; +using System.Collections.Generic; +using System.Linq; + +namespace CoreActivities.BrowserActivity +{ + public interface IBrowserActivity + { + bool IsBrowserOpen(BrowserType browserType); + IList EnlistAllOpenTabs(BrowserType browserType); + string EnlistActiveTabUrl(BrowserType browserType); + string EnlistActiveTabTitle(BrowserType browserType); + } + + public class BrowserActivityAdapter : IBrowserActivity + { + private readonly BrowserActivityAdaptee _browserActivityAdaptee; + private readonly BrowserActivityEnumAdaptee _browserActivityEnumAdaptee; + + public BrowserActivityAdapter(BrowserActivityAdaptee browserActivityAdaptee, + BrowserActivityEnumAdaptee browserActivityEnumAdaptee) + { + _browserActivityAdaptee = browserActivityAdaptee; + _browserActivityEnumAdaptee = browserActivityEnumAdaptee; + } + + public string EnlistActiveTabTitle(BrowserType browserType) + { + var tabTitle = _browserActivityAdaptee.GetActiveTabTitle(browserType); + + if (string.IsNullOrWhiteSpace(tabTitle)) + throw new Exception($"No active tab title found in {_browserActivityEnumAdaptee.ToDescriptionString(browserType)} browser"); + + return tabTitle; + } + + public string EnlistActiveTabUrl(BrowserType browserType) + { + var tabUrl = _browserActivityAdaptee.GetActiveTabUrl(browserType); + + if (string.IsNullOrWhiteSpace(tabUrl)) + throw new Exception($"No URL found in {_browserActivityEnumAdaptee.ToDescriptionString(browserType)} browser"); + + return tabUrl; + } + + public IList EnlistAllOpenTabs(BrowserType browserType) + { + var tabs = _browserActivityAdaptee.GetOpenTabsInfos(browserType); + if (tabs == null || tabs.Count == 0) + throw new Exception($"No tabs found in {_browserActivityEnumAdaptee.ToDescriptionString(browserType)} browser"); + + return tabs; + } + + public bool IsBrowserOpen(BrowserType browserType) + { + var title = _browserActivityEnumAdaptee.ToDescriptionString(browserType).ToLower(); + var browserTitles = _browserActivityAdaptee.GetBrowserProcessByBrowserType(browserType); + return browserTitles.Count > 0 && browserTitles.Any(x => x.MainWindowTitle.ToLower().Contains(title.ToLower())); + } + } +} diff --git a/CSharpLibraryTools/CoreActivities/BrowserActivity/BrowserActivityEnumAdaptee.cs b/CSharpLibraryTools/CoreActivities/BrowserActivity/BrowserActivityEnumAdaptee.cs new file mode 100644 index 0000000..1a10033 --- /dev/null +++ b/CSharpLibraryTools/CoreActivities/BrowserActivity/BrowserActivityEnumAdaptee.cs @@ -0,0 +1,17 @@ +using System.ComponentModel; + +namespace CoreActivities.BrowserActivity +{ + public class BrowserActivityEnumAdaptee + { + public string ToDescriptionString(BrowserType val) + { + var attributes = (DescriptionAttribute[])val + .GetType() + .GetField(val.ToString()) + .GetCustomAttributes(typeof(DescriptionAttribute), false); + + return attributes.Length > 0 ? attributes[0].Description : string.Empty; + } + } +} diff --git a/CSharpLibraryTools/CoreActivities/BrowserActivity/BrowserActivityPackage.cs b/CSharpLibraryTools/CoreActivities/BrowserActivity/BrowserActivityPackage.cs new file mode 100644 index 0000000..2090128 --- /dev/null +++ b/CSharpLibraryTools/CoreActivities/BrowserActivity/BrowserActivityPackage.cs @@ -0,0 +1,19 @@ +using Autofac; + +namespace CoreActivities.BrowserActivity +{ + public class BrowserActivityPackage : Module + { + protected override void Load(ContainerBuilder builder) + { + builder.RegisterType().As() + .InstancePerLifetimeScope(); + builder.RegisterType() + .InstancePerLifetimeScope(); + builder.RegisterType() + .InstancePerLifetimeScope(); + + base.Load(builder); + } + } +} diff --git a/CSharpLibraryTools/CoreActivities/BrowserActivity/BrowserType.cs b/CSharpLibraryTools/CoreActivities/BrowserActivity/BrowserType.cs new file mode 100644 index 0000000..8d3c2ea --- /dev/null +++ b/CSharpLibraryTools/CoreActivities/BrowserActivity/BrowserType.cs @@ -0,0 +1,18 @@ +using System.ComponentModel; + +namespace CoreActivities.BrowserActivity +{ + public enum BrowserType + { + [Description("chrome")] + Chrome=1, + [Description("firefox")] + FireFox =2, + [Description("edge")] + Edge =3, + [Description("opera")] + Opera =4, + [Description("safari")] + Safari = 5 + } +} diff --git a/CSharpLibraryTools/CoreActivities/CoreActivities.csproj b/CSharpLibraryTools/CoreActivities/CoreActivities.csproj new file mode 100644 index 0000000..60932e1 --- /dev/null +++ b/CSharpLibraryTools/CoreActivities/CoreActivities.csproj @@ -0,0 +1,32 @@ + + + + Library + net5.0-windows + netcoreapp3.1 + false + Md Shams Wadud + Reason Follower + ReasonFollower.CSharpLibraryTools.CoreActivities + Aim of this package is to separate daily code in a SOLID manner so that we could re-use the code again without reinventing the wheel. + MIT + https://github.com/abbirku/CSharpLibraryTools + Screen Capture, Running Programs, Google Drive, File Manager, Directory manager, Browser Activity, Active Program + false + 1.2.1 + Add EnlistActiveTabTitle in IBrowserActivity + + + + + + + + + + + + + + + diff --git a/CSharpLibraryTools/CoreActivities/DirectoryManager/DirectoryManagerAdaptee.cs b/CSharpLibraryTools/CoreActivities/DirectoryManager/DirectoryManagerAdaptee.cs new file mode 100644 index 0000000..7937e10 --- /dev/null +++ b/CSharpLibraryTools/CoreActivities/DirectoryManager/DirectoryManagerAdaptee.cs @@ -0,0 +1,12 @@ +using System; +using System.IO; + +namespace CoreActivities.DirectoryManager +{ + public class DirectoryManagerAdaptee + { + public string CommonApplicationPath => Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData); + public bool Exists(string directory) => Directory.Exists(directory); + public void CreateDirectory(string directory) => Directory.CreateDirectory(directory); + } +} diff --git a/CSharpLibraryTools/CoreActivities/DirectoryManager/DirectoryManagerAdapter.cs b/CSharpLibraryTools/CoreActivities/DirectoryManager/DirectoryManagerAdapter.cs new file mode 100644 index 0000000..4d82408 --- /dev/null +++ b/CSharpLibraryTools/CoreActivities/DirectoryManager/DirectoryManagerAdapter.cs @@ -0,0 +1,61 @@ +using System; + +namespace CoreActivities.DirectoryManager +{ + public interface IDirectoryManager + { + string GetProgramDataDirectoryPath(string appFolder); + bool ChecknCreateDirectory(string directoryPath); + string CreateProgramDataFilePath(string folderName, string fileName); + } + + public class DirectoryManagerAdapter : IDirectoryManager + { + private readonly DirectoryManagerAdaptee _directoryManagerAdaptee; + + public DirectoryManagerAdapter(DirectoryManagerAdaptee directoryManagerAdaptee) + => _directoryManagerAdaptee = directoryManagerAdaptee; + + /// + /// Given a directory path of a folder it creates the folder under the directory if not exists + /// + public bool ChecknCreateDirectory(string directoryPath) + { + if (string.IsNullOrWhiteSpace(directoryPath)) + return false; + + if (!_directoryManagerAdaptee.Exists(directoryPath)) + { + _directoryManagerAdaptee.CreateDirectory(directoryPath); + return true; + } + else + return false; + } + + /// + /// Create a file path of given folder name which is under C:\ProgramData + /// + public string GetProgramDataDirectoryPath(string appFolder) + { + if (string.IsNullOrWhiteSpace(appFolder)) + throw new Exception("App folder string is empty."); + + return $"{_directoryManagerAdaptee.CommonApplicationPath}\\{appFolder}"; + } + + /// + /// Create a file path (If not exists) under given folderName in C:\ProgramData + /// + public string CreateProgramDataFilePath(string folderName, string fileName) + { + if (string.IsNullOrWhiteSpace(folderName) || string.IsNullOrWhiteSpace(fileName)) + throw new Exception("Given folder or File name is empty."); + + var directory = GetProgramDataDirectoryPath(folderName); + ChecknCreateDirectory(directory); + + return $"{directory}\\{fileName}"; + } + } +} diff --git a/CSharpLibraryTools/CoreActivities/DirectoryManager/DirectoryManagerPackage.cs b/CSharpLibraryTools/CoreActivities/DirectoryManager/DirectoryManagerPackage.cs new file mode 100644 index 0000000..4345908 --- /dev/null +++ b/CSharpLibraryTools/CoreActivities/DirectoryManager/DirectoryManagerPackage.cs @@ -0,0 +1,17 @@ +using Autofac; + +namespace CoreActivities.DirectoryManager +{ + public class DirectoryManagerPackage: Module + { + protected override void Load(ContainerBuilder builder) + { + builder.RegisterType().As() + .InstancePerLifetimeScope(); + builder.RegisterType() + .InstancePerLifetimeScope(); + + base.Load(builder); + } + } +} diff --git a/CSharpLibraryTools/CoreActivities/EgmaCV/EgmaCvAdapter.cs b/CSharpLibraryTools/CoreActivities/EgmaCV/EgmaCvAdapter.cs new file mode 100644 index 0000000..e10aa0e --- /dev/null +++ b/CSharpLibraryTools/CoreActivities/EgmaCV/EgmaCvAdapter.cs @@ -0,0 +1,27 @@ +using Emgu.CV; +using System; +using System.Threading.Tasks; + +namespace CoreActivities.EgmaCV +{ + public interface IEgmaCv + { + Task CaptureImageAsync(int camIndex, string filePath); + } + + public class EgmaCvAdapter : IEgmaCv + { + public async Task CaptureImageAsync(int camIndex, string filePath) + { + await Task.Run(() => + { + if (string.IsNullOrWhiteSpace(filePath)) + throw new Exception("Provide a valid path of file"); + + using var capture = new VideoCapture(camIndex, VideoCapture.API.DShow); + var image = capture.QueryFrame(); //take a picture + image.Save(filePath); + }); + } + } +} diff --git a/CSharpLibraryTools/CoreActivities/EgmaCV/EgmaCvPackage.cs b/CSharpLibraryTools/CoreActivities/EgmaCV/EgmaCvPackage.cs new file mode 100644 index 0000000..6bfbb7c --- /dev/null +++ b/CSharpLibraryTools/CoreActivities/EgmaCV/EgmaCvPackage.cs @@ -0,0 +1,15 @@ +using Autofac; + +namespace CoreActivities.EgmaCV +{ + public class EgmaCvPackage : Module + { + protected override void Load(ContainerBuilder builder) + { + builder.RegisterType().As() + .InstancePerLifetimeScope(); + + base.Load(builder); + } + } +} diff --git a/CSharpLibraryTools/CoreActivities/EgmaCV/source.txt b/CSharpLibraryTools/CoreActivities/EgmaCV/source.txt new file mode 100644 index 0000000..fbf5cd9 --- /dev/null +++ b/CSharpLibraryTools/CoreActivities/EgmaCV/source.txt @@ -0,0 +1,4 @@ +Source +====== +https://blog.dotnetframework.org/2020/12/29/capture-a-webcam-image-using-net-core-and-opencv/ +https://blog.dotnetframework.org/2020/12/30/record-mp4-h264-video-from-a-webcam-in-c-net-core/ \ No newline at end of file diff --git a/CSharpLibraryTools/CoreActivities/FileManager/FileAdapter.cs b/CSharpLibraryTools/CoreActivities/FileManager/FileAdapter.cs new file mode 100644 index 0000000..1f64200 --- /dev/null +++ b/CSharpLibraryTools/CoreActivities/FileManager/FileAdapter.cs @@ -0,0 +1,100 @@ +using Microsoft.AspNetCore.StaticFiles; +using System; +using System.Collections.Generic; +using System.IO; +using System.Threading.Tasks; + +namespace CoreActivities.FileManager +{ + public interface IFile + { + string FileName(string filePath); + bool DoesExists(string filePath); + void CreateFile(string filePath); + string GetMimeType(string filePath); + Task ReadFileAsByteAsync(string filePath); + string ConvertByteToBase64String(byte[] file); + Task WriteBytesStreamAsync(string filePath, byte[] file); + Task WriteAllLineAsync(List lines, string filePath); + Task WriteAllTextAsync(string text, string filePath); + Task AppendAllLineAsync(List lines, string filePath); + Task AppendAllTextAsync(string text, string filePath); + Task ReadAllLineAsync(string filePath); + Task ReadAllTextAsync(string filePath); + } + + public class FileAdapter : IFile + { + public string FileName(string filePath) => Path.GetFileName(filePath); + + public void CreateFile(string filePath) + { + var stream = File.Create(filePath); + stream.Close(); + } + + public bool DoesExists(string filePath) + { + return File.Exists(filePath); + } + + public string GetMimeType(string filePath) + { + var provider = new FileExtensionContentTypeProvider(); + if (!provider.TryGetContentType(filePath, out string contentType)) + contentType = "application/octet-stream"; + + return contentType; + } + + public async Task ReadFileAsByteAsync(string filePath) + { + byte[] result; + using (var stream = File.Open(filePath, FileMode.Open)) + { + result = new byte[stream.Length]; + await stream.ReadAsync(result, 0, (int)stream.Length); + } + + return result; + } + + public string ConvertByteToBase64String(byte[] file) => Convert.ToBase64String(file); + + public async Task WriteBytesStreamAsync(string filePath, byte[] file) + { + using var fileStream = new FileStream(filePath, FileMode.Create, FileAccess.ReadWrite); + await fileStream.WriteAsync(file, 0, file.Length); + } + + public async Task WriteAllLineAsync(List lines, string filePath) + { + await File.WriteAllLinesAsync(filePath, lines); + } + + public async Task WriteAllTextAsync(string text, string filePath) + { + await File.WriteAllTextAsync(filePath, text); + } + + public async Task AppendAllLineAsync(List lines, string filePath) + { + await File.AppendAllLinesAsync(filePath, lines); + } + + public async Task AppendAllTextAsync(string text, string filePath) + { + await File.AppendAllTextAsync(filePath, text); + } + + public async Task ReadAllLineAsync(string filePath) + { + return await File.ReadAllLinesAsync(filePath); + } + + public async Task ReadAllTextAsync(string filePath) + { + return await File.ReadAllTextAsync(filePath); + } + } +} diff --git a/CSharpLibraryTools/CoreActivities/FileManager/FileInfoAdapter.cs b/CSharpLibraryTools/CoreActivities/FileManager/FileInfoAdapter.cs new file mode 100644 index 0000000..bd2bdca --- /dev/null +++ b/CSharpLibraryTools/CoreActivities/FileManager/FileInfoAdapter.cs @@ -0,0 +1,39 @@ +using System; +using System.IO; + +namespace CoreActivities.FileManager +{ + public interface IFileInfo + { + long FileSize(string filePath); + bool IsReadOnly(string filePath); + DateTime CreatedOn(string filePath); + DateTime LastAccessOn(string filePath); + DateTime LastUpdateOn(string filePath); + } + + public class FileInfoAdapter : IFileInfo + { + private FileInfo ObjectCreationAndValidation(string filePath) + { + if (string.IsNullOrEmpty(filePath)) + throw new Exception("Provide valid file path"); + + var fileInfo = new FileInfo(filePath); + if (!fileInfo.Exists) + throw new Exception("File does not exists"); + + return fileInfo; + } + + public DateTime CreatedOn(string filePath) => ObjectCreationAndValidation(filePath).CreationTime; + + public long FileSize(string filePath) => ObjectCreationAndValidation(filePath).Length; + + public bool IsReadOnly(string filePath) => ObjectCreationAndValidation(filePath).IsReadOnly; + + public DateTime LastAccessOn(string filePath) => ObjectCreationAndValidation(filePath).LastAccessTime; + + public DateTime LastUpdateOn(string filePath) => ObjectCreationAndValidation(filePath).LastWriteTime; + } +} diff --git a/CSharpLibraryTools/CoreActivities/FileManager/FileManagerAdapter.cs b/CSharpLibraryTools/CoreActivities/FileManager/FileManagerAdapter.cs new file mode 100644 index 0000000..94c607f --- /dev/null +++ b/CSharpLibraryTools/CoreActivities/FileManager/FileManagerAdapter.cs @@ -0,0 +1,64 @@ +using System; +using System.Drawing; +using System.Drawing.Imaging; +using System.IO; +using System.Threading.Tasks; + +namespace CoreActivities.FileManager +{ + public interface IFileManager + { + void CreateFile(string filePath); + Task ReadFileAsByteAsync(string filePath); + Task SaveByteStreamAsync(string filePath, byte[] file); + void SaveBitmapImage(string filePath, Bitmap bitmap); + } + + public class FileManagerAdapter : IFileManager + { + private readonly IFile _file; + + public FileManagerAdapter(IFile file) + => _file = file; + + public void CreateFile(string path) + { + if (string.IsNullOrWhiteSpace(path)) + throw new Exception("Provide valid file path"); + + if (!_file.DoesExists(path)) + _file.CreateFile(path); + } + + public async Task ReadFileAsByteAsync(string filePath) + { + if (string.IsNullOrWhiteSpace(filePath)) + throw new Exception("Provide valid file path read the file stream."); + + if (!_file.DoesExists(filePath)) + throw new Exception("File does not exists"); + + return await _file.ReadFileAsByteAsync(filePath); + } + + public async Task SaveByteStreamAsync(string filePath, byte[] file) + { + if (string.IsNullOrWhiteSpace(filePath) || file == null || file.Length == 0) + throw new Exception("Provide valid file path and byte array to save the file stream."); + + await _file.WriteBytesStreamAsync(filePath, file); + } + + public void SaveBitmapImage(string filePath, Bitmap bitmap) + { + if (string.IsNullOrWhiteSpace(filePath) || bitmap == null) + throw new Exception("Provide valid file path and bitmap to save the image."); + + using var memory = new MemoryStream(); + using var fs = new FileStream(filePath, FileMode.Open, FileAccess.ReadWrite, FileShare.None); + bitmap.Save(memory, ImageFormat.Jpeg); + var bytes = memory.ToArray(); + fs.Write(bytes, 0, bytes.Length); + } + } +} diff --git a/CSharpLibraryTools/CoreActivities/FileManager/FileManagerPackage.cs b/CSharpLibraryTools/CoreActivities/FileManager/FileManagerPackage.cs new file mode 100644 index 0000000..3834d40 --- /dev/null +++ b/CSharpLibraryTools/CoreActivities/FileManager/FileManagerPackage.cs @@ -0,0 +1,19 @@ +using Autofac; + +namespace CoreActivities.FileManager +{ + public class FileManagerPackage : Module + { + protected override void Load(ContainerBuilder builder) + { + builder.RegisterType().As() + .InstancePerLifetimeScope(); + builder.RegisterType().As() + .InstancePerLifetimeScope(); + builder.RegisterType().As() + .InstancePerLifetimeScope(); + + base.Load(builder); + } + } +} diff --git a/CSharpLibraryTools/CoreActivities/FileManager/Notes.txt b/CSharpLibraryTools/CoreActivities/FileManager/Notes.txt new file mode 100644 index 0000000..a28b36b --- /dev/null +++ b/CSharpLibraryTools/CoreActivities/FileManager/Notes.txt @@ -0,0 +1,6 @@ +Notes: +====== +1. IFile and IFileManager both have CreateFile() method. But it is better to use IFileManager->CreateFile() as it has more control + for creating a file. +2. IFileStream and IFileManager both have ReadFileAsByte() method. But it is better to use IFileManager->ReadFileAsByte() as it has more control + for reading bytes from a file. diff --git a/CSharpLibraryTools/CoreActivities/GoogleDriveApi/GoogleDriveApiManager.cs b/CSharpLibraryTools/CoreActivities/GoogleDriveApi/GoogleDriveApiManager.cs new file mode 100644 index 0000000..464353b --- /dev/null +++ b/CSharpLibraryTools/CoreActivities/GoogleDriveApi/GoogleDriveApiManager.cs @@ -0,0 +1,324 @@ +using CoreActivities.GoogleDriveApi.Models; +using CoreActivities.GoogleDriveApi.Parms; +using Google.Apis.Auth.OAuth2; +using Google.Apis.Download; +using Google.Apis.Drive.v3; +using Google.Apis.Drive.v3.Data; +using Google.Apis.Services; +using Google.Apis.Upload; +using System; +using System.Collections.Generic; +using System.Threading; +using System.Threading.Tasks; + +namespace CoreActivities.GoogleDriveApi +{ + public interface IGoogleDriveApiManager + { + Task GetFilesAndFolders(string nextPageToken = null, FilesListOptionalParms optional = null); + Task> GetAllFilesAndFolders(FilesListOptionalParms optional = null); + Task UploadFileAsync(UploadFileInfo uploadFileInfo, Action uploadProgress = null); + Task DeleteAsync(string fileId, FilesDeleteOptionalParms optional = null); + Task DownloadAsync(File file, string filePath, Action downloadProgress = null); + } + + public class GoogleDriveApiManagerAdapter : IGoogleDriveApiManager + { + private readonly string _authfilePath; + private readonly string _directoryId; + private readonly DriveService _driveService; + private long _fileSize = 0; + private long _uploaded = 0; + private long _downloaded = 0; + + public GoogleDriveApiManagerAdapter(string authfilePath, + string directoryId) + { + _authfilePath = authfilePath; + _directoryId = directoryId; + + var credential = GoogleCredential.FromFile(_authfilePath) + .CreateScoped(DriveService.ScopeConstants.Drive); + + _driveService = new DriveService(new BaseClientService.Initializer() + { + HttpClientInitializer = credential + }); + } + + public async Task GetFilesAndFolders(string nextPageToken = null, FilesListOptionalParms optional = null) + { + + return await Task.Run(() => + { + try + { + var files = new List(); + + // Initial validation. + if (_driveService == null) + throw new ArgumentNullException("service"); + + //Providing default query parameter 'Q' to retrive only specific folder or files + var defaultQueryPatter = $"'{_directoryId}' in parents"; + + if (!string.IsNullOrWhiteSpace(_directoryId)) + { + if (optional == null) + optional = new FilesListOptionalParms + { + Q = defaultQueryPatter + }; + else if (optional != null && string.IsNullOrWhiteSpace(optional.Q)) + optional.Q = defaultQueryPatter; + } + + // Building the initial request. + var request = _driveService.Files.List(); + + // Applying optional parameters to the request. + request = (FilesResource.ListRequest)ApplyOptionalParams(request, optional); + + // Requesting data. + if (!string.IsNullOrWhiteSpace(nextPageToken)) + request.PageToken = nextPageToken; + + var fileFeed = request.Execute(); + + foreach (var item in fileFeed.Files) + files.Add(item); + + var data = new GoogleDriveFiles + { + NextPageToken = fileFeed.NextPageToken, + Files = files + }; + + return data; + } + catch (Exception ex) + { + throw new InvalidOperationException(ex.Message); + } + }); + + } + + public async Task> GetAllFilesAndFolders(FilesListOptionalParms optional = null) + { + GoogleDriveFiles results = null; + FilesListOptionalParms optionals = null; + var files = new List(); + + if(optional == null) + { + optionals = new FilesListOptionalParms + { + PageSize = 5, //Provide positive integer for pagination + Fields = "nextPageToken, files(id, name, mimeType, kind, trashed)" //Follow this pattern to retrive only specified object fields + }; + } + + do + { + if (results == null) + results = await GetFilesAndFolders(null, optionals); + else + results = await GetFilesAndFolders(results.NextPageToken, optionals); + + files.AddRange(results.Files); + + } while (results != null && !string.IsNullOrEmpty(results.NextPageToken)); + + return files; + } + + public async Task UploadFileAsync(UploadFileInfo uploadFileInfo, Action uploadProgress = null) + { + //Initialization + _uploaded = 0; + + // Initial validation. + if (_driveService == null) + throw new ArgumentNullException("service"); + + if (uploadFileInfo != null && !string.IsNullOrWhiteSpace(uploadFileInfo.FilePath) && + !string.IsNullOrWhiteSpace(uploadFileInfo.FileName) && + !string.IsNullOrWhiteSpace(uploadFileInfo.MimeType) && + uploadFileInfo.FileSize != 0) + { + _fileSize = uploadFileInfo.FileSize; + + // Upload file Metadata + var fileMetadata = new File() + { + Name = uploadFileInfo.FileName, + Parents = new List() { _directoryId } + }; + + // Create a new file on Google Drive + await using var fsSource = new System.IO.FileStream(uploadFileInfo.FilePath, System.IO.FileMode.Open, System.IO.FileAccess.Read); + + // Create a new file, with metadata and stream. + var request = _driveService.Files.Create(fileMetadata, fsSource, uploadFileInfo.MimeType); + request.Fields = "*"; + request.ChunkSize = 262144; + if (uploadProgress != null) + request.ProgressChanged += uploadProgress; + else + request.ProgressChanged += UploadProgress; + + var results = await request.UploadAsync(CancellationToken.None); + + if (results.Status == UploadStatus.Failed) + throw new Exception($"Error uploading file: {results.Exception.Message}"); + + return request.ResponseBody; + } + else + throw new Exception("Provide valid upload file information"); + } + + public async Task DeleteAsync(string fileId, FilesDeleteOptionalParms optional = null) + { + await Task.Run(() => + { + try + { + // Initial validation. + if (_driveService == null) + throw new ArgumentNullException("service"); + + if (string.IsNullOrWhiteSpace(fileId)) + throw new ArgumentNullException("fileId"); + + // Building the initial request. + var request = _driveService.Files.Delete(fileId); + + // Applying optional parameters to the request. + request = (FilesResource.DeleteRequest)ApplyOptionalParams(request, optional); + + // Requesting data. + request.Execute(); + } + catch (Exception ex) + { + throw new Exception("Request Files.Delete failed.", ex); + } + }); + } + + public async Task DownloadAsync(File file, string filePath, Action downloadProgress = null) + { + if (file == null || string.IsNullOrWhiteSpace(filePath)) + throw new Exception("Provide valid file object and file path"); + + try + { + var request = _driveService.Files.Get(file.Id); + if (downloadProgress != null) + request.MediaDownloader.ProgressChanged += downloadProgress; + else + request.MediaDownloader.ProgressChanged += DownloadProgress; + + using var output = System.IO.File.Create(filePath); + await request.DownloadAsync(output); + } + catch (Exception e) + { + Console.WriteLine("An error occurred: " + e.Message); + } + } + + #region Private section + public void ClearCurrentConsoleLine() + { + if (Console.CursorTop > 0) + Console.SetCursorPosition(0, Console.CursorTop - 1); + + int currentLineCursor = Console.CursorTop; + Console.SetCursorPosition(0, Console.CursorTop); + Console.Write(new string(' ', Console.WindowWidth)); + Console.SetCursorPosition(0, currentLineCursor); + } + + private void UploadProgress(IUploadProgress progress) + { + PrintUploadProgressByPercentage(progress.BytesSent, _fileSize); + } + + private void DownloadProgress(IDownloadProgress progress) + { + _downloaded = 0; + PrintDownloadProgress(progress.BytesDownloaded); + } + + private void PrintUploadProgressByPercentage(long progress, long total) + { + ClearCurrentConsoleLine(); + + _uploaded += progress; + Console.WriteLine($"Uploaded: {100 * _uploaded / total}%"); + } + + private void PrintDownloadProgress(long progress) + { + ClearCurrentConsoleLine(); + + _downloaded += progress; + Console.WriteLine($"Downloaded: {(decimal)_downloaded / 1024} Kilo Bytes"); + } + + private void DrawTextProgressBar(long progress, long total) + { + //draw empty progress bar + Console.CursorLeft = 0; + Console.Write("["); //start + Console.CursorLeft = 32; + Console.Write("]"); //end + Console.CursorLeft = 1; + float onechunk = 30.0f / total; + + //draw filled part + int position = 1; + for (int i = 0; i < onechunk * progress; i++) + { + Console.BackgroundColor = ConsoleColor.Gray; + Console.CursorLeft = position++; + Console.Write(" "); + } + + //draw unfilled part + for (int i = position; i <= 31; i++) + { + Console.BackgroundColor = ConsoleColor.Green; + Console.CursorLeft = position++; + Console.Write(" "); + } + + //draw totals + Console.CursorLeft = 35; + Console.BackgroundColor = ConsoleColor.Black; + Console.Write(progress.ToString() + " of " + total.ToString() + " "); //blanks at the end remove any excess + } + + private object ApplyOptionalParams(object request, object optional) + { + if (optional == null) + return request; + + System.Reflection.PropertyInfo[] optionalProperties = (optional.GetType()).GetProperties(); + + foreach (System.Reflection.PropertyInfo property in optionalProperties) + { + // Copy value from optional parms to the request. They should have the same names and datatypes. + System.Reflection.PropertyInfo piShared = (request.GetType()).GetProperty(property.Name); + if (property.GetValue(optional, null) != null) // TODO Test that we do not add values for items that are null + piShared.SetValue(request, property.GetValue(optional, null), null); + } + + return request; + } + #endregion + } +} diff --git a/CSharpLibraryTools/CoreActivities/GoogleDriveApi/GoogleDriveApiPackage.cs b/CSharpLibraryTools/CoreActivities/GoogleDriveApi/GoogleDriveApiPackage.cs new file mode 100644 index 0000000..937c5b8 --- /dev/null +++ b/CSharpLibraryTools/CoreActivities/GoogleDriveApi/GoogleDriveApiPackage.cs @@ -0,0 +1,27 @@ +using Autofac; + +namespace CoreActivities.GoogleDriveApi +{ + public class GoogleDriveApiPackage : Module + { + private readonly string _authfilePath; + private readonly string _directoryId; + + public GoogleDriveApiPackage(string authfilePath, + string directoryId) + { + _authfilePath = authfilePath; + _directoryId = directoryId; + } + + protected override void Load(ContainerBuilder builder) + { + builder.RegisterType().As() + .WithParameter("authfilePath", _authfilePath) + .WithParameter("directoryId", _directoryId) + .InstancePerLifetimeScope(); + + base.Load(builder); + } + } +} diff --git a/CSharpLibraryTools/CoreActivities/GoogleDriveApi/Models/GoogleDriveFiles.cs b/CSharpLibraryTools/CoreActivities/GoogleDriveApi/Models/GoogleDriveFiles.cs new file mode 100644 index 0000000..2a7d067 --- /dev/null +++ b/CSharpLibraryTools/CoreActivities/GoogleDriveApi/Models/GoogleDriveFiles.cs @@ -0,0 +1,11 @@ +using Google.Apis.Drive.v3.Data; +using System.Collections.Generic; + +namespace CoreActivities.GoogleDriveApi.Models +{ + public class GoogleDriveFiles + { + public string NextPageToken { get; set; } + public IList Files { get; set; } + } +} diff --git a/CSharpLibraryTools/CoreActivities/GoogleDriveApi/Models/UploadFileInfo.cs b/CSharpLibraryTools/CoreActivities/GoogleDriveApi/Models/UploadFileInfo.cs new file mode 100644 index 0000000..473c924 --- /dev/null +++ b/CSharpLibraryTools/CoreActivities/GoogleDriveApi/Models/UploadFileInfo.cs @@ -0,0 +1,10 @@ +namespace CoreActivities.GoogleDriveApi.Models +{ + public class UploadFileInfo + { + public string FilePath { get; set; } + public string FileName { get; set; } + public long FileSize { get; set; } + public string MimeType { get; set; } + } +} diff --git a/CSharpLibraryTools/CoreActivities/GoogleDriveApi/Parms/FilesDeleteOptionalParms.cs b/CSharpLibraryTools/CoreActivities/GoogleDriveApi/Parms/FilesDeleteOptionalParms.cs new file mode 100644 index 0000000..ea133d7 --- /dev/null +++ b/CSharpLibraryTools/CoreActivities/GoogleDriveApi/Parms/FilesDeleteOptionalParms.cs @@ -0,0 +1,8 @@ +namespace CoreActivities.GoogleDriveApi.Parms +{ + public class FilesDeleteOptionalParms + { + /// Whether the requesting application supports Team Drives. + public bool? SupportsTeamDrives { get; set; } + } +} diff --git a/CSharpLibraryTools/CoreActivities/GoogleDriveApi/Parms/FilesListOptionalParms.cs b/CSharpLibraryTools/CoreActivities/GoogleDriveApi/Parms/FilesListOptionalParms.cs new file mode 100644 index 0000000..61beff6 --- /dev/null +++ b/CSharpLibraryTools/CoreActivities/GoogleDriveApi/Parms/FilesListOptionalParms.cs @@ -0,0 +1,28 @@ +namespace CoreActivities.GoogleDriveApi.Parms +{ + public class FilesListOptionalParms + { + /// Comma-separated list of bodies of items (files/documents) to which the query applies. Supported bodies are 'user', 'domain', 'teamDrive' and 'allTeamDrives'. 'allTeamDrives' must be combined with 'user'; all other values must be used in isolation. Prefer 'user' or 'teamDrive' to 'allTeamDrives' for efficiency. + public string Corpora { get; set; } + /// The source of files to list. Deprecated: use 'corpora' instead. + public string Corpus { get; set; } + /// Whether Team Drive items should be included in results. + public bool? IncludeTeamDriveItems { get; set; } + /// A comma-separated list of sort keys. Valid keys are 'createdTime', 'folder', 'modifiedByMeTime', 'modifiedTime', 'name', 'name_natural', 'quotaBytesUsed', 'recency', 'sharedWithMeTime', 'starred', and 'viewedByMeTime'. Each key sorts ascending by default, but may be reversed with the 'desc' modifier. Example usage: ?orderBy=folder,modifiedTime desc,name. Please note that there is a current limitation for users with approximately one million files in which the requested sort order is ignored. + public string OrderBy { get; set; } + /// The maximum number of files to return per page. Partial or empty result pages are possible even before the end of the files list has been reached. + public int? PageSize { get; set; } + /// The token for continuing a previous list request on the next page. This should be set to the value of 'nextPageToken' from the previous response. + public string PageToken { get; set; } + /// A query for filtering the file results. See the "Search for Files" guide for supported syntax. + public string Q { get; set; } + /// A comma-separated list of spaces to query within the corpus. Supported values are 'drive', 'appDataFolder' and 'photos'. + public string Spaces { get; set; } + /// Whether the requesting application supports Team Drives. + public bool? SupportsTeamDrives { get; set; } + /// ID of Team Drive to search. + public string TeamDriveId { get; set; } + // Provide fields to retrive specified fields + public string Fields { get; set; } + } +} diff --git a/CSharpLibraryTools/CoreActivities/GoogleDriveApi/source.txt b/CSharpLibraryTools/CoreActivities/GoogleDriveApi/source.txt new file mode 100644 index 0000000..0e8ed6c --- /dev/null +++ b/CSharpLibraryTools/CoreActivities/GoogleDriveApi/source.txt @@ -0,0 +1,12 @@ +jskeet commented on Mar 7, 2020 +=============================== +https://github.com/googleapis/google-api-dotnet-client/issues/1525 + +GitHub +====== +https://github.com/LindaLawton/Google-Dotnet-Samples/blob/master/Samples/Drive%20API/v3/FilesSample.cs +https://gist.github.com/LindaLawton/9e512d95ef874d0c4dbc8d0783dcc4bc + +Google Drive API with C# .net +============================= +https://www.daimto.com/google-drive-api-c-download/ \ No newline at end of file diff --git a/CSharpLibraryTools/CoreActivities/RunningPrograms/RunningProgramAdapter.cs b/CSharpLibraryTools/CoreActivities/RunningPrograms/RunningProgramAdapter.cs new file mode 100644 index 0000000..b83a6a4 --- /dev/null +++ b/CSharpLibraryTools/CoreActivities/RunningPrograms/RunningProgramAdapter.cs @@ -0,0 +1,47 @@ +using System.Collections.Generic; +using System.Diagnostics; +using System.Linq; + +namespace CoreActivities.RunningPrograms +{ + public interface IRunningPrograms + { + List GetRunningProgramsList(); + List GetRunningProcessList(); + } + + public class RunningProgramAdapter : IRunningPrograms + { + public List GetRunningProcessList() + { + var processes = Process.GetProcesses(); + var processNames = new List(); + + foreach (var process in processes) + { + if (!string.IsNullOrWhiteSpace(process.ProcessName)) + processNames.Add(process.ProcessName); + } + + processNames = processNames.GroupBy(x => x).Select(x => x.Key).ToList(); + + return processNames; + } + + public List GetRunningProgramsList() + { + var processes = Process.GetProcesses(); + var titles = new List(); + + foreach (var process in processes) + { + if (!string.IsNullOrWhiteSpace(process.MainWindowTitle)) + titles.Add(process.MainWindowTitle); + } + + titles = titles.GroupBy(x => x).Select(x => x.Key).ToList(); + + return titles; + } + } +} diff --git a/CSharpLibraryTools/CoreActivities/RunningPrograms/RunningProgramPackage.cs b/CSharpLibraryTools/CoreActivities/RunningPrograms/RunningProgramPackage.cs new file mode 100644 index 0000000..06e51ac --- /dev/null +++ b/CSharpLibraryTools/CoreActivities/RunningPrograms/RunningProgramPackage.cs @@ -0,0 +1,15 @@ +using Autofac; + +namespace CoreActivities.RunningPrograms +{ + public class RunningProgramPackage : Module + { + protected override void Load(ContainerBuilder builder) + { + builder.RegisterType().As() + .InstancePerLifetimeScope(); + + base.Load(builder); + } + } +} diff --git a/CSharpLibraryTools/CoreActivities/ScreenCapture/ScreenCaptureAdapter.cs b/CSharpLibraryTools/CoreActivities/ScreenCapture/ScreenCaptureAdapter.cs new file mode 100644 index 0000000..900adcb --- /dev/null +++ b/CSharpLibraryTools/CoreActivities/ScreenCapture/ScreenCaptureAdapter.cs @@ -0,0 +1,26 @@ +using System.Drawing; + +namespace CoreActivities.ScreenCapture +{ + public interface IScreenCapture + { + Bitmap CaptureUserScreen(int width, int height); + } + + public class ScreenCaptureAdapter : IScreenCapture + { + public Bitmap CaptureUserScreen(int width, int height) + { + if (width == 0 || height == 0) + return null; + + using var bitmap = new Bitmap(width, height); + using var g = Graphics.FromImage(bitmap); + g.CopyFromScreen(0, 0, 0, 0, bitmap.Size, CopyPixelOperation.SourceCopy); + + var cloneImage = (Bitmap)bitmap.Clone(); + + return cloneImage; + } + } +} diff --git a/CSharpLibraryTools/CoreActivities/ScreenCapture/ScreenCapturePackage.cs b/CSharpLibraryTools/CoreActivities/ScreenCapture/ScreenCapturePackage.cs new file mode 100644 index 0000000..c518f61 --- /dev/null +++ b/CSharpLibraryTools/CoreActivities/ScreenCapture/ScreenCapturePackage.cs @@ -0,0 +1,15 @@ +using Autofac; + +namespace CoreActivities.ScreenCapture +{ + public class ScreenCapturePackage : Module + { + protected override void Load(ContainerBuilder builder) + { + builder.RegisterType().As() + .InstancePerLifetimeScope(); + + base.Load(builder); + } + } +} diff --git a/README.md b/README.md index 606ef95..733e61b 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,200 @@ -# CSharpLibraryTools -Target of this repository is to collect and document different working classes for later use in different project +# *CSharpLibraryTools* + +## *Aim* + +Aim of this project is to separate daily code in a SOLID manner so that we could re-use the code again without reinventing the wheel. + +## *Library Architecture & Details* + +- Each library item is a package. Just need to register the package with Autofac and use the interfaces. There is no overhead of registering library dependencies. Package registration is enough. +- Each library try to follow Adapter Pattern so that user could do unit testing. +- Also there are implementations for each library item for easer understanding. +- And last we have used console app to simulate library results. + +## *Library List* + +- Active Program +- Browser Activity +- Directory Manager +- EgmaCV +- File Manager +- Google Drive Api +- Running Programs +- Screen Capture + +### **Active Program** +_**Dependencies**_ +- user32.dll + +_**Interface & Its members**_ +- IActiveProgram + +| Member | Details | +| ------ | ------ | +| CaptureActiveProgramTitle() | Returns string of current active foreground program on windows. Null otherwise. | + +_**Usage**_ +- Follow _ActiveProgramImp_ + +### **Browser Activity** +_**Dependencies**_ +- System.Diagnostics.Process + +_**Interface & Its members**_ +- IBrowserActivity + +| Member | Details | +| ------ | ------ | +| EnlistAllOpenTabs(BrowserType browserType) | Returns list of open tabs title of a browser. | +| EnlistActiveTabUrl(BrowserType browserType) | Returns url string of present visting website in a browser. | +| EnlistActiveTabTitle(BrowserType browserType) | Returns tab title of present visting website in a browser. | +| IsBrowserOpen(BrowserType browserType) | Returns bool. | + +_**Notes**_ +- **BrowserType** is an Enum which contains **Chrome**, **FireFox**, **Edge**, **Opera**, **Safari** + +_**Usage**_ +- Follow _DirectoryManagerImp_ + +### **Directory Manager** +_**Dependencies**_ +- System.Environment +- System.IO.Directory + +_**Interface & Its members**_ +- IDirectoryManager + +| Member | Details | +| ------ | ------ | +| GetProgramDataDirectoryPath(string appFolder) | Returns directory path of C:\ProgramData with given {appFolder}. | +| ChecknCreateDirectory(string directoryPath) | Creates a folder and returns bool. **Note:** {directoryPath} must contain a folder name. | +| CreateProgramDataFilePath(string folderName, string fileName) | Creates a folder under C:\ProgramData for {folderName} and return file path for given {fileName}. i.e. C:\ProgramData\\{folderName}\\{FileN} | + +_**Notes**_ +- **BrowserType** is an Enum which contains **Chrome**, **FireFox**, **Edge**, **Opera**, **Safari** + +_**Usage**_ +- Follow _BrowseActivityImp_ + +### **EgmaCV** +_**Dependencies**_ +- nuget package Egma.CV (4.5.3.4721) + +_**Interface & Its members**_ +- IEgmaCv + +| Member | Details | +| ------ | ------ | +| CaptureImageAsync(int camIndex, string filePath) | Capture a picture from webcam for given {camIndex} and valid .jpg file path. | + +_**Usage**_ +- Follow _EgmaCvImp_ + +### **File Manager** +_**Dependencies**_ +- System.IO +- System.Drawing + +_**Interface & Its members**_ +- IFile + +| Member | Details | +| ------ | ------ | +| FileName(string filePath) | Returns file name for a given filePath. | +| DoesExists(string filePath) | Check if a file exists or not for a given filePath. Returns bool | +| CreateFile(string filePath) | Creates a file for a given file path. | +| GetMimeType(string filePath) | Returns mime type for a given file path. | +| ReadFileAsByteAsync(string filePath) | For a given file path return bytes of a file. | +| ConvertByteToBase64String(byte[] file) | For given byte array return base 64 string. | +| WriteBytesStreamAsync(string filePath, byte[] file) | Write bytes in a file for a given {filePath}. | +| WriteAllLineAsync(List lines, string filePath) | Write list of string to a file. | +| WriteAllTextAsync(string text, string filePath) | Write string to a file. | +| AppendAllLineAsync(List lines, string filePath) | Append list of string to a file. | +| AppendAllTextAsync(string text, string filePath) | Append a string to a file. | +| ReadAllLineAsync(string filePath) | Read all line of text file and retuns string array. | +| ReadAllTextAsync(string filePath) | Read all text of text file and retuns string. | + +- IFileInfo + +| Member | Details | +| ------ | ------ | +| FileSize(string filePath) | Returns file size for a given filePath. | +| IsReadOnly(string filePath) | Check if a file is readonly or not. Returns bool | +| CreatedOn(string filePath) | Returns file created date time for a given filePath. | +| LastAccessOn(string filePath) | Returns file last access date time for a given filePath. | +| LastUpdateOn(string filePath) | Returns file last update date time for a given filePath. | + +- IFileManager + +| Member | Details | +| ------ | ------ | +| CreateFile(string filePath) | Creates a file for a given file path. | +| ReadFileAsByteAsync(string filePath) | Read file for a given filePath and return byte array | +| SaveByteStreamAsync(string filePath, byte[] file) | Save bytes to a file for a given filePath. | +| SaveBitmapImage(string filePath, Bitmap bitmap) | Save Bitmap to a file for a given filePath. | + +_**Notes**_ +- **IFileManager** and **IFile** both have **CreateFile** and **ReadFileAsByteAsync**. It is preferred to use **IFileManager** members. + +_**Usage**_ +- Follow _FileManagerImp_ + +### **Google Drive Api Manager** +_**Dependencies**_ +- Google.Apis.Drive.v3 (1.54.0.2397) + +_**Interface & Its members**_ +- IGoogleDriveApiManager + +| Member | Details | +| ------ | ------ | +| GetFilesAndFolders(string nextPageToken = null, FilesListOptionalParms optional = null) | Returns file and folder informations for an authenticated google drive folder. | +| UploadFileAsync(UploadFileInfo uploadFileInfo, Action uploadProgress = null) | Upload a file in a google drive autneticated folder. Can check upload progress by providing IUploadProgress as delegate. | +| DeleteAsync(string fileId, FilesDeleteOptionalParms optional = null) | Delete a file from google drive by fileId. | +| DownloadAsync(File file, string filePath, Action downloadProgress = null) | Download a file by providing google drive file type. Can check download progress by providing IDownloadProgress delegate. | + +_**Models**_ +- FilesListOptionalParms +- FilesDeleteOptionalParms +- UploadFileInfo + +_**Notes**_ +- Need google drive .json authentication file. Like webcamsync.json. +- Follow appsettings.json + +_**Usage**_ +- Follow _GoogleDriveApiImp_ + +### **Running Programs** +_**Dependencies**_ +- System.Process + +_**Interface & Its members**_ +- IRunningPrograms + +| Member | Details | +| ------ | ------ | +| GetRunningProgramsList() | Returns all running process. | +| GetRunningProcessList() | Returns all running foreground program names. | + + +_**Usage**_ +- Follow _RunningProgramImp_ + +### **Screen Capture** +_**Dependencies**_ +- System.Drawing + +_**Interface & Its members**_ +- IScreenCapture + +| Member | Details | +| ------ | ------ | +| CaptureUserScreen(int width, int height) | Capture desktop screen for given width and height and return Bitmap | + +_**Usage**_ +- Follow _ScreenCaptureImp_ + +_**Observation Notes**_ +- Follow .csproj if fall into dependency issue. +- Follow Program.cs for Package registration. \ No newline at end of file