-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathClient.cs
1426 lines (1267 loc) · 58.2 KB
/
Client.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
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
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// <copyright>Copyright 2010 Thaddeus L Ryker</copyright>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
// Dynamics Nav is a registered trademark of the Microsoft Corporation
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Runtime.InteropServices.ComTypes;
using System.Threading;
using Org.Edgerunner.Dynamics.Nav.CSide.EventArguments;
using Org.Edgerunner.Dynamics.Nav.CSide.Exceptions;
using Org.Edgerunner.Dynamics.Nav.CSide.Interfaces;
using Org.Edgerunner.Dynamics.Nav.CSide.Threading;
// ReSharper disable RedundantNameQualifier
// ReSharper disable SuspiciousTypeConversion.Global
// ReSharper disable RedundantCast
namespace Org.Edgerunner.Dynamics.Nav.CSide
{
/// <summary>
/// Represents an instance of a Dynamics Nav client
/// </summary>
public class Client : IDisposable
{
#region Non-Public Fields (18)
// The GUID constant is left for reference of those reading the project, but it isn't actually used here.
// ReSharper disable once UnusedMember.Local
private const string NavisionClientInterfaceGuid = "50000004-0000-1000-0004-0000836BD2D2";
private const uint SecondsTimeout = 5;
private readonly IObjectDesigner _ObjectDesigner;
private readonly ClientRepository _Repository;
private Dictionary<NavObjectType, Dictionary<int, CSide.Object>> _Objects;
private EventHandler<DatabaseChangedEventArgs> _DatabaseChanged;
private EventHandler<CompanyChangedEventArgs> _CompanyChanged;
private EventHandler<ServerChangedEventArgs> _ServerChanged;
private string _ApplicationVersion;
private bool _TransactionInProgress;
internal string _PreviousCompany;
internal string _PreviousDatabase;
internal ServerType _PreviousServerType;
internal string _PreviousServer;
internal bool _PreviousBusyStatus;
#endregion Non-Public Fields
#region Constructors/Deconstructors (3)
/// <summary>
/// Initializes a new instance of the <see cref="Org.Edgerunner.Dynamics.Nav.CSide.Client" /> class.
/// </summary>
/// <param name="repository">The repository that generated the client instance.</param>
/// <param name="objectDesigner">The object designer.</param>
/// <param name="identifier">The unique identifier for the client.</param>
/// <param name="windowsHandle">The client windows handle.</param>
/// <param name="processId">The client process identifier.</param>
/// <exception cref="T:Org.Edgerunner.Dynamics.Nav.CSide.Exceptions.CSideException">Thrown if the timeoutPeriod expires and the client is still busy.</exception>
internal Client(ClientRepository repository, IObjectDesigner objectDesigner, long identifier, int windowsHandle, int processId)
{
_Repository = repository;
_ObjectDesigner = objectDesigner;
Identifier = identifier;
ProcessId = processId;
WindowHandle = windowsHandle;
lock (GetSyncObject())
{
_ObjectDesigner.GetCompanyName(out var companyName);
_ObjectDesigner.GetDatabaseName(out var databaseName);
_ObjectDesigner.GetServerName(out var serverName);
_ObjectDesigner.GetServerType(out var serverType);
_ObjectDesigner.GetCSIDEVersion(out var csideVersion);
_ObjectDesigner.GetApplicationVersion(out var appVersion);
_PreviousCompany = companyName ?? string.Empty;
_PreviousDatabase = databaseName ?? string.Empty;
_PreviousServerType = (ServerType)serverType;
_PreviousServer = serverName ?? string.Empty;
CSideVersion = csideVersion;
_ApplicationVersion = appVersion;
}
}
/// <summary>
/// Finalizes an instance of the <see cref="Client"/> class.
/// Releases unmanaged resources and performs other cleanup operations before the
/// <see cref="Org.Edgerunner.Dynamics.Nav.CSide.Client"/> is reclaimed by garbage collection.
/// </summary>
~Client()
{
Dispose(false);
}
#endregion Constructors/Deconstructors
#region Delegates and Events (5)
/// <summary>
/// Delegate used for busy status changed events
/// </summary>
/// <param name="sender">The sender.</param>
/// <param name="isBusy">if set to <c>true</c> [is busy].</param>
public delegate void BusyStatusEventHandler(object sender, bool isBusy);
#region Events (4)
/// <summary>
/// Occurs when the client instance changes company.
/// </summary>
public event EventHandler<CompanyChangedEventArgs> CompanyChanged
{
add
{
if (_CompanyChanged == null)
{
// TODO: If needed, add code to respond to the first event hook-up.
}
_CompanyChanged = (EventHandler<CompanyChangedEventArgs>)Delegate.Combine(_CompanyChanged, value);
}
remove
{
_CompanyChanged = (EventHandler<CompanyChangedEventArgs>)Delegate.Remove(_CompanyChanged, value);
if (_CompanyChanged == null)
{
// TODO: Add code to clean up if necessary.
}
}
}
/// <summary>
/// Occurs when the client instance changes database.
/// </summary>
public event EventHandler<DatabaseChangedEventArgs> DatabaseChanged
{
add
{
if (_DatabaseChanged == null)
{
// TODO: If needed, add code to respond to the first event hook-up.
}
_DatabaseChanged = (EventHandler<DatabaseChangedEventArgs>)Delegate.Combine(_DatabaseChanged, value);
}
remove
{
_DatabaseChanged = (EventHandler<DatabaseChangedEventArgs>)Delegate.Remove(_DatabaseChanged, value);
if (_DatabaseChanged == null)
{
// TODO: Add code to clean up if necessary.
}
}
}
/// <summary>
/// Occurs when the client instance changes server.
/// </summary>
public event EventHandler<ServerChangedEventArgs> ServerChanged
{
add
{
if (_ServerChanged == null)
{
// TODO: If needed, add code to respond to the first event hook-up.
}
_ServerChanged = (EventHandler<ServerChangedEventArgs>)Delegate.Combine(_ServerChanged, value);
}
remove
{
_ServerChanged = (EventHandler<ServerChangedEventArgs>)Delegate.Remove(_ServerChanged, value);
if (_ServerChanged == null)
{
// TODO: Add code to clean up if necessary.
}
}
}
/// <summary>
/// Occurs when [busy status changed].
/// </summary>
public event BusyStatusEventHandler BusyStatusChanged;
#endregion Events
#endregion Delegates and Events
/// <summary>
/// Gets the windows process identifier of the client.
/// </summary>
/// <value>The windows process identifier.</value>
internal int ProcessId { get; }
/// <summary>
/// Gets the <see cref="IObjectDesigner"/> instance corresponding to the client.
/// </summary>
/// <value>The <see cref="IObjectDesigner"/> instance.</value>
internal IObjectDesigner Designer => _ObjectDesigner;
/// <summary>
/// Gets the unique identifier for the client.
/// </summary>
/// <value>The unique identifier.</value>
public long Identifier { get; }
#region Locking support
private object _SyncLock;
/// <summary>
/// Gets the sync object to lock upon.
/// </summary>
/// <returns>An object to be used for all synchronization locks within the client.</returns>
/// <exception cref="T:Org.Edgerunner.Dynamics.Nav.CSide.Exceptions.CSideException">Thrown if the timeoutPeriod expires and the client is still busy.</exception>
internal object GetSyncObject()
{
TimeSpan waitPeriod = TimeSpan.Zero;
return GetSyncObject(waitPeriod);
}
/// <summary>
/// Gets the sync object to lock upon.
/// </summary>
/// <param name="timeoutPeriod">The timeout period.</param>
/// <returns>An object to be used for all synchronization locks within the client.</returns>
/// <exception cref="CSideException">Thrown if the timeoutPeriod expires and the client is still busy.</exception>
internal object GetSyncObject(TimeSpan timeoutPeriod)
{
if (_SyncLock == null)
_SyncLock = new object();
DateTime startTime = DateTime.Now;
// If the client is busy, we wait until it is not, then we return the synchronization lock object.
while (true)
{
if (IsBusy)
Thread.Sleep(500);
else
return _SyncLock;
if ((timeoutPeriod != TimeSpan.Zero) && ((startTime - DateTime.Now) > timeoutPeriod))
throw new CSideException("Timed out waiting for synchronization lock");
}
}
/// <summary>
/// Attempts to get the sync object to lock upon.
/// </summary>
/// <param name="timeoutPeriod">The timeout period.</param>
/// <returns>An object to be used for all synchronization locks within the client or null if the lock could not be obtained.</returns>
internal object TryGetSyncObject(TimeSpan timeoutPeriod)
{
if (_SyncLock == null)
_SyncLock = new object();
DateTime startTime = DateTime.Now;
// If the client is busy, we wait until it is not, then we return the synchronization lock object.
while (true)
{
if (IsBusy)
Thread.Sleep(500);
else
return _SyncLock;
if ((timeoutPeriod != TimeSpan.Zero) && ((startTime - DateTime.Now) > timeoutPeriod))
return null;
}
}
/// <summary>
/// Tries the get lock for the client, while waiting for a specified timeout period.
/// </summary>
/// <param name="timeoutPeriod">The period to wait for a lock before timing out.</param>
/// <param name="lockManager">The lock manager.</param>
/// <returns><c>true</c> if a lock is acquired, <c>false</c> otherwise.</returns>
internal bool TryGetLock(TimeSpan timeoutPeriod, out LockManager lockManager)
{
var start = DateTime.Now;
bool success = false;
lockManager = null;
Monitor.TryEnter(_SyncLock, timeoutPeriod, ref success);
if (!success)
return false;
if (!IsBusy)
{
lockManager = new LockManager(_SyncLock);
return true;
}
if (timeoutPeriod != TimeSpan.Zero)
while (IsBusy && timeoutPeriod < start - DateTime.Now)
Thread.Sleep(500);
if (IsBusy)
{
Monitor.Exit(_SyncLock);
return false;
}
lockManager = new LockManager(_SyncLock);
return true;
}
/// <summary>
/// Tries the get lock for the client.
/// </summary>
/// <param name="lockManager">The lock manager.</param>
/// <returns><c>true</c> if a lock is acquired, <c>false</c> otherwise.</returns>
internal bool TryGetLock(out LockManager lockManager)
{
return TryGetLock(TimeSpan.Zero, out lockManager);
}
/// <summary>
/// Gets a value indicating whether the Dynamics Nav client associated with this instance is running.
/// </summary>
/// <value>
/// <c>true</c> if this instance is running; otherwise, <c>false</c>.
/// </value>
public bool IsRunning
{
get
{
// We attempt to fetch the window handle since it should have very little overhead, and if successful we know the client is responding
try
{
// ReSharper disable once SuspiciousTypeConversion.Global
INSHyperlink app = _ObjectDesigner as INSHyperlink;
// ReSharper disable once NotAccessedVariable
int handle;
// If we can't retrieve an INSHyperlink reference then the likely hood is that the client is no longer valid.
// In this case we will return false because the client isn't waiting for anything. Validity issues should be handled elsewhere.
if (app == null)
return false;
app.GetNavWindowHandle(out handle);
}
catch (COMException ex)
{
// we received a call rejected or retry later error which means the client is busy
if ((ex.ErrorCode == CSideError.RPC_E_CALL_REJECTED) ||
(ex.ErrorCode == CSideError.RPC_E_SERVERCALL_RETRYLATER))
return true;
return false;
}
catch (InvalidComObjectException)
{
return false;
}
return true;
}
}
/// <summary>
/// Gets a value indicating whether the Dynamics Nav client associated with instance is busy.
/// </summary>
/// <value><c>true</c> if this instance is busy; otherwise, <c>false</c>.</value>
public bool IsBusy
{
get
{
bool result = false;
// We attempt to fetch the window handle since it should have very little overhead, and if successful we know the client is responding
try
{
// ReSharper disable once SuspiciousTypeConversion.Global
INSHyperlink app = _ObjectDesigner as INSHyperlink;
// If we can't retrieve an INSHyperlink reference then the likely hood is that the client is no longer valid.
// In this case we will return false because the client isn't waiting for anything. Validity issues should be handled elsewhere.
app?.GetNavWindowHandle(out var handle);
}
catch (COMException ex)
{
if ((ex.ErrorCode == CSideError.RPC_E_CALL_REJECTED) ||
(ex.ErrorCode == CSideError.RPC_E_SERVERCALL_RETRYLATER))
result = true;
}
_PreviousBusyStatus = result;
return result;
}
}
#endregion
#region Other Methods (24)
/// <summary>
/// Returns a pointer to an implementation of IBindCtx (a bind context object).
/// This object stores information about a particular moniker-binding operation.
/// </summary>
/// <param name="reserved">This parameter is reserved and must be 0.</param>
/// <param name="bindContext">Address of an IBindCtx* pointer variable that receives
/// the interface pointer to the new bind context object. When the function is
/// successful, the caller is responsible for calling Release on the bind context.
/// A NULL value for the bind context indicates that an error occurred.</param>
[DllImport("ole32.dll")]
// ReSharper disable once StyleCop.SA1650
private static extern void CreateBindCtx(int reserved, out IBindCtx bindContext);
/// <summary>
/// The CreateStreamOnHGlobal function creates a stream object that uses an HGLOBAL memory handle to store the stream contents.
/// This object is the OLE-provided implementation of the IStream interface.
/// The returned stream object supports both reading and writing, is not transacted, and does not support region locking.
/// The object calls the GlobalReAlloc function to grow the memory block as required
/// </summary>
/// <param name="globalMemoryHandle">The global memory handle.</param>
/// <param name="deleteOnRelease">A value that indicates whether the underlying handle for this stream object should be automatically freed when the stream object is released.
/// If set to <c>false</c>, the caller must free the hGlobal after the final release.
/// If set to <c>true</c>, the final release will automatically free the hGlobal parameter.</param>
/// <param name="newStream">The address of <see cref="System.Runtime.InteropServices.ComTypes.IStream"/>* pointer variable that receives the interface pointer to the new stream object. Its value cannot be <c>null</c>.</param>
/// <returns>The resulting error code which is 0 on success.</returns>
[DllImport("OLE32.DLL")]
// ReSharper disable once StyleCop.SA1650
private static extern int CreateStreamOnHGlobal(int globalMemoryHandle, bool deleteOnRelease, out IStream newStream);
/// <summary>
/// Gets the active client list.
/// </summary>
/// <returns>A list of designer objects corresponding to running client instances</returns>
/// <remarks>If there are multiple instances with the same database and company, only the first is exposed</remarks>
// ReSharper disable once StyleCop.SA1204
internal static List<object> GetActiveClientList()
{
List<object> clientList = new List<object>();
IntPtr numFetched = IntPtr.Zero;
IRunningObjectTable runningObjectTable = null;
IEnumMoniker monikerEnumerator = null;
IBindCtx ctx = null;
IMoniker[] monikers = new IMoniker[1];
try
{
GetRunningObjectTable(0, out runningObjectTable);
runningObjectTable.EnumRunning(out monikerEnumerator);
monikerEnumerator.Reset();
int clientNo = 0;
while (monikerEnumerator.Next(1, monikers, numFetched) == 0)
{
CreateBindCtx(0, out ctx);
monikers[0].GetDisplayName(ctx, null, out var runningObjectName);
runningObjectTable.GetObject(monikers[0], out var runningObjectVal);
if ((runningObjectName.IndexOf("!C/SIDE!navision://client/run?") != -1) &&
!clientList.Contains(runningObjectVal))
{
clientNo += 1;
clientList.Add(runningObjectVal);
}
}
}
finally
{
// Free resources
if (runningObjectTable != null)
Marshal.ReleaseComObject(runningObjectTable);
if (monikerEnumerator != null)
Marshal.ReleaseComObject(monikerEnumerator);
if (ctx != null)
Marshal.ReleaseComObject(ctx);
}
return clientList;
}
/// <summary>
/// Returns a pointer to the IRunningObjectTable interface on the local running object table (ROT).
/// </summary>
/// <param name="reserved">This parameter is reserved and must be 0.</param>
/// <param name="prot">The address of an IRunningObjectTable* pointer variable that receives the interface pointer to the local ROT.
/// When the function is successful, the caller is responsible for calling Release on the interface pointer. If an error occurs, *pprot is undefined.</param>
[DllImport("ole32.dll")]
internal static extern void GetRunningObjectTable(int reserved, out IRunningObjectTable prot);
/// <summary>
/// Gets the specific <see cref="IObjectDesigner"/> instance that corresponds to the supplied serverType/server/database/company.
/// </summary>
/// <param name="serverType">The server type.</param>
/// <param name="server">The server.</param>
/// <param name="database">The database.</param>
/// <param name="company">The company.</param>
/// <returns>The matching <see cref="IObjectDesigner"/>.</returns>
internal static IObjectDesigner GetDesigner(ServerType serverType, string server, string database, string company)
{
List<object> runningObjects = GetActiveClientList();
foreach (IObjectDesigner designer in runningObjects)
{
if (designer != null)
{
try
{
string currentDatabase;
int currentServerType;
string currentServer;
string currentCompany;
designer.GetServerType(out currentServerType);
designer.GetServerName(out currentServer);
designer.GetDatabaseName(out currentDatabase);
designer.GetCompanyName(out currentCompany);
if (((currentServerType == (int)ServerType.Unknown) || ((currentServerType != (int)ServerType.Unknown) && ((int)serverType == currentServerType))) &&
(string.IsNullOrEmpty(server) || (!string.IsNullOrEmpty(currentServer) && (server == currentServer))) &&
(string.IsNullOrEmpty(database) || (!string.IsNullOrEmpty(currentDatabase) && (database == currentDatabase))) &&
(string.IsNullOrEmpty(company) || (!string.IsNullOrEmpty(currentCompany) && (company == currentCompany))))
{
return designer;
}
}
catch (COMException ex)
{
// unresponsive client, so we skip it for now
}
}
}
return null;
}
/// <summary>
/// Updates the server, database, and company information for the client instance.
/// </summary>
internal void UpdateServerDatabaseCompanyInfo()
{
try
{
// ReSharper disable once ExceptionNotDocumented
lock (GetSyncObject(TimeSpan.FromMilliseconds(10)))
{
_ObjectDesigner.GetCompanyName(out var companyName);
_ObjectDesigner.GetDatabaseName(out var databaseName);
_ObjectDesigner.GetServerName(out var serverName);
_ObjectDesigner.GetServerType(out var serverType);
if ((ServerType)serverType != _PreviousServerType || serverName != _PreviousServer)
{
var previousServerType = _PreviousServerType;
var previousServerName = _PreviousServer;
_PreviousServerType = (ServerType)serverType;
_PreviousServer = serverName ?? string.Empty;
ThreadPool.QueueUserWorkItem(delegate { RaiseServerChanged(new ServerChangedEventArgs(previousServerType, previousServerName, (ServerType)serverType, serverName)); });
}
if (databaseName != _PreviousDatabase)
{
var previousDatabase = _PreviousDatabase;
_PreviousDatabase = databaseName ?? string.Empty;
ThreadPool.QueueUserWorkItem(delegate { RaiseDatabaseChanged(new DatabaseChangedEventArgs(previousDatabase, databaseName)); });
}
if (companyName != _PreviousCompany)
{
var previousCompanyName = _PreviousCompany;
_PreviousCompany = companyName ?? string.Empty;
ThreadPool.QueueUserWorkItem(delegate { RaiseCompanyChanged(new CompanyChangedEventArgs(previousCompanyName, companyName)); });
}
}
}
catch (CSideException)
{
// fail silently in this case
}
}
/// <summary>
/// Posts the busy status changed event.
/// </summary>
/// <param name="state">The state.</param>
private void PostBusyStatusChangedEvent(object state)
{
BusyStatusChanged?.Invoke(this, (bool)state);
}
/// <summary>
/// Posts the company changed event.
/// </summary>
/// <param name="state">The state.</param>
private void PostCompanyChangedEvent(object state)
{
_CompanyChanged(this, state as CompanyChangedEventArgs);
}
/// <summary>
/// Posts the database changed event.
/// </summary>
/// <param name="state">The state.</param>
private void PostDatabaseChangedEvent(object state)
{
_DatabaseChanged(this, state as DatabaseChangedEventArgs);
}
/// <summary>
/// Posts the server changed event.
/// </summary>
/// <param name="state">The state.</param>
private void PostServerChangedEvent(object state)
{
_ServerChanged(this, state as ServerChangedEventArgs);
}
/// <summary>
/// Raises the BusyStatusChanged event.
/// </summary>
/// <param name="isBusy">if set to <c>true</c> [is busy].</param>
// ReSharper disable once StyleCop.SA1305
internal void RaiseBusyStatusChanged(bool isBusy)
{
if (BusyStatusChanged != null)
{
if (_Repository.Context != null)
_Repository.Context.Post(PostBusyStatusChangedEvent, isBusy);
else
PostBusyStatusChangedEvent(isBusy);
}
}
/// <summary>
/// Raises the CompanyChanged.
/// </summary>
/// <param name="args">The <see cref="CSideEventArgs"/> instance containing the event data.</param>
internal void RaiseCompanyChanged(CompanyChangedEventArgs args)
{
if (_CompanyChanged != null)
{
if (_Repository.Context != null)
_Repository.Context.Post(PostCompanyChangedEvent, args);
else
PostCompanyChangedEvent(args);
}
}
/// <summary>
/// Raises the DatabaseChanged.
/// </summary>
/// <param name="args">The <see cref="CSideEventArgs"/> instance containing the event data.</param>
internal void RaiseDatabaseChanged(DatabaseChangedEventArgs args)
{
if (_DatabaseChanged != null)
{
if (_Repository.Context != null)
_Repository.Context.Post(PostDatabaseChangedEvent, args);
else
PostDatabaseChangedEvent(args);
}
}
/// <summary>
/// Raises the ServerChanged event.
/// </summary>
/// <param name="args">The <see cref="CSideEventArgs"/> instance containing the event data.</param>
internal void RaiseServerChanged(ServerChangedEventArgs args)
{
if (_ServerChanged != null)
{
if (_Repository.Context != null)
_Repository.Context.Post(PostServerChangedEvent, args);
else
PostServerChangedEvent(args);
}
}
/// <summary>
/// Transfers the contents of a Stream into an IStream.
/// </summary>
/// <param name="stream">The <see cref="System.IO.Stream"/>.</param>
/// <returns>An <see cref="System.Runtime.InteropServices.ComTypes.IStream"/></returns>
private unsafe IStream ToIStream(Stream stream)
{
byte[] buffer = new byte[stream.Length];
stream.Read(buffer, 0, buffer.Length);
uint num = 0;
IntPtr pointerToBytesWritten = new IntPtr((void*)&num);
CreateStreamOnHGlobal(0, true, out var outStream);
outStream.Write(buffer, buffer.Length, pointerToBytesWritten);
outStream.Seek((long)0, 0, IntPtr.Zero);
return outStream;
}
/// <summary>
/// Transfers the contents of an IStream into a MemoryStream.
/// </summary>
/// <param name="comStream">The COM <see cref="System.Runtime.InteropServices.ComTypes.IStream"/>.</param>
/// <returns>A <see cref="System.IO.MemoryStream"/></returns>
private unsafe MemoryStream ToMemoryStream(IStream comStream)
{
MemoryStream stream = new MemoryStream();
byte[] pv = new byte[100];
uint num = 0;
IntPtr pcbRead = new IntPtr((void*)&num);
comStream.Seek((long)0, 0, IntPtr.Zero);
do
{
num = 0;
comStream.Read(pv, pv.Length, pcbRead);
stream.Write(pv, 0, (int)num);
}
while (num > 0);
return stream;
}
/// <summary>
/// Returns a string that represents the current object.
/// </summary>
/// <returns>
/// A string that represents the current object.
/// </returns>
/// <exception cref="T:Org.Edgerunner.Dynamics.Nav.CSide.Exceptions.CSideException">Thrown if the timeoutPeriod expires and the client is still busy.</exception>
public override string ToString()
{
return string.Format(@"{0}\{1}-{2}", Server, Database, Company);
}
#endregion Methods
#region IObjectDesigner functionality
/// <summary>
/// Compiles the specified object.
/// </summary>
/// <param name="navObjectType">Type of the Nav object.</param>
/// <param name="objectId">The object Id.</param>
/// <exception cref="T:Org.Edgerunner.Dynamics.Nav.CSide.Exceptions.CSideException">Either the client is busy, invalid or there was a license permission issue.</exception>
/// <exception cref="T:System.TimeoutException">The request timed out due to a busy client.</exception>
public void CompileObject(NavObjectType navObjectType, int objectId)
{
// ReSharper disable once ExceptionNotDocumented
var lockObtained = TryGetLock(TimeSpan.FromSeconds(SecondsTimeout), out LockManager manager);
if (lockObtained)
using (manager)
{
int result = _ObjectDesigner.CompileObject((int)navObjectType, objectId);
if (result != 0)
throw CSideException.GetException(result);
}
throw new TimeoutException();
}
/// <summary>
/// Compiles the objects within the supplied filter.
/// </summary>
/// <param name="filter">The filter.</param>
/// <exception cref="T:Org.Edgerunner.Dynamics.Nav.CSide.Exceptions.CSideException">Either the client is busy, invalid or there was a license permission issue.</exception>
/// <exception cref="T:System.TimeoutException">The request timed out due to a busy client.</exception>
public void CompileObjects(string filter)
{
// ReSharper disable once ExceptionNotDocumented
var lockObtained = TryGetLock(TimeSpan.FromSeconds(SecondsTimeout), out LockManager manager);
if (lockObtained)
using (manager)
{
int result = _ObjectDesigner.CompileObjects(filter);
if (result != 0)
throw CSideException.GetException(result);
}
throw new TimeoutException();
}
/// <summary>
/// Gets the company name.
/// </summary>
/// <value>The company.</value>
public string Company
{
get
{
var lockObtained = TryGetLock(out LockManager manager);
if (!lockObtained)
return _PreviousCompany;
using (manager)
{
_ObjectDesigner.GetCompanyName(out var companyName);
companyName = companyName ?? string.Empty;
if (companyName != _PreviousCompany)
{
var previousCompany = _PreviousCompany;
_PreviousCompany = companyName;
ThreadPool.QueueUserWorkItem(delegate { RaiseCompanyChanged(new CompanyChangedEventArgs(previousCompany, companyName)); });
}
return _PreviousCompany;
}
}
}
/// <summary>
/// Gets the database name.
/// </summary>
/// <value>The database.</value>
public string Database
{
get
{
var lockObtained = TryGetLock(out LockManager manager);
if (!lockObtained)
return _PreviousDatabase;
using (manager)
{
_ObjectDesigner.GetDatabaseName(out var databaseName);
databaseName = databaseName ?? string.Empty;
if (databaseName != _PreviousDatabase)
{
var previousDatabase = _PreviousDatabase;
_PreviousDatabase = databaseName;
ThreadPool.QueueUserWorkItem(delegate { RaiseDatabaseChanged(new DatabaseChangedEventArgs(previousDatabase, databaseName)); });
}
return _PreviousDatabase;
}
}
}
/// <summary>
/// Gets the server name.
/// </summary>
/// <value>The server.</value>
public string Server
{
get
{
var lockObtained = TryGetLock(out LockManager manager);
if (!lockObtained)
return _PreviousServer;
using (manager)
{
_ObjectDesigner.GetServerName(out var serverName);
serverName = serverName ?? string.Empty;
if (serverName != _PreviousServer)
{
var previousServerName = _PreviousServer;
_PreviousServer = serverName;
_ObjectDesigner.GetServerType(out var serverType);
var previousServerType = _PreviousServerType;
_PreviousServerType = (ServerType)serverType;
ThreadPool.QueueUserWorkItem(delegate { RaiseServerChanged(new ServerChangedEventArgs(previousServerType, previousServerName, (ServerType)serverType, serverName)); });
}
return _PreviousServer;
}
}
}
/// <summary>
/// Gets the type of the server.
/// </summary>
/// <value>The type of the server.</value>
public ServerType ServerType
{
get
{
var lockObtained = TryGetLock(out LockManager manager);
if (!lockObtained)
return _PreviousServerType;
using (manager)
{
_ObjectDesigner.GetServerType(out var serverType);
_PreviousServerType = (ServerType)serverType;
if ((ServerType)serverType != _PreviousServerType)
{
var previousServerType = _PreviousServerType;
_PreviousServerType = (ServerType)serverType;
_ObjectDesigner.GetServerName(out var serverName);
serverName = serverName ?? string.Empty;
var previousServerName = _PreviousServer;
_PreviousServer = serverName;
ThreadPool.QueueUserWorkItem(delegate
{
RaiseServerChanged(new ServerChangedEventArgs(previousServerType, previousServerName, (ServerType)serverType, serverName));
});
}
return _PreviousServerType;
}
}
}
/// <summary>
/// Gets the C/Side version.
/// </summary>
/// <value>The C/Side version.</value>
public string CSideVersion { get; }
/// <summary>
/// Gets the application version.
/// </summary>
/// <value>The application version.</value>
public string ApplicationVersion
{
get
{
var lockObtained = TryGetLock(out LockManager manager);
if (!lockObtained)
return _ApplicationVersion;
using (manager)
{
int result = _ObjectDesigner.GetApplicationVersion(out var appVersion);
if (result != 0)
throw CSideException.GetException(result);
_ApplicationVersion = appVersion ?? string.Empty;
return appVersion;
}
}
}
/// <summary>
/// Reads the specified object to a stream in its text format.
/// </summary>
/// <param name="navObjectType">Type of the Navision object.</param>
/// <param name="objectId">The object Id.</param>
/// <returns>A <see cref="System.IO.MemoryStream"/> containing the text for the specified object</returns>
/// <exception cref="T:Org.Edgerunner.Dynamics.Nav.CSide.Exceptions.CSideException">Either the client is invalid or there was a license permission issue.</exception>
/// <exception cref="T:System.TimeoutException">The request timed out due to a busy client.</exception>
public MemoryStream ReadObjectToStream(NavObjectType navObjectType, int objectId)
{
// ReSharper disable once ExceptionNotDocumented
var lockObtained = TryGetLock(TimeSpan.FromSeconds(SecondsTimeout), out LockManager manager);
if (lockObtained)
using (manager)
{
CreateStreamOnHGlobal(0, true, out var outStream);
// We Use ReadObjects() here instead of ReadObject() because ReadObject() is very buggy and outputs bad files
int result = _ObjectDesigner.ReadObjects(
string.Format(
"WHERE(Type=CONST({0}),ID=CONST({1}))",
(int)navObjectType,
objectId),
outStream);
if (result != 0)
throw CSideException.GetException(result);
return ToMemoryStream(outStream);
}
throw new TimeoutException();
}
/// <summary>
/// Reads the specified objects to a stream in their text format.
/// </summary>
/// <param name="navObjectType">Type of the Navision object.</param>
/// <param name="objectIdRangeStart">The object number to read from.</param>
/// <param name="objectIdRangeStop">The object number to read to.</param>
/// <returns>A <see cref="System.IO.MemoryStream" /> containing the text for the specified objects</returns>
/// <exception cref="T:Org.Edgerunner.Dynamics.Nav.CSide.Exceptions.CSideException">An error occurred while attempting the read. A likely cause is a license permission issue.</exception>
/// <exception cref="T:System.TimeoutException">The request timed out due to a busy client.</exception>
public MemoryStream ReadObjectsToStream(NavObjectType navObjectType, int objectIdRangeStart, int objectIdRangeStop)
{
// ReSharper disable once ExceptionNotDocumented
var lockObtained = TryGetLock(TimeSpan.FromSeconds(SecondsTimeout), out LockManager manager);
if (lockObtained)
using (manager)
{
CreateStreamOnHGlobal(0, true, out var outStream);
// We Use ReadObjects() here instead of ReadObject() because ReadObject() is very buggy and outputs bad files
int result = _ObjectDesigner.ReadObjects(
string.Format(
"WHERE(Type=CONST({0}),ID=FILTER({1}..{2}))",
(int)navObjectType,
objectIdRangeStart,
objectIdRangeStop),
outStream);
if (result != 0)
throw CSideException.GetException(result);
return ToMemoryStream(outStream);