├── .github └── workflows │ └── dotnet.yml ├── .gitignore ├── KLUSOLVE_LICENSE.txt ├── LICENSE ├── OPENDSS_LICENSE ├── README.md ├── README.pt-BR.md ├── docs └── images │ └── dss_sharp.png ├── dss_sharp.csproj ├── dss_sharp.targets ├── examples └── WinFormsAppSample │ ├── Form1.Designer.cs │ ├── Form1.cs │ ├── Form1.resx │ ├── Program.cs │ ├── README.md │ ├── WinFormsAppSample.csproj │ ├── WinFormsAppSample.csproj.user │ ├── WinFormsAppSample.sln │ └── images │ ├── 1-version-button.png │ ├── 2-textbox-run.png │ ├── 3-textbox-run-output.png │ ├── 4-before-plotting.png │ └── 5-after-plotting.png ├── scripts ├── ci_update_versions.sh └── download_native_libs.sh └── src ├── dss_capi_lib.cs ├── dss_sharp.cs └── dss_sharp_util.cs /.github/workflows/dotnet.yml: -------------------------------------------------------------------------------- 1 | name: Build package 2 | 3 | on: 4 | push: 5 | branches: [ "master" ] 6 | tags: [ "*" ] 7 | 8 | pull_request: 9 | branches: [ "master" ] 10 | jobs: 11 | build: 12 | runs-on: ubuntu-latest 13 | 14 | steps: 15 | - uses: actions/checkout@v3 16 | - name: Adjust versions 17 | run: bash scripts/ci_update_versions.sh 18 | - name: Download DSS C-API binaries 19 | run: bash scripts/download_native_libs.sh 20 | - name: Setup .NET 21 | uses: actions/setup-dotnet@v3 22 | with: 23 | dotnet-version: 6.0.x 24 | - name: Restore dependencies 25 | run: dotnet restore 26 | - name: Build 27 | run: dotnet build --no-restore -c Release 28 | - name: Pack 29 | run: dotnet pack -c Release 30 | # - name: Test --- TODO! 31 | # run: dotnet test --no-build --verbosity normal 32 | - name: 'Upload artifacts' 33 | uses: "actions/upload-artifact@v3" 34 | with: 35 | name: 'packages' 36 | path: '${{ github.workspace }}/bin/Release/*.nupkg' 37 | 38 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .vs 2 | obj 3 | bin/ 4 | messages/ 5 | runtimes/ 6 | .vscode/ -------------------------------------------------------------------------------- /KLUSOLVE_LICENSE.txt: -------------------------------------------------------------------------------- 1 | GNU LESSER GENERAL PUBLIC LICENSE 2 | Version 2.1, February 1999 3 | 4 | Copyright (C) 1991, 1999 Free Software Foundation, Inc. 5 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 6 | Everyone is permitted to copy and distribute verbatim copies 7 | of this license document, but changing it is not allowed. 8 | 9 | [This is the first released version of the Lesser GPL. It also counts 10 | as the successor of the GNU Library Public License, version 2, hence 11 | the version number 2.1.] 12 | 13 | Preamble 14 | 15 | The licenses for most software are designed to take away your 16 | freedom to share and change it. By contrast, the GNU General Public 17 | Licenses are intended to guarantee your freedom to share and change 18 | free software--to make sure the software is free for all its users. 19 | 20 | This license, the Lesser General Public License, applies to some 21 | specially designated software packages--typically libraries--of the 22 | Free Software Foundation and other authors who decide to use it. You 23 | can use it too, but we suggest you first think carefully about whether 24 | this license or the ordinary General Public License is the better 25 | strategy to use in any particular case, based on the explanations below. 26 | 27 | When we speak of free software, we are referring to freedom of use, 28 | not price. Our General Public Licenses are designed to make sure that 29 | you have the freedom to distribute copies of free software (and charge 30 | for this service if you wish); that you receive source code or can get 31 | it if you want it; that you can change the software and use pieces of 32 | it in new free programs; and that you are informed that you can do 33 | these things. 34 | 35 | To protect your rights, we need to make restrictions that forbid 36 | distributors to deny you these rights or to ask you to surrender these 37 | rights. These restrictions translate to certain responsibilities for 38 | you if you distribute copies of the library or if you modify it. 39 | 40 | For example, if you distribute copies of the library, whether gratis 41 | or for a fee, you must give the recipients all the rights that we gave 42 | you. You must make sure that they, too, receive or can get the source 43 | code. If you link other code with the library, you must provide 44 | complete object files to the recipients, so that they can relink them 45 | with the library after making changes to the library and recompiling 46 | it. And you must show them these terms so they know their rights. 47 | 48 | We protect your rights with a two-step method: (1) we copyright the 49 | library, and (2) we offer you this license, which gives you legal 50 | permission to copy, distribute and/or modify the library. 51 | 52 | To protect each distributor, we want to make it very clear that 53 | there is no warranty for the free library. Also, if the library is 54 | modified by someone else and passed on, the recipients should know 55 | that what they have is not the original version, so that the original 56 | author's reputation will not be affected by problems that might be 57 | introduced by others. 58 | 59 | Finally, software patents pose a constant threat to the existence of 60 | any free program. We wish to make sure that a company cannot 61 | effectively restrict the users of a free program by obtaining a 62 | restrictive license from a patent holder. Therefore, we insist that 63 | any patent license obtained for a version of the library must be 64 | consistent with the full freedom of use specified in this license. 65 | 66 | Most GNU software, including some libraries, is covered by the 67 | ordinary GNU General Public License. This license, the GNU Lesser 68 | General Public License, applies to certain designated libraries, and 69 | is quite different from the ordinary General Public License. We use 70 | this license for certain libraries in order to permit linking those 71 | libraries into non-free programs. 72 | 73 | When a program is linked with a library, whether statically or using 74 | a shared library, the combination of the two is legally speaking a 75 | combined work, a derivative of the original library. The ordinary 76 | General Public License therefore permits such linking only if the 77 | entire combination fits its criteria of freedom. The Lesser General 78 | Public License permits more lax criteria for linking other code with 79 | the library. 80 | 81 | We call this license the "Lesser" General Public License because it 82 | does Less to protect the user's freedom than the ordinary General 83 | Public License. It also provides other free software developers Less 84 | of an advantage over competing non-free programs. These disadvantages 85 | are the reason we use the ordinary General Public License for many 86 | libraries. However, the Lesser license provides advantages in certain 87 | special circumstances. 88 | 89 | For example, on rare occasions, there may be a special need to 90 | encourage the widest possible use of a certain library, so that it becomes 91 | a de-facto standard. To achieve this, non-free programs must be 92 | allowed to use the library. A more frequent case is that a free 93 | library does the same job as widely used non-free libraries. In this 94 | case, there is little to gain by limiting the free library to free 95 | software only, so we use the Lesser General Public License. 96 | 97 | In other cases, permission to use a particular library in non-free 98 | programs enables a greater number of people to use a large body of 99 | free software. For example, permission to use the GNU C Library in 100 | non-free programs enables many more people to use the whole GNU 101 | operating system, as well as its variant, the GNU/Linux operating 102 | system. 103 | 104 | Although the Lesser General Public License is Less protective of the 105 | users' freedom, it does ensure that the user of a program that is 106 | linked with the Library has the freedom and the wherewithal to run 107 | that program using a modified version of the Library. 108 | 109 | The precise terms and conditions for copying, distribution and 110 | modification follow. Pay close attention to the difference between a 111 | "work based on the library" and a "work that uses the library". The 112 | former contains code derived from the library, whereas the latter must 113 | be combined with the library in order to run. 114 | 115 | GNU LESSER GENERAL PUBLIC LICENSE 116 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 117 | 118 | 0. This License Agreement applies to any software library or other 119 | program which contains a notice placed by the copyright holder or 120 | other authorized party saying it may be distributed under the terms of 121 | this Lesser General Public License (also called "this License"). 122 | Each licensee is addressed as "you". 123 | 124 | A "library" means a collection of software functions and/or data 125 | prepared so as to be conveniently linked with application programs 126 | (which use some of those functions and data) to form executables. 127 | 128 | The "Library", below, refers to any such software library or work 129 | which has been distributed under these terms. A "work based on the 130 | Library" means either the Library or any derivative work under 131 | copyright law: that is to say, a work containing the Library or a 132 | portion of it, either verbatim or with modifications and/or translated 133 | straightforwardly into another language. (Hereinafter, translation is 134 | included without limitation in the term "modification".) 135 | 136 | "Source code" for a work means the preferred form of the work for 137 | making modifications to it. For a library, complete source code means 138 | all the source code for all modules it contains, plus any associated 139 | interface definition files, plus the scripts used to control compilation 140 | and installation of the library. 141 | 142 | Activities other than copying, distribution and modification are not 143 | covered by this License; they are outside its scope. The act of 144 | running a program using the Library is not restricted, and output from 145 | such a program is covered only if its contents constitute a work based 146 | on the Library (independent of the use of the Library in a tool for 147 | writing it). Whether that is true depends on what the Library does 148 | and what the program that uses the Library does. 149 | 150 | 1. You may copy and distribute verbatim copies of the Library's 151 | complete source code as you receive it, in any medium, provided that 152 | you conspicuously and appropriately publish on each copy an 153 | appropriate copyright notice and disclaimer of warranty; keep intact 154 | all the notices that refer to this License and to the absence of any 155 | warranty; and distribute a copy of this License along with the 156 | Library. 157 | 158 | You may charge a fee for the physical act of transferring a copy, 159 | and you may at your option offer warranty protection in exchange for a 160 | fee. 161 | 162 | 2. You may modify your copy or copies of the Library or any portion 163 | of it, thus forming a work based on the Library, and copy and 164 | distribute such modifications or work under the terms of Section 1 165 | above, provided that you also meet all of these conditions: 166 | 167 | a) The modified work must itself be a software library. 168 | 169 | b) You must cause the files modified to carry prominent notices 170 | stating that you changed the files and the date of any change. 171 | 172 | c) You must cause the whole of the work to be licensed at no 173 | charge to all third parties under the terms of this License. 174 | 175 | d) If a facility in the modified Library refers to a function or a 176 | table of data to be supplied by an application program that uses 177 | the facility, other than as an argument passed when the facility 178 | is invoked, then you must make a good faith effort to ensure that, 179 | in the event an application does not supply such function or 180 | table, the facility still operates, and performs whatever part of 181 | its purpose remains meaningful. 182 | 183 | (For example, a function in a library to compute square roots has 184 | a purpose that is entirely well-defined independent of the 185 | application. Therefore, Subsection 2d requires that any 186 | application-supplied function or table used by this function must 187 | be optional: if the application does not supply it, the square 188 | root function must still compute square roots.) 189 | 190 | These requirements apply to the modified work as a whole. If 191 | identifiable sections of that work are not derived from the Library, 192 | and can be reasonably considered independent and separate works in 193 | themselves, then this License, and its terms, do not apply to those 194 | sections when you distribute them as separate works. But when you 195 | distribute the same sections as part of a whole which is a work based 196 | on the Library, the distribution of the whole must be on the terms of 197 | this License, whose permissions for other licensees extend to the 198 | entire whole, and thus to each and every part regardless of who wrote 199 | it. 200 | 201 | Thus, it is not the intent of this section to claim rights or contest 202 | your rights to work written entirely by you; rather, the intent is to 203 | exercise the right to control the distribution of derivative or 204 | collective works based on the Library. 205 | 206 | In addition, mere aggregation of another work not based on the Library 207 | with the Library (or with a work based on the Library) on a volume of 208 | a storage or distribution medium does not bring the other work under 209 | the scope of this License. 210 | 211 | 3. You may opt to apply the terms of the ordinary GNU General Public 212 | License instead of this License to a given copy of the Library. To do 213 | this, you must alter all the notices that refer to this License, so 214 | that they refer to the ordinary GNU General Public License, version 2, 215 | instead of to this License. (If a newer version than version 2 of the 216 | ordinary GNU General Public License has appeared, then you can specify 217 | that version instead if you wish.) Do not make any other change in 218 | these notices. 219 | 220 | Once this change is made in a given copy, it is irreversible for 221 | that copy, so the ordinary GNU General Public License applies to all 222 | subsequent copies and derivative works made from that copy. 223 | 224 | This option is useful when you wish to copy part of the code of 225 | the Library into a program that is not a library. 226 | 227 | 4. You may copy and distribute the Library (or a portion or 228 | derivative of it, under Section 2) in object code or executable form 229 | under the terms of Sections 1 and 2 above provided that you accompany 230 | it with the complete corresponding machine-readable source code, which 231 | must be distributed under the terms of Sections 1 and 2 above on a 232 | medium customarily used for software interchange. 233 | 234 | If distribution of object code is made by offering access to copy 235 | from a designated place, then offering equivalent access to copy the 236 | source code from the same place satisfies the requirement to 237 | distribute the source code, even though third parties are not 238 | compelled to copy the source along with the object code. 239 | 240 | 5. A program that contains no derivative of any portion of the 241 | Library, but is designed to work with the Library by being compiled or 242 | linked with it, is called a "work that uses the Library". Such a 243 | work, in isolation, is not a derivative work of the Library, and 244 | therefore falls outside the scope of this License. 245 | 246 | However, linking a "work that uses the Library" with the Library 247 | creates an executable that is a derivative of the Library (because it 248 | contains portions of the Library), rather than a "work that uses the 249 | library". The executable is therefore covered by this License. 250 | Section 6 states terms for distribution of such executables. 251 | 252 | When a "work that uses the Library" uses material from a header file 253 | that is part of the Library, the object code for the work may be a 254 | derivative work of the Library even though the source code is not. 255 | Whether this is true is especially significant if the work can be 256 | linked without the Library, or if the work is itself a library. The 257 | threshold for this to be true is not precisely defined by law. 258 | 259 | If such an object file uses only numerical parameters, data 260 | structure layouts and accessors, and small macros and small inline 261 | functions (ten lines or less in length), then the use of the object 262 | file is unrestricted, regardless of whether it is legally a derivative 263 | work. (Executables containing this object code plus portions of the 264 | Library will still fall under Section 6.) 265 | 266 | Otherwise, if the work is a derivative of the Library, you may 267 | distribute the object code for the work under the terms of Section 6. 268 | Any executables containing that work also fall under Section 6, 269 | whether or not they are linked directly with the Library itself. 270 | 271 | 6. As an exception to the Sections above, you may also combine or 272 | link a "work that uses the Library" with the Library to produce a 273 | work containing portions of the Library, and distribute that work 274 | under terms of your choice, provided that the terms permit 275 | modification of the work for the customer's own use and reverse 276 | engineering for debugging such modifications. 277 | 278 | You must give prominent notice with each copy of the work that the 279 | Library is used in it and that the Library and its use are covered by 280 | this License. You must supply a copy of this License. If the work 281 | during execution displays copyright notices, you must include the 282 | copyright notice for the Library among them, as well as a reference 283 | directing the user to the copy of this License. Also, you must do one 284 | of these things: 285 | 286 | a) Accompany the work with the complete corresponding 287 | machine-readable source code for the Library including whatever 288 | changes were used in the work (which must be distributed under 289 | Sections 1 and 2 above); and, if the work is an executable linked 290 | with the Library, with the complete machine-readable "work that 291 | uses the Library", as object code and/or source code, so that the 292 | user can modify the Library and then relink to produce a modified 293 | executable containing the modified Library. (It is understood 294 | that the user who changes the contents of definitions files in the 295 | Library will not necessarily be able to recompile the application 296 | to use the modified definitions.) 297 | 298 | b) Use a suitable shared library mechanism for linking with the 299 | Library. A suitable mechanism is one that (1) uses at run time a 300 | copy of the library already present on the user's computer system, 301 | rather than copying library functions into the executable, and (2) 302 | will operate properly with a modified version of the library, if 303 | the user installs one, as long as the modified version is 304 | interface-compatible with the version that the work was made with. 305 | 306 | c) Accompany the work with a written offer, valid for at 307 | least three years, to give the same user the materials 308 | specified in Subsection 6a, above, for a charge no more 309 | than the cost of performing this distribution. 310 | 311 | d) If distribution of the work is made by offering access to copy 312 | from a designated place, offer equivalent access to copy the above 313 | specified materials from the same place. 314 | 315 | e) Verify that the user has already received a copy of these 316 | materials or that you have already sent this user a copy. 317 | 318 | For an executable, the required form of the "work that uses the 319 | Library" must include any data and utility programs needed for 320 | reproducing the executable from it. However, as a special exception, 321 | the materials to be distributed need not include anything that is 322 | normally distributed (in either source or binary form) with the major 323 | components (compiler, kernel, and so on) of the operating system on 324 | which the executable runs, unless that component itself accompanies 325 | the executable. 326 | 327 | It may happen that this requirement contradicts the license 328 | restrictions of other proprietary libraries that do not normally 329 | accompany the operating system. Such a contradiction means you cannot 330 | use both them and the Library together in an executable that you 331 | distribute. 332 | 333 | 7. You may place library facilities that are a work based on the 334 | Library side-by-side in a single library together with other library 335 | facilities not covered by this License, and distribute such a combined 336 | library, provided that the separate distribution of the work based on 337 | the Library and of the other library facilities is otherwise 338 | permitted, and provided that you do these two things: 339 | 340 | a) Accompany the combined library with a copy of the same work 341 | based on the Library, uncombined with any other library 342 | facilities. This must be distributed under the terms of the 343 | Sections above. 344 | 345 | b) Give prominent notice with the combined library of the fact 346 | that part of it is a work based on the Library, and explaining 347 | where to find the accompanying uncombined form of the same work. 348 | 349 | 8. You may not copy, modify, sublicense, link with, or distribute 350 | the Library except as expressly provided under this License. Any 351 | attempt otherwise to copy, modify, sublicense, link with, or 352 | distribute the Library is void, and will automatically terminate your 353 | rights under this License. However, parties who have received copies, 354 | or rights, from you under this License will not have their licenses 355 | terminated so long as such parties remain in full compliance. 356 | 357 | 9. You are not required to accept this License, since you have not 358 | signed it. However, nothing else grants you permission to modify or 359 | distribute the Library or its derivative works. These actions are 360 | prohibited by law if you do not accept this License. Therefore, by 361 | modifying or distributing the Library (or any work based on the 362 | Library), you indicate your acceptance of this License to do so, and 363 | all its terms and conditions for copying, distributing or modifying 364 | the Library or works based on it. 365 | 366 | 10. Each time you redistribute the Library (or any work based on the 367 | Library), the recipient automatically receives a license from the 368 | original licensor to copy, distribute, link with or modify the Library 369 | subject to these terms and conditions. You may not impose any further 370 | restrictions on the recipients' exercise of the rights granted herein. 371 | You are not responsible for enforcing compliance by third parties with 372 | this License. 373 | 374 | 11. If, as a consequence of a court judgment or allegation of patent 375 | infringement or for any other reason (not limited to patent issues), 376 | conditions are imposed on you (whether by court order, agreement or 377 | otherwise) that contradict the conditions of this License, they do not 378 | excuse you from the conditions of this License. If you cannot 379 | distribute so as to satisfy simultaneously your obligations under this 380 | License and any other pertinent obligations, then as a consequence you 381 | may not distribute the Library at all. For example, if a patent 382 | license would not permit royalty-free redistribution of the Library by 383 | all those who receive copies directly or indirectly through you, then 384 | the only way you could satisfy both it and this License would be to 385 | refrain entirely from distribution of the Library. 386 | 387 | If any portion of this section is held invalid or unenforceable under any 388 | particular circumstance, the balance of the section is intended to apply, 389 | and the section as a whole is intended to apply in other circumstances. 390 | 391 | It is not the purpose of this section to induce you to infringe any 392 | patents or other property right claims or to contest validity of any 393 | such claims; this section has the sole purpose of protecting the 394 | integrity of the free software distribution system which is 395 | implemented by public license practices. Many people have made 396 | generous contributions to the wide range of software distributed 397 | through that system in reliance on consistent application of that 398 | system; it is up to the author/donor to decide if he or she is willing 399 | to distribute software through any other system and a licensee cannot 400 | impose that choice. 401 | 402 | This section is intended to make thoroughly clear what is believed to 403 | be a consequence of the rest of this License. 404 | 405 | 12. If the distribution and/or use of the Library is restricted in 406 | certain countries either by patents or by copyrighted interfaces, the 407 | original copyright holder who places the Library under this License may add 408 | an explicit geographical distribution limitation excluding those countries, 409 | so that distribution is permitted only in or among countries not thus 410 | excluded. In such case, this License incorporates the limitation as if 411 | written in the body of this License. 412 | 413 | 13. The Free Software Foundation may publish revised and/or new 414 | versions of the Lesser General Public License from time to time. 415 | Such new versions will be similar in spirit to the present version, 416 | but may differ in detail to address new problems or concerns. 417 | 418 | Each version is given a distinguishing version number. If the Library 419 | specifies a version number of this License which applies to it and 420 | "any later version", you have the option of following the terms and 421 | conditions either of that version or of any later version published by 422 | the Free Software Foundation. If the Library does not specify a 423 | license version number, you may choose any version ever published by 424 | the Free Software Foundation. 425 | 426 | 14. If you wish to incorporate parts of the Library into other free 427 | programs whose distribution conditions are incompatible with these, 428 | write to the author to ask for permission. For software which is 429 | copyrighted by the Free Software Foundation, write to the Free 430 | Software Foundation; we sometimes make exceptions for this. Our 431 | decision will be guided by the two goals of preserving the free status 432 | of all derivatives of our free software and of promoting the sharing 433 | and reuse of software generally. 434 | 435 | NO WARRANTY 436 | 437 | 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO 438 | WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW. 439 | EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR 440 | OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY 441 | KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE 442 | IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 443 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE 444 | LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME 445 | THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 446 | 447 | 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN 448 | WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY 449 | AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU 450 | FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR 451 | CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE 452 | LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING 453 | RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A 454 | FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF 455 | SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH 456 | DAMAGES. 457 | 458 | END OF TERMS AND CONDITIONS 459 | 460 | How to Apply These Terms to Your New Libraries 461 | 462 | If you develop a new library, and you want it to be of the greatest 463 | possible use to the public, we recommend making it free software that 464 | everyone can redistribute and change. You can do so by permitting 465 | redistribution under these terms (or, alternatively, under the terms of the 466 | ordinary General Public License). 467 | 468 | To apply these terms, attach the following notices to the library. It is 469 | safest to attach them to the start of each source file to most effectively 470 | convey the exclusion of warranty; and each file should have at least the 471 | "copyright" line and a pointer to where the full notice is found. 472 | 473 | 474 | Copyright (C) 475 | 476 | This library is free software; you can redistribute it and/or 477 | modify it under the terms of the GNU Lesser General Public 478 | License as published by the Free Software Foundation; either 479 | version 2.1 of the License, or (at your option) any later version. 480 | 481 | This library is distributed in the hope that it will be useful, 482 | but WITHOUT ANY WARRANTY; without even the implied warranty of 483 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 484 | Lesser General Public License for more details. 485 | 486 | You should have received a copy of the GNU Lesser General Public 487 | License along with this library; if not, write to the Free Software 488 | Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 489 | USA 490 | 491 | Also add information on how to contact you by electronic and paper mail. 492 | 493 | You should also get your employer (if you work as a programmer) or your 494 | school, if any, to sign a "copyright disclaimer" for the library, if 495 | necessary. Here is a sample; alter the names: 496 | 497 | Yoyodyne, Inc., hereby disclaims all copyright interest in the 498 | library `Frob' (a library for tweaking knobs) written by James Random 499 | Hacker. 500 | 501 | , 1 April 1990 502 | Ty Coon, President of Vice 503 | 504 | That's all there is to it! 505 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Copyright (c) 2016-2023 Paulo Meira 2 | Copyright (c) 2018-2023 DSS-Extensions contributors 3 | All rights reserved. 4 | 5 | Redistribution and use in source and binary forms, with or without 6 | modification, are permitted provided that the following conditions are met: 7 | 8 | * Redistributions of source code must retain the above copyright notice, this 9 | list of conditions and the following disclaimer. 10 | 11 | * Redistributions in binary form must reproduce the above copyright notice, 12 | this list of conditions and the following disclaimer in the documentation 13 | and/or other materials provided with the distribution. 14 | 15 | * Neither the name of the copyright holder nor the names of its 16 | contributors may be used to endorse or promote products derived from 17 | this software without specific prior written permission. 18 | 19 | THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" 20 | AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 21 | IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 22 | DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE 23 | FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL 24 | DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR 25 | SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER 26 | CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, 27 | OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE 28 | OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. 29 | -------------------------------------------------------------------------------- /OPENDSS_LICENSE: -------------------------------------------------------------------------------- 1 | * Copyright (c) 2008-2021, Electric Power Research Institute, Inc. 2 | * All rights reserved. 3 | * 4 | * Redistribution and use in source and binary forms, with or without 5 | * modification, are permitted provided that the following conditions are met: 6 | * * Redistributions of source code must retain the above copyright 7 | * notice, this list of conditions and the following disclaimer. 8 | * * Redistributions in binary form must reproduce the above copyright 9 | * notice, this list of conditions and the following disclaimer in the 10 | * documentation and/or other materials provided with the distribution. 11 | * * Neither the name of the Electric Power Research Institute, Inc., nor 12 | * the names of its contributors may be used to endorse or promote 13 | * products derived from this software without specific prior written 14 | * permission. 15 | * 16 | * THIS SOFTWARE IS PROVIDED BY Electric Power Research Institute, Inc., "AS IS" 17 | * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE 18 | * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE 19 | * DISCLAIMED. IN NO EVENT SHALL Electric Power Research Institute, Inc., BE 20 | * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR 21 | * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF 22 | * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS 23 | * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN 24 | * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 25 | * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE 26 | * POSSIBILITY OF SUCH DAMAGE. 27 | 28 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [![Build](https://github.com/dss-extensions/dss_sharp/actions/workflows/dotnet.yml/badge.svg)](https://github.com/dss-extensions/dss_sharp/actions/workflows/dotnet.yml) 2 | [![Latest NuGet release](https://img.shields.io/nuget/v/dss_sharp?label=NuGet+release&cacheSeconds=3600)](https://www.nuget.org/packages/dss_sharp/) 3 | 4 | *Para uma versão em português 🇧🇷 deste arquivo, veja [README.pt-BR.md](https://github.com/dss-extensions/dss_sharp/blob/master/README.pt-BR.md).* 5 | 6 | # DSS Sharp 7 | 8 | DSS Sharp is a C#/.NET wrapper library for DSS C-API, which is an open-source, multi-platform, multi-architecture, extended alternative (unofficial, not provided by EPRI) OpenDSS engine, highly compatible with the official OpenDSS COM implementation and more. 9 | 10 | DSS Sharp tries to mimic the organization of the official OpenDSS COM interfaces, plus several extensions (new properties and methods, and whole new classes). If you find conflicting behavior, feel free to report. 11 | 12 | This projects exposes most of the functionality implemented in DSS C-API, including performance benefits, ZIP file support, initial JSON exports, multi-platform (Linux, Windows, macOS) support, including Intel x86/x64 and ARM architectures. Contrary to the official implementation, DSS Sharp supports multiple OpenDSS instances ([`dss_sharp.DSS.NewContext()`](https://dss-extensions.org/dss_sharp/html/d0e4d400-3bd9-1244-3cac-8f1234cbad9f.htm)), effectively enabling user-controlled multi-threading applications. Most of the official [parallel-machine](https://dss-extensions.org/dss_sharp/html/f3440753-3e74-bdb2-81c6-9052f8742d7e.htm) functions are also available. 13 | 14 | For a general introduction visit https://dss-extensions.org and follow the development of the general documentation at https://github.com/dss-extensions/dss-extensions 15 | 16 |

