├── .gitignore ├── Dataverse.Sdk.Extensions ├── Coverage.bat ├── Dataverse.Sdk.Extensions.ForCoverage │ ├── Dataverse.Sdk.Extensions.ForCoverage.csproj │ ├── Properties │ │ └── AssemblyInfo.cs │ └── packages.config ├── Dataverse.Sdk.Extensions.Samples │ ├── Dataverse.Sdk.Extensions.Samples.csproj │ ├── EarlyBoundEntities │ │ └── Account.cs │ ├── EntityReferenceSamples.cs │ ├── EntitySamples.cs │ ├── OrganizationServiceSamples.cs │ ├── Properties │ │ └── AssemblyInfo.cs │ ├── SystemTypesSamples.cs │ ├── ToStringDebugSamples.cs │ └── packages.config ├── Dataverse.Sdk.Extensions.Tests │ ├── Dataverse.Sdk.Extensions.Tests.csproj │ ├── EarlyBoundEntities │ │ ├── Account.cs │ │ ├── AttributeMap.cs │ │ ├── Contact.cs │ │ ├── EntityMap.cs │ │ └── Lead.cs │ ├── EntityReferenceTests.cs │ ├── EntityTests.cs │ ├── FakeMessageExecutors │ │ └── RetrieveMetadataChangesRequestExecutor.cs │ ├── FakeXrmEasyTestsBase.cs │ ├── IOrganizationServiceTests.cs │ ├── MetadataModels │ │ ├── AccountMetadata.cs │ │ └── GlobalMetadata.cs │ ├── Properties │ │ └── AssemblyInfo.cs │ ├── SystemTypesTests.cs │ ├── ToStringDebugTests.cs │ ├── app.config │ └── packages.config ├── Dataverse.Sdk.Extensions.sln ├── Dataverse.Sdk.Extensions │ ├── Dataverse.Sdk.Extensions.projitems │ ├── Dataverse.Sdk.Extensions.shproj │ ├── EntityExtensions.cs │ ├── EntityReferenceExtensions.cs │ ├── IOrganizationServiceExtensions.cs │ ├── Readme.md │ ├── SystemTypesExtensions.cs │ └── ToStringDebugExtensions.cs └── NuGet Package │ ├── Dataverse.Sdk.Extensions.nuspec │ └── Dataverse.Sdk.Extensions.targets ├── LICENSE └── README.md /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | ## 4 | ## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore 5 | 6 | # User-specific files 7 | *.rsuser 8 | *.suo 9 | *.user 10 | *.userosscache 11 | *.sln.docstates 12 | 13 | # User-specific files (MonoDevelop/Xamarin Studio) 14 | *.userprefs 15 | 16 | # Mono auto generated files 17 | mono_crash.* 18 | 19 | # Build results 20 | [Dd]ebug/ 21 | [Dd]ebugPublic/ 22 | [Rr]elease/ 23 | [Rr]eleases/ 24 | x64/ 25 | x86/ 26 | [Aa][Rr][Mm]/ 27 | [Aa][Rr][Mm]64/ 28 | bld/ 29 | [Bb]in/ 30 | [Oo]bj/ 31 | [Ll]og/ 32 | [Ll]ogs/ 33 | 34 | # Visual Studio 2015/2017 cache/options directory 35 | .vs/ 36 | # Uncomment if you have tasks that create the project's static files in wwwroot 37 | #wwwroot/ 38 | 39 | # Visual Studio 2017 auto generated files 40 | Generated\ Files/ 41 | 42 | # MSTest test Results 43 | [Tt]est[Rr]esult*/ 44 | [Bb]uild[Ll]og.* 45 | 46 | # NUnit 47 | *.VisualState.xml 48 | TestResult.xml 49 | nunit-*.xml 50 | 51 | # Build Results of an ATL Project 52 | [Dd]ebugPS/ 53 | [Rr]eleasePS/ 54 | dlldata.c 55 | 56 | # Benchmark Results 57 | BenchmarkDotNet.Artifacts/ 58 | 59 | # .NET Core 60 | project.lock.json 61 | project.fragment.lock.json 62 | artifacts/ 63 | 64 | # StyleCop 65 | StyleCopReport.xml 66 | 67 | # Files built by Visual Studio 68 | *_i.c 69 | *_p.c 70 | *_h.h 71 | *.ilk 72 | *.meta 73 | *.obj 74 | *.iobj 75 | *.pch 76 | *.pdb 77 | *.ipdb 78 | *.pgc 79 | *.pgd 80 | *.rsp 81 | *.sbr 82 | *.tlb 83 | *.tli 84 | *.tlh 85 | *.tmp 86 | *.tmp_proj 87 | *_wpftmp.csproj 88 | *.log 89 | *.vspscc 90 | *.vssscc 91 | .builds 92 | *.pidb 93 | *.svclog 94 | *.scc 95 | 96 | # Chutzpah Test files 97 | _Chutzpah* 98 | 99 | # Visual C++ cache files 100 | ipch/ 101 | *.aps 102 | *.ncb 103 | *.opendb 104 | *.opensdf 105 | *.sdf 106 | *.cachefile 107 | *.VC.db 108 | *.VC.VC.opendb 109 | 110 | # Visual Studio profiler 111 | *.psess 112 | *.vsp 113 | *.vspx 114 | *.sap 115 | 116 | # Visual Studio Trace Files 117 | *.e2e 118 | 119 | # TFS 2012 Local Workspace 120 | $tf/ 121 | 122 | # Guidance Automation Toolkit 123 | *.gpState 124 | 125 | # ReSharper is a .NET coding add-in 126 | _ReSharper*/ 127 | *.[Rr]e[Ss]harper 128 | *.DotSettings.user 129 | 130 | # TeamCity is a build add-in 131 | _TeamCity* 132 | 133 | # DotCover is a Code Coverage Tool 134 | *.dotCover 135 | 136 | # AxoCover is a Code Coverage Tool 137 | .axoCover/* 138 | !.axoCover/settings.json 139 | 140 | # Visual Studio code coverage results 141 | *.coverage 142 | *.coveragexml 143 | 144 | # NCrunch 145 | _NCrunch_* 146 | .*crunch*.local.xml 147 | nCrunchTemp_* 148 | 149 | # MightyMoose 150 | *.mm.* 151 | AutoTest.Net/ 152 | 153 | # Web workbench (sass) 154 | .sass-cache/ 155 | 156 | # Installshield output folder 157 | [Ee]xpress/ 158 | 159 | # DocProject is a documentation generator add-in 160 | DocProject/buildhelp/ 161 | DocProject/Help/*.HxT 162 | DocProject/Help/*.HxC 163 | DocProject/Help/*.hhc 164 | DocProject/Help/*.hhk 165 | DocProject/Help/*.hhp 166 | DocProject/Help/Html2 167 | DocProject/Help/html 168 | 169 | # Click-Once directory 170 | publish/ 171 | 172 | # Publish Web Output 173 | *.[Pp]ublish.xml 174 | *.azurePubxml 175 | # Note: Comment the next line if you want to checkin your web deploy settings, 176 | # but database connection strings (with potential passwords) will be unencrypted 177 | *.pubxml 178 | *.publishproj 179 | 180 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 181 | # checkin your Azure Web App publish settings, but sensitive information contained 182 | # in these scripts will be unencrypted 183 | PublishScripts/ 184 | 185 | # NuGet Packages 186 | *.nupkg 187 | # NuGet Symbol Packages 188 | *.snupkg 189 | # The packages folder can be ignored because of Package Restore 190 | **/[Pp]ackages/* 191 | # except build/, which is used as an MSBuild target. 192 | !**/[Pp]ackages/build/ 193 | # Uncomment if necessary however generally it will be regenerated when needed 194 | #!**/[Pp]ackages/repositories.config 195 | # NuGet v3's project.json files produces more ignorable files 196 | *.nuget.props 197 | *.nuget.targets 198 | 199 | # Microsoft Azure Build Output 200 | csx/ 201 | *.build.csdef 202 | 203 | # Microsoft Azure Emulator 204 | ecf/ 205 | rcf/ 206 | 207 | # Windows Store app package directories and files 208 | AppPackages/ 209 | BundleArtifacts/ 210 | Package.StoreAssociation.xml 211 | _pkginfo.txt 212 | *.appx 213 | *.appxbundle 214 | *.appxupload 215 | 216 | # Visual Studio cache files 217 | # files ending in .cache can be ignored 218 | *.[Cc]ache 219 | # but keep track of directories ending in .cache 220 | !?*.[Cc]ache/ 221 | 222 | # Others 223 | ClientBin/ 224 | ~$* 225 | *~ 226 | *.dbmdl 227 | *.dbproj.schemaview 228 | *.jfm 229 | *.pfx 230 | *.publishsettings 231 | orleans.codegen.cs 232 | 233 | # Including strong name files can present a security risk 234 | # (https://github.com/github/gitignore/pull/2483#issue-259490424) 235 | #*.snk 236 | 237 | # Since there are multiple workflows, uncomment next line to ignore bower_components 238 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 239 | #bower_components/ 240 | 241 | # RIA/Silverlight projects 242 | Generated_Code/ 243 | 244 | # Backup & report files from converting an old project file 245 | # to a newer Visual Studio version. Backup files are not needed, 246 | # because we have git ;-) 247 | _UpgradeReport_Files/ 248 | Backup*/ 249 | UpgradeLog*.XML 250 | UpgradeLog*.htm 251 | ServiceFabricBackup/ 252 | *.rptproj.bak 253 | 254 | # SQL Server files 255 | *.mdf 256 | *.ldf 257 | *.ndf 258 | 259 | # Business Intelligence projects 260 | *.rdl.data 261 | *.bim.layout 262 | *.bim_*.settings 263 | *.rptproj.rsuser 264 | *- [Bb]ackup.rdl 265 | *- [Bb]ackup ([0-9]).rdl 266 | *- [Bb]ackup ([0-9][0-9]).rdl 267 | 268 | # Microsoft Fakes 269 | FakesAssemblies/ 270 | 271 | # GhostDoc plugin setting file 272 | *.GhostDoc.xml 273 | 274 | # Node.js Tools for Visual Studio 275 | .ntvs_analysis.dat 276 | node_modules/ 277 | 278 | # Visual Studio 6 build log 279 | *.plg 280 | 281 | # Visual Studio 6 workspace options file 282 | *.opt 283 | 284 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 285 | *.vbw 286 | 287 | # Visual Studio LightSwitch build output 288 | **/*.HTMLClient/GeneratedArtifacts 289 | **/*.DesktopClient/GeneratedArtifacts 290 | **/*.DesktopClient/ModelManifest.xml 291 | **/*.Server/GeneratedArtifacts 292 | **/*.Server/ModelManifest.xml 293 | _Pvt_Extensions 294 | 295 | # Paket dependency manager 296 | .paket/paket.exe 297 | paket-files/ 298 | 299 | # FAKE - F# Make 300 | .fake/ 301 | 302 | # CodeRush personal settings 303 | .cr/personal 304 | 305 | # Python Tools for Visual Studio (PTVS) 306 | __pycache__/ 307 | *.pyc 308 | 309 | # Cake - Uncomment if you are using it 310 | # tools/** 311 | # !tools/packages.config 312 | 313 | # Tabs Studio 314 | *.tss 315 | 316 | # Telerik's JustMock configuration file 317 | *.jmconfig 318 | 319 | # BizTalk build output 320 | *.btp.cs 321 | *.btm.cs 322 | *.odx.cs 323 | *.xsd.cs 324 | 325 | # OpenCover UI analysis results 326 | OpenCover/ 327 | 328 | # Azure Stream Analytics local run output 329 | ASALocalRun/ 330 | 331 | # MSBuild Binary and Structured Log 332 | *.binlog 333 | 334 | # NVidia Nsight GPU debugger configuration file 335 | *.nvuser 336 | 337 | # MFractors (Xamarin productivity tool) working folder 338 | .mfractor/ 339 | 340 | # Local History for Visual Studio 341 | .localhistory/ 342 | 343 | # BeatPulse healthcheck temp database 344 | healthchecksdb 345 | 346 | # Backup folder for Package Reference Convert tool in Visual Studio 2017 347 | MigrationBackup/ 348 | 349 | # Ionide (cross platform F# VS Code tools) working folder 350 | .ionide/ 351 | -------------------------------------------------------------------------------- /Dataverse.Sdk.Extensions/Coverage.bat: -------------------------------------------------------------------------------- 1 | @echo off 2 | 3 | SET OUTPUT_FORMAT=Html 4 | SET NO_SHOW=0 5 | 6 | :loop 7 | IF NOT "%1"=="" ( 8 | IF "%1"=="-format" ( 9 | SET OUTPUT_FORMAT=%2 10 | SHIFT 11 | ) 12 | IF "%1"=="-no-show" ( 13 | SET NO_SHOW=%2 14 | SHIFT 15 | ) 16 | SHIFT 17 | GOTO :loop 18 | ) 19 | 20 | SET OPEN_COVER= 21 | for /D %%D in ("packages\opencover*") do ( 22 | SET OPEN_COVER=%%~D\tools\OpenCover.Console.exe 23 | ) 24 | 25 | SET REPORT_GENERATOR= 26 | for /D %%D in ("packages\ReportGenerator*") do ( 27 | SET REPORT_GENERATOR=%%~D\tools\net47\ReportGenerator.exe 28 | ) 29 | 30 | SET XUNIT_RUNNER= 31 | for /D %%D in ("packages\xunit.runner.console*") do ( 32 | SET XUNIT_RUNNER=%%~D\tools\net46\xunit.console.exe 33 | ) 34 | 35 | IF "%OPEN_COVER%"=="" ( 36 | ECHO Could not find OpenCover. Make sure to restore NuGet packages 1>&2 37 | EXIT 1 38 | ) 39 | 40 | IF "%REPORT_GENERATOR%"=="" ( 41 | ECHO Could not find Report Generator. Make sure to restore NuGet packages 1>&2 42 | EXIT 1 43 | ) 44 | 45 | IF "%XUNIT_RUNNER%"=="" ( 46 | ECHO Could not find xunit.runner.console. Make sure to restore NuGet packages 1>&2 47 | EXIT 1 48 | ) 49 | 50 | "%OPEN_COVER%" -target:"%XUNIT_RUNNER%" -targetargs:"""Dataverse.Sdk.Extensions.Tests\bin\Debug\Dataverse.Sdk.Extensions.Tests.dll"" -noshadow" -output:"..\.coverage\Dataverse.Sdk.Extensions.Coverage.xml" -register:Path64 -filter:"+[Dataverse.Sdk.Extensions]* -[Dataverse.Sdk.Extensions.Tests]*" 51 | "%REPORT_GENERATOR%" -reports:"../.coverage/Dataverse.Sdk.Extensions.Coverage.xml" -targetdir:"..\.coverage\report" -reporttypes:"%OUTPUT_FORMAT%" 52 | 53 | IF "%NO_SHOW%"=="0" ( 54 | start ..\.coverage\report\index.htm 55 | ) -------------------------------------------------------------------------------- /Dataverse.Sdk.Extensions/Dataverse.Sdk.Extensions.ForCoverage/Dataverse.Sdk.Extensions.ForCoverage.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | Debug 6 | AnyCPU 7 | {D8E26203-DC67-4AF7-BC3C-074FB323A3B7} 8 | Library 9 | Properties 10 | Dataverse.Sdk.Extensions 11 | Dataverse.Sdk.Extensions 12 | v4.6.2 13 | 512 14 | true 15 | 16 | 17 | true 18 | full 19 | false 20 | bin\Debug\ 21 | DEBUG;TRACE 22 | prompt 23 | 4 24 | 25 | 26 | pdbonly 27 | true 28 | bin\Release\ 29 | TRACE 30 | prompt 31 | 4 32 | 33 | 34 | 35 | ..\packages\Microsoft.CrmSdk.CoreAssemblies.9.0.2.33\lib\net462\Microsoft.Crm.Sdk.Proxy.dll 36 | 37 | 38 | ..\packages\Microsoft.CrmSdk.CoreAssemblies.9.0.2.33\lib\net462\Microsoft.Xrm.Sdk.dll 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | -------------------------------------------------------------------------------- /Dataverse.Sdk.Extensions/Dataverse.Sdk.Extensions.ForCoverage/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.CompilerServices; 3 | using System.Runtime.InteropServices; 4 | 5 | // General Information about an assembly is controlled through the following 6 | // set of attributes. Change these attribute values to modify the information 7 | // associated with an assembly. 8 | [assembly: AssemblyTitle("Dataverse.Sdk.Extensions.Coverage")] 9 | [assembly: AssemblyDescription("")] 10 | [assembly: AssemblyConfiguration("")] 11 | [assembly: AssemblyCompany("")] 12 | [assembly: AssemblyProduct("Dataverse.Sdk.Extensions.Coverage")] 13 | [assembly: AssemblyCopyright("Copyright © 2021")] 14 | [assembly: AssemblyTrademark("")] 15 | [assembly: AssemblyCulture("")] 16 | 17 | // Setting ComVisible to false makes the types in this assembly not visible 18 | // to COM components. If you need to access a type in this assembly from 19 | // COM, set the ComVisible attribute to true on that type. 20 | [assembly: ComVisible(false)] 21 | 22 | // The following GUID is for the ID of the typelib if this project is exposed to COM 23 | [assembly: Guid("d8e26203-dc67-4af7-bc3c-074fb323a3b7")] 24 | 25 | // Version information for an assembly consists of the following four values: 26 | // 27 | // Major Version 28 | // Minor Version 29 | // Build Number 30 | // Revision 31 | // 32 | // You can specify all the values or you can default the Build and Revision Numbers 33 | // by using the '*' as shown below: 34 | // [assembly: AssemblyVersion("1.0.*")] 35 | [assembly: AssemblyVersion("1.0.0.0")] 36 | [assembly: AssemblyFileVersion("1.0.0.0")] 37 | -------------------------------------------------------------------------------- /Dataverse.Sdk.Extensions/Dataverse.Sdk.Extensions.ForCoverage/packages.config: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | -------------------------------------------------------------------------------- /Dataverse.Sdk.Extensions/Dataverse.Sdk.Extensions.Samples/Dataverse.Sdk.Extensions.Samples.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | Debug 6 | AnyCPU 7 | {67DFD80E-FB87-431D-A48D-D3C73CABDFA1} 8 | Library 9 | Properties 10 | Dataverse.Sdk.Extensions.Samples 11 | Dataverse.Sdk.Extensions.Samples 12 | v4.6.2 13 | 512 14 | true 15 | 16 | 17 | true 18 | full 19 | false 20 | bin\Debug\ 21 | DEBUG;TRACE 22 | prompt 23 | 4 24 | 25 | 26 | pdbonly 27 | true 28 | bin\Release\ 29 | TRACE 30 | prompt 31 | 4 32 | 33 | 34 | 35 | ..\packages\Microsoft.CrmSdk.CoreAssemblies.9.0.2.33\lib\net462\Microsoft.Crm.Sdk.Proxy.dll 36 | 37 | 38 | ..\packages\Microsoft.CrmSdk.CoreAssemblies.9.0.2.33\lib\net462\Microsoft.Xrm.Sdk.dll 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | 50 | 51 | 52 | 53 | 54 | 55 | 56 | 57 | 58 | 59 | 60 | 61 | 62 | 63 | 64 | 65 | 66 | 67 | 68 | 69 | 70 | 71 | 72 | -------------------------------------------------------------------------------- /Dataverse.Sdk.Extensions/Dataverse.Sdk.Extensions.Samples/EntityReferenceSamples.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using System.Linq; 4 | using System.Text; 5 | using System.Threading.Tasks; 6 | using Microsoft.Xrm.Sdk; 7 | 8 | namespace Dataverse.Sdk.Extensions.Samples 9 | { 10 | public class EntityReferenceSamples 11 | { 12 | public void GetNameId() 13 | { 14 | var display = ((EntityReference)null).GetNameId(); 15 | display = new EntityReference("account", Guid.NewGuid()).GetNameId(); 16 | display = new EntityReference("account", Guid.NewGuid()){ Name = "Bart Simpson"}.GetNameId(); 17 | } 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /Dataverse.Sdk.Extensions/Dataverse.Sdk.Extensions.Samples/EntitySamples.cs: -------------------------------------------------------------------------------- 1 | using Dataverse.Sdk.Extensions.Samples.EarlyBoundEntities; 2 | using Microsoft.Xrm.Sdk; 3 | using Microsoft.Xrm.Sdk.Query; 4 | using System.Linq; 5 | 6 | namespace Dataverse.Sdk.Extensions.Samples 7 | { 8 | public class EntitySamples 9 | { 10 | /// 11 | /// Sample that demonstrates how to add an activity party to an 12 | /// activity table 13 | /// 14 | /// Reference to a dataverse contact row 15 | /// Reference to a dataverse account row 16 | public void AddPartiesToActivityTable(EntityReference contactReference, EntityReference accountReference) 17 | { 18 | var email = new Entity("email"); 19 | email["subject"] = "A test email"; 20 | email.AddParties("to", contactReference, accountReference); 21 | } 22 | 23 | /// 24 | /// Sample that demonstrates how to add an activity party to an 25 | /// activity table 26 | /// 27 | /// Reference to a dataverse row 28 | public void AddPartyToActivityTable(EntityReference contactReference) 29 | { 30 | var email = new Entity("email"); 31 | email["subject"] = "A test email"; 32 | email.AddParty("to", contactReference); 33 | } 34 | 35 | /// 36 | /// Sample that demonstrates how to clone a Dataverse row 37 | /// 38 | /// 39 | /// In this sample, the account is cloned by adding " (clone)" after 40 | /// the name and excluding specifically "accountnumber" and "ownerid" 41 | /// columns 42 | /// 43 | /// Dataverse row of type Account 44 | /// Dataverse Organization service 45 | public void CloneDataverseRow(Account accountRow, IOrganizationService service) 46 | { 47 | Entity clonedRow = accountRow.Clone(service, true, "accountnumber", "ownerid"); 48 | } 49 | 50 | /// 51 | /// Sample that demonstrates how to check for multiple columns that 52 | /// have been emptied before processing 53 | /// 54 | /// 55 | /// This can be useful in code that process plugin input data to 56 | /// check faster if column(s) have been emptied 57 | /// Standard code would have been: 58 | /// if(account.Contains("address1_line1") && account.GetAttributeValue("address1_line1") == null 59 | /// && account.Contains("address1_city") && account.GetAttributeValue("address1_city") == null){ 60 | /// // Do something 61 | /// } 62 | /// 63 | /// Account row data 64 | public void ProcessOnlyIfColumnsHaveBeenEmptied(Account account) 65 | { 66 | // Process only if address1_line1 and address1_city columns 67 | // have been emptied 68 | if (account.ContainsNullValue(a => a.Address1_Line1, a => a.Address1_City)) 69 | { 70 | // Do something 71 | } 72 | } 73 | 74 | /// 75 | /// Sample that demonstrates how to check for multiple columns that 76 | /// have been set before processing 77 | /// 78 | /// 79 | /// This can be useful in code that process plugin input data to 80 | /// check faster if column(s) have been set 81 | /// Standard code would have been: 82 | /// if(account.Contains("address1_line1") && account.GetAttributeValue("address1_line1") != null 83 | /// && account.Contains("address1_city") && account.GetAttributeValue("address1_city") != null){ 84 | /// // Do something 85 | /// } 86 | /// 87 | /// Account row data 88 | public void ProcessOnlyIfColumnsHaveBeenSet(Account account) 89 | { 90 | // Process only if address1_line1 and address1_city columns 91 | // have been set with values different from null 92 | if (account.ContainsValue(a => a.Address1_Line1, a => a.Address1_City)) 93 | { 94 | // Do something 95 | } 96 | } 97 | 98 | /// 99 | /// Sample that demonstrates how to read the value of a linked entity 100 | /// column in a more concise way than the standard way 101 | /// 102 | /// Dataverse Organization service 103 | public void ReadAliasedValueFromEntity(IOrganizationService service) 104 | { 105 | var query = new QueryExpression("account") 106 | { 107 | TopCount = 1, 108 | ColumnSet = new ColumnSet("name"), 109 | LinkEntities = 110 | { 111 | new LinkEntity 112 | { 113 | LinkFromEntityName = "account", 114 | LinkFromAttributeName = "primarycontactid", 115 | LinkToAttributeName = "contactid", 116 | LinkToEntityName = "contact", 117 | EntityAlias = "primarycontact", 118 | Columns = new ColumnSet("fullname") 119 | } 120 | } 121 | }; 122 | 123 | EntityCollection ec = service.RetrieveMultiple(query); 124 | Entity record = ec.Entities.FirstOrDefault(); 125 | 126 | if (record != null) 127 | { 128 | // The standard way 129 | string contactFullname = record.GetAttributeValue("primarycontact.fullname")?.Value?.ToString(); 130 | 131 | // With the extension 132 | contactFullname = record.GetAliasedValue("primarycontact", "fullname"); 133 | } 134 | } 135 | } 136 | } -------------------------------------------------------------------------------- /Dataverse.Sdk.Extensions/Dataverse.Sdk.Extensions.Samples/OrganizationServiceSamples.cs: -------------------------------------------------------------------------------- 1 | using Dataverse.Sdk.Extensions.Samples.EarlyBoundEntities; 2 | using Microsoft.Crm.Sdk.Messages; 3 | using Microsoft.Xrm.Sdk; 4 | using Microsoft.Xrm.Sdk.Query; 5 | using System; 6 | using System.Linq; 7 | using System.Collections.Generic; 8 | 9 | namespace Dataverse.Sdk.Extensions.Samples 10 | { 11 | public class OrganizationServiceSamples 12 | { 13 | /// 14 | /// This sample demonstrates how to create a related row using system 15 | /// mapping 16 | /// 17 | /// 18 | /// Using system mapping avoids to map columns directly in code. 19 | /// This way, one can change the mapping by using only Dataverse 20 | /// customization 21 | /// 22 | /// Reference to the parent account 23 | /// Dataverse Organization service 24 | public void CreateChildAccountUsingSystemMappingAndInitializeFromMessage(EntityReference parentAccountRef, IOrganizationService service) 25 | { 26 | // Sets additional columns to add in the generated row 27 | var additionalColumns = new Dictionary{ 28 | { "new_issubsidiary", true }, 29 | { "new_needsvalidation", true} 30 | }; 31 | 32 | Account childAccount = service.CreateFromInitialization(parentAccountRef, TargetFieldType.All, additionalColumns); 33 | } 34 | 35 | /// 36 | /// This sample demonstrates how to delete a row using its alternate key 37 | /// 38 | /// 39 | /// This sample deletes an account that has an alternate key made of 40 | /// column "accountnumber". The account number of the account to delete 41 | /// is ABCDEFGH 42 | /// 43 | /// Dataverse Organization service 44 | public void DeleteFromAlternateKey(IOrganizationService service) 45 | { 46 | service.Delete("accountnumber", "ABCDEFGH"); 47 | 48 | // or 49 | 50 | service.Delete("account", "accountnumber", "ABCDEFGH"); 51 | } 52 | 53 | /// 54 | /// This sample demonstrates how to delete a row using its alternate key 55 | /// 56 | /// 57 | /// This sample deletes an account that has an alternate key made of 58 | /// column "accountnumber" and "address1_country". The account number 59 | /// of the account to delete is ABCDEFGH and the country is France 60 | /// 61 | /// Dataverse Organization service 62 | public void DeleteFromAlternateKeyCollection(IOrganizationService service) 63 | { 64 | service.Delete(new KeyAttributeCollection 65 | { 66 | {"accountnumber","ABCDEFGH" }, 67 | {"address1_country","France" } 68 | } 69 | ); 70 | 71 | // or 72 | 73 | service.Delete("account", new KeyAttributeCollection 74 | { 75 | {"accountnumber","ABCDEFGH" }, 76 | {"address1_country","France" } 77 | } 78 | ); 79 | } 80 | 81 | /// 82 | /// This sample demonstrates how to delete a row 83 | /// 84 | /// 85 | /// The standard way requires to provide EntityLogicalName and Id. This 86 | /// samples allows to use the Entity object directly 87 | /// 88 | /// Row to delete 89 | /// Dataverse Organization service 90 | public void DeleteFromEntity(Entity row, IOrganizationService service) 91 | { 92 | service.Delete(row); 93 | } 94 | 95 | /// 96 | /// This sample demonstrates how to delete a row using its reference 97 | /// 98 | /// 99 | /// The standard way requires to provide EntityLogicalName and Id. This 100 | /// samples allows to use the EntityReference directly 101 | /// 102 | /// Reference to the row to delete 103 | /// Dataverse Organization service 104 | public void DeleteFromEntityReference(EntityReference reference, IOrganizationService service) 105 | { 106 | service.Delete(reference); 107 | } 108 | 109 | /// 110 | /// This sample demonstrates how to retrieve current user roles in one 111 | /// line of code 112 | /// 113 | /// Dataverse Organization service 114 | public void RetrieveCurrentUserRoles(IOrganizationService service) 115 | { 116 | List roles = service.GetCurrentUserRoles(); 117 | } 118 | 119 | /// 120 | /// This sample demonstrates how to retrieve multiple Environment 121 | /// variables in one line 122 | /// 123 | /// Dataverse Organization service 124 | /// Schema names of the of Environment variables to retrieve 125 | public void RetrieveMultipleEnvironmentVariables(IOrganizationService service, params string[] variablesSchemaNames) 126 | { 127 | Dictionary environmentVariables = service.GetEnvironmentVariables(variablesSchemaNames); 128 | 129 | foreach (var key in environmentVariables.Keys) 130 | { 131 | Console.WriteLine($"{key} : {environmentVariables[key]}"); 132 | } 133 | } 134 | 135 | /// 136 | /// This sample demonstrates how to retrieve on Environment 137 | /// variable in one line 138 | /// 139 | /// Dataverse Organization service 140 | /// Schema name of the Environment variable to retrieve 141 | public void RetrieveOneEnvironmentVariable(IOrganizationService service, string variableSchemaName) 142 | { 143 | string environmentVariableValue = service.GetEnvironmentVariable(variableSchemaName); 144 | } 145 | 146 | /// 147 | /// This sample demonstrates how to retrieve an account row typed as an Account object 148 | /// 149 | /// Dataverse Organization service 150 | /// The primary key of an account to retrieve 151 | public void RetrieveTyped(IOrganizationService service, Guid accountId) 152 | { 153 | Account row = service.Retrieve(accountId, new ColumnSet(Account.Fields.Name)); 154 | } 155 | 156 | /// 157 | /// This sample demonstrates how to retrieve multiple accounts with the results typed as an Account object 158 | /// 159 | /// Dataverse Organization service 160 | public void RetrieveMultipleTyped(IOrganizationService service) 161 | { 162 | QueryExpression qe = new QueryExpression(Account.EntityLogicalName) 163 | { 164 | TopCount = 10, 165 | ColumnSet = new ColumnSet(Account.Fields.Name) 166 | }; 167 | 168 | List rows = service.RetrieveMultiple(qe); 169 | } 170 | 171 | /// 172 | /// This sample demonstrates how to retrieve all accounts using a Query Expression 173 | /// 174 | /// Dataverse Organization service 175 | public void RetrieveAll_QueryExpression(IOrganizationService service) 176 | { 177 | QueryExpression queryExpression = new QueryExpression(Account.EntityLogicalName) 178 | { 179 | ColumnSet = new ColumnSet(Account.Fields.Name) 180 | }; 181 | 182 | IEnumerable enumerableResults = service.RetrieveAll(queryExpression); 183 | var genericResultsAsList = enumerableResults.ToList(); 184 | } 185 | 186 | /// 187 | /// This sample demonstrates how to retrieve all accounts using a Query Expression, with the results typed as an Account object 188 | /// 189 | /// Dataverse Organization service 190 | public void RetrieveAllTyped_QueryExpression(IOrganizationService service) 191 | { 192 | QueryExpression queryExpression = new QueryExpression(Account.EntityLogicalName) 193 | { 194 | ColumnSet = new ColumnSet(Account.Fields.Name) 195 | }; 196 | 197 | IEnumerable enumerableResults = service.RetrieveAll(queryExpression); 198 | var resultsAsList = enumerableResults.ToList(); 199 | } 200 | 201 | /// 202 | /// This sample demonstrates how to retrieve all accounts using a Query By Attribute 203 | /// 204 | /// Dataverse Organization service 205 | public void RetrieveAll_QueryByAttribute(IOrganizationService service) 206 | { 207 | QueryByAttribute queryByAttribute = new QueryByAttribute(Account.EntityLogicalName); 208 | queryByAttribute.AddAttributeValue(Account.Fields.Name, "Account Name"); 209 | queryByAttribute.ColumnSet = new ColumnSet(Account.Fields.Name); 210 | 211 | IEnumerable enumerableResults = service.RetrieveAll(queryByAttribute); 212 | var resultsAsList = enumerableResults.ToList(); 213 | } 214 | 215 | /// 216 | /// This sample demonstrates how to retrieve all accounts using a Query By Attribute, with the results typed as an Account object 217 | /// 218 | /// Dataverse Organization service 219 | public void RetrieveAllTyped_QueryByAttribute(IOrganizationService service) 220 | { 221 | QueryByAttribute queryByAttribute = new QueryByAttribute(Account.EntityLogicalName); 222 | queryByAttribute.AddAttributeValue(Account.Fields.Name, "Account Name"); 223 | queryByAttribute.ColumnSet = new ColumnSet(Account.Fields.Name); 224 | 225 | IEnumerable enumerableResults = service.RetrieveAll(queryByAttribute); 226 | var resultsAsList = enumerableResults.ToList(); 227 | } 228 | 229 | /// 230 | /// This sample demonstrates how to retrieve all accounts using a Fetch Expression 231 | /// 232 | /// Dataverse Organization service 233 | public void RetrieveAll_FetchExpression(IOrganizationService service) 234 | { 235 | var fetchXml = $@" 236 | 237 | 238 | 239 | 240 | "; 241 | FetchExpression fe = new FetchExpression(fetchXml); 242 | 243 | IEnumerable enumerableResults = service.RetrieveAll(fe); 244 | var resultsAsList = enumerableResults.ToList(); 245 | } 246 | 247 | /// 248 | /// This sample demonstrates how to retrieve all accounts using a Fetch Expression, with the results typed as an Account object 249 | /// 250 | /// Dataverse Organization service 251 | public void RetrieveAllTyped_FetchExpression(IOrganizationService service) 252 | { 253 | var fetchXml = $@" 254 | 255 | 256 | 257 | 258 | "; 259 | FetchExpression fetchExpression = new FetchExpression(fetchXml); 260 | 261 | IEnumerable enumerableResults = service.RetrieveAll(fetchExpression); 262 | var resultsAsList = enumerableResults.ToList(); 263 | } 264 | } 265 | } -------------------------------------------------------------------------------- /Dataverse.Sdk.Extensions/Dataverse.Sdk.Extensions.Samples/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.CompilerServices; 3 | using System.Runtime.InteropServices; 4 | 5 | // Les informations générales relatives à un assembly dépendent de 6 | // l'ensemble d'attributs suivant. Changez les valeurs de ces attributs pour modifier les informations 7 | // associées à un assembly. 8 | [assembly: AssemblyTitle("Dataverse.Sdk.Extensions.Samples")] 9 | [assembly: AssemblyDescription("")] 10 | [assembly: AssemblyConfiguration("")] 11 | [assembly: AssemblyCompany("")] 12 | [assembly: AssemblyProduct("Dataverse.Sdk.Extensions.Samples")] 13 | [assembly: AssemblyCopyright("Copyright © 2021")] 14 | [assembly: AssemblyTrademark("")] 15 | [assembly: AssemblyCulture("")] 16 | 17 | // L'affectation de la valeur false à ComVisible rend les types invisibles dans cet assembly 18 | // aux composants COM. Si vous devez accéder à un type dans cet assembly à partir de 19 | // COM, affectez la valeur true à l'attribut ComVisible sur ce type. 20 | [assembly: ComVisible(false)] 21 | 22 | // Le GUID suivant est pour l'ID de la typelib si ce projet est exposé à COM 23 | [assembly: Guid("67dfd80e-fb87-431d-a48d-d3c73cabdfa1")] 24 | 25 | // Les informations de version pour un assembly se composent des quatre valeurs suivantes : 26 | // 27 | // Version principale 28 | // Version secondaire 29 | // Numéro de build 30 | // Révision 31 | // 32 | // Vous pouvez spécifier toutes les valeurs ou indiquer les numéros de build et de révision par défaut 33 | // en utilisant '*', comme indiqué ci-dessous : 34 | // [assembly: AssemblyVersion("1.0.*")] 35 | [assembly: AssemblyVersion("1.0.0.0")] 36 | [assembly: AssemblyFileVersion("1.0.0.0")] 37 | -------------------------------------------------------------------------------- /Dataverse.Sdk.Extensions/Dataverse.Sdk.Extensions.Samples/SystemTypesSamples.cs: -------------------------------------------------------------------------------- 1 | using Dataverse.Sdk.Extensions.Samples.EarlyBoundEntities; 2 | using Microsoft.Xrm.Sdk; 3 | using System; 4 | 5 | namespace Dataverse.Sdk.Extensions.Samples 6 | { 7 | public class SystemTypesSamples 8 | { 9 | public void ConvertGuidToEntityReference(Guid id) 10 | { 11 | EntityReference er = id.ToEntityReference("account"); 12 | } 13 | 14 | public void ConvertGuidToEntityReferenceWithGeneric(Guid id) 15 | { 16 | EntityReference er = id.ToEntityReference(); 17 | } 18 | } 19 | } -------------------------------------------------------------------------------- /Dataverse.Sdk.Extensions/Dataverse.Sdk.Extensions.Samples/ToStringDebugSamples.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.Xrm.Sdk; 2 | using Microsoft.Xrm.Sdk.Query; 3 | 4 | namespace Dataverse.Sdk.Extensions.Samples 5 | { 6 | public class ToStringDebugSamples 7 | { 8 | public void ToStringDebugEntity() 9 | { 10 | var display = new Entity().ToStringDebug(); 11 | } 12 | 13 | public void ToStringDebugEntityCollection(IOrganizationService service, QueryExpression qe) 14 | { 15 | var display = service.RetrieveMultiple(qe).ToStringDebug(); 16 | } 17 | 18 | public void ToStringDebugContext(IPluginExecutionContext context) 19 | { 20 | var display = context.ToStringDebug(); 21 | } 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /Dataverse.Sdk.Extensions/Dataverse.Sdk.Extensions.Samples/packages.config: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | -------------------------------------------------------------------------------- /Dataverse.Sdk.Extensions/Dataverse.Sdk.Extensions.Tests/Dataverse.Sdk.Extensions.Tests.csproj: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | Debug 10 | AnyCPU 11 | {6B5D2F34-E85C-4CBB-AF53-4E2C12A7D1B9} 12 | Library 13 | Properties 14 | Dataverse.Sdk.Extensions.Tests 15 | Dataverse.Sdk.Extensions.Tests 16 | v4.6.2 17 | 512 18 | true 19 | 20 | 21 | 22 | 23 | true 24 | full 25 | false 26 | bin\Debug\ 27 | DEBUG;TRACE 28 | prompt 29 | 4 30 | 31 | 32 | pdbonly 33 | true 34 | bin\Release\ 35 | TRACE 36 | prompt 37 | 4 38 | 39 | 40 | 41 | ..\packages\Castle.Core.4.4.1\lib\net45\Castle.Core.dll 42 | 43 | 44 | ..\packages\FakeItEasy.6.2.1\lib\net45\FakeItEasy.dll 45 | 46 | 47 | ..\packages\FakeXrmEasy.9.1.57.1\lib\net462\FakeXrmEasy.dll 48 | 49 | 50 | ..\packages\Microsoft.CrmSdk.CoreAssemblies.9.0.2.33\lib\net462\Microsoft.Crm.Sdk.Proxy.dll 51 | 52 | 53 | ..\packages\Microsoft.IdentityModel.Clients.ActiveDirectory.5.2.9\lib\net45\Microsoft.IdentityModel.Clients.ActiveDirectory.dll 54 | 55 | 56 | ..\packages\Microsoft.CrmSdk.XrmTooling.CoreAssembly.9.1.0.79\lib\net462\Microsoft.Rest.ClientRuntime.dll 57 | 58 | 59 | ..\packages\Microsoft.CrmSdk.CoreAssemblies.9.0.2.33\lib\net462\Microsoft.Xrm.Sdk.dll 60 | 61 | 62 | ..\packages\Microsoft.CrmSdk.Deployment.9.0.2.33\lib\net462\Microsoft.Xrm.Sdk.Deployment.dll 63 | 64 | 65 | ..\packages\Microsoft.CrmSdk.Workflow.9.0.2.33\lib\net462\Microsoft.Xrm.Sdk.Workflow.dll 66 | 67 | 68 | ..\packages\Microsoft.CrmSdk.XrmTooling.CoreAssembly.9.1.0.79\lib\net462\Microsoft.Xrm.Tooling.Connector.dll 69 | 70 | 71 | ..\packages\Newtonsoft.Json.13.0.1\lib\net45\Newtonsoft.Json.dll 72 | 73 | 74 | 75 | 76 | 77 | 78 | 79 | 80 | 81 | 82 | 83 | 84 | 85 | ..\packages\System.Net.Http.4.3.4\lib\net46\System.Net.Http.dll 86 | 87 | 88 | 89 | 90 | 91 | 92 | ..\packages\System.Security.Cryptography.Algorithms.4.3.0\lib\net461\System.Security.Cryptography.Algorithms.dll 93 | 94 | 95 | ..\packages\System.Security.Cryptography.Encoding.4.3.0\lib\net46\System.Security.Cryptography.Encoding.dll 96 | 97 | 98 | ..\packages\System.Security.Cryptography.Primitives.4.3.0\lib\net46\System.Security.Cryptography.Primitives.dll 99 | 100 | 101 | ..\packages\System.Security.Cryptography.X509Certificates.4.3.0\lib\net461\System.Security.Cryptography.X509Certificates.dll 102 | 103 | 104 | 105 | 106 | 107 | 108 | 109 | 110 | 111 | 112 | 113 | 114 | 115 | 116 | 117 | ..\packages\xunit.abstractions.2.0.3\lib\net35\xunit.abstractions.dll 118 | 119 | 120 | ..\packages\xunit.assert.2.4.1\lib\netstandard1.1\xunit.assert.dll 121 | 122 | 123 | ..\packages\xunit.extensibility.core.2.4.1\lib\net452\xunit.core.dll 124 | 125 | 126 | ..\packages\xunit.extensibility.execution.2.4.1\lib\net452\xunit.execution.desktop.dll 127 | 128 | 129 | 130 | 131 | 132 | 133 | 134 | 135 | 136 | 137 | 138 | 139 | 140 | 141 | 142 | 143 | 144 | 145 | 146 | 147 | 148 | 149 | 150 | 151 | 152 | 153 | 154 | 155 | {d8e26203-dc67-4af7-bc3c-074fb323a3b7} 156 | Dataverse.Sdk.Extensions.ForCoverage 157 | 158 | 159 | 160 | 161 | 162 | 163 | This project references NuGet package(s) that are missing on this computer. Use NuGet Package Restore to download them. For more information, see http://go.microsoft.com/fwlink/?LinkID=322105. The missing file is {0}. 164 | 165 | 166 | 167 | 168 | 169 | 170 | 171 | 172 | -------------------------------------------------------------------------------- /Dataverse.Sdk.Extensions/Dataverse.Sdk.Extensions.Tests/EarlyBoundEntities/AttributeMap.cs: -------------------------------------------------------------------------------- 1 | //------------------------------------------------------------------------------ 2 | // 3 | // This code was generated by a tool. 4 | // Runtime Version:4.0.30319.42000 5 | // 6 | // Changes to this file may cause incorrect behavior and will be lost if 7 | // the code is regenerated. 8 | // 9 | //------------------------------------------------------------------------------ 10 | 11 | namespace Dataverse.Sdk.Extensions.Tests.EarlyBoundEntities 12 | { 13 | 14 | 15 | [System.Runtime.Serialization.DataContractAttribute()] 16 | [Microsoft.Xrm.Sdk.Client.EntityLogicalNameAttribute("attributemap")] 17 | [System.CodeDom.Compiler.GeneratedCodeAttribute("CrmSvcUtil", "9.1.0.80")] 18 | public partial class AttributeMap : Microsoft.Xrm.Sdk.Entity, System.ComponentModel.INotifyPropertyChanging, System.ComponentModel.INotifyPropertyChanged 19 | { 20 | 21 | public AttributeMap() : 22 | base(EntityLogicalName) 23 | { 24 | } 25 | 26 | public const string EntityLogicalName = "attributemap"; 27 | 28 | public const string EntityLogicalCollectionName = "attributemaps"; 29 | 30 | public const string EntitySetName = "attributemaps"; 31 | 32 | public const int EntityTypeCode = 4601; 33 | 34 | public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged; 35 | 36 | public event System.ComponentModel.PropertyChangingEventHandler PropertyChanging; 37 | 38 | private void OnPropertyChanged(string propertyName) 39 | { 40 | if ((this.PropertyChanged != null)) 41 | { 42 | this.PropertyChanged(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName)); 43 | } 44 | } 45 | 46 | private void OnPropertyChanging(string propertyName) 47 | { 48 | if ((this.PropertyChanging != null)) 49 | { 50 | this.PropertyChanging(this, new System.ComponentModel.PropertyChangingEventArgs(propertyName)); 51 | } 52 | } 53 | 54 | [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("attributemapid")] 55 | public System.Nullable AttributeMapId 56 | { 57 | get 58 | { 59 | return this.GetAttributeValue>("attributemapid"); 60 | } 61 | set 62 | { 63 | this.OnPropertyChanging("AttributeMapId"); 64 | this.SetAttributeValue("attributemapid", value); 65 | if (value.HasValue) 66 | { 67 | base.Id = value.Value; 68 | } 69 | else 70 | { 71 | base.Id = System.Guid.Empty; 72 | } 73 | this.OnPropertyChanged("AttributeMapId"); 74 | } 75 | } 76 | 77 | [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("attributemapid")] 78 | public override System.Guid Id 79 | { 80 | get 81 | { 82 | return base.Id; 83 | } 84 | set 85 | { 86 | this.AttributeMapId = value; 87 | } 88 | } 89 | 90 | [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("attributemapidunique")] 91 | public System.Nullable AttributeMapIdUnique 92 | { 93 | get 94 | { 95 | return this.GetAttributeValue>("attributemapidunique"); 96 | } 97 | } 98 | 99 | [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("componentstate")] 100 | public Microsoft.Xrm.Sdk.OptionSetValue ComponentState 101 | { 102 | get 103 | { 104 | return this.GetAttributeValue("componentstate"); 105 | } 106 | } 107 | 108 | [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("createdby")] 109 | public Microsoft.Xrm.Sdk.EntityReference CreatedBy 110 | { 111 | get 112 | { 113 | return this.GetAttributeValue("createdby"); 114 | } 115 | } 116 | 117 | [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("createdon")] 118 | public System.Nullable CreatedOn 119 | { 120 | get 121 | { 122 | return this.GetAttributeValue>("createdon"); 123 | } 124 | } 125 | 126 | [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("createdonbehalfby")] 127 | public Microsoft.Xrm.Sdk.EntityReference CreatedOnBehalfBy 128 | { 129 | get 130 | { 131 | return this.GetAttributeValue("createdonbehalfby"); 132 | } 133 | } 134 | 135 | [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("entitymapid")] 136 | public Microsoft.Xrm.Sdk.EntityReference EntityMapId 137 | { 138 | get 139 | { 140 | return this.GetAttributeValue("entitymapid"); 141 | } 142 | set 143 | { 144 | this.OnPropertyChanging("EntityMapId"); 145 | this.SetAttributeValue("entitymapid", value); 146 | this.OnPropertyChanged("EntityMapId"); 147 | } 148 | } 149 | 150 | [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("ismanaged")] 151 | public System.Nullable IsManaged 152 | { 153 | get 154 | { 155 | return this.GetAttributeValue>("ismanaged"); 156 | } 157 | } 158 | 159 | [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("issystem")] 160 | public System.Nullable IsSystem 161 | { 162 | get 163 | { 164 | return this.GetAttributeValue>("issystem"); 165 | } 166 | set 167 | { 168 | this.OnPropertyChanging("IsSystem"); 169 | this.SetAttributeValue("issystem", value); 170 | this.OnPropertyChanged("IsSystem"); 171 | } 172 | } 173 | 174 | [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("modifiedby")] 175 | public Microsoft.Xrm.Sdk.EntityReference ModifiedBy 176 | { 177 | get 178 | { 179 | return this.GetAttributeValue("modifiedby"); 180 | } 181 | } 182 | 183 | [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("modifiedon")] 184 | public System.Nullable ModifiedOn 185 | { 186 | get 187 | { 188 | return this.GetAttributeValue>("modifiedon"); 189 | } 190 | } 191 | 192 | [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("modifiedonbehalfby")] 193 | public Microsoft.Xrm.Sdk.EntityReference ModifiedOnBehalfBy 194 | { 195 | get 196 | { 197 | return this.GetAttributeValue("modifiedonbehalfby"); 198 | } 199 | } 200 | 201 | [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("organizationid")] 202 | public Microsoft.Xrm.Sdk.EntityReference OrganizationId 203 | { 204 | get 205 | { 206 | return this.GetAttributeValue("organizationid"); 207 | } 208 | } 209 | 210 | [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("overwritetime")] 211 | public System.Nullable OverwriteTime 212 | { 213 | get 214 | { 215 | return this.GetAttributeValue>("overwritetime"); 216 | } 217 | } 218 | 219 | [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("parentattributemapid")] 220 | public Microsoft.Xrm.Sdk.EntityReference ParentAttributeMapId 221 | { 222 | get 223 | { 224 | return this.GetAttributeValue("parentattributemapid"); 225 | } 226 | set 227 | { 228 | this.OnPropertyChanging("ParentAttributeMapId"); 229 | this.SetAttributeValue("parentattributemapid", value); 230 | this.OnPropertyChanged("ParentAttributeMapId"); 231 | } 232 | } 233 | 234 | [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("solutionid")] 235 | public System.Nullable SolutionId 236 | { 237 | get 238 | { 239 | return this.GetAttributeValue>("solutionid"); 240 | } 241 | } 242 | 243 | [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("sourceattributename")] 244 | public string SourceAttributeName 245 | { 246 | get 247 | { 248 | return this.GetAttributeValue("sourceattributename"); 249 | } 250 | set 251 | { 252 | this.OnPropertyChanging("SourceAttributeName"); 253 | this.SetAttributeValue("sourceattributename", value); 254 | this.OnPropertyChanged("SourceAttributeName"); 255 | } 256 | } 257 | 258 | [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("targetattributename")] 259 | public string TargetAttributeName 260 | { 261 | get 262 | { 263 | return this.GetAttributeValue("targetattributename"); 264 | } 265 | set 266 | { 267 | this.OnPropertyChanging("TargetAttributeName"); 268 | this.SetAttributeValue("targetattributename", value); 269 | this.OnPropertyChanged("TargetAttributeName"); 270 | } 271 | } 272 | 273 | [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("versionnumber")] 274 | public System.Nullable VersionNumber 275 | { 276 | get 277 | { 278 | return this.GetAttributeValue>("versionnumber"); 279 | } 280 | } 281 | 282 | public sealed class Fields 283 | { 284 | 285 | public const string AttributeMapId = "attributemapid"; 286 | 287 | public const string Id = "attributemapid"; 288 | 289 | public const string AttributeMapIdUnique = "attributemapidunique"; 290 | 291 | public const string ComponentState = "componentstate"; 292 | 293 | public const string CreatedBy = "createdby"; 294 | 295 | public const string CreatedOn = "createdon"; 296 | 297 | public const string CreatedOnBehalfBy = "createdonbehalfby"; 298 | 299 | public const string EntityMapId = "entitymapid"; 300 | 301 | public const string IsManaged = "ismanaged"; 302 | 303 | public const string IsSystem = "issystem"; 304 | 305 | public const string ModifiedBy = "modifiedby"; 306 | 307 | public const string ModifiedOn = "modifiedon"; 308 | 309 | public const string ModifiedOnBehalfBy = "modifiedonbehalfby"; 310 | 311 | public const string OrganizationId = "organizationid"; 312 | 313 | public const string OverwriteTime = "overwritetime"; 314 | 315 | public const string ParentAttributeMapId = "parentattributemapid"; 316 | 317 | public const string SolutionId = "solutionid"; 318 | 319 | public const string SourceAttributeName = "sourceattributename"; 320 | 321 | public const string TargetAttributeName = "targetattributename"; 322 | 323 | public const string VersionNumber = "versionnumber"; 324 | } 325 | } 326 | } 327 | -------------------------------------------------------------------------------- /Dataverse.Sdk.Extensions/Dataverse.Sdk.Extensions.Tests/EarlyBoundEntities/EntityMap.cs: -------------------------------------------------------------------------------- 1 | //------------------------------------------------------------------------------ 2 | // 3 | // This code was generated by a tool. 4 | // Runtime Version:4.0.30319.42000 5 | // 6 | // Changes to this file may cause incorrect behavior and will be lost if 7 | // the code is regenerated. 8 | // 9 | //------------------------------------------------------------------------------ 10 | 11 | namespace Dataverse.Sdk.Extensions.Tests.EarlyBoundEntities 12 | { 13 | 14 | 15 | [System.Runtime.Serialization.DataContractAttribute()] 16 | [Microsoft.Xrm.Sdk.Client.EntityLogicalNameAttribute("entitymap")] 17 | [System.CodeDom.Compiler.GeneratedCodeAttribute("CrmSvcUtil", "9.1.0.80")] 18 | public partial class EntityMap : Microsoft.Xrm.Sdk.Entity, System.ComponentModel.INotifyPropertyChanging, System.ComponentModel.INotifyPropertyChanged 19 | { 20 | 21 | public EntityMap() : 22 | base(EntityLogicalName) 23 | { 24 | } 25 | 26 | public const string EntityLogicalName = "entitymap"; 27 | 28 | public const string EntityLogicalCollectionName = "entitymaps"; 29 | 30 | public const string EntitySetName = "entitymaps"; 31 | 32 | public const int EntityTypeCode = 4600; 33 | 34 | public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged; 35 | 36 | public event System.ComponentModel.PropertyChangingEventHandler PropertyChanging; 37 | 38 | private void OnPropertyChanged(string propertyName) 39 | { 40 | if ((this.PropertyChanged != null)) 41 | { 42 | this.PropertyChanged(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName)); 43 | } 44 | } 45 | 46 | private void OnPropertyChanging(string propertyName) 47 | { 48 | if ((this.PropertyChanging != null)) 49 | { 50 | this.PropertyChanging(this, new System.ComponentModel.PropertyChangingEventArgs(propertyName)); 51 | } 52 | } 53 | 54 | [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("componentstate")] 55 | public Microsoft.Xrm.Sdk.OptionSetValue ComponentState 56 | { 57 | get 58 | { 59 | return this.GetAttributeValue("componentstate"); 60 | } 61 | } 62 | 63 | [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("createdby")] 64 | public Microsoft.Xrm.Sdk.EntityReference CreatedBy 65 | { 66 | get 67 | { 68 | return this.GetAttributeValue("createdby"); 69 | } 70 | } 71 | 72 | [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("createdon")] 73 | public System.Nullable CreatedOn 74 | { 75 | get 76 | { 77 | return this.GetAttributeValue>("createdon"); 78 | } 79 | } 80 | 81 | [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("createdonbehalfby")] 82 | public Microsoft.Xrm.Sdk.EntityReference CreatedOnBehalfBy 83 | { 84 | get 85 | { 86 | return this.GetAttributeValue("createdonbehalfby"); 87 | } 88 | } 89 | 90 | [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("entitymapid")] 91 | public System.Nullable EntityMapId 92 | { 93 | get 94 | { 95 | return this.GetAttributeValue>("entitymapid"); 96 | } 97 | set 98 | { 99 | this.OnPropertyChanging("EntityMapId"); 100 | this.SetAttributeValue("entitymapid", value); 101 | if (value.HasValue) 102 | { 103 | base.Id = value.Value; 104 | } 105 | else 106 | { 107 | base.Id = System.Guid.Empty; 108 | } 109 | this.OnPropertyChanged("EntityMapId"); 110 | } 111 | } 112 | 113 | [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("entitymapid")] 114 | public override System.Guid Id 115 | { 116 | get 117 | { 118 | return base.Id; 119 | } 120 | set 121 | { 122 | this.EntityMapId = value; 123 | } 124 | } 125 | 126 | [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("entitymapidunique")] 127 | public System.Nullable EntityMapIdUnique 128 | { 129 | get 130 | { 131 | return this.GetAttributeValue>("entitymapidunique"); 132 | } 133 | } 134 | 135 | [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("ismanaged")] 136 | public System.Nullable IsManaged 137 | { 138 | get 139 | { 140 | return this.GetAttributeValue>("ismanaged"); 141 | } 142 | } 143 | 144 | [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("modifiedby")] 145 | public Microsoft.Xrm.Sdk.EntityReference ModifiedBy 146 | { 147 | get 148 | { 149 | return this.GetAttributeValue("modifiedby"); 150 | } 151 | } 152 | 153 | [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("modifiedon")] 154 | public System.Nullable ModifiedOn 155 | { 156 | get 157 | { 158 | return this.GetAttributeValue>("modifiedon"); 159 | } 160 | } 161 | 162 | [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("modifiedonbehalfby")] 163 | public Microsoft.Xrm.Sdk.EntityReference ModifiedOnBehalfBy 164 | { 165 | get 166 | { 167 | return this.GetAttributeValue("modifiedonbehalfby"); 168 | } 169 | } 170 | 171 | [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("organizationid")] 172 | public Microsoft.Xrm.Sdk.EntityReference OrganizationId 173 | { 174 | get 175 | { 176 | return this.GetAttributeValue("organizationid"); 177 | } 178 | } 179 | 180 | [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("overwritetime")] 181 | public System.Nullable OverwriteTime 182 | { 183 | get 184 | { 185 | return this.GetAttributeValue>("overwritetime"); 186 | } 187 | } 188 | 189 | [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("solutionid")] 190 | public System.Nullable SolutionId 191 | { 192 | get 193 | { 194 | return this.GetAttributeValue>("solutionid"); 195 | } 196 | } 197 | 198 | [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("sourceentityname")] 199 | public string SourceEntityName 200 | { 201 | get 202 | { 203 | return this.GetAttributeValue("sourceentityname"); 204 | } 205 | set 206 | { 207 | this.OnPropertyChanging("SourceEntityName"); 208 | this.SetAttributeValue("sourceentityname", value); 209 | this.OnPropertyChanged("SourceEntityName"); 210 | } 211 | } 212 | 213 | [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("targetentityname")] 214 | public string TargetEntityName 215 | { 216 | get 217 | { 218 | return this.GetAttributeValue("targetentityname"); 219 | } 220 | set 221 | { 222 | this.OnPropertyChanging("TargetEntityName"); 223 | this.SetAttributeValue("targetentityname", value); 224 | this.OnPropertyChanged("TargetEntityName"); 225 | } 226 | } 227 | 228 | [Microsoft.Xrm.Sdk.AttributeLogicalNameAttribute("versionnumber")] 229 | public System.Nullable VersionNumber 230 | { 231 | get 232 | { 233 | return this.GetAttributeValue>("versionnumber"); 234 | } 235 | } 236 | 237 | public sealed class Fields 238 | { 239 | 240 | public const string ComponentState = "componentstate"; 241 | 242 | public const string CreatedBy = "createdby"; 243 | 244 | public const string CreatedOn = "createdon"; 245 | 246 | public const string CreatedOnBehalfBy = "createdonbehalfby"; 247 | 248 | public const string EntityMapId = "entitymapid"; 249 | 250 | public const string Id = "entitymapid"; 251 | 252 | public const string EntityMapIdUnique = "entitymapidunique"; 253 | 254 | public const string IsManaged = "ismanaged"; 255 | 256 | public const string ModifiedBy = "modifiedby"; 257 | 258 | public const string ModifiedOn = "modifiedon"; 259 | 260 | public const string ModifiedOnBehalfBy = "modifiedonbehalfby"; 261 | 262 | public const string OrganizationId = "organizationid"; 263 | 264 | public const string OverwriteTime = "overwritetime"; 265 | 266 | public const string SolutionId = "solutionid"; 267 | 268 | public const string SourceEntityName = "sourceentityname"; 269 | 270 | public const string TargetEntityName = "targetentityname"; 271 | 272 | public const string VersionNumber = "versionnumber"; 273 | } 274 | } 275 | } 276 | -------------------------------------------------------------------------------- /Dataverse.Sdk.Extensions/Dataverse.Sdk.Extensions.Tests/EntityReferenceTests.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.Xrm.Sdk; 2 | using System; 3 | using Xunit; 4 | 5 | namespace Dataverse.Sdk.Extensions.Tests 6 | { 7 | public class EntityReferenceTests 8 | { 9 | [Fact] 10 | public void GetNameId_Can_Display_Name_And_Id() 11 | { 12 | // Arrange 13 | var nullValue = (EntityReference) null; 14 | var empty = new EntityReference(); 15 | var idOnly = new EntityReference("account", Guid.NewGuid()); 16 | var full = new EntityReference("account", Guid.NewGuid()) 17 | { 18 | Name = "Bart Simpson" 19 | }; 20 | 21 | //Assert 22 | Assert.Equal("null", nullValue.GetNameId()); 23 | Assert.Equal(Guid.Empty.ToString(), empty.GetNameId()); 24 | Assert.Equal(idOnly.Id.ToString(), idOnly.GetNameId()); 25 | Assert.Equal($"{full.Name} ({full.Id})", full.GetNameId()); 26 | Assert.Equal($"{full.Name} {full.Id}", full.GetNameId("{0} {1}")); 27 | } 28 | } 29 | } 30 | -------------------------------------------------------------------------------- /Dataverse.Sdk.Extensions/Dataverse.Sdk.Extensions.Tests/EntityTests.cs: -------------------------------------------------------------------------------- 1 | using Dataverse.Sdk.Extensions.Tests.EarlyBoundEntities; 2 | using Dataverse.Sdk.Extensions.Tests.FakeMessageExecutors; 3 | using Dataverse.Sdk.Extensions.Tests.MetadataModels; 4 | using Microsoft.Xrm.Sdk; 5 | using Microsoft.Xrm.Sdk.Messages; 6 | using Microsoft.Xrm.Sdk.Metadata; 7 | using Microsoft.Xrm.Sdk.Query; 8 | using System; 9 | using System.Linq; 10 | using Xunit; 11 | 12 | namespace Dataverse.Sdk.Extensions.Tests 13 | { 14 | public class EntityTests : FakeXrmEasyTestsBase 15 | { 16 | [Fact] 17 | public void Add_Parties_Without_party_Throws_Exception() 18 | { 19 | var email = new Entity("email"); 20 | var exception = Record.Exception(() => email.AddParties("to")); 21 | 22 | //Assert 23 | Assert.NotNull(exception); 24 | } 25 | 26 | [Fact] 27 | public void Add_Party_Can_Read_Party_From_Record() 28 | { 29 | var id = Guid.NewGuid(); 30 | var contactReference = new EntityReference("contact", id); 31 | 32 | var email = new Entity("email"); 33 | email.AddParty("to", contactReference); 34 | 35 | Assert.Equal(id, email.GetAttributeValue("to").Entities.First().GetAttributeValue("partyid").Id); 36 | } 37 | 38 | [Fact] 39 | public void Add_Two_Parties_Can_Read_Tow_Parties_From_Record() 40 | { 41 | var id = Guid.NewGuid(); 42 | var id2 = Guid.NewGuid(); 43 | var contactReference = new EntityReference("contact", id); 44 | var contactReference2 = new EntityReference("contact", id2); 45 | 46 | var email = new Entity("email"); 47 | email.AddParties("to", contactReference, contactReference2); 48 | 49 | Assert.Equal(2, email.GetAttributeValue("to").Entities.Count); 50 | } 51 | 52 | [Fact] 53 | public void Check_Not_Null_Columns_In_Entity_False_Because_Missing_Column() 54 | { 55 | var account = new Account 56 | { 57 | Name = "account1", 58 | AccountNumber = "ABCDEFGH", 59 | Address1_City = "Paris" 60 | }; 61 | 62 | bool containsNullValue = account.ContainsValue(e => e.AccountNumber, e => e.Address1_City, e => e.Address1_Line1); 63 | 64 | Assert.False(containsNullValue); 65 | } 66 | 67 | [Fact] 68 | public void Check_Not_Null_Columns_In_Entity_True() 69 | { 70 | var account = new Account 71 | { 72 | Name = "account1", 73 | AccountNumber = "ABCDEFGH", 74 | Address1_City = "Paris" 75 | }; 76 | 77 | bool containsNullValue = account.ContainsValue(e => e.AccountNumber, e => e.Address1_City); 78 | 79 | Assert.True(containsNullValue); 80 | } 81 | 82 | [Fact] 83 | public void Check_Null_Columns_In_Entity_False() 84 | { 85 | var account = new Account 86 | { 87 | Name = "account1", 88 | AccountNumber = "ABCDEFGH", 89 | Address1_City = null, 90 | Address1_Line1 = null, 91 | }; 92 | 93 | bool containsNullValue = account.ContainsNullValue(e => e.AccountNumber, e => e.Address1_City); 94 | 95 | Assert.False(containsNullValue); 96 | } 97 | 98 | [Fact] 99 | public void Check_Null_Columns_In_Entity_False_Because_Missing_Column() 100 | { 101 | var account = new Account 102 | { 103 | Name = "account1", 104 | AccountNumber = null, 105 | Address1_City = null 106 | }; 107 | 108 | bool containsNullValue = account.ContainsNullValue(e => e.AccountNumber, e => e.Address1_City, e => e.Address1_Line1); 109 | 110 | Assert.False(containsNullValue); 111 | } 112 | 113 | [Fact] 114 | public void Check_Null_Columns_In_Entity_True() 115 | { 116 | var account = new Account 117 | { 118 | Name = "account1", 119 | Address1_City = null, 120 | AccountNumber = null, 121 | }; 122 | 123 | bool containsNullValue = account.ContainsNullValue(e => e.AccountNumber, e => e.Address1_City); 124 | 125 | Assert.True(containsNullValue); 126 | } 127 | 128 | [Fact] 129 | public void Clone_addCloneLabel_false_Ignores_Clone_Label() 130 | { 131 | var metadata = AccountMetadata.GetEntityMetadata(); 132 | var entityMetadata = new EntityMetadataCollection() { metadata }; 133 | _context.AddFakeMessageExecutor(new RetrieveMetadataChangesRequestExecutor(entityMetadata)); 134 | 135 | var clone = new Entity("account") 136 | { 137 | ["name"] = "Your Company" 138 | }.Clone(_service, false); 139 | 140 | Assert.Equal("Your Company", clone.GetAttributeValue("name")); 141 | } 142 | 143 | [Fact] 144 | public void Clone_columnsToRemove_Ignores_Specified_Columns() 145 | { 146 | var metadata = AccountMetadata.GetEntityMetadata(); 147 | var entityMetadata = new EntityMetadataCollection() { metadata }; 148 | _context.AddFakeMessageExecutor(new RetrieveMetadataChangesRequestExecutor(entityMetadata)); 149 | 150 | var clone = new Entity("account") 151 | { 152 | ["name"] = "Your Company", 153 | ["primarycontactid"] = new EntityReference("contact", Guid.NewGuid()) 154 | }.Clone(_service, true, "primarycontactid"); 155 | 156 | Assert.Null(clone.GetAttributeValue("primarycontactid")); 157 | } 158 | 159 | [Fact] 160 | public void Clone_Correctly_Clones_Record_Without_columnsToRemove() 161 | { 162 | var metadata = AccountMetadata.GetEntityMetadata(); 163 | var entityMetadata = new EntityMetadataCollection() { metadata }; 164 | _context.AddFakeMessageExecutor(new RetrieveMetadataChangesRequestExecutor(entityMetadata)); 165 | 166 | var clone = new Entity("account") 167 | { 168 | ["name"] = "Your Company", 169 | ["primarycontactid"] = new EntityReference("contact", Guid.NewGuid()) 170 | }.Clone(_service); 171 | 172 | Assert.NotNull(clone.GetAttributeValue("primarycontactid")); 173 | } 174 | 175 | [Fact] 176 | public void Clone_default_addCloneLabel_Adds_Clone_Label() 177 | { 178 | var metadata = AccountMetadata.GetEntityMetadata(); 179 | var entityMetadata = new EntityMetadataCollection() { metadata }; 180 | _context.AddFakeMessageExecutor(new RetrieveMetadataChangesRequestExecutor(entityMetadata)); 181 | 182 | var clone = new Entity("account") { ["name"] = "Your Company" }.Clone(_service); 183 | 184 | Assert.Equal("Your Company (clone)", clone.GetAttributeValue("name")); 185 | } 186 | 187 | [Fact] 188 | public void Clone_Ignores_Uniqueidentifier_Columns() 189 | { 190 | var metadata = AccountMetadata.GetEntityMetadata(); 191 | var entityMetadata = new EntityMetadataCollection() { metadata }; 192 | _context.AddFakeMessageExecutor(new RetrieveMetadataChangesRequestExecutor(entityMetadata)); 193 | 194 | var clone = new Entity("account") 195 | { 196 | ["name"] = "Your Company", 197 | ["processid"] = Guid.NewGuid() 198 | }.Clone(_service); 199 | 200 | Assert.Null(clone.GetAttributeValue("processid")); 201 | } 202 | 203 | [Fact] 204 | public void GetAliasedValue_Can_Read_Aliased_Value_From_Record() 205 | { 206 | // Arrange 207 | var contact = new Entity("contact") 208 | { 209 | Id = Guid.NewGuid(), 210 | ["fullname"] = "Unit Test" 211 | }; 212 | var account = new Entity("account") 213 | { 214 | Id = Guid.NewGuid(), 215 | ["primarycontactid"] = contact.ToEntityReference(), 216 | ["name"] = "Your Company" 217 | }; 218 | _context.Initialize(new Entity[] { contact, account }); 219 | 220 | //Act 221 | var query = new QueryExpression("account") 222 | { 223 | TopCount = 1, 224 | ColumnSet = new ColumnSet("name"), 225 | LinkEntities = 226 | { 227 | new LinkEntity 228 | { 229 | LinkFromEntityName = "account", 230 | LinkFromAttributeName = "primarycontactid", 231 | LinkToAttributeName = "contactid", 232 | LinkToEntityName = "contact", 233 | EntityAlias = "primarycontact", 234 | Columns = new ColumnSet("fullname") 235 | } 236 | } 237 | }; 238 | 239 | Entity record = _service.RetrieveMultiple(query).Entities.FirstOrDefault(); 240 | string fullname = record.GetAliasedValue("primarycontact", "fullname"); 241 | 242 | //Assert 243 | Assert.Equal(contact.GetAttributeValue("fullname"), fullname); 244 | } 245 | 246 | [Fact] 247 | public void GetAliasedValue_Retruns_Default_If_Empty() 248 | { 249 | //Arrange 250 | var record = new Entity("account"); 251 | 252 | //Act 253 | var count = record.GetAliasedValue("primarycontact", "debts"); 254 | 255 | //Assert 256 | Assert.Equal(0, count); 257 | } 258 | 259 | [Fact] 260 | public void GetAliasedValue_Throws_If_Wrong_Aliased_Type() 261 | { 262 | // Arrange 263 | var contact = new Entity("contact") 264 | { 265 | Id = Guid.NewGuid(), 266 | ["fullname"] = "Unit Test" 267 | }; 268 | var account = new Entity("account") 269 | { 270 | Id = Guid.NewGuid(), 271 | ["primarycontactid"] = contact.ToEntityReference(), 272 | ["name"] = "Your Company" 273 | }; 274 | _context.Initialize(new Entity[] { contact, account }); 275 | 276 | //Act 277 | var query = new QueryExpression("account") 278 | { 279 | TopCount = 1, 280 | ColumnSet = new ColumnSet("name"), 281 | LinkEntities = 282 | { 283 | new LinkEntity 284 | { 285 | LinkFromEntityName = "account", 286 | LinkFromAttributeName = "primarycontactid", 287 | LinkToAttributeName = "contactid", 288 | LinkToEntityName = "contact", 289 | EntityAlias = "primarycontact", 290 | Columns = new ColumnSet("fullname") 291 | } 292 | } 293 | }; 294 | 295 | Entity record = _service.RetrieveMultiple(query).Entities.FirstOrDefault(); 296 | var exception = Record.Exception(() => record.GetAliasedValue("primarycontact", "fullname")); 297 | 298 | //Assert 299 | Assert.NotNull(exception); 300 | } 301 | 302 | [Fact] 303 | public void Set_Parties_When_Parties_Contains_Record_Can_Read_Two_Parties_From_Record() 304 | { 305 | var id = Guid.NewGuid(); 306 | var id2 = Guid.NewGuid(); 307 | var id3 = Guid.NewGuid(); 308 | var id4 = Guid.NewGuid(); 309 | var contactReference = new EntityReference("contact", id); 310 | var contactReference2 = new EntityReference("contact", id2); 311 | var contactReference3 = new EntityReference("contact", id3); 312 | var contactReference4 = new EntityReference("contact", id4); 313 | 314 | var email = new Entity("email"); 315 | email.AddParties("to", contactReference, contactReference2); 316 | email.SetParties("to", contactReference3, contactReference4); 317 | 318 | Assert.Equal(2, email.GetAttributeValue("to").Entities.Count); 319 | } 320 | 321 | [Fact] 322 | public void Set_Parties_Without_party_Throws_Exception() 323 | { 324 | var email = new Entity("email"); 325 | var exception = Record.Exception(() => email.SetParties("to")); 326 | 327 | //Assert 328 | Assert.NotNull(exception); 329 | } 330 | 331 | [Fact] 332 | public void Set_Party_When_Parties_Contains_Record_Can_Read_One_Party_From_Record() 333 | { 334 | var id = Guid.NewGuid(); 335 | var id2 = Guid.NewGuid(); 336 | var id3 = Guid.NewGuid(); 337 | var contactReference = new EntityReference("contact", id); 338 | var contactReference2 = new EntityReference("contact", id2); 339 | var contactReference3 = new EntityReference("contact", id3); 340 | 341 | var email = new Entity("email"); 342 | email.AddParty("to", contactReference); 343 | email.AddParty("to", contactReference2); 344 | email.SetParty("to", contactReference3); 345 | 346 | Assert.Single(email.GetAttributeValue("to").Entities); 347 | Assert.Equal(id3, email.GetAttributeValue("to").Entities.First().GetAttributeValue("partyid").Id); 348 | } 349 | } 350 | } -------------------------------------------------------------------------------- /Dataverse.Sdk.Extensions/Dataverse.Sdk.Extensions.Tests/FakeMessageExecutors/RetrieveMetadataChangesRequestExecutor.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using FakeXrmEasy; 3 | using FakeXrmEasy.FakeMessageExecutors; 4 | using Microsoft.Xrm.Sdk; 5 | using Microsoft.Xrm.Sdk.Messages; 6 | using Microsoft.Xrm.Sdk.Metadata; 7 | 8 | namespace Dataverse.Sdk.Extensions.Tests.FakeMessageExecutors 9 | { 10 | class RetrieveMetadataChangesRequestExecutor : IFakeMessageExecutor 11 | { 12 | private EntityMetadataCollection entityMetadata; 13 | 14 | public RetrieveMetadataChangesRequestExecutor(EntityMetadataCollection entityMetadata) 15 | { 16 | this.entityMetadata = entityMetadata; 17 | } 18 | 19 | public bool CanExecute(OrganizationRequest request) 20 | { 21 | return request is RetrieveMetadataChangesRequest; 22 | } 23 | 24 | public OrganizationResponse Execute(OrganizationRequest request, XrmFakedContext ctx) 25 | { 26 | return new RetrieveMetadataChangesResponse() 27 | { 28 | Results ={ 29 | ["EntityMetadata"] = entityMetadata 30 | } 31 | }; 32 | } 33 | 34 | public Type GetResponsibleRequestType() 35 | { 36 | return typeof(RetrieveMetadataChangesRequest); 37 | } 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /Dataverse.Sdk.Extensions/Dataverse.Sdk.Extensions.Tests/FakeXrmEasyTestsBase.cs: -------------------------------------------------------------------------------- 1 | using FakeXrmEasy; 2 | using Microsoft.Xrm.Sdk; 3 | 4 | namespace Dataverse.Sdk.Extensions.Tests 5 | { 6 | public class FakeXrmEasyTestsBase 7 | { 8 | protected readonly IOrganizationService _service; 9 | protected readonly XrmFakedContext _context; 10 | 11 | public FakeXrmEasyTestsBase() 12 | { 13 | _context = new XrmFakedContext(); 14 | _service = _context.GetOrganizationService(); 15 | } 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /Dataverse.Sdk.Extensions/Dataverse.Sdk.Extensions.Tests/IOrganizationServiceTests.cs: -------------------------------------------------------------------------------- 1 | using Dataverse.Sdk.Extensions.Tests.EarlyBoundEntities; 2 | using Dataverse.Sdk.Extensions.Tests.MetadataModels; 3 | using FakeXrmEasy; 4 | using FakeXrmEasy.Extensions; 5 | using Microsoft.Crm.Sdk.Messages; 6 | using Microsoft.Xrm.Sdk; 7 | using Microsoft.Xrm.Sdk.Metadata; 8 | using Microsoft.Xrm.Sdk.Query; 9 | using System; 10 | using System.Collections.Generic; 11 | using System.Linq; 12 | using Xunit; 13 | 14 | namespace Dataverse.Sdk.Extensions.Tests 15 | { 16 | 17 | public class IOrganizationServiceTests : FakeXrmEasyTestsBase 18 | { 19 | [Fact] 20 | public void CreateFromInitialization_Creates_Another_Row_Using_Standard_Columns() 21 | { 22 | //Arrange 23 | var current = new Entity("account") 24 | { 25 | Id = Guid.NewGuid(), 26 | ["name"] = "Your Company", 27 | ["description"] = "Will not be used" 28 | }; 29 | var entityMap = new Entity("entitymap") 30 | { 31 | Id = Guid.NewGuid(), 32 | ["sourceentityname"] = "account", 33 | ["targetentityname"] = "account" 34 | }; 35 | var attributeMap = new Entity("attributemap") 36 | { 37 | Id = Guid.NewGuid(), 38 | ["entitymapid"] = entityMap.ToEntityReference(), 39 | ["sourceattributename"] = "name", 40 | ["targetattributename"] = "name" 41 | }; 42 | _context.Initialize(new Entity[] { current, entityMap, attributeMap }); 43 | 44 | //Act 45 | var created = _service.CreateFromInitialization("account", current.ToEntityReference(), TargetFieldType.All); 46 | 47 | //Assert 48 | Assert.NotEqual(current.Id, created.Id); 49 | Assert.Equal(current.GetAttributeValue("name"), created.GetAttributeValue("name")); 50 | Assert.Null(created.GetAttributeValue("description")); 51 | } 52 | 53 | [Fact] 54 | public void CreateFromInitialization_Creates_Another_Row_Using_Additional_Columns() 55 | { 56 | //Arrange 57 | var current = new Entity("account") 58 | { 59 | Id = Guid.NewGuid(), 60 | ["name"] = "Your Company", 61 | ["description"] = "Will not be used" 62 | }; 63 | var entityMap = new Entity("entitymap") 64 | { 65 | Id = Guid.NewGuid(), 66 | ["sourceentityname"] = "account", 67 | ["targetentityname"] = "account" 68 | }; 69 | var attributeMap = new Entity("attributemap") 70 | { 71 | Id = Guid.NewGuid(), 72 | ["entitymapid"] = entityMap.ToEntityReference(), 73 | ["sourceattributename"] = "name", 74 | ["targetattributename"] = "name" 75 | }; 76 | _context.Initialize(new Entity[] { current, entityMap, attributeMap }); 77 | 78 | //Act 79 | var created = _service.CreateFromInitialization( 80 | "account", 81 | current.ToEntityReference(), 82 | TargetFieldType.All, 83 | new Dictionary { { "description", "New Description" } } 84 | ); 85 | 86 | //Assert 87 | Assert.NotEqual(current.Id, created.Id); 88 | Assert.Equal(current.GetAttributeValue("name"), created.GetAttributeValue("name")); 89 | Assert.Equal("New Description", created.GetAttributeValue("description")); 90 | } 91 | 92 | [Fact] 93 | public void CreateFromInitialization_Creates_Another_Earlybound_Row_Using_Additional_Columns() 94 | { 95 | //Arrange 96 | var current = new Account() 97 | { 98 | Id = Guid.NewGuid(), 99 | Name = "Your Company", 100 | Description = "Will not be used" 101 | }; 102 | var entityMap = new EntityMap() 103 | { 104 | Id = Guid.NewGuid(), 105 | SourceEntityName = "account", 106 | TargetEntityName = "account" 107 | }; 108 | var attributeMap = new AttributeMap() 109 | { 110 | Id = Guid.NewGuid(), 111 | EntityMapId = entityMap.ToEntityReference(), 112 | SourceAttributeName = "name", 113 | TargetAttributeName = "name" 114 | }; 115 | _context.Initialize(new Entity[] { current, entityMap, attributeMap }); 116 | 117 | //Act 118 | var created = _service.CreateFromInitialization( 119 | current.ToEntityReference(), 120 | TargetFieldType.All, 121 | new Dictionary { { "description", "New Description" } } 122 | ); 123 | 124 | //Assert 125 | Assert.NotEqual(current.Id, created.Id); 126 | Assert.Equal(current.Name, created.Name); 127 | Assert.Equal("New Description", created.Description); 128 | } 129 | 130 | [Fact] 131 | public void Delete_Can_Delete_Record_By_EntityReference() 132 | { 133 | //Arrange 134 | var accountToDelete = new Entity("account") 135 | { 136 | Id = Guid.NewGuid(), 137 | ["name"] = "Your Company" 138 | }; 139 | 140 | _context.Initialize(accountToDelete); 141 | 142 | //Act 143 | _service.Delete(accountToDelete.ToEntityReference()); 144 | 145 | //Assert 146 | Assert.Empty(_context.CreateQuery("account")); 147 | } 148 | 149 | [Fact] 150 | public void Delete_Can_Delete_Record_By_Entity() 151 | { 152 | //Arrange 153 | var accountToDelete = new Entity("account") 154 | { 155 | Id = Guid.NewGuid(), 156 | ["name"] = "Your Company" 157 | }; 158 | 159 | _context.Initialize(accountToDelete); 160 | 161 | //Act 162 | _service.Delete(accountToDelete); 163 | 164 | //Assert 165 | Assert.Empty(_context.CreateQuery("account")); 166 | } 167 | 168 | [Fact] 169 | public void Delete_Can_Delete_Record_By_Alternate_Key() 170 | { 171 | //Arrange 172 | var accountToDelete = new Entity("account") 173 | { 174 | Id = Guid.NewGuid(), 175 | ["name"] = "Your Company" 176 | }; 177 | var metadata = AccountMetadata.GetEntityMetadata(); 178 | metadata.SetSealedPropertyValue( 179 | nameof(metadata.Keys), 180 | new EntityKeyMetadata[] { 181 | new EntityKeyMetadata() 182 | { 183 | KeyAttributes = new string[] { "name" } 184 | } 185 | }); 186 | _context.InitializeMetadata(metadata); 187 | _context.Initialize(accountToDelete); 188 | 189 | //Act 190 | _service.Delete("account", "name", accountToDelete.GetAttributeValue("name")); 191 | 192 | //Assert 193 | Assert.Empty(_context.CreateQuery("account")); 194 | } 195 | 196 | [Fact] 197 | public void Delete_Can_Delete_EarlyBound_Record_By_Alternate_Key() 198 | { 199 | //Arrange 200 | var accountToDelete = new Account() 201 | { 202 | Id = Guid.NewGuid(), 203 | Name = "Your Company" 204 | }; 205 | var metadata = AccountMetadata.GetEntityMetadata(); 206 | metadata.SetSealedPropertyValue( 207 | nameof(metadata.Keys), 208 | new EntityKeyMetadata[] { 209 | new EntityKeyMetadata() 210 | { 211 | KeyAttributes = new string[] { Account.Fields.Name } 212 | } 213 | }); 214 | _context.InitializeMetadata(metadata); 215 | _context.Initialize(accountToDelete); 216 | 217 | //Act 218 | _service.Delete(Account.Fields.Name, accountToDelete.Name); 219 | 220 | //Assert 221 | Assert.Empty(_context.CreateQuery()); 222 | } 223 | 224 | [Fact] 225 | public void Delete_Can_Delete_Record_By_Alternate_Key_Multi() 226 | { 227 | //Arrange 228 | var accountToDelete = new Entity("account") 229 | { 230 | Id = Guid.NewGuid(), 231 | ["name"] = "Your Company", 232 | ["accountnumber"] = "1234567890" 233 | }; 234 | var metadata = AccountMetadata.GetEntityMetadata(); 235 | metadata.SetSealedPropertyValue( 236 | nameof(metadata.Keys), 237 | new EntityKeyMetadata[] { 238 | new EntityKeyMetadata() 239 | { 240 | KeyAttributes = new string[] { "name", "accountnumber" } 241 | } 242 | }); 243 | _context.InitializeMetadata(metadata); 244 | _context.Initialize(accountToDelete); 245 | 246 | var keys = new KeyAttributeCollection 247 | { 248 | { "name", accountToDelete.GetAttributeValue("name") }, 249 | { "accountnumber", accountToDelete.GetAttributeValue("accountnumber") } 250 | }; 251 | 252 | 253 | //Act 254 | _service.Delete("account", keys); 255 | 256 | //Assert 257 | Assert.Empty(_context.CreateQuery("account")); 258 | } 259 | 260 | [Fact] 261 | public void Delete_Can_Delete_EarlyBound_Record_By_Alternate_Key_Multi() 262 | { 263 | //Arrange 264 | var accountToDelete = new Account() 265 | { 266 | Id = Guid.NewGuid(), 267 | Name = "Your Company", 268 | AccountNumber = "1234567890" 269 | }; 270 | var metadata = AccountMetadata.GetEntityMetadata(); 271 | metadata.SetSealedPropertyValue( 272 | nameof(metadata.Keys), 273 | new EntityKeyMetadata[] { 274 | new EntityKeyMetadata() 275 | { 276 | KeyAttributes = new string[] { Account.Fields.Name, Account.Fields.AccountNumber } 277 | } 278 | }); 279 | _context.InitializeMetadata(metadata); 280 | _context.Initialize(accountToDelete); 281 | 282 | var keys = new KeyAttributeCollection 283 | { 284 | { Account.Fields.Name, accountToDelete.Name }, 285 | { Account.Fields.AccountNumber, accountToDelete.AccountNumber } 286 | }; 287 | 288 | //Act 289 | _service.Delete(keys); 290 | 291 | //Assert 292 | Assert.Empty(_context.CreateQuery()); 293 | } 294 | 295 | [Fact] 296 | public void GetCurrentUserRoles_Returns_The_Current_User_Roles() 297 | { 298 | //Arrange 299 | var currentUserEntity = new Entity("systemuser") 300 | { 301 | Id = Guid.NewGuid() 302 | }; 303 | var currentUser = currentUserEntity.ToEntityReference(); 304 | _context.CallerId = currentUser; 305 | var sysAdmin = new Entity("role") 306 | { 307 | Id = Guid.NewGuid(), 308 | ["Name"] = "System Administrator", 309 | }; 310 | var sysCustomizer = new Entity("role") 311 | { 312 | Id = Guid.NewGuid(), 313 | ["Name"] = "System Customizer", 314 | }; 315 | var entities = new Entity[] 316 | { 317 | new Entity("systemuserroles") 318 | { 319 | Id=Guid.NewGuid(), 320 | ["roleid"] = sysCustomizer.ToEntityReference(), 321 | ["systemuserid"] = currentUser 322 | }, 323 | new Entity("systemuserroles") 324 | { 325 | Id=Guid.NewGuid(), 326 | ["roleid"] = sysAdmin.ToEntityReference(), 327 | ["systemuserid"] = currentUser 328 | }, 329 | new Entity("systemuserroles") 330 | { 331 | Id=Guid.NewGuid(), 332 | ["roleid"]=sysCustomizer.ToEntityReference(), 333 | ["systemuserid"] = new EntityReference("systemuser", Guid.NewGuid()) 334 | }, 335 | sysAdmin, 336 | sysCustomizer, 337 | currentUserEntity 338 | }; 339 | _context.Initialize(entities); 340 | 341 | //Act 342 | var roles = _service.GetCurrentUserRoles(); 343 | 344 | //Assert 345 | Assert.Equal(2, roles.Count); 346 | } 347 | 348 | [Fact] 349 | public void GetCurrentUserRoles_Returns_Empty_If_No_Roles() 350 | { 351 | //Arrange 352 | var currentUserEntity = new Entity("systemuser") 353 | { 354 | Id = Guid.NewGuid() 355 | }; 356 | var currentUser = currentUserEntity.ToEntityReference(); 357 | _context.CallerId = currentUser; 358 | var sysAdmin = new Entity("role") 359 | { 360 | Id = Guid.NewGuid(), 361 | ["Name"] = "System Administrator", 362 | }; 363 | var entities = new Entity[] 364 | { 365 | new Entity("systemuserroles") 366 | { 367 | Id=Guid.NewGuid(), 368 | ["roleid"]=sysAdmin.ToEntityReference(), 369 | ["systemuserid"] = new EntityReference("systemuser", Guid.NewGuid()) 370 | }, 371 | sysAdmin, 372 | currentUserEntity 373 | }; 374 | _context.Initialize(entities); 375 | 376 | //Act 377 | var roles = _service.GetCurrentUserRoles(); 378 | 379 | //Assert 380 | Assert.Empty(roles); 381 | } 382 | 383 | [Fact] 384 | public void GetEnvironmentVariable_Throws_If_Variable_Does_Not_Exist() 385 | { 386 | //Arrange 387 | var fakedContext = new XrmFakedContext(); 388 | 389 | //Act 390 | var exception = Record.Exception(() => fakedContext.GetOrganizationService().GetEnvironmentVariable("nonexistent")); 391 | 392 | //Assert 393 | Assert.NotNull(exception); 394 | } 395 | 396 | [Fact] 397 | public void GetEnvironmentVariable_Returns_Value_as_String() 398 | { 399 | //Arrange 400 | var environmentvariabledefinition = new Entity("environmentvariabledefinition") 401 | { 402 | Id = Guid.NewGuid(), 403 | ["schemaname"] = "environmentVariable" 404 | }; 405 | var environmentvariablevalue = new Entity("environmentvariablevalue") 406 | { 407 | Id = Guid.NewGuid(), 408 | ["value"] = "Environment Variable", 409 | ["environmentvariabledefinitionid"] = environmentvariabledefinition.ToEntityReference() 410 | }; 411 | _context.Initialize(new Entity[] { environmentvariabledefinition, environmentvariablevalue }); 412 | 413 | //Act 414 | var value = _service.GetEnvironmentVariable("environmentVariable"); 415 | 416 | //Assert 417 | Assert.Equal("Environment Variable", value); 418 | } 419 | 420 | [Fact] 421 | public void GetEnvironmentVariables_Returns_Values_as_Dictionary() 422 | { 423 | //Arrange 424 | var environmentvariabledefinition1 = new Entity("environmentvariabledefinition") 425 | { 426 | Id = Guid.NewGuid(), 427 | ["schemaname"] = "environmentVariable1" 428 | }; 429 | var environmentvariablevalue1 = new Entity("environmentvariablevalue") 430 | { 431 | Id = Guid.NewGuid(), 432 | ["value"] = "First Environment Variable", 433 | ["environmentvariabledefinitionid"] = environmentvariabledefinition1.ToEntityReference() 434 | }; 435 | var environmentvariabledefinition2 = new Entity("environmentvariabledefinition") 436 | { 437 | Id = Guid.NewGuid(), 438 | ["schemaname"] = "environmentVariable2" 439 | }; 440 | var environmentvariablevalue2 = new Entity("environmentvariablevalue") 441 | { 442 | Id = Guid.NewGuid(), 443 | ["value"] = "Second Environment Variable", 444 | ["environmentvariabledefinitionid"] = environmentvariabledefinition2.ToEntityReference() 445 | }; 446 | _context.Initialize(new Entity[] { 447 | environmentvariabledefinition1, 448 | environmentvariablevalue1, 449 | environmentvariabledefinition2, 450 | environmentvariablevalue2 }); 451 | 452 | //Act 453 | var values = _service.GetEnvironmentVariables("environmentVariable1", "environmentVariable2"); 454 | 455 | //Assert 456 | Assert.Equal(2, values.Count); 457 | Assert.True(values.ContainsKey("environmentVariable1")); 458 | Assert.Equal("First Environment Variable", values["environmentVariable1"]); 459 | } 460 | 461 | [Fact] 462 | public void GetEnvironmentVariables_Throws_If_No_Variables_Are_Found() 463 | { 464 | //Arrange 465 | 466 | //Act 467 | var exception = Record.Exception(() => _service.GetEnvironmentVariables("environmentVariable1", "environmentVariable2")); 468 | 469 | //Assert 470 | Assert.NotNull(exception); 471 | } 472 | 473 | [Fact] 474 | public void GetEnvironmentVariables_Throws_If_Not_All_Variables_Are_Found() 475 | { 476 | //Arrange 477 | var environmentvariabledefinition = new Entity("environmentvariabledefinition") 478 | { 479 | Id = Guid.NewGuid(), 480 | ["schemaname"] = "environmentVariable1" 481 | }; 482 | var environmentvariablevalue = new Entity("environmentvariablevalue") 483 | { 484 | Id = Guid.NewGuid(), 485 | ["value"] = "Environment Variable", 486 | ["environmentvariabledefinitionid"] = environmentvariabledefinition.ToEntityReference() 487 | }; 488 | _context.Initialize(new Entity[] { environmentvariabledefinition, environmentvariablevalue }); 489 | 490 | //Act 491 | var exception = Record.Exception(() => _service.GetEnvironmentVariables("environmentVariable1", "environmentVariable2")); 492 | 493 | //Assert 494 | Assert.NotNull(exception); 495 | } 496 | 497 | [Fact] 498 | public void Upsert_Creates_Record_If_Not_Exists() 499 | { 500 | //Arrange 501 | _context.Initialize(new Entity("account") 502 | { 503 | Id = Guid.NewGuid(), 504 | ["name"] = "Another Company" 505 | }); 506 | var account = new Entity("account") 507 | { 508 | Id = Guid.NewGuid(), 509 | ["name"] = "Your Company" 510 | }; 511 | 512 | //Act 513 | var created = _service.Upsert(account); 514 | 515 | //Assert 516 | Assert.True(created); 517 | Assert.NotEmpty(_context.CreateQuery("account").Where(x => x.Id == account.Id)); 518 | } 519 | 520 | [Fact] 521 | public void Upsert_Updates_Record_If_Exists() 522 | { 523 | //Arrange 524 | var account = new Entity("account") 525 | { 526 | Id = Guid.NewGuid(), 527 | ["name"] = "Your Company" 528 | }; 529 | _context.Initialize(account); 530 | account["name"] = "Still Your Company"; 531 | 532 | //Act 533 | var created = _service.Upsert(account); 534 | 535 | //Assert 536 | Assert.False(created); 537 | Assert.NotEmpty(_context.CreateQuery("account").Where(x => x.Id == account.Id)); 538 | Assert.Equal("Still Your Company", _context.CreateQuery("account").First().GetAttributeValue("name")); 539 | } 540 | 541 | [Fact] 542 | public void RetrieveSingleTyped() 543 | { 544 | //Arrange 545 | var id = Guid.NewGuid(); 546 | var account = new Account() 547 | { 548 | Id = id, 549 | Name = "Testing Account" 550 | }; 551 | 552 | _context.Initialize(account); 553 | 554 | //Act 555 | Account retrievedAccount = _service.Retrieve(id, new Microsoft.Xrm.Sdk.Query.ColumnSet(Account.Fields.Name)); 556 | 557 | //Assert 558 | Assert.Equal(account.Name, retrievedAccount.Name); 559 | } 560 | 561 | [Fact] 562 | public void RetrieveMultipleTyped() 563 | { 564 | //Arrange 565 | string distinctAccountName = Guid.NewGuid().ToString(); 566 | 567 | List accounts = new List(); 568 | for (int i = 0; i < 5; i++) 569 | { 570 | accounts.Add(new Account() 571 | { 572 | Id = Guid.NewGuid(), 573 | Name = distinctAccountName 574 | }); 575 | } 576 | _context.Initialize(accounts); 577 | 578 | //Act 579 | Microsoft.Xrm.Sdk.Query.QueryExpression queryExpression = new Microsoft.Xrm.Sdk.Query.QueryExpression(Account.EntityLogicalName) 580 | { 581 | ColumnSet = new Microsoft.Xrm.Sdk.Query.ColumnSet(Account.Fields.Name) 582 | }; 583 | queryExpression.Criteria.AddCondition(Account.Fields.Name, Microsoft.Xrm.Sdk.Query.ConditionOperator.Equal, distinctAccountName); 584 | 585 | List retrievedAccounts = _service.RetrieveMultiple(queryExpression); 586 | 587 | //Assert 588 | Assert.Equal(5, retrievedAccounts.Count()); 589 | } 590 | 591 | [Fact] 592 | public void RetrieveAll_QueryExpression() 593 | { 594 | //Arrange 595 | int totalRecords = 5010; 596 | string distinctAccountName = Guid.NewGuid().ToString(); 597 | 598 | List accounts = new List(); 599 | for (int i = 0; i < totalRecords; i++) 600 | { 601 | accounts.Add(new Account() 602 | { 603 | Id = Guid.NewGuid(), 604 | Name = distinctAccountName 605 | }); 606 | } 607 | _context.Initialize(accounts); 608 | 609 | //Act 610 | Microsoft.Xrm.Sdk.Query.QueryExpression queryExpression = new Microsoft.Xrm.Sdk.Query.QueryExpression(Account.EntityLogicalName) 611 | { 612 | ColumnSet = new Microsoft.Xrm.Sdk.Query.ColumnSet(Account.Fields.Name) 613 | }; 614 | queryExpression.Criteria.AddCondition(Account.Fields.Name, Microsoft.Xrm.Sdk.Query.ConditionOperator.Equal, distinctAccountName); 615 | 616 | IEnumerable results = _service.RetrieveAll(queryExpression); 617 | 618 | //Assert 619 | Assert.Equal(totalRecords, results.Count()); 620 | } 621 | 622 | [Fact] 623 | public void RetrieveAll_QueryExpression_Typed() 624 | { 625 | //Arrange 626 | int totalRecords = 5010; 627 | string distinctAccountName = Guid.NewGuid().ToString(); 628 | 629 | List accounts = new List(); 630 | for (int i = 0; i < totalRecords; i++) 631 | { 632 | accounts.Add(new Account() 633 | { 634 | Id = Guid.NewGuid(), 635 | Name = distinctAccountName 636 | }); 637 | } 638 | _context.Initialize(accounts); 639 | 640 | //Act 641 | Microsoft.Xrm.Sdk.Query.QueryExpression queryExpression = new Microsoft.Xrm.Sdk.Query.QueryExpression(Account.EntityLogicalName) 642 | { 643 | ColumnSet = new Microsoft.Xrm.Sdk.Query.ColumnSet(Account.Fields.Name) 644 | }; 645 | queryExpression.Criteria.AddCondition(Account.Fields.Name, Microsoft.Xrm.Sdk.Query.ConditionOperator.Equal, distinctAccountName); 646 | 647 | IEnumerable results = _service.RetrieveAll(queryExpression); 648 | 649 | //Assert 650 | Assert.Equal(totalRecords, results.Count()); 651 | } 652 | 653 | [Fact] 654 | public void RetrieveAll_QueryByAttribute() 655 | { 656 | //Arrange 657 | int totalRecords = 5010; 658 | string distinctAccountName = Guid.NewGuid().ToString(); 659 | 660 | List accounts = new List(); 661 | for (int i = 0; i < totalRecords; i++) 662 | { 663 | accounts.Add(new Account() 664 | { 665 | Id = Guid.NewGuid(), 666 | Name = distinctAccountName 667 | }); 668 | } 669 | _context.Initialize(accounts); 670 | 671 | //Act 672 | QueryByAttribute queryByAttribute = new QueryByAttribute(Account.EntityLogicalName); 673 | queryByAttribute.AddAttributeValue(Account.Fields.Name, distinctAccountName); 674 | queryByAttribute.ColumnSet = new ColumnSet(Account.Fields.Name); 675 | 676 | IEnumerable results = _service.RetrieveAll(queryByAttribute); 677 | 678 | //Assert 679 | Assert.Equal(totalRecords, results.Count()); 680 | } 681 | 682 | [Fact] 683 | public void RetrieveAll_QueryByAttribute_Typed() 684 | { 685 | //Arrange 686 | int totalRecords = 5010; 687 | string distinctAccountName = Guid.NewGuid().ToString(); 688 | 689 | List accounts = new List(); 690 | for (int i = 0; i < totalRecords; i++) 691 | { 692 | accounts.Add(new Account() 693 | { 694 | Id = Guid.NewGuid(), 695 | Name = distinctAccountName 696 | }); 697 | } 698 | _context.Initialize(accounts); 699 | 700 | //Act 701 | QueryByAttribute queryByAttribute = new QueryByAttribute(Account.EntityLogicalName); 702 | queryByAttribute.AddAttributeValue(Account.Fields.Name, distinctAccountName); 703 | queryByAttribute.ColumnSet = new ColumnSet(Account.Fields.Name); 704 | 705 | IEnumerable results = _service.RetrieveAll(queryByAttribute); 706 | 707 | //Assert 708 | Assert.Equal(totalRecords, results.Count()); 709 | } 710 | 711 | [Fact] 712 | public void RetrieveAll_FetchExpression() 713 | { 714 | //Arrange 715 | int totalRecords = 5010; 716 | string distinctAccountName = Guid.NewGuid().ToString(); 717 | 718 | List accounts = new List(); 719 | for (int i = 0; i < totalRecords; i++) 720 | { 721 | accounts.Add(new Account() 722 | { 723 | Id = Guid.NewGuid(), 724 | Name = distinctAccountName 725 | }); 726 | } 727 | _context.Initialize(accounts); 728 | 729 | //Act 730 | var fetchXml = $@" 731 | 732 | 733 | 734 | 735 | "; 736 | FetchExpression fe = new FetchExpression(fetchXml); 737 | 738 | IEnumerable results = _service.RetrieveAll(fe); 739 | 740 | //Assert 741 | Assert.Equal(totalRecords, results.Count()); 742 | } 743 | 744 | [Fact] 745 | public void RetrieveAll_FetchExpression_Typed() 746 | { 747 | //Arrange 748 | int totalRecords = 5010; 749 | string distinctAccountName = Guid.NewGuid().ToString(); 750 | 751 | List accounts = new List(); 752 | for (int i = 0; i < totalRecords; i++) 753 | { 754 | accounts.Add(new Account() 755 | { 756 | Id = Guid.NewGuid(), 757 | Name = distinctAccountName 758 | }); 759 | } 760 | _context.Initialize(accounts); 761 | 762 | //Act 763 | var fetchXml = $@" 764 | 765 | 766 | 767 | 768 | "; 769 | FetchExpression fe = new FetchExpression(fetchXml); 770 | 771 | IEnumerable results = _service.RetrieveAll(fe); 772 | 773 | //Assert 774 | Assert.Equal(totalRecords, results.Count()); 775 | } 776 | } 777 | } 778 | -------------------------------------------------------------------------------- /Dataverse.Sdk.Extensions/Dataverse.Sdk.Extensions.Tests/MetadataModels/AccountMetadata.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.Xrm.Sdk.Metadata; 2 | using FakeXrmEasy.Extensions; 3 | using System.Linq; 4 | 5 | namespace Dataverse.Sdk.Extensions.Tests.MetadataModels 6 | { 7 | class AccountMetadata 8 | { 9 | public static EntityMetadata GetEntityMetadata() 10 | { 11 | var metadata = new EntityMetadata 12 | { 13 | LogicalName = "account" 14 | }; 15 | metadata.SetSealedPropertyValue(nameof(metadata.PrimaryIdAttribute), "accountid"); 16 | metadata.SetSealedPropertyValue(nameof(metadata.PrimaryNameAttribute), "name"); 17 | 18 | var accountid = new UniqueIdentifierAttributeMetadata("accountid") 19 | { 20 | LogicalName = "accountid" 21 | }; 22 | accountid.SetSealedPropertyValue(nameof(accountid.IsPrimaryId), true); 23 | accountid.SetSealedPropertyValue(nameof(accountid.IsValidForCreate), true); 24 | 25 | var name = new StringAttributeMetadata("name") 26 | { 27 | LogicalName = "name" 28 | }; 29 | name.SetSealedPropertyValue(nameof(name.IsPrimaryName), true); 30 | name.SetSealedPropertyValue(nameof(name.IsValidForCreate), true); 31 | 32 | var primarycontactid = new LookupAttributeMetadata() 33 | { 34 | LogicalName = "primarycontactid", 35 | SchemaName = "primarycontactid" 36 | }; 37 | primarycontactid.SetSealedPropertyValue(nameof(primarycontactid.IsValidForCreate), true); 38 | 39 | metadata.SetAttributeCollection( 40 | new AttributeMetadata[] { accountid, name, primarycontactid } 41 | .Concat(GlobalMetadata.GetGlobalMetadata()) 42 | .Concat(GlobalMetadata.GetOwnerMetadata()) 43 | .Concat(GlobalMetadata.GetProcessMetadata()) 44 | .ToArray()); 45 | 46 | return metadata; 47 | } 48 | } 49 | } 50 | -------------------------------------------------------------------------------- /Dataverse.Sdk.Extensions/Dataverse.Sdk.Extensions.Tests/MetadataModels/GlobalMetadata.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.Xrm.Sdk.Metadata; 2 | using System.Collections.Generic; 3 | using FakeXrmEasy.Extensions; 4 | 5 | namespace Dataverse.Sdk.Extensions.Tests.MetadataModels 6 | { 7 | class GlobalMetadata 8 | { 9 | public static IEnumerable GetGlobalMetadata() 10 | { 11 | var createdon = new DateTimeAttributeMetadata(DateTimeFormat.DateAndTime, "createdon") 12 | { 13 | LogicalName = "createdon" 14 | }; 15 | yield return createdon; 16 | var createdonbehalfby = new LookupAttributeMetadata() 17 | { 18 | SchemaName = "createdonbehalfby", 19 | LogicalName = "createdonbehalfby" 20 | }; 21 | yield return createdonbehalfby; 22 | var createdby = new LookupAttributeMetadata() 23 | { 24 | SchemaName = "createdby", 25 | LogicalName = "createdby" 26 | }; 27 | yield return createdby; 28 | var modifiedon = new DateTimeAttributeMetadata(DateTimeFormat.DateAndTime, "modifiedon") 29 | { 30 | LogicalName = "modifiedon" 31 | }; 32 | yield return modifiedon; 33 | var modifiedonbehalfby = new LookupAttributeMetadata() 34 | { 35 | SchemaName = "modifiedonbehalfby", 36 | LogicalName = "modifiedonbehalfby" 37 | }; 38 | yield return modifiedonbehalfby; 39 | var modifiedby = new LookupAttributeMetadata() 40 | { 41 | SchemaName = "modifiedby", 42 | LogicalName = "modifiedby" 43 | }; 44 | yield return modifiedby; 45 | var overridencreatedon = new DateTimeAttributeMetadata(DateTimeFormat.DateAndTime, "overridencreatedon") 46 | { 47 | LogicalName = "overridencreatedon" 48 | }; 49 | yield return overridencreatedon; 50 | var overridencreatedby = new LookupAttributeMetadata() 51 | { 52 | SchemaName = "overridencreatedby", 53 | LogicalName = "overridencreatedby" 54 | }; 55 | yield return overridencreatedby; 56 | var statecode = new StateAttributeMetadata() 57 | { 58 | SchemaName = "statecode", 59 | LogicalName = "statecode" 60 | }; 61 | yield return statecode; 62 | } 63 | 64 | public static IEnumerable GetProcessMetadata() 65 | { 66 | var stageid = new UniqueIdentifierAttributeMetadata("StageId") 67 | { 68 | LogicalName = "stageid" 69 | }; 70 | stageid.SetSealedPropertyValue(nameof(stageid.IsValidForCreate), true); 71 | yield return stageid; 72 | var processid = new UniqueIdentifierAttributeMetadata("ProcessId") 73 | { 74 | LogicalName = "processid" 75 | }; 76 | processid.SetSealedPropertyValue(nameof(processid.IsValidForCreate), true); 77 | yield return processid; 78 | } 79 | 80 | public static IEnumerable GetOwnerMetadata() 81 | { 82 | var ownerid = new LookupAttributeMetadata() 83 | { 84 | SchemaName = "ownerid", 85 | LogicalName = "ownerid" 86 | }; 87 | yield return ownerid; 88 | } 89 | } 90 | } 91 | -------------------------------------------------------------------------------- /Dataverse.Sdk.Extensions/Dataverse.Sdk.Extensions.Tests/Properties/AssemblyInfo.cs: -------------------------------------------------------------------------------- 1 | using System.Reflection; 2 | using System.Runtime.CompilerServices; 3 | using System.Runtime.InteropServices; 4 | 5 | // General Information about an assembly is controlled through the following 6 | // set of attributes. Change these attribute values to modify the information 7 | // associated with an assembly. 8 | [assembly: AssemblyTitle("Dataverse.Sdk.Extensions.Samples.Tests")] 9 | [assembly: AssemblyDescription("")] 10 | [assembly: AssemblyConfiguration("")] 11 | [assembly: AssemblyCompany("")] 12 | [assembly: AssemblyProduct("Dataverse.Sdk.Extensions.Samples.Tests")] 13 | [assembly: AssemblyCopyright("Copyright © 2021")] 14 | [assembly: AssemblyTrademark("")] 15 | [assembly: AssemblyCulture("")] 16 | 17 | // Setting ComVisible to false makes the types in this assembly not visible 18 | // to COM components. If you need to access a type in this assembly from 19 | // COM, set the ComVisible attribute to true on that type. 20 | [assembly: ComVisible(false)] 21 | 22 | // The following GUID is for the ID of the typelib if this project is exposed to COM 23 | [assembly: Guid("6b5d2f34-e85c-4cbb-af53-4e2c12a7d1b9")] 24 | 25 | // Version information for an assembly consists of the following four values: 26 | // 27 | // Major Version 28 | // Minor Version 29 | // Build Number 30 | // Revision 31 | // 32 | // You can specify all the values or you can default the Build and Revision Numbers 33 | // by using the '*' as shown below: 34 | // [assembly: AssemblyVersion("1.0.*")] 35 | [assembly: AssemblyVersion("1.0.0.0")] 36 | [assembly: AssemblyFileVersion("1.0.0.0")] 37 | -------------------------------------------------------------------------------- /Dataverse.Sdk.Extensions/Dataverse.Sdk.Extensions.Tests/SystemTypesTests.cs: -------------------------------------------------------------------------------- 1 | using Dataverse.Sdk.Extensions.Tests.EarlyBoundEntities; 2 | using System; 3 | using Xunit; 4 | 5 | namespace Dataverse.Sdk.Extensions.Tests 6 | { 7 | public class SystemTypesTests 8 | { 9 | [Fact] 10 | public void ToEntityReference_Can_Convert_Guid_To_EntityReference() 11 | { 12 | //Arrange 13 | var entity = "account"; 14 | var guid = Guid.NewGuid(); 15 | 16 | //Act 17 | var entityReference = guid.ToEntityReference(entity); 18 | 19 | //Assert 20 | Assert.Equal(entity, entityReference.LogicalName); 21 | Assert.Equal(guid, entityReference.Id); 22 | } 23 | 24 | [Fact] 25 | public void ToEntityReference_Can_Convert_Guid_To_EarlyBound_EntityReference() 26 | { 27 | //Arrange 28 | var guid = Guid.NewGuid(); 29 | 30 | //Act 31 | var entityReference = guid.ToEntityReference(); 32 | 33 | //Assert 34 | Assert.Equal(Account.EntityLogicalName, entityReference.LogicalName); 35 | Assert.Equal(guid, entityReference.Id); 36 | } 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /Dataverse.Sdk.Extensions/Dataverse.Sdk.Extensions.Tests/ToStringDebugTests.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | using Dataverse.Sdk.Extensions.Tests.EarlyBoundEntities; 4 | using Microsoft.Xrm.Sdk; 5 | using Xunit; 6 | 7 | namespace Dataverse.Sdk.Extensions.Tests 8 | { 9 | public class ToStringDebugTests 10 | { 11 | private void AssertAreEqualHandleSpaces(string expected, string actual, int tabSpaces = 2) 12 | { 13 | var space = new string(new []{ (char)160 }); // This is not a space, it is a Non-Breaking Space (alt+255). In the log things get trimmed, and this will prevent that from happening; 14 | expected = expected.Replace("\t", new string(' ', tabSpaces)).Replace("\r\n", "\n"); // The AppVeyor environment runs on Unix based environment, so this changes to handle new-line discrepancies. 15 | actual = actual.Replace(space, " ").Replace("\r\n", "\n"); 16 | 17 | if (!expected.Equals(actual)) 18 | { 19 | for (var i = 0; i < expected.Length && i < actual.Length; i++) 20 | { 21 | if (expected[i] != actual[i]) 22 | { 23 | Assert.Equal(expected, actual); 24 | } 25 | } 26 | } 27 | 28 | AssertAreSameLength(expected, actual); 29 | 30 | Assert.Equal(expected, actual); 31 | 32 | } 33 | 34 | private static void AssertAreSameLength(string expected, string actual) 35 | { 36 | if (expected.Length == actual.Length) 37 | { 38 | return; 39 | } 40 | 41 | var info = expected.Length < actual.Length 42 | ? new { Shorter = expected, ShorterName = "Expected", Longer = actual, LongerName = "Actual" } 43 | : new { Shorter = actual, ShorterName = "Actual", Longer = expected, LongerName = "Expected" }; 44 | 45 | var longer = info.Longer.Substring(0, info.Shorter.Length); 46 | if (longer == info.Shorter) 47 | { 48 | Assert.Equal(expected, actual); 49 | } 50 | } 51 | 52 | [Fact] 53 | public void Entity_Should_Show_Attributes() 54 | { 55 | // Arrange 56 | var account = new Account 57 | { 58 | Name = "MyName", 59 | AccountNumber = "XYZ", 60 | AccountCategoryCode = new OptionSetValue(1), 61 | ParentAccountId = new EntityReference("account", Guid.NewGuid()), 62 | Address1_Longitude = 123d, 63 | CreditLimit = new Money(10m) 64 | }; 65 | 66 | // Act 67 | var sut = account.ToStringDebug(); 68 | 69 | // Assert 70 | Assert.Equal( 71 | $@"{{ 72 |   Id: ""00000000-0000-0000-0000-000000000000"", 73 |   LogicalName: ""account"", 74 |   accountcategorycode: 1, 75 |   accountnumber: ""XYZ"", 76 |   address1_longitude: 123, 77 |   creditlimit: 10, 78 |   name: ""MyName"", 79 |   parentaccountid: {{LogicalName: ""account"", Id: ""{account.ParentAccountId.Id}""}} 80 | }}",sut); 81 | } 82 | 83 | 84 | [Fact] 85 | public void EntityImageCollection_Should_Show_Images() 86 | { 87 | var entity1 = new Contact { Id = Guid.NewGuid(), LastName = "Doe" }; 88 | var sut = new EntityImageCollection 89 | { 90 | { "PreImage1", entity1 } 91 | }; 92 | 93 | AssertAreEqualHandleSpaces($@"PreImage_{entity1.LogicalName}_{entity1.Id:N}: {{ 94 | contactid: ""{entity1.Id}"", 95 | lastname: ""Doe"" 96 | }}", sut.ToStringDebug("PreImage")); 97 | 98 | 99 | var entity2 = new Contact { Id = Guid.NewGuid(), FirstName = "John" }; 100 | sut.Add("PreImage2", entity2); 101 | 102 | AssertAreEqualHandleSpaces($@"PreImage: {{ 103 | PreImage1: {{ 104 | Id: ""{entity1.Id}"", 105 | LogicalName: ""contact"", 106 | contactid: ""{entity1.Id}"", 107 | lastname: ""Doe"" 108 | }}, 109 | PreImage2: {{ 110 | Id: ""{entity2.Id}"", 111 | LogicalName: ""contact"", 112 | contactid: ""{entity2.Id}"", 113 | firstname: ""John"" 114 | }} 115 | }}", sut.ToStringDebug("PreImage")); 116 | 117 | 118 | } 119 | 120 | [Fact] 121 | public void EntityReference_Should_Show_Values() 122 | { 123 | var sut = new EntityReference 124 | { 125 | Id = Guid.NewGuid(), 126 | LogicalName = Lead.EntityLogicalName 127 | }; 128 | 129 | Assert.Equal($"{{LogicalName: \"{sut.LogicalName}\", Id: \"{sut.Id}\"}}", sut.ToStringDebug()); 130 | 131 | sut.Name = "Test"; 132 | Assert.Equal($"{{Name: \"{sut.Name}\", LogicalName: \"{sut.LogicalName}\", Id: \"{sut.Id}\"}}", sut.ToStringDebug()); 133 | } 134 | 135 | #region Entity.ToStringAttributes 136 | 137 | [Fact] 138 | public void Entity_Should_Handle_Bool() 139 | { 140 | var sut = new Contact 141 | { 142 | CreditOnHold = true, 143 | DoNotBulkEMail = false, 144 | DoNotEMail = null 145 | }; 146 | AssertAreEqualHandleSpaces($@"{{ 147 | creditonhold: {sut.CreditOnHold.ToString().ToLower()}, 148 | donotbulkemail: {sut.DoNotBulkEMail.ToString().ToLower()}, 149 | donotemail: null 150 | }}", sut.ToStringAttributes()); 151 | } 152 | 153 | [Fact] 154 | public void Entity_Should_Handle_ByteArray() 155 | { 156 | var sut = new Contact 157 | { 158 | EntityImage = new byte[] { 0, 2, 1 } 159 | }; 160 | AssertAreEqualHandleSpaces($@"{{ 161 | entityimage: {{length: 3}} 162 | }}", sut.ToStringAttributes()); 163 | } 164 | 165 | [Fact] 166 | public void Entity_Should_Handle_Date() 167 | { 168 | var sut = new Contact 169 | { 170 | Anniversary = DateTime.UtcNow, 171 | BirthDate = DateTime.UtcNow.AddDays(-1d), 172 | OverriddenCreatedOn = null 173 | }; 174 | AssertAreEqualHandleSpaces($@"{{ 175 | anniversary: ""{sut.Anniversary}"", 176 | birthdate: ""{sut.BirthDate}"", 177 | overriddencreatedon: null 178 | }}", sut.ToStringAttributes()); 179 | } 180 | 181 | [Fact] 182 | public void Entity_Should_Handle_Double() 183 | { 184 | var sut = new Contact 185 | { 186 | Address1_Latitude = 1.1, 187 | Address1_Longitude = 2.12, 188 | Address2_Latitude = null 189 | }; 190 | AssertAreEqualHandleSpaces($@"{{ 191 | address1_latitude: {sut.Address1_Latitude}, 192 | address1_longitude: {sut.Address1_Longitude}, 193 | address2_latitude: null 194 | }}", sut.ToStringAttributes()); 195 | } 196 | 197 | [Fact] 198 | public void Entity_Should_Handle_EntityRef() 199 | { 200 | var sut = new Contact 201 | { 202 | ParentCustomerId = new EntityReference(Account.EntityLogicalName, Guid.NewGuid()), 203 | CreatedBy = new EntityReference("systemuser",Guid.NewGuid()) 204 | { 205 | Name = "John Doe" 206 | } 207 | }; 208 | AssertAreEqualHandleSpaces($@"{{ 209 | createdby: {{Name: ""{sut.CreatedBy.Name}"", LogicalName: ""systemuser"", Id: ""{sut.CreatedBy.Id}""}}, 210 | parentcustomerid: {{LogicalName: ""account"", Id: ""{sut.ParentCustomerId.Id}""}} 211 | }}", sut.ToStringAttributes()); 212 | } 213 | 214 | [Fact] 215 | public void Entity_Should_Handle_Guid() 216 | { 217 | var sut = new Contact 218 | { 219 | Id = Guid.NewGuid() 220 | }; 221 | AssertAreEqualHandleSpaces($@"{{ 222 | contactid: ""{sut.Id}"" 223 | }}", sut.ToStringAttributes()); 224 | } 225 | 226 | 227 | [Fact] 228 | public void Entity_Should_Handle_Int() 229 | { 230 | var sut = new Contact 231 | { 232 | Address1_UTCOffset = 1, 233 | Address2_UTCOffset = -1, 234 | Address3_UTCOffset = null 235 | }; 236 | AssertAreEqualHandleSpaces($@"{{ 237 | address1_utcoffset: {sut.Address1_UTCOffset}, 238 | address2_utcoffset: {sut.Address2_UTCOffset}, 239 | address3_utcoffset: null 240 | }}", sut.ToStringAttributes()); 241 | } 242 | 243 | [Fact] 244 | public void Entity_Should_Handle_Money() 245 | { 246 | var sut = new Contact 247 | { 248 | AccountRoleCode = null, 249 | AnnualIncome = new Money(10m), 250 | CreditLimit = new Money(400m) 251 | }; 252 | AssertAreEqualHandleSpaces($@"{{ 253 | accountrolecode: null, 254 | annualincome: {sut.AnnualIncome.Value}, 255 | creditlimit: {sut.CreditLimit.Value} 256 | }}", sut.ToStringAttributes()); 257 | } 258 | 259 | 260 | [Fact] 261 | public void Entity_Should_Handle_Osv() 262 | { 263 | var sut = new Contact 264 | { 265 | Address1_AddressTypeCode = new OptionSetValue(1), 266 | AccountRoleCode = new OptionSetValue(2), 267 | Address1_FreightTermsCode = null 268 | }; 269 | AssertAreEqualHandleSpaces($@"{{ 270 | accountrolecode: {sut.AccountRoleCode.Value}, 271 | address1_addresstypecode: {sut.Address1_AddressTypeCode.Value}, 272 | address1_freighttermscode: null 273 | }}", sut.ToStringAttributes()); 274 | } 275 | 276 | [Fact] 277 | public void Entity_Should_Handle_String() 278 | { 279 | var sut = new Contact 280 | { 281 | FirstName = "In", 282 | LastName = "Dent" 283 | }; 284 | AssertAreEqualHandleSpaces(@"{ 285 | firstname: ""In"", 286 | lastname: ""Dent"" 287 | }", sut.ToStringAttributes()); 288 | } 289 | 290 | #endregion Entity.ToStringAttributes 291 | 292 | [Fact] 293 | public void ParameterCollection_Should_Display_Values() 294 | { 295 | var now = DateTime.UtcNow; 296 | var ids = new List 297 | { 298 | Guid.NewGuid(), 299 | Guid.NewGuid(), 300 | Guid.NewGuid(), 301 | Guid.NewGuid(), 302 | Guid.NewGuid(), 303 | Guid.NewGuid() 304 | }; 305 | var sut = new ParameterCollection 306 | { 307 | {"EntityRef", new EntityReference(Lead.EntityLogicalName, ids[0])}, 308 | { 309 | "EntityRefCollection", new EntityReferenceCollection(new List 310 | { 311 | new EntityReference(Lead.EntityLogicalName, ids[1]), 312 | new EntityReference(Contact.EntityLogicalName, ids[2]), 313 | new EntityReference(Account.EntityLogicalName, ids[3]) 314 | }) 315 | }, 316 | {"IEnumerable", new List {"v1", "v2", "v3"}}, 317 | { 318 | "EntityCollection", new EntityCollection(new List 319 | { 320 | new Lead {Id = ids[4], FirstName = "Great"}, 321 | new Contact {Id = ids[5], LastName = "Good"} 322 | }) 323 | }, 324 | {"OSV", new OptionSetValue(1)}, 325 | {"Entity", new Contact {ManagerName = "Owner", BirthDate = now}}, 326 | { 327 | "Dict", new Dictionary 328 | { 329 | {"Key1", "Value1"}, 330 | {"Key2", "Value2"} 331 | } 332 | } 333 | }; 334 | 335 | AssertAreEqualHandleSpaces($@"InputParameters: {{ 336 | Dict: {{ 337 | Key1: ""Value1"", 338 | Key2: ""Value2"" 339 | }}, 340 | Entity: {{ 341 | birthdate: ""{now}"", 342 | managername: ""Owner"" 343 | }}, 344 | EntityCollection: [ 345 | {{ 346 | firstname: ""Great"", 347 | leadid: ""{ids[4]}"" 348 | }}, 349 | {{ 350 | contactid: ""{ids[5]}"", 351 | lastname: ""Good"" 352 | }} 353 | ], 354 | EntityRef: {{LogicalName: ""lead"", Id: ""{ids[0]}""}}, 355 | EntityRefCollection: [ 356 | {{LogicalName: ""lead"", Id: ""{ids[1]}""}}, 357 | {{LogicalName: ""contact"", Id: ""{ids[2]}""}}, 358 | {{LogicalName: ""account"", Id: ""{ids[3]}""}} 359 | ], 360 | IEnumerable: {{ 361 | ""List`1"": [ 362 | ""v1"", 363 | ""v2"", 364 | ""v3"" 365 | ] 366 | }}, 367 | OSV: 1 368 | }}", sut.ToStringDebug("InputParameters")); 369 | 370 | } 371 | 372 | [Fact] 373 | public void ParameterCollection_Should_Display_Parameters() 374 | { 375 | // Entities only collections should not indent. 376 | var contact = new Contact 377 | { 378 | Id = Guid.NewGuid(), 379 | AccountRoleCode = new OptionSetValue(1) 380 | }; 381 | var sut = new ParameterCollection 382 | { 383 | {"Target", contact} 384 | }; 385 | AssertAreEqualHandleSpaces($@"InputParameters: {{ 386 | Target: {{ 387 | accountrolecode: 1, 388 | contactid: ""{contact.Id}"" 389 | }} 390 | }}", sut.ToStringDebug("InputParameters")); 391 | } 392 | } 393 | } 394 | -------------------------------------------------------------------------------- /Dataverse.Sdk.Extensions/Dataverse.Sdk.Extensions.Tests/app.config: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | -------------------------------------------------------------------------------- /Dataverse.Sdk.Extensions/Dataverse.Sdk.Extensions.Tests/packages.config: -------------------------------------------------------------------------------- 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 | -------------------------------------------------------------------------------- /Dataverse.Sdk.Extensions/Dataverse.Sdk.Extensions.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio 15 4 | VisualStudioVersion = 15.0.28307.1145 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{D954291E-2A0B-460D-934E-DC6B0785DB48}") = "Dataverse.Sdk.Extensions", "Dataverse.Sdk.Extensions\Dataverse.Sdk.Extensions.shproj", "{B80203FC-9038-4596-9484-1031F2912BDF}" 7 | EndProject 8 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Dataverse.Sdk.Extensions.Samples", "Dataverse.Sdk.Extensions.Samples\Dataverse.Sdk.Extensions.Samples.csproj", "{67DFD80E-FB87-431D-A48D-D3C73CABDFA1}" 9 | EndProject 10 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Dataverse.Sdk.Extensions.Tests", "Dataverse.Sdk.Extensions.Tests\Dataverse.Sdk.Extensions.Tests.csproj", "{6B5D2F34-E85C-4CBB-AF53-4E2C12A7D1B9}" 11 | EndProject 12 | Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution Items", "{D6230D62-D625-49D9-A9C5-A47968F461CE}" 13 | ProjectSection(SolutionItems) = preProject 14 | Coverage.bat = Coverage.bat 15 | NuGet Package\Dataverse.Sdk.Extensions.nuspec = NuGet Package\Dataverse.Sdk.Extensions.nuspec 16 | NuGet Package\Dataverse.Sdk.Extensions.targets = NuGet Package\Dataverse.Sdk.Extensions.targets 17 | EndProjectSection 18 | EndProject 19 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "Dataverse.Sdk.Extensions.ForCoverage", "Dataverse.Sdk.Extensions.ForCoverage\Dataverse.Sdk.Extensions.ForCoverage.csproj", "{D8E26203-DC67-4AF7-BC3C-074FB323A3B7}" 20 | EndProject 21 | Global 22 | GlobalSection(SharedMSBuildProjectFiles) = preSolution 23 | Dataverse.Sdk.Extensions\Dataverse.Sdk.Extensions.projitems*{67dfd80e-fb87-431d-a48d-d3c73cabdfa1}*SharedItemsImports = 4 24 | Dataverse.Sdk.Extensions\Dataverse.Sdk.Extensions.projitems*{b80203fc-9038-4596-9484-1031f2912bdf}*SharedItemsImports = 13 25 | Dataverse.Sdk.Extensions\Dataverse.Sdk.Extensions.projitems*{d8e26203-dc67-4af7-bc3c-074fb323a3b7}*SharedItemsImports = 4 26 | EndGlobalSection 27 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 28 | Debug|Any CPU = Debug|Any CPU 29 | Release|Any CPU = Release|Any CPU 30 | EndGlobalSection 31 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 32 | {67DFD80E-FB87-431D-A48D-D3C73CABDFA1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 33 | {67DFD80E-FB87-431D-A48D-D3C73CABDFA1}.Debug|Any CPU.Build.0 = Debug|Any CPU 34 | {67DFD80E-FB87-431D-A48D-D3C73CABDFA1}.Release|Any CPU.ActiveCfg = Release|Any CPU 35 | {67DFD80E-FB87-431D-A48D-D3C73CABDFA1}.Release|Any CPU.Build.0 = Release|Any CPU 36 | {6B5D2F34-E85C-4CBB-AF53-4E2C12A7D1B9}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 37 | {6B5D2F34-E85C-4CBB-AF53-4E2C12A7D1B9}.Debug|Any CPU.Build.0 = Debug|Any CPU 38 | {6B5D2F34-E85C-4CBB-AF53-4E2C12A7D1B9}.Release|Any CPU.ActiveCfg = Release|Any CPU 39 | {6B5D2F34-E85C-4CBB-AF53-4E2C12A7D1B9}.Release|Any CPU.Build.0 = Release|Any CPU 40 | {D8E26203-DC67-4AF7-BC3C-074FB323A3B7}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 41 | {D8E26203-DC67-4AF7-BC3C-074FB323A3B7}.Debug|Any CPU.Build.0 = Debug|Any CPU 42 | {D8E26203-DC67-4AF7-BC3C-074FB323A3B7}.Release|Any CPU.ActiveCfg = Release|Any CPU 43 | {D8E26203-DC67-4AF7-BC3C-074FB323A3B7}.Release|Any CPU.Build.0 = Release|Any CPU 44 | EndGlobalSection 45 | GlobalSection(SolutionProperties) = preSolution 46 | HideSolutionNode = FALSE 47 | EndGlobalSection 48 | GlobalSection(ExtensibilityGlobals) = postSolution 49 | SolutionGuid = {8173C9ED-EE77-4DA1-9692-90D88C461771} 50 | EndGlobalSection 51 | EndGlobal 52 | -------------------------------------------------------------------------------- /Dataverse.Sdk.Extensions/Dataverse.Sdk.Extensions/Dataverse.Sdk.Extensions.projitems: -------------------------------------------------------------------------------- 1 |  2 | 3 | 4 | $(MSBuildAllProjects);$(MSBuildThisFileFullPath) 5 | true 6 | b80203fc-9038-4596-9484-1031f2912bdf 7 | 8 | 9 | Dataverse.Sdk.Extensions 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | -------------------------------------------------------------------------------- /Dataverse.Sdk.Extensions/Dataverse.Sdk.Extensions/Dataverse.Sdk.Extensions.shproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | b80203fc-9038-4596-9484-1031f2912bdf 5 | 14.0 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | -------------------------------------------------------------------------------- /Dataverse.Sdk.Extensions/Dataverse.Sdk.Extensions/EntityExtensions.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.Xrm.Sdk; 2 | using Microsoft.Xrm.Sdk.Messages; 3 | using Microsoft.Xrm.Sdk.Metadata.Query; 4 | using System; 5 | using System.Collections.Generic; 6 | using System.Linq; 7 | using System.Linq.Expressions; 8 | using System.Reflection; 9 | 10 | namespace Dataverse.Sdk.Extensions 11 | { 12 | public static class EntityExtensions 13 | { 14 | /// 15 | /// Get value of an attribute from a linked entity 16 | /// 17 | /// Type of the attribute to get 18 | /// Record containing the attribute 19 | /// Alias of the linked entity 20 | /// Logical name of the attribute 21 | /// Value of the attribute 22 | public static T GetAliasedValue(this Entity record, string alias, string attribute) 23 | { 24 | var aliasedAttribute = $"{alias}.{attribute}"; 25 | 26 | if (!record.Contains(aliasedAttribute)) 27 | { 28 | return default(T); 29 | } 30 | 31 | var aliasedValue = record.GetAttributeValue(aliasedAttribute); 32 | 33 | if (!(aliasedValue.Value is T)) 34 | { 35 | var message = $"The attribute {aliasedValue.AttributeLogicalName} in entity {aliasedValue.EntityLogicalName} is not of type {typeof(T)}"; 36 | throw new InvalidCastException(message); 37 | } 38 | 39 | return (T)aliasedValue.Value; 40 | } 41 | 42 | /// 43 | /// Adds a party to the activity entity 44 | /// 45 | /// Activity entity 46 | /// Logical name of the party list column 47 | /// Reference to the record to add as a party 48 | public static void AddParty(this Entity record, string columnName, EntityReference partyReference) 49 | { 50 | if (!record.Contains(columnName)) 51 | { 52 | record[columnName] = new EntityCollection(); 53 | } 54 | 55 | record.GetAttributeValue(columnName).Entities.Add( 56 | new Entity("activityparty") 57 | { 58 | Attributes = 59 | { 60 | {"partyid", partyReference } 61 | } 62 | }); 63 | } 64 | 65 | /// 66 | /// Adds parties to the activity entity 67 | /// 68 | /// Activity entity 69 | /// Logical name of the party list column 70 | /// Reference to the record to add as a party 71 | public static void AddParties(this Entity record, string columnName, params EntityReference[] partiesReferences) 72 | { 73 | if (!partiesReferences.Any()) 74 | { 75 | throw new ArgumentException("AddParties requires at least one item", nameof(partiesReferences)); 76 | } 77 | 78 | foreach (var partyReference in partiesReferences) 79 | { 80 | record.AddParty(columnName, partyReference); 81 | } 82 | } 83 | 84 | /// 85 | /// Set a party to the activity entity 86 | /// 87 | /// 88 | /// This method replaces existing party list with the specified party 89 | /// reference 90 | /// 91 | /// Activity entity 92 | /// Logical name of the party list column 93 | /// Reference to the record to add as a party 94 | public static void SetParty(this Entity record, string columnName, EntityReference partyReference) 95 | { 96 | record[columnName] = new EntityCollection(new List{ 97 | new Entity("activityparty") 98 | { 99 | Attributes = 100 | { 101 | {"partyid", partyReference } 102 | } 103 | } 104 | }); 105 | } 106 | 107 | /// 108 | /// Adds parties to the activity entity 109 | /// 110 | /// Activity entity 111 | /// Logical name of the party list column 112 | /// References to the records to add as a party 113 | public static void SetParties(this Entity record, string columnName, params EntityReference[] partiesReferences) 114 | { 115 | if (!partiesReferences.Any()) 116 | { 117 | throw new ArgumentException("SetParties requires at least one item", nameof(partiesReferences)); 118 | } 119 | 120 | record.SetParty(columnName, partiesReferences.First()); 121 | 122 | foreach (var partyReference in partiesReferences.Skip(1)) 123 | { 124 | record.AddParty(columnName, partyReference); 125 | } 126 | } 127 | 128 | /// 129 | /// Clone a row 130 | /// 131 | /// Dataverse row 132 | /// Dataverse Organization Service 133 | /// Indicates if a "(clone)" text must be added in the newly created row name 134 | /// Specific columns to exclude when cloning the row 135 | /// Cloned row 136 | public static Entity Clone(this Entity row, IOrganizationService service, bool addCloneLabel = true, params string[] columnsToRemove) 137 | { 138 | // There are specific columns we don't want to clone anyway 139 | var standardToRemove = new[] { "createdon", "createdonbehalfby", "createdby", "modifiedon", "modifiedonbehalfby", "modifiedby", "overridencreatedon", "overridencreatedby", "ownerid" }; 140 | var toRemove = standardToRemove.Concat(columnsToRemove).ToArray(); 141 | 142 | // Query metadata for the table to understand what columns are valid for create 143 | var mdQuery = new EntityQueryExpression 144 | { 145 | Properties = new MetadataPropertiesExpression("Attributes", "PrimaryIdAttribute", "PrimaryNameAttribute"), 146 | Criteria = new MetadataFilterExpression 147 | { 148 | Conditions = 149 | { 150 | new MetadataConditionExpression("LogicalName", MetadataConditionOperator.Equals, 151 | row.LogicalName) 152 | } 153 | }, 154 | AttributeQuery = new AttributeQueryExpression 155 | { 156 | Properties = new MetadataPropertiesExpression("IsValidForCreate", "LogicalName") 157 | } 158 | }; 159 | 160 | var response = (RetrieveMetadataChangesResponse)service.Execute(new RetrieveMetadataChangesRequest 161 | { 162 | Query = mdQuery, 163 | ClientVersionStamp = null 164 | }); 165 | 166 | var cloned = new Entity(row.LogicalName); 167 | 168 | // Processing columns 169 | foreach (var column in response.EntityMetadata.First().Attributes) 170 | { 171 | // Do not add columns to remove 172 | if (toRemove.Contains(column.LogicalName)) 173 | { 174 | continue; 175 | } 176 | 177 | // Do not add primary column, which is the unique identifier 178 | if (column.LogicalName == response.EntityMetadata.First().PrimaryIdAttribute) 179 | { 180 | continue; 181 | } 182 | 183 | // If the column is the primary column, process adding additional "(clone)" text 184 | if (column.LogicalName == response.EntityMetadata.First().PrimaryNameAttribute) 185 | { 186 | cloned[column.LogicalName] = $"{row.GetAttributeValue(column.LogicalName)}{(addCloneLabel ? " (clone)" : "")}"; 187 | continue; 188 | } 189 | 190 | // Process column only if it's valid for create 191 | if ((column.IsValidForCreate ?? false) && row.Contains(column.LogicalName)) 192 | { 193 | if (row[column.LogicalName] is Guid) 194 | { 195 | continue; 196 | } 197 | 198 | cloned[column.LogicalName] = row[column.LogicalName]; 199 | } 200 | } 201 | 202 | return cloned; 203 | } 204 | 205 | /// 206 | /// Indicates if the table row contains columns that have been reseted 207 | /// 208 | /// 209 | /// bool containsNullValue = account.ContainsNullValue(a => a.Name, a => a.AccountNumber); 210 | /// 211 | /// Type of the table 212 | /// Table row 213 | /// Columns to check for null value 214 | /// True if all columns specified are present in the table row with a null value 215 | public static bool ContainsNullValue(this T record, params Expression>[] columns) where T : Entity 216 | { 217 | return record.ContainsNullValue(columns.Select(c => GetLogicalName(c.Body)).ToArray()); 218 | } 219 | 220 | /// 221 | /// Indicates if the table row contains columns that have been reseted 222 | /// 223 | /// 224 | /// bool containsNullValue = account.ContainsNullValue("name", "accountnumber"); 225 | /// 226 | /// Table row 227 | /// Columns to check for null value 228 | /// True if all columns specified are present in the table row with a null value 229 | public static bool ContainsNullValue(this Entity record, params string[] columns) 230 | { 231 | bool result = true; 232 | 233 | foreach (var column in columns) 234 | { 235 | result &= record.Contains(column) && record[column] == null; 236 | } 237 | 238 | return result; 239 | } 240 | 241 | /// 242 | /// Indicates if the table row contains columns that have a value not null 243 | /// 244 | /// 245 | /// bool containsNullValue = account.ContainsValue(a => a.Name, a => a.AccountNumber); 246 | /// 247 | /// Type of the table 248 | /// Table row 249 | /// Columns to check for not null value 250 | /// True if all columns specified are present in the table row with a value different from null 251 | public static bool ContainsValue(this T record, params Expression>[] columns) where T : Entity 252 | { 253 | return record.ContainsValue(columns.Select(c => GetLogicalName(c.Body)).ToArray()); 254 | } 255 | 256 | /// 257 | /// Indicates if the table row contains columns that have a value not null 258 | /// 259 | /// 260 | /// bool containsNullValue = account.ContainsValue("name", "accountnumber"); 261 | /// 262 | /// Table row 263 | /// Columns to check for not null value 264 | /// True if all columns specified are present in the table row with a value different from null 265 | public static bool ContainsValue(this Entity record, params string[] columns) 266 | { 267 | bool result = true; 268 | 269 | foreach (var column in columns) 270 | { 271 | result &= record.Contains(column) && record[column] != null; 272 | } 273 | 274 | return result; 275 | } 276 | 277 | private static string GetLogicalName(Expression expr) 278 | { 279 | MemberExpression me = expr as MemberExpression; 280 | var pi = (PropertyInfo)me.Member; 281 | return pi.GetCustomAttribute().LogicalName; 282 | } 283 | } 284 | } -------------------------------------------------------------------------------- /Dataverse.Sdk.Extensions/Dataverse.Sdk.Extensions/EntityReferenceExtensions.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.Xrm.Sdk; 2 | 3 | namespace Dataverse.Sdk.Extensions 4 | { 5 | public static class EntityReferenceExtensions 6 | { 7 | /// 8 | /// Returns the Name and Id of an entity reference in a format "Name (id)" (default) if it has a name, and "(id)" if it has no name. 9 | /// 10 | /// 11 | /// The format to use when displaying the name and id. {0} is the name of the entity reference, {1} is the Guid and {2} is the logical name. 12 | /// The format to use when displaying the name id. {0} is the name of the entity reference, {1} is the Guid and {2} is the logical name. 13 | /// The value to use when the entity reference is null.. 14 | /// 15 | public static string GetNameId(this EntityReference entity, string formatNonEmptyName = "{0} ({1})", string formatEmptyName = "{1}", string nullFormat = "null") 16 | { 17 | if (entity == null) 18 | { 19 | return nullFormat; 20 | } 21 | 22 | return string.IsNullOrWhiteSpace(entity.Name) 23 | ? string.Format(formatEmptyName, entity.Name, entity.Id, entity.LogicalName) 24 | : string.Format(formatNonEmptyName, entity.Name, entity.Id, entity.LogicalName); 25 | } 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /Dataverse.Sdk.Extensions/Dataverse.Sdk.Extensions/IOrganizationServiceExtensions.cs: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/Power-Platform-Patterns-and-Practices/Dataverse.Sdk.Extensions/ac816cd660666699413f4aeb9dfa2c605db780b8/Dataverse.Sdk.Extensions/Dataverse.Sdk.Extensions/IOrganizationServiceExtensions.cs -------------------------------------------------------------------------------- /Dataverse.Sdk.Extensions/Dataverse.Sdk.Extensions/Readme.md: -------------------------------------------------------------------------------- 1 | List of extensions class and methods 2 | 3 | - [EntityExtensions](https://github.com/Power-Platform-Patterns-and-Practices/Dataverse.Sdk.Extensions/blob/main/Dataverse.Sdk.Extensions/Dataverse.Sdk.Extensions/EntityExtensions.cs) : 4 | - AddParty : Add activity party to an activity table row 5 | - AddParties : Add activity parties to an activity table row 6 | - ContainsNullValue : Check if specified columns are present in a table row with null value (ie. if they have been emptied) 7 | - ContainsValue : Check if specified columns are present in a table row with not null value (ie. if they have been set) 8 | - GetAliasedValue : Get value of an attribute from a linked entity 9 | - Clone : Clone a row 10 | - SetParty : Set activity party to an activity table row (ie. empty then add activity party) 11 | - SetParties : Add activity parties to an activity table row (ie. empty then add activity parties) 12 | 13 | - [IOrganizationServiceExtensions](https://github.com/Power-Platform-Patterns-and-Practices/Dataverse.Sdk.Extensions/blob/main/Dataverse.Sdk.Extensions/Dataverse.Sdk.Extensions/IOrganizationServiceExtensions.cs): 14 | - CreateFromInitialization : Creates a table row from another table row using standard columns mapping 15 | - Delete : Deletes a row by its reference 16 | - Delete : Deletes a row directly 17 | - Delete : Deletes a row using its alternate key(s) 18 | - GetCurrentUserRoles : Gets the list of current user affected roles 19 | - GetEnvironmentVariable : Retrieves an Environment variable value 20 | - GetEnvironmentVariables : Retrieves multiple Environment variables values 21 | - Upsert : Creates or Updates a row, depending if it already exists in the targeted environment 22 | 23 | - [SystemTypesExtensions](https://github.com/Power-Platform-Patterns-and-Practices/Dataverse.Sdk.Extensions/blob/main/Dataverse.Sdk.Extensions/Dataverse.Sdk.Extensions/SystemTypesExtensions.cs) : 24 | - ToEntityReference : Returns a reference to an entity based on an unique identifier 25 | 26 | -------------------------------------------------------------------------------- /Dataverse.Sdk.Extensions/Dataverse.Sdk.Extensions/SystemTypesExtensions.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.Xrm.Sdk; 2 | using System; 3 | 4 | namespace Dataverse.Sdk.Extensions 5 | { 6 | public static class SystemTypesExtensions 7 | { 8 | /// 9 | /// Returns a reference to an entity based on an unique identifier 10 | /// 11 | /// Unique identifier 12 | /// Logical name of the entity to reference 13 | /// Reference to the entity with provided id 14 | public static EntityReference ToEntityReference(this Guid id, string entityLogicalName) 15 | { 16 | return new EntityReference(entityLogicalName, id); 17 | } 18 | 19 | /// 20 | /// Returns a reference to an entity based on an unique identifier 21 | /// 22 | /// Unique identifier 23 | /// Logical name of the entity to reference 24 | /// Reference to the entity with provided id 25 | public static EntityReference ToEntityReference(this Guid id) where T : Entity 26 | { 27 | var entityLogicalName = typeof(T).GetField("EntityLogicalName").GetRawConstantValue().ToString(); 28 | 29 | return new EntityReference(entityLogicalName, id); 30 | } 31 | } 32 | } -------------------------------------------------------------------------------- /Dataverse.Sdk.Extensions/Dataverse.Sdk.Extensions/ToStringDebugExtensions.cs: -------------------------------------------------------------------------------- 1 | using Microsoft.Xrm.Sdk; 2 | using System; 3 | using System.Collections; 4 | using System.Collections.Generic; 5 | using System.Configuration; 6 | using System.Globalization; 7 | using System.Linq; 8 | 9 | namespace Dataverse.Sdk.Extensions 10 | 11 | { 12 | public static class ToStringDebugExtensions 13 | { 14 | 15 | #region byte[] 16 | 17 | /// 18 | /// Returns the length of the number of byte array 19 | /// 20 | /// The Byte Array. 21 | public static string ToStringDebug(this byte[] bits) 22 | { 23 | if (bits == null) 24 | { 25 | return "null"; 26 | } 27 | 28 | return "{length: " + bits.Length + "}"; 29 | } 30 | 31 | #endregion byte[] 32 | 33 | #region DataCollection 34 | 35 | private static IEnumerable ToStringDebug(this DataCollection items, StringDebugInfo info) 36 | { 37 | foreach (var item in items.OrderBy(kvp => kvp.Key)) 38 | { 39 | yield return item.Key + ": " + ObjectToStringDebug(item.Value, info).TrimStart(); 40 | } 41 | } 42 | 43 | private static string ObjectToStringDebug(object obj, StringDebugInfo info) 44 | { 45 | string value; 46 | switch (obj) 47 | { 48 | case null: 49 | value = "null"; 50 | break; 51 | 52 | case Entity entity: 53 | value = entity.ToStringAttributes(info); 54 | break; 55 | 56 | case EntityReference entityRef: 57 | value = entityRef.ToStringDebug(); 58 | break; 59 | 60 | case EntityCollection entities: 61 | value = entities.ToStringDebug(info); 62 | break; 63 | 64 | case EntityReferenceCollection entityRefCollection: 65 | value = entityRefCollection.ToStringDebug(info); 66 | break; 67 | 68 | case Dictionary dict: 69 | value = dict.ToStringDebug(info); 70 | break; 71 | 72 | case byte[] imageArray: 73 | value = imageArray.ToStringDebug(); 74 | break; 75 | 76 | case IEnumerable enumerable when !(enumerable is string): 77 | value = enumerable.ToStringDebug(info); 78 | break; 79 | 80 | case OptionSetValue optionSet: 81 | value = optionSet.Value.ToString(CultureInfo.InvariantCulture); 82 | break; 83 | 84 | case Money money: 85 | value = money.Value.ToString(CultureInfo.InvariantCulture); 86 | break; 87 | 88 | case bool yesNo: 89 | value = yesNo 90 | ? "true" 91 | : "false"; 92 | break; 93 | 94 | default: 95 | value = obj.IsNumeric() 96 | ? obj.ToString() 97 | : $"\"{obj}\""; 98 | break; 99 | } 100 | 101 | return value; 102 | } 103 | 104 | #endregion DataCollection 105 | 106 | #region Dictionary 107 | 108 | /// 109 | /// Iterates and displays the values of the dictionary. 110 | /// 111 | /// The dictionary. 112 | /// Optional arguments. 113 | public static string ToStringDebug(this Dictionary dict, StringDebugInfo info = null) 114 | { 115 | return Wrap("{", 116 | dict.Select(e => $@"{e.Key}: ""{e.Value}"""), 117 | "}", 118 | info); 119 | } 120 | 121 | #endregion Dictionary 122 | 123 | #region Entity 124 | 125 | /// 126 | /// Iterates and displays the attributes listed in the entity's Attributes collection. 127 | /// 128 | /// The entity. 129 | /// Optional arguments. 130 | public static string ToStringAttributes(this Entity entity, StringDebugInfo info = null) 131 | { 132 | info = info ?? StringDebugInfo.Default; 133 | if (entity == null) 134 | { 135 | return info.Indent + "null"; 136 | } 137 | 138 | return Wrap("{", 139 | entity.Attributes.ToStringDebug(info), 140 | "}", 141 | info); 142 | } 143 | 144 | /// 145 | /// Iterates and displays the attributes listed in the entity's Attributes collection as well as the Id and LogicalName. 146 | /// 147 | /// The entity. 148 | /// Optional arguments. 149 | public static string ToStringDebug(this Entity entity, StringDebugInfo info = null) 150 | { 151 | info = info ?? StringDebugInfo.Default; 152 | if (entity == null) 153 | { 154 | return info.Indent + "null"; 155 | } 156 | 157 | return Wrap("{", 158 | new[] 159 | { 160 | "Id: \"" + entity.Id + "\"", 161 | "LogicalName: \"" + entity.LogicalName + "\"" 162 | }.Concat( 163 | entity.Attributes.ToStringDebug(info) 164 | ), 165 | "}", 166 | info); 167 | } 168 | 169 | #endregion Entity 170 | 171 | #region EntityCollection 172 | 173 | /// 174 | /// Iterates and displays the entities in the entity collection. 175 | /// 176 | /// The collection. 177 | /// Optional arguments. 178 | public static string ToStringDebug(this EntityCollection collection, StringDebugInfo info = null) 179 | { 180 | info = info ?? StringDebugInfo.Default; 181 | if (collection == null) 182 | { 183 | return info.Indent + "null"; 184 | } 185 | 186 | var values = collection.Entities.Select(r => r.ToStringAttributes(info.IncreaseIndent()).TrimStart()); 187 | if (string.IsNullOrWhiteSpace(collection.EntityName)) 188 | { 189 | return Wrap("[", 190 | values, 191 | "]", 192 | info, 193 | string.Empty); 194 | } 195 | 196 | var prefix = info.SingleLine 197 | ? string.Empty 198 | : Environment.NewLine + info.Indent; 199 | 200 | var start = $"{{{prefix}{collection.EntityName}:{prefix}["; 201 | var end = info.SingleLine 202 | ? "]}" 203 | : $"]{Environment.NewLine + info.Indent}}}"; 204 | return Wrap(start, 205 | collection.Entities.Select(r => r.ToStringAttributes(info)), 206 | end, 207 | info, 208 | string.Empty); 209 | } 210 | 211 | #endregion EntityCollection 212 | 213 | #region EntityImageCollection 214 | 215 | /// 216 | /// Iterates and displays the entity images in the entity image collection. 217 | /// 218 | /// The images. 219 | /// The name. 220 | /// Optional arguments. 221 | public static string ToStringDebug(this EntityImageCollection images, string name, StringDebugInfo info = null) 222 | { 223 | info = info ?? StringDebugInfo.Default; 224 | if (images == null) 225 | { 226 | return info.Indent + name + ": null"; 227 | } 228 | 229 | 230 | if (images.Count == 1) 231 | { 232 | var kvp = images.First(); 233 | var id = kvp.Value?.Id == Guid.Empty 234 | ? string.Empty 235 | : "_" + kvp.Value?.LogicalName + "_" + kvp.Value?.Id.ToString("N"); 236 | return info.Indent + name + id + ": " + images.Values.First().ToStringAttributes(info).TrimStart(); 237 | } 238 | 239 | return Wrap(name + ": {", 240 | images.Select(v => v.Key + ": " + v.Value.ToStringDebug(info).TrimStart()), 241 | "}", 242 | info.WithNoTab(), 243 | string.Empty); 244 | } 245 | 246 | #endregion EntityImageCollection 247 | 248 | #region EntityReference 249 | 250 | /// 251 | /// Returns the Logical Name, Name, and Id of the EntityReference 252 | /// 253 | /// The EntityReference. 254 | /// 255 | public static string ToStringDebug(this EntityReference entity) 256 | { 257 | if (entity == null) 258 | { 259 | return "null"; 260 | } 261 | 262 | var required = $"LogicalName: \"{entity.LogicalName}\", Id: \"{entity.Id}\""; 263 | var name = string.IsNullOrWhiteSpace(entity.Name) 264 | ? string.Empty 265 | : $"Name: \"{entity.Name}\", "; 266 | return "{" + name + required + "}"; 267 | } 268 | 269 | #endregion EntityReference 270 | 271 | #region EntityReferenceCollection 272 | 273 | /// 274 | /// Iterates and displays the entity references in the entity reference collection. 275 | /// 276 | /// The collection. 277 | /// Optional arguments. 278 | public static string ToStringDebug(this EntityReferenceCollection collection, StringDebugInfo info = null) 279 | { 280 | if (collection == null) 281 | { 282 | return "null"; 283 | } 284 | 285 | return Wrap("[", 286 | collection.Select(r => r.ToStringDebug()), 287 | "]", 288 | info); 289 | } 290 | 291 | #endregion EntityReferenceCollection 292 | 293 | #region IEnumerable 294 | 295 | /// 296 | /// Iterates and displays the values in the IEnumerable. 297 | /// 298 | /// The images. 299 | /// Optional arguments. 300 | public static string ToStringDebug(this IEnumerable collection, StringDebugInfo info = null) 301 | { 302 | info = info ?? StringDebugInfo.Default; 303 | var prefix = info.SingleLine 304 | ? string.Empty 305 | : Environment.NewLine + info.Indent + info.Tab; 306 | 307 | var start = $"{{{prefix}\"{collection.GetType().Name}\": ["; 308 | var end = info.SingleLine 309 | ? "]}" 310 | : $"]{Environment.NewLine + info.Indent}}}"; 311 | return Wrap(start, 312 | from object item in collection select ObjectToStringDebug(item, info), 313 | end, 314 | info.IncreaseIndent()); 315 | } 316 | 317 | #endregion IEnumerable 318 | 319 | #region IExecutionContext 320 | 321 | /// 322 | /// Returns an in depth view of the context 323 | /// 324 | /// The Context 325 | /// 326 | internal static List ToStringDebug(this IExecutionContext context) 327 | { 328 | var info = StringDebugInfo.Default; 329 | var lines = new List 330 | { 331 | "BusinessUnitId: " + context.BusinessUnitId, 332 | "CorrelationId: " + context.CorrelationId, 333 | "Depth: " + context.Depth, 334 | "InitiatingUserId: " + context.InitiatingUserId, 335 | "IsInTransaction: " + context.IsInTransaction, 336 | "IsolationMode: " + context.IsolationMode, 337 | "MessageName: " + context.MessageName, 338 | "Mode: " + context.Mode, 339 | "OperationCreatedOn: " + context.OperationCreatedOn, 340 | "OperationId: " + context.OperationId, 341 | "Organization: " + context.OrganizationName + "(" + context.OrganizationId + ")", 342 | "OwningExtension: " + (context.OwningExtension == null ? "Null" : context.OwningExtension.GetNameId()), 343 | "PrimaryEntityId: " + context.PrimaryEntityId, 344 | "PrimaryEntityName: " + context.PrimaryEntityName, 345 | "SecondaryEntityName: " + context.SecondaryEntityName, 346 | "UserId: " + context.UserId, 347 | context.InputParameters.ToStringDebug("InputParameters", info), 348 | context.OutputParameters.ToStringDebug("OutputParameters", info), 349 | context.PostEntityImages.ToStringDebug("PostEntityImages", info), 350 | context.PreEntityImages.ToStringDebug("PreEntityImages", info), 351 | context.SharedVariables.ToStringDebug("SharedVariables", info) 352 | }; 353 | 354 | // Useful for On-Prem 355 | if (ConfigurationManager.AppSettings.AllKeys.Any()) 356 | { 357 | lines.Add("* App Config Values *"); 358 | lines.AddRange(ConfigurationManager.AppSettings.AllKeys.Select(key => $" [{key}]: {GetConfigValueMaskingPasswords(key)}")); 359 | } 360 | 361 | return lines; 362 | } 363 | 364 | #endregion IExecutionContext 365 | 366 | #region ParameterCollection 367 | 368 | /// 369 | /// Iterates and displays the parameters in the parameter collection. 370 | /// 371 | /// The parameters. 372 | /// The name. 373 | /// Optional arguments. 374 | public static string ToStringDebug(this ParameterCollection parameters, string name, StringDebugInfo info = null) 375 | { 376 | info = info ?? StringDebugInfo.Default; 377 | if (parameters == null) 378 | { 379 | return info.Indent + name + ": null"; 380 | } 381 | 382 | if (parameters.Count <= 0) 383 | { 384 | return info.Indent + name + ": {}"; 385 | } 386 | 387 | var allEntities = parameters.Values.All(a => a is Entity); 388 | return Wrap(info.Indent + name + ": {", 389 | parameters.ToStringDebug(allEntities ? info : info.IncreaseIndent()), 390 | "}", 391 | allEntities ? info.WithNoTab() : info, string.Empty); 392 | } 393 | 394 | #endregion ParameterCollection 395 | 396 | #region IPluginExecutionContext 397 | 398 | /// 399 | /// Returns an in-depth view of the context 400 | /// 401 | /// The context. 402 | /// 403 | public static string ToStringDebug(this IPluginExecutionContext context) 404 | { 405 | var lines = ((IExecutionContext)context).ToStringDebug(); 406 | lines.AddRange(new[] 407 | { 408 | "Has Parent Context: " + (context.ParentContext != null), 409 | "Stage: " + context.Stage 410 | }); 411 | 412 | return string.Join(Environment.NewLine, lines); 413 | } 414 | 415 | #endregion IPluginExecutionContext 416 | 417 | private static bool IsNumeric(this object o) 418 | { 419 | return o is byte 420 | || o is sbyte 421 | || o is ushort 422 | || o is uint 423 | || o is ulong 424 | || o is short 425 | || o is int 426 | || o is long 427 | || o is float 428 | || o is double 429 | || o is decimal; 430 | } 431 | 432 | internal static string GenerateNonBreakingSpace(int spaces) 433 | { 434 | const string space = " "; // This is not a space, it is a Non-Breaking Space (alt+255). In the log spaces get trimmed, and this will prevent that from happening; 435 | return new string(space[0], spaces); 436 | } 437 | 438 | private static string Wrap(string start, IEnumerable middle, string end, StringDebugInfo info, string initialIndent = null, string middleJoinSeparator = ",") 439 | { 440 | initialIndent = initialIndent ?? info.Indent; 441 | if (info.SingleLine) 442 | { 443 | return initialIndent + start + string.Join(middleJoinSeparator, middle) + end; 444 | } 445 | 446 | var tab = Environment.NewLine + info.Indent + info.Tab; 447 | var joinedMiddle = string.Join(middleJoinSeparator + tab, middle); 448 | if (string.IsNullOrWhiteSpace(joinedMiddle)) 449 | { 450 | return initialIndent + start + end; 451 | } 452 | 453 | return initialIndent 454 | + start 455 | + tab + joinedMiddle + Environment.NewLine 456 | + info.Indent 457 | + end; 458 | } 459 | 460 | private static string GetConfigValueMaskingPasswords(string key) 461 | { 462 | var value = ConfigurationManager.AppSettings[key]; 463 | if (!string.IsNullOrWhiteSpace(value) && key.IndexOf("password", StringComparison.InvariantCultureIgnoreCase) >= 0) 464 | { 465 | value = new string('*', value.Length); 466 | } 467 | 468 | return value; 469 | } 470 | 471 | } 472 | 473 | /// 474 | /// Used to control indenting/formatting of StringDebug/ToStringAttributes Methods 475 | /// 476 | public class StringDebugInfo 477 | { 478 | /// 479 | /// Number of Spaces of the current indent. 480 | /// 481 | public int IndentSpaces { get; } 482 | /// 483 | /// Width of a single Tab. 484 | /// 485 | public int TabWidth { get; } 486 | /// 487 | /// If the ToString should output on a single line. 488 | /// 489 | public bool SingleLine { get; } 490 | 491 | /// 492 | /// Indent string. 493 | /// 494 | public string Indent { get; } 495 | /// 496 | /// Tab string. 497 | /// 498 | public string Tab { get; } 499 | private Dictionary IncreasedIndents { get; set; } 500 | private StringDebugInfo NoTab { get; set; } 501 | 502 | /// 503 | /// Default StringDebugInfo. 504 | /// 505 | public static StringDebugInfo Default = new StringDebugInfo(); 506 | 507 | /// 508 | /// Creates a new StringDebugInfo 509 | /// 510 | /// Number of Spaces of the Indent. 511 | /// Number of Spaces of a Tab. 512 | /// If the ToStringDebug should be a single line. 513 | public StringDebugInfo(int indentSpaces = 0, int tabWidth = 2, bool singleLine = false) 514 | : this(null, indentSpaces, tabWidth, singleLine) 515 | { 516 | } 517 | 518 | private StringDebugInfo(StringDebugInfo toCopy, int? indentSpaces = null, int? tabWidth = null, bool? singleLine = null) 519 | { 520 | IndentSpaces = indentSpaces ?? toCopy.IndentSpaces; 521 | TabWidth = tabWidth ?? toCopy.TabWidth; 522 | SingleLine = singleLine ?? toCopy.SingleLine; 523 | 524 | Indent = ToStringDebugExtensions.GenerateNonBreakingSpace(IndentSpaces); 525 | Tab = ToStringDebugExtensions.GenerateNonBreakingSpace(TabWidth); 526 | IncreasedIndents = new Dictionary(); 527 | } 528 | 529 | /// 530 | /// Increases the number of Tabs to increase the Current indent 531 | /// 532 | /// 533 | /// 534 | public StringDebugInfo IncreaseIndent(int tabs = 1) 535 | { 536 | if (!IncreasedIndents.TryGetValue(tabs, out var indent)) 537 | { 538 | indent = new StringDebugInfo(this, IndentSpaces + TabWidth * tabs); 539 | IncreasedIndents[tabs] = indent; 540 | } 541 | 542 | return indent; 543 | } 544 | 545 | /// 546 | /// Returns a StringDebugInfo with no tabs. 547 | /// 548 | /// 549 | public StringDebugInfo WithNoTab() 550 | { 551 | if (this.TabWidth == 0) 552 | { 553 | return this; 554 | } 555 | return NoTab ?? (NoTab = new StringDebugInfo(this, tabWidth: 0)); 556 | } 557 | } 558 | } -------------------------------------------------------------------------------- /Dataverse.Sdk.Extensions/NuGet Package/Dataverse.Sdk.Extensions.nuspec: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Dataverse.Sdk.Extensions 5 | $version$ 6 | Dataverse.Sdk.Extensions 7 | MscrmTools 8 | MscrmTools 9 | false 10 | Power Platform Patterns and Practices 11 | MscrmTools (c) 2021 12 | https://github.com/Power-Platform-Patterns-and-Practices/Dataverse.Sdk.Extensions 13 | 14 | 15 | $version$: First Release 16 | 17 | MIT 18 | Dataverse msdyn365 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | -------------------------------------------------------------------------------- /Dataverse.Sdk.Extensions/NuGet Package/Dataverse.Sdk.Extensions.targets: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Dataverse.Sdk.Extensions 2 | A repository that provides extension methods to work with Microsoft Dataverse SDK and simplifies writing of code 3 | --------------------------------------------------------------------------------