Jump to content

Search the Community

Showing results for tags 'C\#'.



More search options

  • Search By Tags

    Type tags separated by commas.
  • Search By Author

Content Type


Forums

  • General
    • Announcements and Site News
    • Administration
  • AutoIt v3
    • AutoIt Help and Support
    • AutoIt Technical Discussion
    • AutoIt Example Scripts
  • Scripting and Development
    • Developer General Discussion
    • Language Specific Discussion
  • IT Administration
    • Operating System Deployment
    • Windows Client
    • Windows Server
    • Office

Categories

  • AutoIt Team
    • Beta
    • MVP
  • AutoIt
    • Automation
    • Databases and web connections
    • Data compression
    • Encryption and hash
    • Games
    • GUI Additions
    • Hardware
    • Information gathering
    • Internet protocol suite
    • Maths
    • Media
    • PDF
    • Security
    • Social Media and other Website API
    • Windows
  • Scripting and Development
  • IT Administration
    • Operating System Deployment
    • Windows Client
    • Windows Server
    • Office

Categories

  • Forum
  • AutoIt

Calendars

  • Community Calendar

Found 26 results

  1. Hi UPDATED Notes: =============================================================================== UPDATED: My main and second questions answered. Here the answers: To add/access WinMenuSelectItem you need to [Thanks to Fernando_Marinho]: Add AutoItX.Dotnet in Manage NuGet Packages Right Click in your Project -> Add -> Reference... -> COM ( Type Libraries )than, check the option AutoItX3 1.0 Type Library using AutoItX3Lib; AutoItX3 au3 = new AutoItX3(); au3.WinMenuSelectItem("", ...) My full source code in C# exists in 11 posts in below. How to access those overloaded methods in AutoitX3 that are not accessible via above method!? Or how to fix AutoitX3 DLL Registration need in target computers without Autoit pre-installed on them!? Please check my post at 14 posts below! =============================================================================== Original Post: I was writing a small app in Autoit to close ĀµTorrent app. It was working. Then I try to import AutoItX into C#, but unfortunately this method WinMenuSelectItem Couldn't find by IntelliSense and If I typed completely it still give me this message: Please check the image. I Google it and I found this QA at stackoverflow: Autoit error within C# application I saw they use this line: au = new AutoItX3Lib.AutoItX3Class(); I figure it how to add 'AutoItX3Lib' to project (by adding 'AutoItX3.dll' to reference) but again! When I use this line: var au = new AutoItX3Class(); I got this error message: Interop type 'AutoItX3Class' cannot be embedded. Use the applicable interface instead. My system info: Visual Studio 2017 Enterprise - v15.5.4 X64 Windows 10 Enterprise 1607 Thanks in advanced IgImAx
  2. FileStream vs Excel Application

    Not one usually to post non-AutoIt things, but as I have this question on StackExchange I thought I would throw it up here as well for any of our C# folks: I currently have an AutoIt GUI that calls a powershell script; the intent is to allow low-level technicians to batch create VMs in vSphere. Due to some changes in requirements from the customer, I am re-writing as a wpf app. The app itself is complete and working; this is more of a curiosity question. I have two methods attached to buttons on the GUI - one to pull all the data out of a listview and export to csv and another to do the reverse; importing from csv to the listview element. I wrote the export first, and went with manipulating the Excel application: private void Launch(object sender, RoutedEventArgs e) { Microsoft.Office.Interop.Excel.Application oExcel = new Microsoft.Office.Interop.Excel.Application(); oExcel.Visible = true; Microsoft.Office.Interop.Excel.Workbook oWorkBook = oExcel.Workbooks.Add(Microsoft.Office.Interop.Excel.XlSheetType.xlWorksheet); Microsoft.Office.Interop.Excel.Worksheet oSheet = (Microsoft.Office.Interop.Excel.Worksheet)oExcel.ActiveSheet; int row = 2; //allow for header row int column = 1; oSheet.Cells[1, 1] = "Name"; oSheet.Cells[1, 2] = "CPU"; oSheet.Cells[1, 3] = "RAM"; oSheet.Cells[1, 4] = "IP Address"; oSheet.Cells[1, 5] = "Subnet Mask"; oSheet.Cells[1, 6] = "Port Group"; oSheet.Cells[1, 7] = "Default Gateway"; oSheet.Cells[1, 8] = "DNS"; oSheet.Cells[1, 9] = "Description"; oSheet.Cells[1, 10] = "Template"; oSheet.Cells[1, 11] = "Host"; oSheet.Cells[1, 12] = "Site"; oSheet.Cells[1, 13] = "Folder"; oSheet.Cells[1, 14] = "DataStore"; oSheet.Cells[1, 15] = "Patch Method"; oSheet.Cells[1, 16] = "HDD1Size"; oSheet.Cells[1, 17] = "HDD1Format"; oSheet.Cells[1, 18] = "HDD2Size"; oSheet.Cells[1, 19] = "HDD2Format"; oSheet.Cells[1, 20] = "HDD3Size"; oSheet.Cells[1, 21] = "HDD3Format"; oSheet.Cells[1, 22] = "HDD4Size"; oSheet.Cells[1, 23] = "HDD4Format"; oSheet.Cells[1, 24] = "HDD5Size"; oSheet.Cells[1, 25] = "HDD5Format"; foreach (var oVM in MyItems) { oSheet.Cells[row, column] = oVM.Name; oSheet.Cells[row, (column + 1)] = oVM.CPU; oSheet.Cells[row, (column + 2)] = oVM.RAM; oSheet.Cells[row, (column + 3)] = oVM.IP; oSheet.Cells[row, (column + 4)] = oVM.Subnet; oSheet.Cells[row, (column + 5)] = oVM.PortGroup; oSheet.Cells[row, (column + 6)] = oVM.Gateway; oSheet.Cells[row, (column + 7)] = oVM.DNS; oSheet.Cells[row, (column + 8)] = oVM.Description; oSheet.Cells[row, (column + 9)] = oVM.Template; oSheet.Cells[row, (column + 10)] = oVM.Host; oSheet.Cells[row, (column + 11)] = oVM.Site; oSheet.Cells[row, (column + 12)] = oVM.Folder; oSheet.Cells[row, (column + 13)] = oVM.Datastore; oSheet.Cells[row, (column + 14)] = oVM.Patch; oSheet.Cells[row, (column + 15)] = oVM.HDD1Size; oSheet.Cells[row, (column + 16)] = oVM.HDD1Format; oSheet.Cells[row, (column + 17)] = oVM.HDD2Size; oSheet.Cells[row, (column + 18)] = oVM.HDD2Format; oSheet.Cells[row, (column + 19)] = oVM.HDD3Size; oSheet.Cells[row, (column + 20)] = oVM.HDD3Format; oSheet.Cells[row, (column + 21)] = oVM.HDD4Size; oSheet.Cells[row, (column + 22)] = oVM.HDD4Format; oSheet.Cells[row, (column + 23)] = oVM.HDD5Size; oSheet.Cells[row, (column + 24)] = oVM.HDD5Format; row++; } oExcel.Application.ActiveWorkbook.SaveAs(Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory) + "\\example", 6); } It works, but it is slow. I have Excel set to visible for testing, and it is a good 6 or 7 seconds on a pretty high end box before the app even pops up. It then takes another 2 seconds to populate 11 rows (this could be in the hundreds of rows at some point). I then wrote the code for the reverse, and decided to try a StreamReader object. The result, surprisingly, was almost immediate: OpenFileDialog xls = new OpenFileDialog(); xls.Multiselect = false; xls.Filter = "CSV files (*.csv)|*.csv"; xls.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory); xls.ShowDialog(); string ins; if (xls.FileName != null) { FileStream srcFS; srcFS = new FileStream(xls.FileName, FileMode.Open); StreamReader srcSR = new StreamReader(srcFS, System.Text.Encoding.Default); do { ins = srcSR.ReadLine(); if (ins != null) { string[] parts = ins.Split(','); MyItems.Add(new MyItem { Name = parts[0], CPU = parts[1], RAM = parts[2], IP = parts[3], Subnet = parts[4], PortGroup = parts[5], Gateway = parts[6], DNS = parts[7], Description = parts[8], Template = parts[9], Host = parts[10], Site = parts[11], Folder = parts[12], Datastore = parts[13], Patch = parts[14], HDD1Size = parts[15], HDD1Format = parts[16], HDD2Size = parts[17], HDD2Format = parts[18], HDD3Size = parts[19], HDD3Format = parts[20], HDD4Size = parts[21], HDD4Format = parts[22], HDD5Size = parts[23], HDD5Format = parts[24] }); } } while (ins != null); srcSR.Close(); } } So, I thought I would go back and change the export to use the same method: FileStream srcFS; srcFS = new FileStream(Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory) + "\\testingout.csv", FileMode.CreateNew, FileAccess.Write); StreamWriter srcWrt = new StreamWriter(srcFS, System.Text.Encoding.Default); StringBuilder header = new StringBuilder(); header.Append("Name").Append(',') .Append("CPU").Append(',') .Append("RAM").Append(',') .Append("IP Address").Append(',') .Append("Port Group").Append(',') .Append("Default Gateway").Append(',') .Append("DNS").Append(',') .Append("Description").Append(',') .Append("Template").Append(',') .Append("Host").Append(',') .Append("Site").Append(',') .Append("Folder").Append(',') .Append("Datastore").Append(',') .Append("Patch").Append(',') .Append("HDD1Size").Append(',') .Append("HDD1Format").Append(',') .Append("HDD2Size").Append(',') .Append("HDD2Format").Append(',') .Append("HDD3Size").Append(',') .Append("HDD3Format").Append(',') .Append("HDD4Size").Append(',') .Append("HDD4Format").Append(',') .Append("HDD5Size").Append(',') .Append("HDDFormat").Append(','); srcWrt.WriteLine(header); foreach (MyItem item in MyItems) { StringBuilder builder = new StringBuilder(); builder.Append(item.Name).Append(',') .Append(item.CPU).Append(',') .Append(item.RAM).Append(',') .Append(item.IP).Append(',') .Append(item.Subnet).Append(',') .Append(item.PortGroup).Append(',') .Append(item.Gateway).Append(',') .Append(item.DNS).Append(',') .Append(item.Description).Append(',') .Append(item.Template).Append(',') .Append(item.Host).Append(',') .Append(item.Site).Append(',') .Append(item.Folder).Append(',') .Append(item.Datastore).Append(',') .Append(item.Patch).Append(',') .Append(item.HDD1Size).Append(',') .Append(item.HDD1Format).Append(',') .Append(item.HDD2Size).Append(',') .Append(item.HDD2Format).Append(',') .Append(item.HDD3Size).Append(',') .Append(item.HDD3Format).Append(',') .Append(item.HDD4Size).Append(',') .Append(item.HDD4Format).Append(',') .Append(item.HDD5Size).Append(',') .Append(item.HDD5Format); srcWrt.WriteLine(builder); } MessageBox.Show("Task Complete"); What surprised me is this method is exponentially slower; on the order of 40 seconds to return the MsgBox. I also noticed that even though the loop is complete and shows the message, is seems the stream is still writing. If I open the file too quickly it shows that it is still in use by "Another User". So by the time the file is available to me it is actually closer to a minute for an 11-line csv. I'm just curious at the difference in speed read vs write using FileStream. Is it something I borked on implementation (eminently possible) or is this a known issue? If interacting with Excel is the way to go (not ideal) is there something I could do to shorten the initial lag?
  3. Greetings, someone can give a exemple, how send a error from a C#'s dll to AutoIt? I use this line, to send an error... but, I want get a error code In AutoIt with macro @error, it's possible? throw new ArgumentException("arquivo map não existe", "value" ); In this way, work, I know ther are error, but, @errror always is zero. I don't want this, I want a number as error code. Can you help me? Best regards
  4. AutoIT AU3info doeas not detect all gui objects uniquely for .NET GUIs developed in C#. this is not working now i am using COM windows approach for this, But its very difficult. Please let me know if anyone has done it before.
  5. What's the best way to receive file from a desktop app? app.exe will execute a cmd with "au3file.exe /path/of/the/file.xml" and the au3file.exe will get and delete that. Or else? THE MOST IMPORTANT PART OF THE QUESTION And best way to transfer file to a desktop app? au3file.exe do a $_POST request and the app.exe MUST HAVE a local HTTP server that can receive $_POST, but it looks heavy 'cause the app must have a server such XAMPP. au3file.exe execute a cmd with "app.exe /path/of/the/file.xml" and the app.exe will now get that file and delete. Or else?
  6. Hello everyone, Finally I decide to ask hard question about one of the project which I currently maintain: Big World Setup aka mod installer for infinity engine games like BG, IWD, PST etc Project page: https://bitbucket.org/BigWorldSetup/bigworldsetup/overview More screenshot: https://forums.beamdog.com/discussion/44476/tool-big-world-setup-bws-mod-manager-for-baldurs-gate-enhanced-edition-trilogy-for-windows/p1 General Features downloading mods (please see remarks!) easy mod installation correct install order of mods/components handle mod and components conflicts and auto solve them easy backup creation/restoring ability to add you own mods Internal Features (every single feature which you see here is already working in autoit) It look as simple GUI application but it has quite complicated logic regarding "handle mod and components conflicts and auto solve them" - this is most important feature of the app. This app needs to be converted into multi-platform GUI application because Enhanced Editions of the game can be played on OSX and Linux also. But for the past 6 years, there wasn't a single gamer/developer who would try to convert this app using multi-platform language and GUI. This is the moment when I'm asking for help: - Which language would suit the best for multi-platform GUI application? c#,python,java or other? - Is there any general approach for such conversion? - Does autoit community/developer have some experience with converting autoit GUI applications into multi-platform GUI app by using multi-platform language like c#,python,java - Is there someone who isn't scared by looking at the source code of the application and feature list to help me with converting or even begin with creating multi-platform GUI app template which will just simply run the same commandline for every system ? If there is something else which you would know, pleas ask and I will try to answer my best.
  7. vs2010 does vs2015 doesn't

    I'm trying to follow a tutorial on youtube dealing with service based database. In the video, the guy adds a service based database to project, and a DataSource Configuration Wizard pops up, where he selects entity data model, which maps a load of stuff, creates classes automatically, has diagrams the lot, an all singing all dancing dealy, but in my vs2015 it does not pop up, and I don't know how to get to the same place in another fashion, I've only ever used sqlite see. Hoping someone know how to do what he does some other way. Skip to about 2 minutes if you are interested and can be bothered.
  8. Hello every body!!! I was try this code is work in AutoIt (au3) #include <MsgBoxConstants.au3> #include <GuiListView.au3> Global $hWndWindow = WinGetHandle("Form1") Global $hWndLv = ControlGetHandle($hWndWindow, "", "WindowsForms10.SysListView32.app.0.bf7771_r11_ad11") MsgBox($MB_SYSTEMMODAL, "", ControlListView($hWndWindow, "", $hWndLv, "GetItemCount")) _GUICtrlListView_ClickItem($hWndLv, 1, "left", False, 2) But now, I want to use _GUICtrlListView_ClickItem in C#. I was add reference AutoItX3.dll and AutoItX3.Assembly.dll for my project but i could not found any function which same _GUICtrlListView_ClickItem from them. Please help me
  9. Hello! I have a script in autoit which I made yesterday and Im still getting the hang of autoit My question is, is there anyone here who would be able to explain how the convertion would go between AutoIt and C# when it comes to these lines of code, would I need to declare an array to show the $x & $y position? Also The LC is a function I have a bit down the code While (Not($it_full)) $pixels = PixelSearch(257, 181, 276, 202,0xA19695,10) ;Check color If NOT(@error) Then LC($pixels[0],$pixels[1]) EndIf $pixels = PixelSearch(693, 479, 729, 504,0x000001,3) ;Search If NOT(@error) Then ; MsgBox(0,"Title","Found It!") $it_full = True Sleep(8000) EndIf WEnd
  10. I added to my project in c# referenced the dll's : AutoitX3.Assembly.dll and AutoitX3Lib.dll In my code i'm trying to simulate a combination of Ctrl + O So I did: AutoIt.AutoItX.ControlSend(processTitle, "", processFileName, "^^{r}"); When using a break point: In processTitle I see: Game In the processFileName I see: C:\Program Files (x86)\Game\Game\Game.exe For checking I looked into Task Manager and there I see in the tab details: Game.exe as name and in Description I see Game And if I will click manually on my own Ctrl + O it will work it will do what I need it will take effect. But when using the AutoIt it will not work will do nothing no effect at all. And I see it's getting and doing the line with the ControlSend but nothing happen. And it did work few hours ago. What is wrong ?
  11. I'm using csharp with the autoitx3. I added to my project referenced the autoit dll's. Everything was working find until I got exception say: "Unable to load DLL 'AutoItX3_x64.dll': The specified module could not be found. (Exception from HRESULT: 0x8007007E)" And I downloaded and installed the autoit and added the dll files referenced them to my project also the file name: AutoitX3_x64.dll but for some reason I don't see this dll file in the project tried to add it as reference few times and in the References I see only two files of Autoit: AutoItX3.Assembly.dll and Interop.AutoItX3Lib.dll but for some reason it's not adding the AutoitX3_x64.dll as reference. How should I add then the AutoitX3_x64.dll to my project ? I keep getting the exception message that it's missing.
  12. Hello everyone! I would like to know (with a AutoIT function/UDF) if an executable is coded in .Net or not. I know that is possible but I don't know how. May you help me?
  13. The following files are provided to allow .NET use: AutoItX3.Assembly.dll - The .NET Assembly for using AutoItX.AutoItX3.Assembly.xml - The Visual Studio Intellisense help file for the .NET Assembly.AutoItX3.dll - The main AutoItX DLL (x86)AutoItX3_x64.dll - The main AutoItX DLL (x64)Using the Assembly from VB/C# within in Visual Studio is very easy: Add a reference to AutoItX3.Assembly.dll to your projectAdd a using AutoIt; statement in the files you want to use AutoIt functionsWrite code like this C# example:using AutoIt; ... // Wow, this is C#! AutoItX.Run("notepad.exe"); AutoItX.WinWaitActive("Untitled"); AutoItX.Send("I'm in notepad"); IntPtr winHandle = AutoItX.WinGetHandle("Untitled"); AutoItX.WinKill(winHandle);Distribute your final executable with the files AutoItX3.Assembly.dll, AutoItX3.dll, AutoItX3_x64.dll.
  14. It seems the AutoIt community does not much venture into AutoItX and the real programmers do not need much to understand how to implement the DLLs -> is there some guidance with explanantions available? This part of the AutoIt site is definitely not getting as much traffic as the rest. Obviously a lot of assumed knowledge and skill applies... I have searched for AutoItX but can not find a single tutorial. There are examples - but what I would really like is a ZIPped project, that explains the C layout, and the link to the AutoIT DLLs. A bit more narrative than code so that I can also learn how... Is there maybe a static Wiki/FAQ on AutoItX that I have missed?
  15. Hello, I am using Lumisoft for a small E-mail project. Everything is fine until now. I managed most of the things i wanted to achieve. However not all of them. I can read the bodytext of the emails but when i display them it is in plain text. Let me show you. When i log-in on my email on my browser the email for example is displayed like this: When i read it with Lumisoft the body text is returned like this: [1]: http://i.stack.imgur.com/LalPL.png However when i read the bodytext and display it in a richtextbox it is, as it is normal, like this: New comment on your post "Spotify Ads Blocker - The best ad blocker for Spotify" https://iblockify.wordpress.com... Author : jc (removed , removed.dynamic.jazztel.es) E-mail : removed@gmail.com URL : Whois : http://whois.arin.net/removed Comment: I have the same problem with another computer with OS Windows 7 x64 bit, without proxy configuration and with the .Net Framework version 4.5.1 Trash it: https://removed Spam it: https://removed You can reply to this comment via email as well, just click the reply button in your email client.So my question is here; What is the best solution to display the email and approche the browser's display? I don't think i can make it 100% similar but there must be a way to make it look better than it is right now... Outlook does it!!! I am just here for some ideas so bring it on!
  16. #region Required project assemblies using System; #endregion namespace IsPrimeNumber { internal class Program { private static bool IsPrimeNumber(int number, out int divisibleBy) { divisibleBy = -1; // Set the out parameter as -1, for those numbers which are prime values. if (number <= 1) { return false; // Return false if the value is less than or equal to one. } for (int i = 2; i <= Math.Sqrt(number); i++) { if (number % i == 0) { divisibleBy = i; // Set the out param as the divisible by value. return false; } } return true; // This means it's a prime number. } private static void Main() { int userChoice; do { Console.Write("Please enter an integer number to see if it's a prime number: "); Int32.TryParse(Console.ReadLine(), out userChoice); Console.WriteLine(); // New line. } while (userChoice <= 0); int numberDivisible; if (IsPrimeNumber(userChoice, out numberDivisible)) { Console.WriteLine("Your number is a prime value."); } else { if (numberDivisible == -1) { Console.WriteLine("Your number is NOT regarded as a prime value."); } else { Console.WriteLine("Your number is NOT a prime value as it's divisible by {0}.", numberDivisible); } } Console.WriteLine(); // New line. Console.WriteLine("Press any key to continue . . ."); Console.ReadKey(true); } } }
  17. Ever wondered how to interact with your compiled .NET assembly and AutoIt script using COM? Then look no further, as I try to explain in simple terms the approach at which to achieve this. The code (AutoIt): As quite a few of you know, I am against the use of Global variables, as more often than not a simple approach such as encapsulating a Local Static variable in a wrapper function is just as good. Some may point out the use of the enumeration, but this is only for the purposes of doing away with "magic numbers", with the chances to expand in the future and not having to remember which number represents what etc... To create the .NET dll: In Visual Studio select a new project and class library. From there, go ahead and rename the namespace and class to something meaningful as you will need it later on when you connect to the COM interface of your .NET assembly. Add [ComVisible(true)] above the class declaration line << IMPORTANT. Once you've added all your wonderful C# related code, build the assembly and copy the .dll file to the location of your AutoIt script. Then it's just as simple as calling the _DotNet_Load() function with the filename of the .dll and voila, you have the power of AutoIt and .NET in one script. Example use of Functions: #include <File.au3> Global Const $DOTNET_PATHS_INDEX = 0, $DOTNET_REGASM_OK = 0 Global Enum $DOTNET_LOADDLL, $DOTNET_UNLOADDLL, $DOTNET_UNLOADDLLALL ; Enumeration used for the _DotNet_* functions. Global Enum $DOTNET_PATHS_FILEPATH, $DOTNET_PATHS_GUID, $DOTNET_PATHS_MAX ; Enumeration used for the internal filepath array. #cs NOTE: Don't forget to add [ComVisible(true)] to the top of the class in the class library. Otherwise it won't work. #ce Example() ; A simple example of registering and unregistering the AutoIt.dll Func Example() If _DotNet_Load('AutoIt.dll') Then ; Load the .NET compiled dll. Local $oPerson = ObjCreate('AutoIt.Person') ; Namespace.Class. If IsObj($oPerson) Then $oPerson.Name = "guinness" $oPerson.Age = Random(18, 99, 1) ConsoleWrite('Person''s age => ' & $oPerson.Age & @CRLF) $oPerson.IncreaseAge() ; A silly method to show the encapsulation of the object around the Age property. ConsoleWrite('Person''s new age => ' & $oPerson.Age & @CRLF) ConsoleWrite($oPerson.ToString() & @CRLF) ; Call the ToString() method which was overriden. Else ConsoleWrite('An error occurred when registering the Dll.' & @CRLF) EndIf Else ConsoleWrite('An error occurred when registering the Dll.' & @CRLF) EndIf ; The dll is automatically unloaded when the application closes. EndFunc ;==>Example ; #FUNCTION# ==================================================================================================================== ; Name ..........: _DotNet_Load ; Description ...: Load a .NET compiled dll assembly. ; Syntax ........: _DotNet_Load($sDllPath) ; Parameters ....: $sDllPath - A .NET compiled dll assembly located in the @ScriptDir directory. ; $bAddAsCurrentUser - [optional] True or false to add to the current user (supresses UAC). Default is False, all users. ; Return values .: Success: True ; Failure: False and sets @error to non-zero: ; 1 = Incorrect filetype aka not a dll. ; 2 = Dll does not exist in the @ScriptDir location. ; 3 = .NET RegAsm.exe file not found. ; 4 = Dll already registered. ; 5 = Unable to retrieve the GUID for registering as a current user. ; Author ........: guinness ; Remarks .......: With ideas by funkey for running under the current user. ; Example .......: Yes ; =============================================================================================================================== Func _DotNet_Load($sDllPath, $bAddAsCurrentUser = Default) If $bAddAsCurrentUser = Default Then $bAddAsCurrentUser = False Local $bReturn = __DotNet_Wrapper($sDllPath, $DOTNET_LOADDLL, $bAddAsCurrentUser) Return SetError(@error, @extended, $bReturn) EndFunc ;==>_DotNet_Load ; #FUNCTION# ==================================================================================================================== ; Name ..........: _DotNet_Unload ; Description ...: Unload a previously registered .NET compiled dll assembly. ; Syntax ........: _DotNet_Unload($sDllPath) ; Parameters ....: $sDllPath - A .NET compiled dll assembly located in the @ScriptDir directory. ; Return values .: Success: True ; Failure: False and sets @error to non-zero: ; 1 = Incorrect filetype aka not a dll. ; 2 = Dll does not exist in the @ScriptDir location. ; 3 = .NET RegAsm.exe file not found. ; Author ........: guinness ; Remarks .......: With ideas by funkey for running under the current user. ; Example .......: Yes ; =============================================================================================================================== Func _DotNet_Unload($sDllPath) Local $bReturn = __DotNet_Wrapper($sDllPath, $DOTNET_UNLOADDLL, Default) Return SetError(@error, @extended, $bReturn) EndFunc ;==>_DotNet_Unload ; #FUNCTION# ==================================================================================================================== ; Name ..........: _DotNet_UnloadAll ; Description ...: Unload all previously registered .NET compiled dll assemblies. ; Syntax ........: _DotNet_UnloadAll() ; Parameters ....: None ; Return values .: Success: True ; Failure: False and sets @error to non-zero: ; 1 = Incorrect filetype aka not a dll. ; 2 = Dll does not exist in the @ScriptDir location. ; 3 = .NET RegAsm.exe file not found. ; 4 = Dll already registered. ; 5 = Unable to retrieve the GUID for registering as a current user. ; Author ........: guinness ; Remarks .......: With ideas by funkey for running under the current user. ; Example .......: Yes ; =============================================================================================================================== Func _DotNet_UnloadAll() Local $bReturn = __DotNet_Wrapper(Null, $DOTNET_UNLOADDLLALL, Default) Return SetError(@error, @extended, $bReturn) EndFunc ;==>_DotNet_UnloadAll ; #INTERNAL_USE_ONLY# =========================================================================================================== ; Name ..........: __DotNet_Wrapper ; Description ...: A wrapper for the _DotNet_* functions. ; Syntax ........: __DotNet_Wrapper($sDllPath, $iType) ; Parameters ....: $sDllPath - A .NET compiled dll assembly located in the @ScriptDir directory. ; $iType - A $DOTNET_* constant. ; Return values .: Success: True ; Failure: False and sets @error to non-zero: ; 1 = Incorrect filetype aka not a dll. ; 2 = Dll does not exist in the @ScriptDir location. ; 3 = .NET RegAsm.exe file not found. ; 4 = Dll already registered. ; 5 = Unable to retrieve the GUID for registering as current user. ; Author ........: guinness ; Remarks .......: ### DO NOT INVOKE, AS THIS IS A WRAPPER FOR THE ABOVE FUNCTIONS. ### ; Remarks .......: With ideas by funkey for running under the current user. ; Related .......: Thanks to Bugfix for the initial idea: http://www.autoitscript.com/forum/topic/129164-create-a-net-class-and-run-it-as-object-from-your-autoit-script/?p=938459 ; Example .......: Yes ; =============================================================================================================================== Func __DotNet_Wrapper($sDllPath, $iType, $bAddAsCurrentUser) Local Static $aDllPaths[Ceiling($DOTNET_PATHS_MAX * 1.3)][$DOTNET_PATHS_MAX] = [[0, 0]], _ $sRegAsmPath = Null If Not ($iType = $DOTNET_UNLOADDLLALL) Then If Not (StringRight($sDllPath, StringLen('dll')) == 'dll') Then ; Check the correct filetype was passed. Return SetError(1, 0, False) ; Incorrect filetype. EndIf If Not FileExists($sDllPath) Then ; Check the filepath exists in @ScriptDir. Return SetError(2, 0, False) ; Filepath does not exist. EndIf EndIf If $sRegAsmPath == Null Then $sRegAsmPath = RegRead('HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\.NETFramework', 'InstallRoot') If @error Then $sRegAsmPath = '' ; Set to an empty string to acknowledge that searching for the path happened. Else Local $aFilePaths = _FileListToArray($sRegAsmPath, '*', $FLTA_FOLDERS), _ $sNETFolder = '' If Not @error Then For $i = UBound($aFilePaths) - 1 To 1 Step -1 If StringRegExp($aFilePaths[$i], '(?:[vV]4\.0\.\d+)') Then $sNETFolder = $aFilePaths[$i] ExitLoop ElseIf StringRegExp($aFilePaths[$i], '(?:[vV]2\.0\.\d+)') Then $sNETFolder = $aFilePaths[$i] ExitLoop EndIf Next EndIf $sRegAsmPath &= $sNETFolder & '\RegAsm.exe' If FileExists($sRegAsmPath) Then OnAutoItExitRegister(_DotNet_UnloadAll) ; Register when the AutoIt executable is closed. Else $sRegAsmPath = '' ; Set to an empty string to acknowledge that searching for the path happened. EndIf EndIf EndIf If $sRegAsmPath == '' Then Return SetError(3, 0, False) ; .NET Framework 2.0 or 4.0 required. EndIf Switch $iType Case $DOTNET_LOADDLL Local $iIndex = -1 For $i = $DOTNET_PATHS_MAX To $aDllPaths[$DOTNET_PATHS_INDEX][$DOTNET_PATHS_FILEPATH] If $sDllPath = $aDllPaths[$i][$DOTNET_PATHS_FILEPATH] Then Return SetError(4, 0, False) ; Dll already registered. EndIf If $iIndex = -1 And $aDllPaths[$i][$DOTNET_PATHS_FILEPATH] == '' Then $iIndex = $i ExitLoop EndIf Next If $iIndex = -1 Then $aDllPaths[$DOTNET_PATHS_INDEX][$DOTNET_PATHS_FILEPATH] += 1 $iIndex = $aDllPaths[$DOTNET_PATHS_INDEX][$DOTNET_PATHS_FILEPATH] EndIf Local Const $iUBound = UBound($aDllPaths) If $aDllPaths[$DOTNET_PATHS_INDEX][$DOTNET_PATHS_FILEPATH] >= $iUBound Then ReDim $aDllPaths[Ceiling($iUBound * 1.3)][$DOTNET_PATHS_MAX] EndIf $aDllPaths[$iIndex][$DOTNET_PATHS_FILEPATH] = $sDllPath $aDllPaths[$iIndex][$DOTNET_PATHS_GUID] = Null If $bAddAsCurrentUser Then ; Idea by funkey, with modification by guinness. Local $sTempDllPath = @TempDir & '\' & $sDllPath & '.reg' If Not (RunWait($sRegAsmPath & ' /s /codebase ' & $sDllPath & ' /regfile:"' & $sTempDllPath & '"', @ScriptDir, @SW_HIDE) = $DOTNET_REGASM_OK) Then Return SetError(5, 0, False) ; Unable to retrieve the GUID for registering as current user. EndIf Local Const $hFileOpen = FileOpen($sTempDllPath, BitOR($FO_READ, $FO_APPEND)) If $hFileOpen > -1 Then FileSetPos($hFileOpen, 0, $FILE_BEGIN) Local $sData = FileRead($hFileOpen) If @error Then $aDllPaths[$DOTNET_PATHS_INDEX][$DOTNET_PATHS_FILEPATH] -= 1 ; Decrease the index due to failure. Return SetError(5, 0, False) ; Unable to retrieve the GUID for registering as current user. EndIf $sData = StringReplace($sData, 'HKEY_CLASSES_ROOT', 'HKEY_CURRENT_USER\Software\Classes') FileSetPos($hFileOpen, 0, $FILE_BEGIN) If Not FileWrite($hFileOpen, $sData) Then $aDllPaths[$DOTNET_PATHS_INDEX][$DOTNET_PATHS_FILEPATH] -= 1 ; Decrease the index due to failure. Return SetError(5, 0, False) ; Unable to retrieve the GUID for registering as current user. EndIf FileClose($hFileOpen) Local $aSRE = StringRegExp($sData, '(?:\R@="{([[:xdigit:]\-]{36})}"\R)', $STR_REGEXPARRAYGLOBALMATCH) If @error Then $aDllPaths[$DOTNET_PATHS_INDEX][$DOTNET_PATHS_FILEPATH] -= 1 ; Decrease the index due to failure. Return SetError(5, 0, False) ; Unable to retrieve the GUID for registering as current user. EndIf $aDllPaths[$iIndex][$DOTNET_PATHS_GUID] = $aSRE[0] ; GUID of the registry key. RunWait('reg import "' & $sTempDllPath & '"', @ScriptDir, @SW_HIDE) ; Import to current users' classes FileDelete($sTempDllPath) EndIf Else Return RunWait($sRegAsmPath & ' /codebase ' & $sDllPath, @ScriptDir, @SW_HIDE) = $DOTNET_REGASM_OK ; Register the .NET Dll. EndIf Case $DOTNET_UNLOADDLL For $i = $DOTNET_PATHS_MAX To $aDllPaths[$DOTNET_PATHS_INDEX][$DOTNET_PATHS_FILEPATH] If $sDllPath = $aDllPaths[$i][$DOTNET_PATHS_FILEPATH] And Not ($aDllPaths[$i][$DOTNET_PATHS_FILEPATH] == Null) Then Return __DotNet_Unregister($sRegAsmPath, $aDllPaths[$i][$DOTNET_PATHS_FILEPATH], $aDllPaths[$iIndex][$DOTNET_PATHS_GUID]) EndIf Next Case $DOTNET_UNLOADDLLALL Local $iCount = 0 If $sDllPath == Null And $aDllPaths[$DOTNET_PATHS_INDEX][$DOTNET_PATHS_FILEPATH] > 0 Then For $i = $DOTNET_PATHS_MAX To $aDllPaths[$DOTNET_PATHS_INDEX][$DOTNET_PATHS_FILEPATH] If Not ($aDllPaths[$i][$DOTNET_PATHS_FILEPATH] == Null) Then $iCount += (__DotNet_Unregister($sRegAsmPath, $aDllPaths[$i][$DOTNET_PATHS_FILEPATH], $aDllPaths[$iIndex][$DOTNET_PATHS_GUID]) ? 1 : 0) EndIf Next $aDllPaths[$DOTNET_PATHS_INDEX][$DOTNET_PATHS_FILEPATH] = 0 ; Reset the count. Return $iCount == $aDllPaths[$DOTNET_PATHS_INDEX][$DOTNET_PATHS_FILEPATH] EndIf EndSwitch Return True EndFunc ;==>__DotNet_Wrapper Func __DotNet_Unregister($sRegAsmPath, ByRef $sDllPath, ByRef $sGUID) Local $bReturn = RunWait($sRegAsmPath & ' /unregister ' & $sDllPath, @ScriptDir, @SW_HIDE) = $DOTNET_REGASM_OK ; Unregister the .NET Dll. If $bReturn Then If Not ($sGUID == Null) Then RegDelete('HKEY_CURRENT_USER\Software\Classes\CLSID\' & $sGUID) ; 32-bit path. RegDelete('HKEY_CLASSES_ROOT\Wow6432Node\CLSID\' & $sGUID) ; 64-bit path. $sGUID = Null ; Remove item. EndIf $sDllPath = Null ; Remove item. EndIf Return $bReturn EndFunc ;==>__DotNet_UnregisterI look forward to the comments and questions people have on this interesting subject, as well as any suggestions of improvement people might have. The ZIP file contains all related source code for both AutoIt and .NET. Dot-NET Assembly in AutoIt.zip
  18. This is a repost from http://www.d3scene.com/forum/development/82572-tutorial-use-autoit-vb-net.html that I came across today. I don't think it is cross posted here already doing a search for .NET related stuff here. Please move to appropriate forum if posted to wrong one (e.g. ActiveX/COM Help and Support (AutoItX) or General Help and Support). If already duplicated here, please delete. Thought it deserves a copy here w/o having users to register over at the source forum to see it. I've yet to personally try the example though, plan to soon. Perhaps a good idea to later on provide the C# version of code snippet for comparison purposes. Original post info modified for clarity: Imports AutoItX3Lib Public Class MainForm Dim AutoitCommand As New AutoItX3 Private Sub StartButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles StartButton.Click AutoitCommand.Run("notepad.exe") AutoitCommand.WinWait("Untitled - Notepad") AutoitCommand.Send("This text sent to notepad by autoit functions{ENTER}Have Fun") AutoitCommand.Sleep(1000) AutoitCommand.WinKill("Untitled - Notepad") End End Sub End Class AutoItX3_x86.rar AutoItX3_x64.rar
  19. Windows forms

    Is it just me or are C# windows forms a bit shit. I was looking for a particular look for my form, in my head it was resizeable with a thin border, but all the sizeable styles have huge fat borders. Does anyone know of a way to get a thin border on a sizeable form?
  20. I'm trying to work on a code base that is pretty chaotic and hard to follow. The code uses an DB2 connector, which I know how to use in autoit, but I really don't know how to use in C#. Can someone point me toward a tutorial or provide some suggestions on what I should be looking at/researching? This is essentially what I need to do: 1) From the DataGrid, loop through each line 2) If the Y/N field is checked, perform different queries 3) Pass the results into another form to validate 4) Push the final results into a separate database (tracking database)
  21. This is for my C# fans out there who enjoy OOP. I have created a really rough draft (I mean it's super basic) of the Stopwatch Class in .NET, because I had the idea whilst travelling home and just thought it's neat to show a different paradigm to that of procedural programming. Enjoy. #include <WinAPISys.au3> Global Const $STOPWATCH_GUID = '804835D8-0DF4-11E4-A11F-29560707A45E', $STOPWATCH_TICKSPERMILLISECOND = 10000, $STOPWATCH_TICKSPERSECOND = $STOPWATCH_TICKSPERMILLISECOND * 1000 Global Enum $STOPWATCH_TIMER, $STOPWATCH_RUNNING, $STOPWATCH_ELAPSED, $STOPWATCH_ISHIGHRESOLUTION, $STOPWATCH_FREQUENCY, $STOPWATCH_TICKFREQUENCY, $STOPWATCH_ID, $STOPWATCH_MAX #Region Example Example() Func Example() Local $hStopWatch = Stopwatch() ConsoleWrite('IsRunning: ' & Stopwatch_IsRunning($hStopWatch) & @CRLF) ; Display running status. ConsoleWrite('Started' & @CRLF) Stopwatch_Start($hStopWatch) ; Start the stopwatch. ConsoleWrite('IsRunning: ' & Stopwatch_IsRunning($hStopWatch) & @CRLF) ; Display running status. Sleep(1000) ; Wait for 1 second. Stopwatch_Stop($hStopWatch) ; Stop the stopwatch. ConsoleWrite('Elapsed ms Time: ' & Stopwatch_ElapsedMilliseconds($hStopWatch) & @CRLF) ConsoleWrite('Stopped.' & @CRLF) ConsoleWrite('Waiting for 3 seconds whilst the stopwatch is stopped.' & @CRLF) Sleep(3000) ; Wait for 3 seconds. ConsoleWrite('Started' & @CRLF) Stopwatch_Start($hStopWatch) ; Start the stopwatch again. ConsoleWrite('Waiting for 2 seconds whilst the stopwatch is running' & @CRLF) Sleep(2000) ; Wait for 2 seconds. For $i = 1 To 10 ; The number of milliseconds is shown even when the stopwatch is running. ConsoleWrite('Elapsed ms Time: ' & Stopwatch_ElapsedMilliseconds($hStopWatch) & @CRLF) Sleep(250) Next Stopwatch_Stop($hStopWatch) ; Stop the stopwatch. ConsoleWrite('Elapsed ms Time: ' & Stopwatch_ElapsedMilliseconds($hStopWatch) & @CRLF) ; This should be about 5 seconds or so. ConsoleWrite('Stopped' & @CRLF) ConsoleWrite('IsRunning: ' & Stopwatch_IsRunning($hStopWatch) & @CRLF) ; Display running status. EndFunc ;==>Example #EndRegion Example ; Stopwatch Class: http://msdn.microsoft.com/en-us/library/system.diagnostics.stopwatch(v=vs.110).aspx Func Stopwatch() Local $aStopwatch[$STOPWATCH_MAX] $aStopwatch[$STOPWATCH_ID] = $STOPWATCH_GUID Stopwatch_Reset($aStopwatch) $aStopwatch[$STOPWATCH_FREQUENCY] = _WinAPI_QueryPerformanceFrequency() If $aStopwatch[$STOPWATCH_FREQUENCY] > 0 Then $aStopwatch[$STOPWATCH_ISHIGHRESOLUTION] = True $aStopwatch[$STOPWATCH_TICKFREQUENCY] = $STOPWATCH_TICKSPERSECOND $aStopwatch[$STOPWATCH_TICKFREQUENCY] /= $aStopwatch[$STOPWATCH_FREQUENCY] Else $aStopwatch[$STOPWATCH_ISHIGHRESOLUTION] = False $aStopwatch[$STOPWATCH_FREQUENCY] = $STOPWATCH_TICKSPERSECOND $aStopwatch[$STOPWATCH_TICKFREQUENCY] = 1 EndIf Return $aStopwatch EndFunc ;==>Stopwatch Func Stopwatch_ElapsedMilliseconds(ByRef $aStopwatch) Return (__Stopwatch_IsStopwatch($aStopwatch) ? __Stopwatch_GetElapsedDateTimeTicks($aStopwatch) / $STOPWATCH_TICKSPERMILLISECOND : 0) EndFunc ;==>Stopwatch_ElapsedMilliseconds Func Stopwatch_ElapsedTicks(ByRef $aStopwatch) Return (__Stopwatch_IsStopwatch($aStopwatch) ? __Stopwatch_GetElapsedDateTimeTicks($aStopwatch) : 0) EndFunc ;==>Stopwatch_ElapsedTicks Func Stopwatch_IsRunning(ByRef $aStopwatch) Return (__Stopwatch_IsStopwatch($aStopwatch) ? $aStopwatch[$STOPWATCH_RUNNING] : Null) EndFunc ;==>Stopwatch_IsRunning Func Stopwatch_Reset(ByRef $aStopwatch) If __Stopwatch_IsStopwatch($aStopwatch) Then $aStopwatch[$STOPWATCH_ELAPSED] = 0 $aStopwatch[$STOPWATCH_RUNNING] = False $aStopwatch[$STOPWATCH_TIMER] = 0 EndIf Return True EndFunc ;==>Stopwatch_Reset Func Stopwatch_Restart(ByRef $aStopwatch) If __Stopwatch_IsStopwatch($aStopwatch) Then Stopwatch_Reset($aStopwatch) Stopwatch_Start($aStopwatch) EndIf Return True EndFunc ;==>Stopwatch_Restart Func Stopwatch_Start(ByRef $aStopwatch) If __Stopwatch_IsStopwatch($aStopwatch) And Not $aStopwatch[$STOPWATCH_RUNNING] Then $aStopwatch[$STOPWATCH_RUNNING] = True $aStopwatch[$STOPWATCH_TIMER] = __Stopwatch_GetTimestamp($aStopwatch) EndIf Return True EndFunc ;==>Stopwatch_Start Func Stopwatch_StartNew() Local $aStopwatch = Stopwatch() Stopwatch_Start($aStopwatch) Return $aStopwatch EndFunc ;==>Stopwatch_StartNew Func Stopwatch_Stop(ByRef $aStopwatch) If __Stopwatch_IsStopwatch($aStopwatch) And $aStopwatch[$STOPWATCH_RUNNING] Then $aStopwatch[$STOPWATCH_ELAPSED] = __Stopwatch_GetRawElapsedTicks($aStopwatch) $aStopwatch[$STOPWATCH_RUNNING] = False EndIf Return True EndFunc ;==>Stopwatch_Stop Func __Stopwatch_GetElapsedDateTimeTicks(ByRef $aStopwatch) Return (__Stopwatch_GetRawElapsedTicks($aStopwatch) * ($aStopwatch[$STOPWATCH_ISHIGHRESOLUTION] ? $aStopwatch[$STOPWATCH_TICKFREQUENCY] : $STOPWATCH_TICKSPERMILLISECOND)) EndFunc ;==>__Stopwatch_GetElapsedDateTimeTicks Func __Stopwatch_GetRawElapsedTicks(ByRef $aStopwatch) Local $iElapsedTime = $aStopwatch[$STOPWATCH_ELAPSED] If $aStopwatch[$STOPWATCH_RUNNING] Then If $aStopwatch[$STOPWATCH_ISHIGHRESOLUTION] Then Local $iTimeStamp = __Stopwatch_GetTimestamp($aStopwatch) $iTimeStamp = $iTimeStamp - $aStopwatch[$STOPWATCH_TIMER] $iElapsedTime += $iTimeStamp Else $iElapsedTime += TimerDiff($aStopwatch[$STOPWATCH_TIMER]) EndIf EndIf Return $iElapsedTime EndFunc ;==>__Stopwatch_GetRawElapsedTicks Func __Stopwatch_GetTimestamp(ByRef $aStopwatch) Return ($aStopwatch[$STOPWATCH_ISHIGHRESOLUTION] ? _WinAPI_QueryPerformanceCounter() : TimerInit()) EndFunc ;==>__Stopwatch_GetTimestamp Func __Stopwatch_IsStopwatch(ByRef $aStopwatch) ; Internal function only. Return (UBound($aStopwatch) = $STOPWATCH_MAX And $aStopwatch[$STOPWATCH_ID] = $STOPWATCH_GUID) EndFunc ;==>__Stopwatch_IsStopwatch
  22. If you are coming from the realm of C# 3.0 then lamda expressions should be pretty familiar to you as it's basic syntactic sugar for creating a function with a conditional return. Since functions in AutoIt are first class objects, the following code should make some sense. It passes an array of integers to a function called IsTrueForAll() that checks whether the function object matches the return condition of that function (you passed). So for example a function called IsGreaterThanOrEqualTo10() checks if all values are greater than or equal to 10 (TRUE). Similarly, IsLessThan10() checks if all values are less than 10 (FALSE). This example should be nothing new to those of you who use v3.3.10.0+ and have an understanding of Call(). #include <MsgBoxConstants.au3> Local $aArray[] = [10, 100, 99, 67] If IsTrueForAll($aArray, IsGreaterThanOrEqualTo10) Then MsgBox($MB_SYSTEMMODAL, '', 'Condition was True.') Else MsgBox($MB_SYSTEMMODAL, '', 'Condition was False') EndIf If IsTrueForAll($aArray, IsLessThan10) Then MsgBox($MB_SYSTEMMODAL, '', 'Condition was True.') Else MsgBox($MB_SYSTEMMODAL, '', 'Condition was False') EndIf Func IsTrueForAll($aArray, $hFunc) ; Loop through the array and check the function passed with a single param matches the condition. For $i = 0 To UBound($aArray) - 1 If Not $hFunc($aArray[$i]) Then Return False EndIf Next Return True EndFunc ;==>IsTrueForAll Func IsGreaterThanOrEqualTo10($x) Return $x >= 10 EndFunc ;==>IsGreaterThanOrEqualTo10 Func IsLessThan10($x) Return $x < 10 EndFunc ;==>IsLessThan10 But, we could easily just forget about writing the functions (less typing is always nice) and let the compiler or pre-processor do all the work for us. It would simply use the lambda expression and create the function for us with whatever we specified. Like so... #include <MsgBoxConstants.au3> Local $aArray[] = [10, 100, 99, 67] If IsTrueForAll($aArray, $x => $x >= 10) Then ; $x is the parameter, => tells us it's a lambda expression and then the condition we are checking. MsgBox($MB_SYSTEMMODAL, '', 'Condition was True.') Else MsgBox($MB_SYSTEMMODAL, '', 'Condition was False') EndIf If IsTrueForAll($aArray, $x => $x < 10) Then ; $x is the parameter, => tells us it's a lambda expression and then the condition we are checking. MsgBox($MB_SYSTEMMODAL, '', 'Condition was True.') Else MsgBox($MB_SYSTEMMODAL, '', 'Condition was False') EndIf Func IsTrueForAll($aArray, $hFunc) ; Loop through the array and check the function passed with a single param matches the condition. For $i = 0 To UBound($aArray) - 1 If Not $hFunc($aArray[$i]) Then Return False EndIf Next Return True EndFunc ;==>IsTrueForAll...which would create the following code with anonymous functions (they're anonymous as we don't care about them in our main script)... #include <MsgBoxConstants.au3> Local $aArray[] = [10, 100, 99, 67] If IsTrueForAll($aArray, D3F7B1B92177415CA70C7FFC35C2649C) Then MsgBox($MB_SYSTEMMODAL, '', 'Condition was True.') Else MsgBox($MB_SYSTEMMODAL, '', 'Condition was False') EndIf If IsTrueForAll($aArray, DA06B548ABF4045AA32F805E6651004) Then MsgBox($MB_SYSTEMMODAL, '', 'Condition was True.') Else MsgBox($MB_SYSTEMMODAL, '', 'Condition was False') EndIf Func IsTrueForAll($aArray, $hFunc) For $i = 0 To UBound($aArray) - 1 If Not $hFunc($aArray[$i]) Then Return False EndIf Next Return True EndFunc ;==>IsTrueForAll Func D3F7B1B92177415CA70C7FFC35C2649C($x) Return $x >= 10 EndFunc ;==>D3F7B1B92177415CA70C7FFC35C2649C Func DA06B548ABF4045AA32F805E6651004($x) Return $x < 10 EndFunc ;==>DA06B548ABF4045AA32F805E6651004 Example of parsing a lambda expression and replacing in the chosen script: #include <WinAPICom.au3> ; Script read from a file. Local $sScript = "#include <MsgBoxConstants.au3>" & @CRLF $sScript &= "" & @CRLF $sScript &= "Local $aArray[] = [10, 100, 99, 67]" & @CRLF $sScript &= "If IsTrueForAll($aArray, $x => $x >= 10) Then" & @CRLF ; Lambda expression. $sScript &= " MsgBox($MB_SYSTEMMODAL, '', 'Condition was True.')" & @CRLF $sScript &= "Else" & @CRLF $sScript &= " MsgBox($MB_SYSTEMMODAL, '', 'Condition was False')" & @CRLF $sScript &= "EndIf" & @CRLF $sScript &= "" & @CRLF $sScript &= "If IsTrueForAll($aArray, $x => $x < 10) Then" & @CRLF ; Lambda expression. $sScript &= " MsgBox($MB_SYSTEMMODAL, '', 'Condition was True.')" & @CRLF $sScript &= "Else" & @CRLF $sScript &= " MsgBox($MB_SYSTEMMODAL, '', 'Condition was False')" & @CRLF $sScript &= "EndIf" & @CRLF $sScript &= "" & @CRLF $sScript &= "Func IsTrueForAll($aArray, $hFunc) ; Loop through the array and check the function passed with a single param matches the condition." & @CRLF $sScript &= " For $i = 0 To UBound($aArray) - 1" & @CRLF $sScript &= " If Not $hFunc($aArray[$i]) Then" & @CRLF $sScript &= " Return False" & @CRLF $sScript &= " EndIf" & @CRLF $sScript &= " Next" & @CRLF $sScript &= " Return True" & @CRLF $sScript &= "EndFunc ;==>IsTrueForAll" & @CRLF ReplaceLambdaInScript($sScript, '$x => $x >= 10') ; Parse the lambda expression and replace it in the above script. ReplaceLambdaInScript($sScript, '$x => $x < 10') ; Parse the lambda expression and replace it in the above script. ConsoleWrite($sScript & @CRLF) ; This is the new script with the lamda expression convert to an anonymous method! ClipPut($sScript) Func CreateLambdaMethod($sExpression) ; Currently no error checking of whether parameters match. Local $bIsReturn = False, _ ; Is the return condition. $sFunction = StringRegExpReplace(_WinAPI_CreateGUID(), '[}{-]', ''), $sParam = '', $sReturn = '' $sFunction = StringRegExpReplace($sFunction, '^\d+', '') ; Remove digits at the beginning of the function name. For $i = 1 To StringLen($sExpression) $sChr = StringMid($sExpression, $i, 1) If $bIsReturn Then $sReturn &= $sChr ElseIf $sChr & StringMid($sExpression, $i + 1, 1) == '=>' Then ; Check for => $i += 1 $bIsReturn = True ElseIf Not $bIsReturn Then $sParam &= $sChr EndIf Next If Not $bIsReturn Then Return "" ; Something went wrong as the => was not found. $sParam = '(' & StringRegExpReplace($sParam, '^\h*|\h*$', '') & ')' $sReturn = @TAB & 'Return ' & $sReturn Return 'Func ' & $sFunction & $sParam & @CRLF & $sReturn & @CRLF & 'EndFunc ;==>' & $sFunction & @CRLF EndFunc ;==>CreateLambdaMethod Func ReplaceLambdaInScript(ByRef $sScript, $sLambda) Local $sFunction = CreateLambdaMethod($sLambda) Local $sFunctionName = StringRegExp($sFunction, 'Func (\w*)\(', 3) If @error Then Return False $sFunctionName = $sFunctionName[0] $sScript = StringReplace($sScript, $sLambda, $sFunctionName, 1) $sScript &= @CRLF & $sFunction Return True EndFunc ;==>ReplaceLambdaInScriptIt was a simple idea I had this morning whilst having breakfast.
  23. C# - Rot13

    Maybe other ideas will follow. using System; using System.Collections.Generic; namespace Rot13 { internal class Program { public static void Main() { Rot13 rot13 = new Rot13(); // Create a rotation 13 object. string encodedString = rot13.Encode("Rotate this string."); // Encode the string. Console.WriteLine("Encoded string: {0}", encodedString); string decodedString = rot13.Decode(encodedString); // Decode the rotated string. Console.WriteLine("Decoded string: {0}", decodedString); Console.WriteLine(""); // Create a new line. Console.Write("Press any key to continue . . . "); Console.ReadKey(true); } } public class Rot13 { private Dictionary<char, char> rot13 = new Dictionary<char, char>(); /// <summary> /// Initialise the dictionary on a per object basis. I guess it could be made static as well?! /// </summary> public Rot13() { string lowLower = "abcdefghijklm", highLower = "nopqrstuvwxyz"; string lowUpper = "ABCDEFGHIJKLM", highUpper = "NOPQRSTUVWXYZ"; for (int i = 0; i < lowUpper.Length; i++) { // Convert a => n and A => N. rot13.Add(lowLower[i], highLower[i]); rot13.Add(highLower[i], lowLower[i]); // Convert n => a and N => A. rot13.Add(lowUpper[i], highUpper[i]); rot13.Add(highUpper[i], lowUpper[i]); } } /// <summary> /// Decode a Rot13 string. /// </summary> /// <param name="data">A Rot13 encoded string.</param> /// <returns>The original string.</returns> public string Decode(string data) { return Encode(data); } /// <summary> /// Encode a string to using Rot13. /// </summary> /// <param name="data">A string to be encoded.</param> /// <returns>An encoded string.</returns> public string Encode(string data) { char rotated = new char(); char[] array = data.ToCharArray(); for (int i = 0; i < array.Length; i++) { if (rot13.TryGetValue(array[i], out rotated)) { array[i] = rotated; } } return new string(array); } } }
  24. Created in only 2 lines. The first Console.WriteLine() is not included as it's there just to report the valid values. using System; namespace RockPaperScissorsFinal { internal class Program { private static void Main() { Console.WriteLine("(1) Rock \n(2) Paper \n(3) Scissors\nEnter your choice: "); do { // Nested ternary statements. What a pain to read , but hey it's only 2 lines ;) Also this uses what we've already learnt. string[] answers = { Console.ReadLine(), "Rock", "Paper", "Scissors", new Random().Next(1, 3).ToString() }; Console.WriteLine(answers[0] != "1" && answers[0] != "2" && answers[0] != "3" ? "Please enter a valid value next time." : "You chose {0} and the computer chose {1} with an outcome of " + (answers[0] == answers[4] ? "the same" : (answers[0] == "1" && answers[4] == "3") || (answers[0] == "2" && answers[4] == "1") || (answers[0] == "3" && answers[4] == "2") ? "winning" : "losing") + ".", answers[int.Parse(answers[0])], answers[int.Parse(answers[4])]); } while (true); } } }
  25. Hello AutoIt Forum, I am in need of some help working with an API using COM. I have been trying to figure this out for over a week, and have come to the conclusion that after much research, this is outside of my ability. Scenario; Software interfacing with is Tekla Structures. I have been using this application for about 10 years for engineering and construction solutions. I know it well, and recently (past few years) started using the API with Autoit. The API (Tekla Open API) is developed on the .NET framework and well documented. The API also fully supports COM technology, though the recommended interface is a .NET application. All example code is C# and VB. I have had great success "translating" from the API documentation and examples to AU3 thus far. My current problem involves returning a value from a method, or a method that modifies the value of a variable. I am not sure how this is "properly" described. For C# sharp it is a "ref" string. public bool GetReportProperty( string Name, ref string Value ) For VB it is a ByRef string. Public Function GetReportProperty ( _ Name As String, _ ByRef Value As String _ ) As Boolean Notation from the documentation; The following is a complete example in C#, note that I am trying to return GetReportProperty while the example is using GetUserProperty. The logic should not differ as both methods are the same (return string type) with the exception of what they are calling. using Tekla.Structures.Model; using System; using System.Windows.Forms; public class Example { public void Example1() { Model Model = new Model(); ModelObjectEnumerator ObjectEnum = Model.GetModelObjectSelector().GetAllObjects(); ObjectEnum.SelectInstances = false; // Set the "SelectInstances" to false to speed up the enquiry; possible because only report properties are asked. string Result = "CHECKED BY, CHECKED DATE, OBJECT LOCKED \n"; while(ObjectEnum.MoveNext()) { if(ObjectEnum.Current != null) { Beam BeamObject = ObjectEnum.Current as Beam; if(BeamObject != null) { string CheckedBy = ""; double DateCheckedValue = 0.0; int LockedStatus = -1; DateTime DateChecked = new System.DateTime(1970, 1, 1); BeamObject.GetUserProperty("CHECKED_BY", ref CheckedBy); BeamObject.GetUserProperty("CHECKED_DATE", ref DateCheckedValue); BeamObject.GetUserProperty("OBJECT_LOCKED", ref LockedStatus); if(CheckedBy.Length > 0 || DateCheckedValue > 0.0 || LockedStatus != -1) DateChecked = DateChecked.AddSeconds(DateCheckedValue); Result += CheckedBy; Result += ", "; Result += DateChecked.ToString("dd.MM.yyyy"); if(LockedStatus == 1) { Result += ", Locked\n"; } else { Result += ", Not locked\n"; } } } } MessageBox.Show(Result); } } The following is my testing script in AutoIt. #AutoIt3Wrapper_UseX64=n #include <Array.au3> $TSMm = ObjCreate("Tekla.Structures.Model.Model") If @error Then MsgBox(1,"ERROR", "Tekla.Structures.Model.Model" & @CRLF & "Could not connect to Tekla, verify and rerun") Exit EndIf If Not $TSMm.GetConnectionStatus() = "True" Then MsgBox(0, "Error", "Tekla Connection Failure") Exit EndIf $ALL_OBJECTS = $TSMm.GetModelObjectSelector().GetAllObjectsWithType(1) ;TYPE 1 = BEAM MODELOBJECTCLASS If @error Then MsgBox(1,"ERROR", "Tekla.Structures.Model.Model" & @CRLF & "ObjectSelector") Exit EndIf $COUNT = 0 $DATA = "DATA:" While $ALL_OBJECTS.MoveNext() Dim $R_VALUE = "ERROR" ;Defined to show change from method below If $ALL_OBJECTS.Current.Name() = "BEAM" Then ;Only Objects with BEAM name - Works $PROP_REPORT = $ALL_OBJECTS.Current.GetReportProperty("PROFILE", $R_VALUE) $DATA = $DATA & @CRLF & "*|PROFLE = " & $PROP_REPORT & " = VALUE = " & $R_VALUE ;$PROP_REPORT returns true unless first string is not found, $R_VALUE is not modified ;$DATA result is PROFILE = TRUE and VALUE = ERROR EndIf $COUNT = $COUNT + 1 WEnd MsgBox(0, "OBJECT COUNT", $COUNT) MsgBox(0, "DATA", $DATA) Everything works as expected with the exception of $R_VALUE does not get modified by the method. I assume (dangerously) that is because "ref". Anyone have an idea of how to handle this?
×