17 | Overview of related repositories 18 |

19 | 20 | If you are looking for the bindings to other languages: 21 | 22 | - [DSS C-API library](http://github.com/dss-extensions/dss_capi/): the base library that exposes a modified version of EPRI's OpenDSS through a more traditional C interface, built with the open-source Free Pascal compiler instead of Delphi. As of 2022, this base library includes several extensive changes, while retaining very good compatibility. 23 | - [dss.hpp](https://dss-extensions.org/dss_capi/): header-only library for C++, hosted within DSS C-API (`include/` directory). Allows using DSS C-API more comfortably from C++, abstract memory management and low-level details such as API conventions of the DSS C-API library. 24 | - Python: we have multiple alternatives! See https://dss-extensions.org/python_apis.html for more context. For drop-in replacement and API compatibility with the COM DLL, consider DSS-Python. 25 | - [OpenDSSDirect.jl](http://github.com/dss-extensions/OpenDSSDirect.jl/): a Julia module, created by Tom Short (@tshort), recently migrated with the help of Dheepak Krishnamurthy (@kdheepak) to DSS C-API instead of the DDLL. 26 | - [DSS_MATLAB](http://github.com/dss-extensions/dss_matlab/): presents multi-platform integration (Windows, Linux, macOS) with DSS C-API and is also very compatible with the COM classes. 27 | - [AltDSS-Rust](https://github.com/dss-extensions/AltDSS-Rust) and [AltDSS-Go](https://github.com/dss-extensions/AltDSS-Go) are new projects to expose the engine to Rust and Go programming languages. 28 | 29 | # Documentation 30 | 31 | We will grow general documentation at [https://github.com/dss-extensions/dss-extensions](https://github.com/dss-extensions/dss-extensions). Several notes and a FAQ are already available there. Some of the new docs are already available at https://dss-extensions.org/ (this DSS language reference and general documents useful for new users). 32 | 33 | Users can rely on the official [OpenDSS COM documentation](https://opendss.epri.com/COMInterface.html). We provide C#/.NET class library docs at https://dss-extensions.org/dss_sharp/ 34 | 35 | ## At a glance 36 | 37 | If you are new to C# or have not use it a few years, it's recommended to check updated material on the current state of .NET and best practices. 38 | 39 | If you are new to OpenDSS in general, there are two main aspects you need to study: 40 | 41 | - The DSS language, which is used to create and edit the components of the circuits, and also run commands to the DSS engine. 42 | - The APIs, mostly notably the class organization and logic sequences of the COM API. These are used to further automate the DSS engine, extract data and integrate to third party software. The current APIs all follow the concept of "active object" that may be new for many users. 43 | - The official COM DLL is available only for Microsoft Windows ([COM is a Microsoft technology](https://en.wikipedia.org/wiki/Component_Object_Model)), while DSS Sharp tries to reproduce the same API without depending on specific platforms — we can use Windows, Linux, or macOS, even on ARM processors. 44 | 45 | The official OpenDSS version from EPRI contains lots of material for both topics and, ignoring the whole installation and registering related to COM, are also applicable to DSS Sharp and other DSS-Extensions. 46 | 47 | You can learn the basics using the official version and migrate to DSS Sharp when required or when you are interested in the extras from DSS-Extensions. 48 | 49 | ### Installing 50 | 51 | There multiple ways, we recommend using NuGet. 52 | 53 | If you are using recent versions of Microsoft Visual Studio, you [install the package using NuGet](https://www.nuget.org/packages/dss_sharp/). 54 | 55 | If you're using the SDK style .csproj, you can add a reference like (remember to adjust the version if required): 56 | 57 | ```xml 58 | 59 | 60 | 61 | ``` 62 | 63 | Finally, if you wish to clone the repository and customize the library code instead, remember to manually download the required DLLs, either using the `scripts/download_native_libs.sh`, or by visiting [the DSS C-API releases](https://github.com/dss-extensions/dss_capi/releases) page. 64 | 65 | ### Minimal usage 66 | 67 | After installing and/or adding the reference to `dss_sharp` in your project, you can test with a circuit. 68 | 69 | Assuming you have OpenDSS installed at `C:\Program Files`, this should work: 70 | 71 | ```cs 72 | using dss_sharp; 73 | 74 | //... 75 | 76 | var dss = new DSS(); 77 | dss.Start(0); 78 | dss.Text.Command = @"redirect 'C:\Program Files\OpenDSS\IEEETestCases\13Bus\IEEE13Nodeckt.dss'"; 79 | var voltageMags = dss.ActiveCircuit.AllBusVmag; 80 | ``` 81 | 82 | You can also download our repository [electricdss-tst](https://github.com/dss-extensions/electricdss-tst) to obtain the test/reference circuits and more already adjusted for multi-platform usage (the original files are distributed in the official OpenDSS installer). 83 | 84 | ### More 85 | 86 | A simple, but almost step-by-step, sample is available here: [WinFormsAppSample](https://github.com/dss-extensions/dss_sharp/tree/master/examples/WinFormsAppSample) -------------------------------------------------------------------------------- /README.pt-BR.md: -------------------------------------------------------------------------------- 1 | [![Build](https://github.com/dss-extensions/dss_sharp/actions/workflows/dotnet.yml/badge.svg)](https://github.com/dss-extensions/dss_sharp/actions/workflows/dotnet.yml) 2 | [![Latest NuGet release](https://img.shields.io/nuget/v/dss_sharp?label=NuGet+release&cacheSeconds=3600)](https://www.nuget.org/packages/dss_sharp/) 3 | 4 | *For an English version of this file, see [README.md](https://github.com/dss-extensions/dss_sharp/blob/master/README.md).* 5 | 6 | # DSS Sharp 7 | 8 | DSS Sharp é um projeto para manter um assembly C#/.NET que exponha o motor do OpenDSS na sua implementação customizada da [biblioteca nativa DSS C-API](https://github.com/dss-extensions/dss_capi/blob/master/README.pt-BR.md). DSS C-API é um motor alternativo (sem suporte do EPRI) do OpenDSS: código aberto (totalmente), multiplataforma, multiarquitetura, com diversas extensões, e altamente compatível com a implementação oficial do OpenDSS conforme exposta em seu módulo COM. 9 | 10 | Para compatibilidade, DSS Sharp tenta reproduzir a mesma interface/API que o módulo COM oficial do OpenDSS em nível de código do usuário, além de conter várias extensões (novas propriedades e métodos, e mesmo classes completas para alguns componentes de circuito). Se você encontrar comportamento conflitante além do documentado, sinta-se à vontade para entrar em contato ou [reportar no GitHub](https://github.com/dss-extensions/dss_sharp/issues). 11 | 12 | Com exceção de gráficos e outros componentes visuais, este projeto expõe a maioria das funcionalidades implementadas na DSS C-API, incluindo algumas otimizações de desempenho, suporte a executar scripts .DSS dentro de arquivos ZIP, suporte inicial a exportação JSON, compatibilidade multiplataforma (Linux, Windows, macOS), includindo Intel x86/x64 e ARM. 13 | Ao contrário da implementação oficial, DSS Sharp suporta a criação de múltiplas instâncias independentes do motor do OpenDSS ([`dss_sharp.DSS.NewContext()`](https://dss-extensions.org/dss_sharp/html/d0e4d400-3bd9-1244-3cac-8f1234cbad9f.htm)), efetivamente permitindo que o usuário empregue aplicações com múltiplos threads de forma mais efetiva. A maioria das funções da versão PM do OpenDSS também estão [disponíveis](https://dss-extensions.org/dss_sharp/html/f3440753-3e74-bdb2-81c6-9052f8742d7e.htm). 14 | 15 | Para uma introdução geral, visite https://dss-extensions.org e siga o desenvolvimento através da organização DSS-Extensions e https://github.com/dss-extensions/dss-extensions 16 | 17 |

18 | Visão geral dos repositórios 19 |

20 | 21 | Caso você tenha interesse em outras linguagens além de .NET: 22 | 23 | - [DSS C-API library](http://github.com/dss-extensions/dss_capi/): a biblioteca base que expõe a versão modificada do OpenDSS através de uma interface C mais tradicional, criada empregando o compilador de código aberto Free Pascal ao invés do Delphi. Em 2023, contém diversas extensões e aprimoramentos, mantendo ainda boa compatibilidade. 24 | - [dss.hpp](https://dss-extensions.org/dss_capi/): biblioteca de headers para C++, hospedada também neste repositório (pasta `include/`). Permite usar a DSS C-API de forma confortável sem ser necessário gerenciar os detalhes como o gerenciamento de memória ou convenção de API da DSS C-API. Atualmente usa Eigen e fmt. 25 | - [DSS-Python](http://github.com/dss-extensions/dss_python/) é o módulo Python multi-plataforma (Windows, Linux, MacOS) bastante compatível com o módulo COM. Veja também [OpenDSSDirect.py](http://github.com/dss-extensions/OpenDSSDirect.py/) caso não precise de compatibilidade com COM, ou deseje empregar as funcionalidades extras do módulo (inclusive em conjunto). Há também o novo projeto [AltDSS-Python](http://github.com/dss-extensions/AltDSS-Python) que expande a API para todos os objetos DSS, manipulação de objetos em lote e mais. 26 | - [OpenDSSDirect.jl](http://github.com/dss-extensions/OpenDSSDirect.jl/) é um módulo em Julia, criado por Tom Short (@tshort), que recentemente passou a empregar DSS C-API no lugar do DLL direto com a ajuda de Dheepak Krishnamurthy (@kdheepak). 27 | - [DSS MATLAB](http://github.com/dss-extensions/dss_matlab/) permite integração multi-plataforma (Windows, Linux, MacOS) bastante compatível com a API do módulo COM oficial, de fato contorna algumas dificuldades de COM. 28 | - [AltDSS-Rust](https://github.com/dss-extensions/AltDSS-Rust) e [AltDSS-Go](https://github.com/dss-extensions/AltDSS-Go) são dois novos projetos para linguagens Rust e Go. 29 | 30 | # Documentação 31 | 32 | Estamos criando documentação geral, inicialmente em inglês, em [https://github.com/dss-extensions/dss-extensions](https://github.com/dss-extensions/dss-extensions). Diversas notas e um FAQ já estão disponíveis. Há também espaço dedicado para discussões, etc. 33 | 34 | No momento, os usuários podem seguir a documentação do módulo COM oficial do OpenDSS, pulando a parte de instalação. Caso não tenha OpenDSS instalado, os arquivos também estão disponíveis no [repositório SVN oficial](https://sourceforge.net/p/electricdss/code/HEAD/tree/trunk/Version8/Distrib/Doc/). 35 | 36 | Em geral atualizada alguns dias após o lançamento de uma nova versão, temos documentação das nossas classes de C#/.NET em https://dss-extensions.org/dss_sharp/ 37 | 38 | ## Primeiros passos 39 | 40 | Se você é um usuário novo de C# ou não tem usado em vários anos, é recomendável buscar por material atualizado sobre .NET e as práticas recomendadas para versões modernas. 41 | 42 | Se ainda não é proficiente em OpenDSS, há dois principais aspectos a investigar: 43 | 44 | - A linguagem DSS, que é usada para criar e editar os componentes dos circuitos elétricos, além de enviar comandos diversos para o motor do OpenDSS. 45 | - As interfaces de programação (APIs), em especial a organização de classes e lógica empregada na API COM. As interfaces são usadas para automatizar ainda mais o uso do motor do DSS, extrair dados e integrar programas e bibliotecas de terceiros. As APIs atuais todas seguem o conceito de "objeto ativo" ("Active...") que pode ser novo para muitos usuários. 46 | - O DLL do módulo COM oficial está disponível apenas no Microsoft Windows ([COM é uma tecnologia da Microsoft](https://pt.wikipedia.org/wiki/Component_Object_Model)). DSS Sharp tenta reproduzir a mesma interface em nível do usuário sem depender de plataformas específicas — podemos usar Windows, Linux, or macOS, mesmo em processadores ARM. 47 | 48 | A instalação da versão oficial do OpenDSS desenvolvida pelo EPRI contém bastante material para ambos os tópicos e, pulando a parte de instalação e registro do módulo COM (não necessário aqui), o material é aplicável para DSS Sharp e outras DSS-Extensions. 49 | 50 | Usuários podem estudar e aprender os principais conceitos empregando a versão oficial e migrar para DSS Sharp quando necessário ou houver interesse de empregar as funcionalidades extras disponíveis nas DSS-Extensions. 51 | 52 | ### Instalação 53 | 54 | Há múltiplas formas. Recomendamos empregar NuGet. 55 | 56 | Se estiver usando versões recentes do Microsoft Visual Studio, pode [instalar empregando o pacote NuGet](https://www.nuget.org/packages/dss_sharp/). 57 | 58 | Caso esteja usando arquivos .csproj no estilo SDK, basta adicionar uma referência no XML como no exemplo abaixo (ajuste a versão de acordo com suas necessidades): 59 | 60 | ```xml 61 | 62 | 63 | 64 | ``` 65 | 66 | Por fim, se houver interesse em editar o código da DSS Sharp em si, após clonar lembra-se de baixar os DLLs necessários, seja usando o script `scripts/download_native_libs.sh`, ou visitando manualmente a [página de lançamentos da DSS C-API](https://github.com/dss-extensions/dss_capi/releases) para obter as versões necessárias. Alternativamente, copiar os DLLs do pacote NuGet pode ser mais prático. 67 | 68 | ### Uso mínimo 69 | 70 | Após a instalação ou inclusão da referência ao `dss_sharp` no seu projeto, é possível testar a execução com um circuito qualquer. 71 | 72 | Assumindo a instalação padrão do OpenDSS para todos os usuários na pasta `C:\Program Files`, o seguinte deve funcionar: 73 | 74 | ```cs 75 | using dss_sharp; 76 | 77 | //... 78 | 79 | var dss = new DSS(); 80 | dss.Start(0); 81 | dss.Text.Command = @"redirect 'C:\Program Files\OpenDSS\IEEETestCases\13Bus\IEEE13Nodeckt.dss'"; 82 | var voltageMags = dss.ActiveCircuit.AllBusVmag; 83 | ``` 84 | 85 | Você também pode baixar o repositório [electricdss-tst](https://github.com/dss-extensions/electricdss-tst) para obter os circuitos de teste e exemplos já ajustados para uso for multiplataforma (os arquivos originais são distribuídos com a instalação do OpenDSS oficial). 86 | 87 | ### Mais 88 | 89 | Um exemplo simples mas quase passo a passo, está disponível aqui, apenas em inglês: [WinFormsAppSample](https://github.com/dss-extensions/dss_sharp/tree/master/examples/WinFormsAppSample) -------------------------------------------------------------------------------- /docs/images/dss_sharp.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dss-extensions/dss_sharp/15de0f33c3cf8d1add3946d6b2f7d4845e52d343/docs/images/dss_sharp.png -------------------------------------------------------------------------------- /dss_sharp.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | netstandard2.1;netstandard2.0;net45 5 | disable 6 | {398768E0-151E-4974-8A2A-2DD2724F6426} 7 | dss_sharp.xml 8 | README.md 9 | 1591 10 | x64 11 | Paulo Meira, DSS-Extensions contributors 12 | 0.14.3 13 | DSS Sharp 14 | 15 | DSS Sharp is a C# wrapper to the native DSS C-API library, a multiplatform multiarchitecture implementation of EPRI's OpenDSS engine. 16 | 17 | Although not an official project from EPRI, DSS Sharp exposes an organization of classes that mimics the official OpenDSS COM implementation, which is Windows-only -- that is, users often can replace or even "#IFDEF" the usage of the official Windows-only implementation with DSS Sharp. Since DSS Sharp uses our C-API directly, it's also common to achieve better performance. 18 | 19 | Extra features include support for .DSS scripts in ZIP files, creation of multiple DSS instances in the same process (including user-controlled multi-threading), and an extended API for various components. 20 | 21 | DSS Sharp is part of the DSS-Extensions group of projects. See more at https://dss-extensions.org/ 22 | 23 | dss_sharp 24 | BSD-3-Clause AND LGPL 25 | 0.14.3.0 26 | 0.14.3.0 27 | https://github.com/dss-extensions/dss_sharp/ 28 | dss;opendss;linux;windows;macos;dss-extensions;powerflow;distribution;electric;simulator 29 | docs/images/dss_sharp.png 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | true 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | PreserveNewest 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | -------------------------------------------------------------------------------- /dss_sharp.targets: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | dss_capi.dll 6 | PreserveNewest 7 | 8 | 9 | libklusolvex.dll 10 | PreserveNewest 11 | 12 | 13 | libwinpthread-1.dll 14 | PreserveNewest 15 | 16 | 17 | dss_capi.dll 18 | PreserveNewest 19 | 20 | 21 | libklusolvex.dll 22 | PreserveNewest 23 | 24 | 25 | 26 | messages\%(FileName)%(Extension) 27 | PreserveNewest 28 | 29 | 30 | -------------------------------------------------------------------------------- /examples/WinFormsAppSample/Form1.Designer.cs: -------------------------------------------------------------------------------- 1 | namespace WinFormsAppSample 2 | { 3 | partial class Form1 4 | { 5 | /// 6 | /// Required designer variable. 7 | /// 8 | private System.ComponentModel.IContainer components = null; 9 | 10 | /// 11 | /// Clean up any resources being used. 12 | /// 13 | /// true if managed resources should be disposed; otherwise, false. 14 | protected override void Dispose(bool disposing) 15 | { 16 | if (disposing && (components != null)) 17 | { 18 | components.Dispose(); 19 | } 20 | base.Dispose(disposing); 21 | } 22 | 23 | #region Windows Form Designer generated code 24 | 25 | /// 26 | /// Required method for Designer support - do not modify 27 | /// the contents of this method with the code editor. 28 | /// 29 | private void InitializeComponent() 30 | { 31 | button1 = new Button(); 32 | button2 = new Button(); 33 | textBox1 = new TextBox(); 34 | button3 = new Button(); 35 | formsPlot1 = new ScottPlot.FormsPlot(); 36 | SuspendLayout(); 37 | // 38 | // button1 39 | // 40 | button1.Location = new Point(26, 12); 41 | button1.Name = "button1"; 42 | button1.Size = new Size(112, 34); 43 | button1.TabIndex = 0; 44 | button1.Text = "Version"; 45 | button1.UseVisualStyleBackColor = true; 46 | button1.Click += button1_Click; 47 | // 48 | // button2 49 | // 50 | button2.Location = new Point(144, 12); 51 | button2.Name = "button2"; 52 | button2.Size = new Size(112, 34); 53 | button2.TabIndex = 1; 54 | button2.Text = "Run"; 55 | button2.UseVisualStyleBackColor = true; 56 | button2.Click += button2_Click; 57 | // 58 | // textBox1 59 | // 60 | textBox1.Location = new Point(26, 52); 61 | textBox1.Multiline = true; 62 | textBox1.Name = "textBox1"; 63 | textBox1.Size = new Size(762, 123); 64 | textBox1.TabIndex = 2; 65 | textBox1.Text = "compile \"C:\\Program Files\\OpenDSS\\IEEETestCases\\13Bus\\IEEE13Nodeckt.dss\"\r\nshow voltages ln\r\n"; 66 | // 67 | // button3 68 | // 69 | button3.Location = new Point(262, 12); 70 | button3.Name = "button3"; 71 | button3.Size = new Size(112, 34); 72 | button3.TabIndex = 3; 73 | button3.Text = "Compare"; 74 | button3.UseVisualStyleBackColor = true; 75 | button3.Click += button3_Click; 76 | // 77 | // formsPlot1 78 | // 79 | formsPlot1.Location = new Point(15, 183); 80 | formsPlot1.Margin = new Padding(6, 5, 6, 5); 81 | formsPlot1.Name = "formsPlot1"; 82 | formsPlot1.Size = new Size(770, 527); 83 | formsPlot1.TabIndex = 4; 84 | // 85 | // Form1 86 | // 87 | AutoScaleDimensions = new SizeF(10F, 25F); 88 | AutoScaleMode = AutoScaleMode.Font; 89 | ClientSize = new Size(800, 711); 90 | Controls.Add(formsPlot1); 91 | Controls.Add(button3); 92 | Controls.Add(textBox1); 93 | Controls.Add(button2); 94 | Controls.Add(button1); 95 | Name = "Form1"; 96 | Text = "Form1"; 97 | ResumeLayout(false); 98 | PerformLayout(); 99 | } 100 | 101 | #endregion 102 | 103 | private Button button1; 104 | private Button button2; 105 | private TextBox textBox1; 106 | private Button button3; 107 | private ScottPlot.FormsPlot formsPlot1; 108 | } 109 | } -------------------------------------------------------------------------------- /examples/WinFormsAppSample/Form1.cs: -------------------------------------------------------------------------------- 1 | using dss_sharp; 2 | using ScottPlot; 3 | using System.Windows.Forms; 4 | 5 | namespace WinFormsAppSample 6 | { 7 | public partial class Form1 : Form 8 | { 9 | DSS engine; 10 | 11 | public Form1() 12 | { 13 | InitializeComponent(); 14 | engine = new DSS(); 15 | } 16 | 17 | private void button1_Click(object sender, EventArgs e) 18 | { 19 | MessageBox.Show(engine.Version); 20 | } 21 | 22 | private void button2_Click(object sender, EventArgs e) 23 | { 24 | var lines = textBox1.Lines; 25 | foreach (var line in lines) 26 | { 27 | try 28 | { 29 | engine.Text.Command = line; 30 | } 31 | catch (DSSException ex) 32 | { 33 | MessageBox.Show(ex.Message); 34 | break; 35 | } 36 | } 37 | } 38 | 39 | private void button3_Click(object sender, EventArgs e) 40 | { 41 | // Try running the test circuit 42 | try 43 | { 44 | engine.Text.Command = @"compile 'C:\Program Files\OpenDSS\IEEETestCases\13Bus\IEEE13Nodeckt.dss'"; 45 | } 46 | catch (DSSException ex) 47 | { 48 | MessageBox.Show(ex.Message); 49 | return; 50 | } 51 | 52 | var circ = engine.ActiveCircuit; 53 | 54 | // Create an array for the x-axis and clear any previous plot 55 | var x = new double[circ.NumNodes]; 56 | for (int i = 0; i < x.Length; ++i) 57 | { 58 | x[i] = i + 1; 59 | } 60 | var plot = formsPlot1.Plot; 61 | plot.Clear(); 62 | 63 | // Ensure the solution mode is snapshot, and solve the base case 64 | circ.Solution.Mode = (int)SolveModes.dssSnapShot; 65 | circ.Solution.LoadMult = 1.0; 66 | circ.Solution.Solve(); 67 | 68 | // Be sure to check the convergency since it doesn't necessarily becomes 69 | // an error/exception if the system fails to converge. 70 | if (!circ.Solution.Converged) 71 | { 72 | MessageBox.Show("Failed to converge."); 73 | return; 74 | } 75 | 76 | // Add the base plot 77 | plot.AddScatter(x, circ.AllBusVmagPu, label: "Base case"); 78 | 79 | // Solve the 1.5x load case, add it to the plot 80 | circ.Solution.LoadMult = 1.5; 81 | circ.Solution.Solve(); 82 | if (!circ.Solution.Converged) 83 | { 84 | MessageBox.Show("Failed to converge."); 85 | return; 86 | } 87 | 88 | plot.AddScatter(x, circ.AllBusVmagPu, label: "1.5x load"); 89 | 90 | // Finishing touches to the chart 91 | plot.Legend(); 92 | plot.XLabel("Bus index"); 93 | plot.YLabel("Voltage (pu)"); 94 | plot.Title($"Circuit: {circ.Name}, NumNodes: {circ.NumNodes}"); 95 | 96 | formsPlot1.Refresh(); 97 | } 98 | } 99 | } 100 | -------------------------------------------------------------------------------- /examples/WinFormsAppSample/Form1.resx: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | text/microsoft-resx 50 | 51 | 52 | 2.0 53 | 54 | 55 | System.Resources.ResXResourceReader, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 56 | 57 | 58 | System.Resources.ResXResourceWriter, System.Windows.Forms, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 59 | 60 | -------------------------------------------------------------------------------- /examples/WinFormsAppSample/Program.cs: -------------------------------------------------------------------------------- 1 | namespace WinFormsAppSample 2 | { 3 | internal static class Program 4 | { 5 | /// 6 | /// The main entry point for the application. 7 | /// 8 | [STAThread] 9 | static void Main() 10 | { 11 | // To customize application configuration such as set high DPI settings or default font, 12 | // see https://aka.ms/applicationconfiguration. 13 | ApplicationConfiguration.Initialize(); 14 | Application.Run(new Form1()); 15 | } 16 | } 17 | } -------------------------------------------------------------------------------- /examples/WinFormsAppSample/README.md: -------------------------------------------------------------------------------- 1 | # WinForms + dss_sharp 2 | 3 | ## Initial setup 4 | 5 | - From Visual Studio's home screen, select "Create a new project" 6 | - Select "Windows Forms App" 7 | - For the prepared version here, we typed "WinFormsAppSample" as name, and marked the option to "Place solution and project in the same directory". 8 | - After the project is created, open the "Project" item in the top menu bar, and select "Manage NuGet Packages..." 9 | - Activate/click the "Browse" tab and type dss_sharp in the search box. 10 | - Our package should be listed; you should recognize the icon. Click it to show its description, then click the "Install" button. 11 | - By installing, on the default settings, the package is automatically added to the project. You can now proceed to code! 12 | 13 | ## Checking the version 14 | 15 | - Add a button. You can do so by double-clicking or dragging a button from the Toolbox. If you don't see the toolbox, click View>Toolbox. 16 | - Change this button's text to "Version". 17 | - Double-click the button. This will show you the code editor for the "Click" event. 18 | - First, add `using dss_sharp;` to top of the file. 19 | - Add a new class member of the type `DSS`. We called it "engine". 20 | - On the form constructor, create the object. 21 | - Finally, in the click event method, use `MessageBox.Show` to show the string from `engine.Version`. 22 | 23 | You code should look like: 24 | 25 | ```csharp 26 | 27 | using dss_sharp; 28 | 29 | namespace WinFormsAppSample 30 | { 31 | public partial class Form1 : Form 32 | { 33 | DSS engine; 34 | 35 | public Form1() 36 | { 37 | InitializeComponent(); 38 | engine = new DSS(); 39 | } 40 | 41 | private void button1_Click(object sender, EventArgs e) 42 | { 43 | MessageBox.Show(engine.Version); 44 | } 45 | } 46 | } 47 | ``` 48 | 49 | Build and run, then click the button to ensure it's working. When run, this is an example output when clicking the button: 50 | 51 |

52 | A button to check the version 53 |

54 | 55 | 56 | ## Running a DSS script 57 | 58 | - Now add a textbox, and another button. 59 | - Change the "Multiline" property of the textbox to true, and resize it to be big enough. 60 | - Change the button's text to "Run". 61 | - Double-click the button, and make sure you fill the new method like the following: 62 | 63 | ```csharp 64 | private void button2_Click(object sender, EventArgs e) 65 | { 66 | var lines = textBox1.Lines; 67 | foreach (var line in lines) 68 | { 69 | try 70 | { 71 | engine.Text.Command = line; 72 | } 73 | catch (DSSException ex) 74 | { 75 | MessageBox.Show(ex.Message); 76 | break; 77 | } 78 | } 79 | } 80 | ``` 81 | 82 | - Finally, build and run again. If you have OpenDSS installed in the default folder, you can paste this in your running app (or previously in the Text property of the textbox): 83 | 84 | ``` 85 | compile "C:\Program Files\OpenDSS\IEEETestCases\13Bus\IEEE13Nodeckt.dss" 86 | show voltages ln 87 | ``` 88 | 89 |

90 | Textbox and Run button 91 |

92 | 93 | And click run! 94 | 95 | If everything is done correctly, you should get a new text editor for the voltage results from the sample circuit. 96 | If the file doesn't exist, you should instead get a new message box telling you something like "Redirect file not found...". 97 | 98 |

99 | Textbox and Run button: example output 100 |

101 | 102 | ## Multiple scenarios and better control through the API 103 | 104 | Although running scripts and exporting text files is useful, the main advantages of the APIs (either dss_sharp or the official COM module), 105 | is the ability to get numeric data directly for different scenarios according to the analysis the user is required to achieve. 106 | 107 | For example, suppose you wanted to compare the voltages for two scenarios of load. 108 | 109 | ```csharp 110 | engine.ActiveCircuit.Solution.LoadMult = 1.0; 111 | engine.ActiveCircuit.Solution.Solve(); 112 | var voltages_base = engine.ActiveCircuit.AllBusVmagPu; 113 | 114 | engine.ActiveCircuit.Solution.LoadMult = 1.5; 115 | engine.ActiveCircuit.Solution.Solve(); 116 | var voltage_150 = engine.ActiveCircuit.AllBusVmagPu; 117 | ``` 118 | 119 | You can of course get references to the API elements to make the code less verbose, for example: 120 | 121 | ```csharp 122 | var circ = engine.ActiveCircuit; 123 | 124 | circ.Solution.LoadMult = 1.0; 125 | circ.Solution.Solve(); 126 | var voltages_base = circ.AllBusVmagPu; 127 | 128 | circ.Solution.LoadMult = 1.5; 129 | engine.ActiveCircuit.Solution.Solve(); 130 | var voltage_150 = circ.AllBusVmagPu; 131 | ``` 132 | 133 | You are free to use various methods and other .NET packages to compare and evaluate the voltage arrays. 134 | 135 | ## Adding a chart 136 | 137 | To better illustrate, let's add a simple chart of the voltages for difference load scenarios. 138 | 139 | - First, open the Manage NuGet Packages again, and this time install "ScottPlot.WinForms". This will also install several dependencies. 140 | 141 | - After the installation, a new item named "FormsPlot" will be available in the Toolbox. Add one to your form. 142 | 143 | - Now add a third button. Change its label to "Compare". You form should look like the example below. 144 | 145 |

146 | Three buttons and the plotting area 147 |

148 | 149 | - Add the following code to its click event handler (read the comments!): 150 | 151 | ```csharp 152 | private void button3_Click(object sender, EventArgs e) 153 | { 154 | // Try running the test circuit 155 | try 156 | { 157 | engine.Text.Command = @"compile 'C:\Program Files\OpenDSS\IEEETestCases\13Bus\IEEE13Nodeckt.dss'"; 158 | } 159 | catch (DSSException ex) 160 | { 161 | MessageBox.Show(ex.Message); 162 | return; 163 | } 164 | 165 | var circ = engine.ActiveCircuit; 166 | 167 | // Create an array for the x-axis and clear any previous plot 168 | var x = new double[circ.NumNodes]; 169 | for (int i = 0; i < x.Length; ++i) 170 | { 171 | x[i] = i + 1; 172 | } 173 | var plot = formsPlot1.Plot; 174 | plot.Clear(); 175 | 176 | // Ensure the solution mode is snapshot, and solve the base case 177 | circ.Solution.Mode = (int)SolveModes.dssSnapShot; 178 | circ.Solution.LoadMult = 1.0; 179 | circ.Solution.Solve(); 180 | 181 | // Be sure to check the convergency since it doesn't necessarily becomes 182 | // an error/exception if the system fails to converge. 183 | if (!circ.Solution.Converged) 184 | { 185 | MessageBox.Show("Failed to converge."); 186 | return; 187 | } 188 | 189 | // Add the base plot 190 | plot.AddScatter(x, circ.AllBusVmagPu, label: "Base case"); 191 | 192 | // Solve the 1.5x load case, add it to the plot 193 | circ.Solution.LoadMult = 1.5; 194 | circ.Solution.Solve(); 195 | if (!circ.Solution.Converged) 196 | { 197 | MessageBox.Show("Failed to converge."); 198 | return; 199 | } 200 | 201 | plot.AddScatter(x, circ.AllBusVmagPu, label: "1.5x load"); 202 | 203 | // Finishing touches to the chart 204 | plot.Legend(); 205 | plot.XLabel("Bus index"); 206 | plot.YLabel("Voltage (pu)"); 207 | plot.Title($"Circuit: {circ.Name}, NumNodes: {circ.NumNodes}"); 208 | 209 | formsPlot1.Refresh(); 210 | } 211 | ``` 212 | 213 | Finally, running the app and clicking compare should give a nice chart: 214 | 215 |

216 | Plotting some output 217 |

218 | 219 | 220 | For most users, this is enough to get the handle of how things work, so we left the sample application 221 | on this point. If you whish to allow your application to run with both the official COM DLL and dss_sharp, 222 | continue below. 223 | 224 | ## Comparing to the official OpenDSS COM DLL 225 | 226 | This project tries to be very compatible with the official COM API, but there are some niceties that are lost when 227 | keeping the code fully compatible. We also avoid adding some conveniences to dss_sharp to keep the codebase more 228 | compatible. This could change in the future, but we would likely create a separate API while maintaining this 229 | classic API for compatibility. 230 | 231 | To be able run with the official OpenDSS, add a COM Reference in the Dependencies list (e.g. in the Solution Explorer). Search for "OpenDSS Engine" and mark its checkbox. 232 | 233 | Now, there's adjust the code to make it work with both versions. 234 | 235 | The first step is to change the the `using` clause. To make it easier to use both versions, we can replace `using dss_sharp;` with: 236 | 237 | ```csharp 238 | #if USE_DSS_SHARP 239 | using dss_sharp; 240 | #else 241 | using OpenDSSengine; 242 | #endif 243 | ``` 244 | 245 | The initialization could also be adjusted to disable certain dss_sharp features 246 | 247 | ```csharp 248 | public Form1() 249 | { 250 | InitializeComponent(); 251 | engine = new DSS(); 252 | engine.Start(0); 253 | engine.AllowForms = false; 254 | #if USE_DSS_SHARP 255 | // Disable the automatic error-to-exception mapping 256 | dss_sharp.Error.UseExceptions = false; 257 | 258 | // Disable the early-abort mechanism. 259 | // Without it, the engine may continue to run ignoring 260 | // some errors -- we highly advice against it, but you 261 | // may need to do this to check your COM-based code before 262 | // migrating to dss_sharp. 263 | engine.Error.EarlyAbort = false; 264 | 265 | // There are other flags that could be useful; 266 | // check the documentation of dss_sharp itself 267 | // and DSS C-API for more insight. 268 | #endif 269 | } 270 | ``` 271 | 272 | And, without exceptions, we need to manually check the error number for most of 273 | API calls. For example, our previous `button2_Click` now becomes: 274 | 275 | ```csharp 276 | private void button2_Click(object sender, EventArgs e) 277 | { 278 | var lines = textBox1.Lines; 279 | foreach (var line in lines) 280 | { 281 | engine.Text.Command = line; 282 | if (engine.Error.Number != 0) 283 | { 284 | MessageBox.Show(engine.Error.Description); 285 | break; 286 | } 287 | } 288 | } 289 | ``` 290 | 291 | If you now run the compiled app, you would be running using the official COM version of OpenDSS. And, with the conditional compilation of the initialization in place, you can easily toggle using dss_sharp. 292 | 293 | To use dss_sharp, just open the project properties, and add `USE_DSS_SHARP` to the custom symbols list (both "Debug Custom Symbols" and "Release Custom Symbols"). So, if instead of WinForms we used a 294 | multi-platform UI like [Avalonia](https://avaloniaui.net/), we could achieve multi-platform OpenDSS usage in .NET, which still maintaining the option to test with the official engine. 295 | 296 | ### A warning about "EarlyAbort" 297 | 298 | To understand this flag (API Extension) from dss_sharp, create a text file, e.g. `c:\temp\errorsample.dss`, with the following contents: 299 | 300 | ``` 301 | compile "C:\Program Files\OpenDSS\IEEETestCases\13Bus\IEEE13Nodeckt.dss" 302 | new TRANSFORMER.SUB 303 | show voltages ln 304 | ``` 305 | 306 | The second line contains an error: there is already a transformer element name "sub" in the circuit! 307 | 308 | Now, try to run it with our sample app, e.g. type `compile c:\temp\errorsample.dss` in the textbox and click Run. 309 | 310 | With the official COM version, with `AllowForms = false` (typical for automation and large scale projects), you not only will get the 311 | output from `show voltages ln`, but will also get no error! 312 | 313 | When we set `engine.Error.EarlyAbort = false` on dss_sharp, you will get the same behavior. 314 | 315 | On the other hand, the default behavior of dss_sharp and DSS-Extensions in general, with `engine.Error.EarlyAbort = true`, 316 | is to stop the execution on the first error found. As such, we don't inhibit errors in automated/unattended 317 | large scale simulations. 318 | 319 | -------------------------------------------------------------------------------- /examples/WinFormsAppSample/WinFormsAppSample.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | WinExe 5 | net6.0-windows 6 | enable 7 | true 8 | enable 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | -------------------------------------------------------------------------------- /examples/WinFormsAppSample/WinFormsAppSample.csproj.user: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | Form 6 | 7 | 8 | 9 | -------------------------------------------------------------------------------- /examples/WinFormsAppSample/WinFormsAppSample.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 17 4 | VisualStudioVersion = 17.5.33516.290 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "WinFormsAppSample", "WinFormsAppSample.csproj", "{62CE6DC0-F0B4-47B7-AD95-F0E6D0E3484E}" 7 | EndProject 8 | Global 9 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 10 | Debug|Any CPU = Debug|Any CPU 11 | Release|Any CPU = Release|Any CPU 12 | EndGlobalSection 13 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 14 | {62CE6DC0-F0B4-47B7-AD95-F0E6D0E3484E}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 15 | {62CE6DC0-F0B4-47B7-AD95-F0E6D0E3484E}.Debug|Any CPU.Build.0 = Debug|Any CPU 16 | {62CE6DC0-F0B4-47B7-AD95-F0E6D0E3484E}.Release|Any CPU.ActiveCfg = Release|Any CPU 17 | {62CE6DC0-F0B4-47B7-AD95-F0E6D0E3484E}.Release|Any CPU.Build.0 = Release|Any CPU 18 | EndGlobalSection 19 | GlobalSection(SolutionProperties) = preSolution 20 | HideSolutionNode = FALSE 21 | EndGlobalSection 22 | GlobalSection(ExtensibilityGlobals) = postSolution 23 | SolutionGuid = {E0D09881-3638-4542-909F-0557EE096EB4} 24 | EndGlobalSection 25 | EndGlobal 26 | -------------------------------------------------------------------------------- /examples/WinFormsAppSample/images/1-version-button.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dss-extensions/dss_sharp/15de0f33c3cf8d1add3946d6b2f7d4845e52d343/examples/WinFormsAppSample/images/1-version-button.png -------------------------------------------------------------------------------- /examples/WinFormsAppSample/images/2-textbox-run.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dss-extensions/dss_sharp/15de0f33c3cf8d1add3946d6b2f7d4845e52d343/examples/WinFormsAppSample/images/2-textbox-run.png -------------------------------------------------------------------------------- /examples/WinFormsAppSample/images/3-textbox-run-output.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dss-extensions/dss_sharp/15de0f33c3cf8d1add3946d6b2f7d4845e52d343/examples/WinFormsAppSample/images/3-textbox-run-output.png -------------------------------------------------------------------------------- /examples/WinFormsAppSample/images/4-before-plotting.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dss-extensions/dss_sharp/15de0f33c3cf8d1add3946d6b2f7d4845e52d343/examples/WinFormsAppSample/images/4-before-plotting.png -------------------------------------------------------------------------------- /examples/WinFormsAppSample/images/5-after-plotting.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/dss-extensions/dss_sharp/15de0f33c3cf8d1add3946d6b2f7d4845e52d343/examples/WinFormsAppSample/images/5-after-plotting.png -------------------------------------------------------------------------------- /scripts/ci_update_versions.sh: -------------------------------------------------------------------------------- 1 | # Update FileVersion 2 | sed -i -r 's/([0-9]+\.[0-9]+\.[0-9]+\.)[0-9]+/\1$(GITHUB_RUN_NUMBER)/' dss_sharp.csproj 3 | 4 | if [ "tag" == "${GITHUB_REF_TYPE}" ]; then 5 | sed -i -r 's/.*<\/PackageVersion>/$(GITHUB_REF_NAME)<\/PackageVersion>/' dss_sharp.csproj 6 | fi 7 | 8 | cat dss_sharp.csproj 9 | -------------------------------------------------------------------------------- /scripts/download_native_libs.sh: -------------------------------------------------------------------------------- 1 | if [ -z ${DSS_CAPI_TAG+x} ]; then 2 | DSS_CAPI_TAG=0.14.3 3 | fi 4 | 5 | rm -rf runtimes messages 6 | mkdir runtimes 7 | cd runtimes 8 | echo Downloading... 9 | curl -s -L https://github.com/dss-extensions/dss_capi/releases/download/${DSS_CAPI_TAG}/dss_capi_${DSS_CAPI_TAG}_linux_x64.tar.gz -o linux.tar.gz 10 | curl -s -L https://github.com/dss-extensions/dss_capi/releases/download/${DSS_CAPI_TAG}/dss_capi_${DSS_CAPI_TAG}_darwin_x64.tar.gz -o macos.tar.gz 11 | curl -s -L https://github.com/dss-extensions/dss_capi/releases/download/${DSS_CAPI_TAG}/dss_capi_${DSS_CAPI_TAG}_darwin_arm64.tar.gz -o macosarm.tar.gz 12 | curl -s -L https://github.com/dss-extensions/dss_capi/releases/download/${DSS_CAPI_TAG}/dss_capi_${DSS_CAPI_TAG}_win_x64.zip -o win64.zip 13 | curl -s -L https://github.com/dss-extensions/dss_capi/releases/download/${DSS_CAPI_TAG}/dss_capi_${DSS_CAPI_TAG}_win_x86.zip -o win32.zip 14 | curl -s -L https://github.com/dss-extensions/dss_capi/releases/download/${DSS_CAPI_TAG}/messages.tar.gz -o messages.tar.gz 15 | 16 | echo Unpacking... 17 | unzip -q -o win64.zip 18 | unzip -q -o win32.zip 19 | tar zxf linux.tar.gz 20 | tar zxf macos.tar.gz 21 | tar zxf macosarm.tar.gz 22 | tar zxf messages.tar.gz 23 | 24 | mkdir -p win-x64/native linux-x64/native osx-x64/native osx.11.0-arm64/native win-x86/native 25 | find . -name '*dss_capid*' -exec rm {} \; 26 | 27 | mv dss_capi/lib/win_x64/*.dll ./win-x64/native/ 28 | mv dss_capi/lib/win_x86/*.dll ./win-x86/native/ 29 | mv dss_capi/lib/linux_x64/*.so ./linux-x64/native/ 30 | mv dss_capi/lib/darwin_arm64/*.dylib ./osx.11.0-arm64/native/ 31 | mv dss_capi/lib/darwin_x64/*.dylib ./osx-x64/native/ 32 | 33 | mv messages .. 34 | 35 | echo Clean-up... 36 | rm *.zip *.tar.gz 37 | rm -rf dss_capi 38 | 39 | echo Done! -------------------------------------------------------------------------------- /src/dss_sharp_util.cs: -------------------------------------------------------------------------------- 1 | // dss_sharp: A compatibility layer for DSS C-API that mimics the official OpenDSS COM interface. 2 | // Copyright (c) 2016-2022 Paulo Meira 3 | // Copyright (c) 2018-2022 DSS-Extensions contributors 4 | // 5 | // See LICENSE for more information. 6 | // 7 | 8 | using System; 9 | using System.IO; 10 | using System.Runtime.InteropServices; 11 | using dss_sharp.native; 12 | 13 | namespace dss_sharp 14 | { 15 | /// 16 | /// DSSException encapsulates the error information from the 17 | /// "DSS.Error" interface. 18 | /// 19 | public class DSSException : Exception 20 | { 21 | public int ErrorNumber; 22 | 23 | public DSSException(int number, string message): base(message) 24 | { 25 | ErrorNumber = number; 26 | } 27 | } 28 | 29 | namespace detail 30 | { 31 | /// 32 | /// ContextState keeps a copy of the DSS engine instance and 33 | /// the utility class (APIUtil). 34 | /// 35 | public class ContextState 36 | { 37 | protected IntPtr ctx; 38 | protected APIUtil apiutil; 39 | 40 | protected void CheckForError() 41 | { 42 | apiutil.CheckForError(); 43 | } 44 | 45 | public ContextState(APIUtil util) 46 | { 47 | apiutil = util; 48 | ctx = util.ctx; 49 | } 50 | 51 | /// 52 | /// Returns the low-level handle of the current OpenDSS/DSS-CAPI instance. 53 | /// 54 | public IntPtr GetContextHandle() 55 | { 56 | return ctx; 57 | } 58 | } 59 | 60 | /// 61 | /// APIUtil provides some common functions to read data and map errors. 62 | /// Member names are kept to mirror DSS-Python and other projects. 63 | /// 64 | public class APIUtil 65 | { 66 | public static bool exceptionsAllowed = true; 67 | private static bool MOLoaded = false; 68 | public delegate void StringArrayDelegate1(IntPtr ctx, ref IntPtr resultPtr, int[] resultCount); 69 | public delegate void StringArrayDelegate2(IntPtr ctx, ref IntPtr resultPtr, int[] resultCount, int param1); 70 | public delegate void StringArrayDelegate3(IntPtr ctx, ref IntPtr resultPtr, int[] resultCount, string param1); 71 | public bool ownsCtx; 72 | public IntPtr ctx; 73 | public IntPtr errorPtr; 74 | private IntPtr 75 | gr_float64_data, gr_float64_count, 76 | gr_int32_data, gr_int32_count, 77 | gr_int8_data, gr_int8_count; 78 | 79 | public APIUtil(IntPtr context, bool ownsContext) 80 | { 81 | IntPtr unused1 = IntPtr.Zero; 82 | IntPtr unused2 = IntPtr.Zero; 83 | 84 | ownsCtx = ownsContext; 85 | ctx = context; 86 | errorPtr = DSS_CAPI.ctx_Error_Get_NumberPtr(ctx); 87 | DSS_CAPI.ctx_DSS_GetGRPointers( 88 | ctx, 89 | ref unused1, 90 | ref gr_float64_data, 91 | ref gr_int32_data, 92 | ref gr_int8_data, 93 | ref unused2, 94 | ref gr_float64_count, 95 | ref gr_int32_count, 96 | ref gr_int8_count 97 | ); 98 | 99 | if (!APIUtil.MOLoaded) 100 | { 101 | var dllPath = new System.Uri(typeof(APIUtil).Assembly.EscapedCodeBase).LocalPath; 102 | var moPath = Path.Combine(Path.GetDirectoryName(dllPath), "messages", "properties-en-US.mo"); 103 | if (File.Exists(moPath)) 104 | { 105 | DSS_CAPI.DSS_SetPropertiesMO(moPath); 106 | } 107 | APIUtil.MOLoaded = true; 108 | } 109 | } 110 | 111 | ~APIUtil() 112 | { 113 | if (!ownsCtx) return; 114 | DSS_CAPI.ctx_Dispose(ctx); 115 | } 116 | 117 | public double[] get_float64_gr_array() 118 | { 119 | int cnt = Marshal.ReadInt32(gr_float64_count); 120 | double[] res = new double[cnt]; 121 | IntPtr actualDataPtr = Marshal.ReadIntPtr(gr_float64_data); 122 | Marshal.Copy(actualDataPtr, res, 0, cnt); 123 | return res; 124 | } 125 | 126 | public int[] get_int32_gr_array() 127 | { 128 | int cnt = Marshal.ReadInt32(gr_int32_count); 129 | int[] res = new int[cnt]; 130 | IntPtr actualDataPtr = Marshal.ReadIntPtr(gr_int32_data); 131 | Marshal.Copy(actualDataPtr, res, 0, cnt); 132 | return res; 133 | } 134 | 135 | public byte[] get_int8_gr_array() 136 | { 137 | int cnt = Marshal.ReadInt32(gr_int8_count); 138 | byte[] res = new byte[cnt]; 139 | IntPtr actualDataPtr = Marshal.ReadIntPtr(gr_int8_data); 140 | Marshal.Copy(actualDataPtr, res, 0, cnt); 141 | return res; 142 | } 143 | 144 | public static string get_string(IntPtr pchar) 145 | { 146 | #if NETSTANDARD2_1_OR_GREATER 147 | return Marshal.PtrToStringUTF8(pchar); 148 | #else 149 | return Marshal.PtrToStringAnsi(pchar); 150 | #endif 151 | } 152 | 153 | public string[] get_string_array(StringArrayDelegate1 fn, bool extra=false, bool empty_to_none=false) 154 | { 155 | IntPtr resultPtr = new IntPtr(); 156 | int[] resultCount = new int[2]; 157 | fn(ctx, ref resultPtr, resultCount); 158 | string[] result = new string[resultCount[0] + (extra ? 1 : 0)]; 159 | for (int i = 0; i < resultCount[0]; ++i) 160 | { 161 | IntPtr resultPtrInternal = Marshal.ReadIntPtr(resultPtr, IntPtr.Size * i); 162 | result[i] = get_string(resultPtrInternal); 163 | } 164 | if (empty_to_none && (resultCount[0] == 0)) 165 | { 166 | result = new string[1]; 167 | result[0] = "NONE"; 168 | } 169 | else if (extra) 170 | { 171 | if (resultCount[0] == 0) 172 | { 173 | result[0] = "None"; 174 | } 175 | else 176 | { 177 | result[resultCount[0]] = ""; 178 | } 179 | } 180 | DSS_CAPI.DSS_Dispose_PPAnsiChar(ref resultPtr, resultCount[1]); 181 | return result; 182 | } 183 | 184 | public string[] get_string_array(StringArrayDelegate2 fn, int param1) 185 | { 186 | IntPtr resultPtr = new IntPtr(); 187 | int[] resultCount = new int[2]; 188 | fn(ctx, ref resultPtr, resultCount, param1); 189 | string[] result = new string[resultCount[0]]; 190 | for (int i = 0; i < resultCount[0]; ++i) 191 | { 192 | IntPtr resultPtrInternal = Marshal.ReadIntPtr(resultPtr, IntPtr.Size * i); 193 | result[i] = get_string(resultPtrInternal); 194 | } 195 | DSS_CAPI.DSS_Dispose_PPAnsiChar(ref resultPtr, resultCount[1]); 196 | return result; 197 | } 198 | 199 | public string[] get_string_array(StringArrayDelegate3 fn, string param1) 200 | { 201 | IntPtr resultPtr = new IntPtr(); 202 | int[] resultCount = new int[2]; 203 | fn(ctx, ref resultPtr, resultCount, param1); 204 | string[] result = new string[resultCount[0]]; 205 | for (int i = 0; i < resultCount[0]; ++i) 206 | { 207 | IntPtr resultPtrInternal = Marshal.ReadIntPtr(resultPtr, IntPtr.Size * i); 208 | result[i] = get_string(resultPtrInternal); 209 | } 210 | DSS_CAPI.DSS_Dispose_PPAnsiChar(ref resultPtr, resultCount[1]); 211 | return result; 212 | } 213 | 214 | /// 215 | /// If the exception mapping mechanism is enabled, the DSS.Error.Number code is inspected. 216 | /// If non-zero, the matching DSS.Error.Description message is read and a DSSException is 217 | /// thrown. This is called internally after most of the dss_sharp DSS C-API calls to ensure 218 | /// most engine errors are being handled as early as possible. 219 | /// 220 | /// If exceptions cannot be used, check `DSS.Error.Number` directly. 221 | /// 222 | public void CheckForError() 223 | { 224 | if (!exceptionsAllowed) return; 225 | var error_num = Marshal.ReadInt32(errorPtr); 226 | if (error_num != 0) 227 | { 228 | Marshal.WriteInt32(errorPtr, 0); 229 | throw new DSSException(error_num, get_string(DSS_CAPI.ctx_Error_Get_Description(ctx))); 230 | } 231 | } 232 | } 233 | } 234 | } 235 | --------------------------------------------------------------------------------