-
Notifications
You must be signed in to change notification settings - Fork 140
/
DataService.cs
2208 lines (1893 loc) · 107 KB
/
DataService.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 file="DataService.cs" company="Intuit">
/*******************************************************************************
* Copyright 2019 Intuit
*
* 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.
*******************************************************************************/
// <summary>This file contains DataService performs CRUD operations on V3 QuickBooks APIs.</summary>
////*********************************************************
using System.Text.RegularExpressions;
namespace Intuit.Ipp.DataService
{
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Globalization;
using System.Linq;
using System.Net;
using System.Reflection;
using Intuit.Ipp.Core;
using Intuit.Ipp.Core.Rest;
using Intuit.Ipp.Data;
using Intuit.Ipp.DataService.Properties;
using Intuit.Ipp.Diagnostics;
using Intuit.Ipp.Exception;
using Intuit.Ipp.Utility;
using System.Text;
using System.IO;
//using Intuit.Ipp.QueryFilter;
//using Intuit.Ipp.LinqExtender;
/// <summary>
/// This class file contains DataService performs CRUD operations on V3 QuickBooks APIs.
/// </summary>
public class DataService : IDataService
{
/// <summary>
/// The Service context object.
/// </summary>
private ServiceContext serviceContext;
/// <summary>
/// Rest Request Handler.
/// </summary>
private IRestHandler restHandler;
/// <summary>
/// Initializes a new instance of the <see cref="DataService"/> class.
/// </summary>
/// <param name="serviceContext">IPP Service Context</param>
public DataService(ServiceContext serviceContext)
{
ServiceContextValidation(serviceContext);
this.serviceContext = serviceContext;
this.restHandler = new SyncRestHandler(this.serviceContext);
// Set the Service type to QBO by calling a method.
this.serviceContext.UseDataServices();
}
#region Async handlers
/// <summary>
/// Gets or sets the call back event for find all method in asynchronous call.
/// </summary>
/// <value>
/// The OnFindAllCompleted call back.
/// </value>
public DataServiceCallback<IEntity>.FindAllCallCompletedEventHandler OnFindAllAsyncCompleted { get; set; }
/// <summary>
/// Gets or sets the call back event for Add method in asynchronous call.
/// </summary>
/// <value>
/// The OnAddAsyncCompleted call back.
/// </value>
public DataServiceCallback<IEntity>.CallCompletedEventHandler OnAddAsyncCompleted { get; set; }
/// <summary>
/// Gets or sets the call back event for FindByid method in asynchronous call.
/// </summary>
/// <value>
/// The OnFindByIdAsyncCompleted call back.
/// </value>
public DataServiceCallback<IEntity>.CallCompletedEventHandler OnFindByIdAsyncCompleted { get; set; }
/// <summary>
/// Gets or sets the call back event for FindByLevel method in asynchronous call.
/// </summary>
/// <value>
/// The OnFindByLevelAsyncCompleted call back.
/// </value>
public DataServiceCallback<IEntity>.FindAllCallCompletedEventHandler OnFindByLevelAsyncCompleted { get; set; }
/// <summary>
/// Gets or sets the call back event for FindByParentId method in asynchronous call.
/// </summary>
/// /// <value>
/// The OnFindByParentIdAsyncCompleted call back.
/// </value>
public DataServiceCallback<IEntity>.FindAllCallCompletedEventHandler OnFindByParentIdAsyncCompleted { get; set; }
/// <summary>
/// Gets or sets the call back event for GetPdf method in asynchronous call.
/// </summary>
/// <value>
/// The OnGetPdfAsyncCompleted call back.
/// </value>
public DataServiceCallback<IEntity>.PdfCallCompletedEventHandler OnGetPdfAsyncCompleted { get; set; }
/// <summary>
/// Gets or sets the call back event for SendEmail method in asynchronous call.
/// </summary>
/// <value>
/// The OnSendEmailAsyncCompleted call back.
/// </value>
public DataServiceCallback<IEntity>.CallCompletedEventHandler OnSendEmailAsyncCompleted { get; set; }
/// <summary>
/// Gets or sets the call back event for Update method in asynchronous call.
/// </summary>
/// <value>
/// The OnUpdateAsyncCompleted call back.
/// </value>
public DataServiceCallback<IEntity>.CallCompletedEventHandler OnUpdateAsyncCompleted { get; set; }
/// <summary>
/// Gets or sets the call back event for Update account method in asynchronous call.
/// </summary>
/// <value>
/// The OnUpdateAccAsyncCompleted call back.
/// </value>
public DataServiceCallback<IEntity>.CallCompletedEventHandler OnUpdateAccAsyncCompleted { get; set; }
/// <summary>
/// Gets or sets the call back event for Update account method in asynchronous call.
/// </summary>
/// <value>
/// The OnDoNotUpdateAccAsyncCompleted call back.
/// </value>
public DataServiceCallback<IEntity>.CallCompletedEventHandler OnDoNotUpdateAccAsyncCompleted { get; set; }
/// <summary>
/// Gets or sets the call back event for Delete method in asynchronous call.
/// </summary>
/// <value>
/// The OnDeleteAsyncCompleted call back.
/// </value>
public DataServiceCallback<IEntity>.CallCompletedEventHandler OnDeleteAsyncCompleted { get; set; }
/// <summary>
/// Gets or sets the call back event for Delete method in asynchronous call.
/// </summary>
/// <value>
/// The OnDeleteAsyncCompleted call back.
/// </value>
public DataServiceCallback<IEntity>.CallCompletedEventHandler OnVoidAsyncCompleted { get; set; }
/// <summary>
/// Gets or sets the call back event for Revert method in asynchronous call.
/// </summary>
/// <value>
/// The OnRevertAsyncCompleted call back.
/// </value>
public DataServiceCallback<IEntity>.CallCompletedEventHandler OnRevertAsyncCompleted { get; set; }
/// <summary>
/// Gets or sets the call back event for CDC method in asynchronous call.
/// </summary>
/// <value>
/// The OnCDCCompleted call back.
/// </value>
public DataServiceCallback<IEntity>.CDCCallCompletedEventHandler OnCDCAsyncCompleted { get; set; }
#endregion
#region Add
/// <summary>
/// Adds an entity under the specified realm. The realm must be set in the context.
/// </summary>
/// <typeparam name="T">Generic Type T.</typeparam>
/// <param name="entity">Entity to Add.</param>
/// <returns>Returns an updated version of the entity with updated identifier and sync token.</returns>
public T Add<T>(T entity) where T : IEntity
{
this.serviceContext.IppConfiguration.Logger.CustomLogger.Log(Diagnostics.TraceLevel.Info, "Called Method Add.");
// Validate parameter
if (!ServicesHelper.IsTypeNull(entity))
{
IdsException exception = new IdsException(Resources.ParameterNotNullMessage, new ArgumentNullException(Resources.EntityString));
this.serviceContext.IppConfiguration.Logger.CustomLogger.Log(Diagnostics.TraceLevel.Error, string.Format(CultureInfo.InvariantCulture, Resources.ExceptionGeneratedMessage, exception.ToString()));
IdsExceptionManager.HandleException(exception);
}
string resourceString = entity.GetType().Name.ToLower(CultureInfo.InvariantCulture);
// Builds resource Uri
string uri = string.Format(CultureInfo.InvariantCulture, "{0}/company/{1}/{2}", CoreConstants.VERSION, this.serviceContext.RealmId, resourceString);
// Creates request parameters
RequestParameters parameters;
if (this.serviceContext.IppConfiguration.Message.Request.SerializationFormat == Intuit.Ipp.Core.Configuration.SerializationFormat.Json)
{
parameters = new RequestParameters(uri, HttpVerbType.POST, CoreConstants.CONTENTTYPE_APPLICATIONJSON);
}
else
{
parameters = new RequestParameters(uri, HttpVerbType.POST, CoreConstants.CONTENTTYPE_APPLICATIONXML);
}
// Prepares request
HttpWebRequest request = this.restHandler.PrepareRequest(parameters, entity);
string response = string.Empty;
try
{
// gets response
response = this.restHandler.GetResponse(request);
}
catch (IdsException ex)
{
IdsExceptionManager.HandleException(ex);
}
CoreHelper.CheckNullResponseAndThrowException(response);
// de serialize object
IntuitResponse restResponse = (IntuitResponse)CoreHelper.GetSerializer(this.serviceContext, false).Deserialize<IntuitResponse>(response);
this.serviceContext.IppConfiguration.Logger.CustomLogger.Log(Diagnostics.TraceLevel.Info, "Finished Executing Method Add.");
return (T)(restResponse.AnyIntuitObject as IEntity);
}
#endregion
#region Delete, Void
/// <summary>
/// Deletes an entity under the specified realm. The realm must be set in the context.
/// </summary>
/// <typeparam name="T">Generic Type T.</typeparam>
/// <param name="entity">Entity to Delete.</param>
public T Delete<T>(T entity) where T : IEntity
{
this.serviceContext.IppConfiguration.Logger.CustomLogger.Log(Diagnostics.TraceLevel.Info, "Called Method Void.");
// Validate parameter
if (!ServicesHelper.IsTypeNull(entity))
{
IdsException exception = new IdsException(Resources.ParameterNotNullMessage, new ArgumentNullException(Resources.EntityString));
this.serviceContext.IppConfiguration.Logger.CustomLogger.Log(Diagnostics.TraceLevel.Error, string.Format(CultureInfo.InvariantCulture, Resources.ExceptionGeneratedMessage, exception.ToString()));
IdsExceptionManager.HandleException(exception);
}
string resourceString = entity.GetType().Name.ToLower(CultureInfo.InvariantCulture);
// Builds resource Uri
string uri = string.Format(CultureInfo.InvariantCulture, "{0}/company/{1}/{2}?operation=delete", CoreConstants.VERSION, this.serviceContext.RealmId, resourceString);
// Creates request parameters
RequestParameters parameters;
if (this.serviceContext.IppConfiguration.Message.Request.SerializationFormat == Intuit.Ipp.Core.Configuration.SerializationFormat.Json)
{
parameters = new RequestParameters(uri, HttpVerbType.POST, CoreConstants.CONTENTTYPE_APPLICATIONJSON);
}
else
{
parameters = new RequestParameters(uri, HttpVerbType.POST, CoreConstants.CONTENTTYPE_APPLICATIONXML);
}
// Prepares request
HttpWebRequest request = this.restHandler.PrepareRequest(parameters, entity);
string response = string.Empty;
try
{
// gets response
response = this.restHandler.GetResponse(request);
}
catch (IdsException ex)
{
IdsExceptionManager.HandleException(ex);
}
CoreHelper.CheckNullResponseAndThrowException(response);
// de serialize object
IntuitResponse restResponse = (IntuitResponse)CoreHelper.GetSerializer(this.serviceContext, false).Deserialize<IntuitResponse>(response);
IntuitEntity intuitEntity = restResponse.AnyIntuitObject as IntuitEntity;
if (intuitEntity != null && intuitEntity.status != EntityStatusEnum.Deleted)
{
IdsException exception = new IdsException(Resources.CommunicationErrorMessage, new CommunicationException(Resources.StatusNotDeleted));
this.serviceContext.IppConfiguration.Logger.CustomLogger.Log(Diagnostics.TraceLevel.Error, string.Format(CultureInfo.InvariantCulture, Resources.ExceptionGeneratedMessage, exception.ToString()));
IdsExceptionManager.HandleException(exception);
}
this.serviceContext.IppConfiguration.Logger.CustomLogger.Log(Diagnostics.TraceLevel.Info, "Finished Executing Method Void.");
return (T)(restResponse.AnyIntuitObject as IEntity);
}
/// <summary>
/// Voids an entity under the specified realm. The realm must be set in the context.
/// </summary>
/// <typeparam name="T">Generic Type T.</typeparam>
/// <param name="entity">Entity to Void (only entities of type Sales Receipt and Payment are supported to be voided)</param>
/// <returns name="T">Returns the voided entity</returns>
public T Void<T>(T entity) where T : IEntity
{
this.serviceContext.IppConfiguration.Logger.CustomLogger.Log(Diagnostics.TraceLevel.Info, "Called Method Void.");
// Validate parameter
if (!ServicesHelper.IsTypeNull(entity))
{
IdsException exception = new IdsException(Resources.ParameterNotNullMessage, new ArgumentNullException(Resources.EntityString));
this.serviceContext.IppConfiguration.Logger.CustomLogger.Log(Diagnostics.TraceLevel.Error, string.Format(CultureInfo.InvariantCulture, Resources.ExceptionGeneratedMessage, exception.ToString()));
IdsExceptionManager.HandleException(exception);
}
CheckForVoidAllowedEntities(entity);
string resourceString = entity.GetType().Name.ToLower(CultureInfo.InvariantCulture);
// Builds resource Uri
string uri = string.Format(CultureInfo.InvariantCulture, "{0}/company/{1}/{2}?include=void", CoreConstants.VERSION, this.serviceContext.RealmId, resourceString);
// Creates request parameters
RequestParameters parameters;
if (this.serviceContext.IppConfiguration.Message.Request.SerializationFormat == Intuit.Ipp.Core.Configuration.SerializationFormat.Json)
{
parameters = new RequestParameters(uri, HttpVerbType.POST, CoreConstants.CONTENTTYPE_APPLICATIONJSON);
}
else
{
parameters = new RequestParameters(uri, HttpVerbType.POST, CoreConstants.CONTENTTYPE_APPLICATIONXML);
}
// Prepares request
HttpWebRequest request = this.restHandler.PrepareRequest(parameters, entity);
string response = string.Empty;
try
{
// gets response
response = this.restHandler.GetResponse(request);
}
catch (IdsException ex)
{
IdsExceptionManager.HandleException(ex);
}
CoreHelper.CheckNullResponseAndThrowException(response);
// de serialize object
IntuitResponse restResponse = (IntuitResponse)CoreHelper.GetSerializer(this.serviceContext, false).Deserialize<IntuitResponse>(response);
if (restResponse.AnyIntuitObjects != null)
{
IntuitEntity intuitEntity = restResponse.AnyIntuitObject as IntuitEntity;
if (restResponse != null && restResponse.status != IntuitResponseStatus.Deleted.ToString())
{
IdsException exception = new IdsException(Resources.CommunicationErrorMessage, new CommunicationException(Resources.StatusNotVoided));
this.serviceContext.IppConfiguration.Logger.CustomLogger.Log(Diagnostics.TraceLevel.Error, string.Format(CultureInfo.InvariantCulture, Resources.ExceptionGeneratedMessage, exception.ToString()));
IdsExceptionManager.HandleException(exception);
}
}
this.serviceContext.IppConfiguration.Logger.CustomLogger.Log(Diagnostics.TraceLevel.Info, "Finished Executing Method Void.");
return (T)(restResponse.AnyIntuitObject as IEntity);
}
#endregion
#region Update
/// <summary>
/// Updates an entity under the specified realm. The realm must be set in the context.
/// </summary>
/// <typeparam name="T">Generic Type T.</typeparam>
/// <param name="entity">Entity to Update.</param>
/// <returns>Returns an updated version of the entity with updated identifier and sync token.</returns>
public T Update<T>(T entity) where T : IEntity
{
this.serviceContext.IppConfiguration.Logger.CustomLogger.Log(Diagnostics.TraceLevel.Info, "Called Method Add.");
// Validate parameter
if (!ServicesHelper.IsTypeNull(entity))
{
IdsException exception = new IdsException(Resources.ParameterNotNullMessage, new ArgumentNullException(Resources.EntityString));
this.serviceContext.IppConfiguration.Logger.CustomLogger.Log(Diagnostics.TraceLevel.Error, string.Format(CultureInfo.InvariantCulture, Resources.ExceptionGeneratedMessage, exception.ToString()));
IdsExceptionManager.HandleException(exception);
}
string resourceString = entity.GetType().Name.ToLower(CultureInfo.InvariantCulture);
// Builds resource Uri
string uri = string.Format(CultureInfo.InvariantCulture, "{0}/company/{1}/{2}", CoreConstants.VERSION, this.serviceContext.RealmId, resourceString);
// Creates request parameters
RequestParameters parameters;
if (this.serviceContext.IppConfiguration.Message.Request.SerializationFormat == Intuit.Ipp.Core.Configuration.SerializationFormat.Json)
{
parameters = new RequestParameters(uri, HttpVerbType.POST, CoreConstants.CONTENTTYPE_APPLICATIONJSON);
}
else
{
parameters = new RequestParameters(uri, HttpVerbType.POST, CoreConstants.CONTENTTYPE_APPLICATIONXML);
}
// Prepares request
HttpWebRequest request = this.restHandler.PrepareRequest(parameters, entity);
string response = string.Empty;
try
{
// gets response
response = this.restHandler.GetResponse(request);
}
catch (IdsException ex)
{
IdsExceptionManager.HandleException(ex);
}
CoreHelper.CheckNullResponseAndThrowException(response);
// de serialize object
IntuitResponse restResponse = (IntuitResponse)CoreHelper.GetSerializer(this.serviceContext, false).Deserialize<IntuitResponse>(response);
this.serviceContext.IppConfiguration.Logger.CustomLogger.Log(Diagnostics.TraceLevel.Info, "Finished Executing Method Add.");
return (T)(restResponse.AnyIntuitObject as IEntity);
}
#endregion
#region updateaccountontxns
/// <summary>
/// updateaccountontxns an entity under the specified realm. The realm must be set in the context.
/// </summary>
/// <typeparam name="T">Generic Type T.</typeparam>
/// <param name="entity">Entity to Update.</param>
/// <returns>Returns an updated version of the entity with updated identifier and sync token.</returns>
public T UpdateAccountOnTxns<T>(T entity) where T : IEntity
{
this.serviceContext.IppConfiguration.Logger.CustomLogger.Log(Diagnostics.TraceLevel.Info, "Called Method Add.");
// Validate parameter
if (!ServicesHelper.IsTypeNull(entity))
{
IdsException exception = new IdsException(Resources.ParameterNotNullMessage, new ArgumentNullException(Resources.EntityString));
this.serviceContext.IppConfiguration.Logger.CustomLogger.Log(Diagnostics.TraceLevel.Error, string.Format(CultureInfo.InvariantCulture, Resources.ExceptionGeneratedMessage, exception.ToString()));
IdsExceptionManager.HandleException(exception);
}
string resourceString = entity.GetType().Name.ToLower(CultureInfo.InvariantCulture);
// Builds resource Uri
string uri = string.Format(CultureInfo.InvariantCulture, "{0}/company/{1}/{2}?include=updateaccountontxns", CoreConstants.VERSION, this.serviceContext.RealmId, resourceString);
// Creates request parameters
RequestParameters parameters;
if (this.serviceContext.IppConfiguration.Message.Request.SerializationFormat == Intuit.Ipp.Core.Configuration.SerializationFormat.Json)
{
parameters = new RequestParameters(uri, HttpVerbType.POST, CoreConstants.CONTENTTYPE_APPLICATIONJSON);
}
else
{
parameters = new RequestParameters(uri, HttpVerbType.POST, CoreConstants.CONTENTTYPE_APPLICATIONXML);
}
// Prepares request
HttpWebRequest request = this.restHandler.PrepareRequest(parameters, entity);
string response = string.Empty;
try
{
// gets response
response = this.restHandler.GetResponse(request);
}
catch (IdsException ex)
{
IdsExceptionManager.HandleException(ex);
}
CoreHelper.CheckNullResponseAndThrowException(response);
// de serialize object
IntuitResponse restResponse = (IntuitResponse)CoreHelper.GetSerializer(this.serviceContext, false).Deserialize<IntuitResponse>(response);
this.serviceContext.IppConfiguration.Logger.CustomLogger.Log(Diagnostics.TraceLevel.Info, "Finished Executing Method Add.");
return (T)(restResponse.AnyIntuitObject as IEntity);
}
#endregion
#region donotupdateaccountontxns
/// <summary>
/// donotupdateaccountontxns an entity under the specified realm. The realm must be set in the context.
/// </summary>
/// <typeparam name="T">Generic Type T.</typeparam>
/// <param name="entity">Entity to Update.</param>
/// <returns>Returns an updated version of the entity with updated identifier and sync token.</returns>
public T DoNotUpdateAccountOnTxns<T>(T entity) where T : IEntity
{
this.serviceContext.IppConfiguration.Logger.CustomLogger.Log(Diagnostics.TraceLevel.Info, "Called Method Add.");
// Validate parameter
if (!ServicesHelper.IsTypeNull(entity))
{
IdsException exception = new IdsException(Resources.ParameterNotNullMessage, new ArgumentNullException(Resources.EntityString));
this.serviceContext.IppConfiguration.Logger.CustomLogger.Log(Diagnostics.TraceLevel.Error, string.Format(CultureInfo.InvariantCulture, Resources.ExceptionGeneratedMessage, exception.ToString()));
IdsExceptionManager.HandleException(exception);
}
string resourceString = entity.GetType().Name.ToLower(CultureInfo.InvariantCulture);
// Builds resource Uri
string uri = string.Format(CultureInfo.InvariantCulture, "{0}/company/{1}/{2}?include=donotupdateaccountontxns", CoreConstants.VERSION, this.serviceContext.RealmId, resourceString);
// Creates request parameters
RequestParameters parameters;
if (this.serviceContext.IppConfiguration.Message.Request.SerializationFormat == Intuit.Ipp.Core.Configuration.SerializationFormat.Json)
{
parameters = new RequestParameters(uri, HttpVerbType.POST, CoreConstants.CONTENTTYPE_APPLICATIONJSON);
}
else
{
parameters = new RequestParameters(uri, HttpVerbType.POST, CoreConstants.CONTENTTYPE_APPLICATIONXML);
}
// Prepares request
HttpWebRequest request = this.restHandler.PrepareRequest(parameters, entity);
string response = string.Empty;
try
{
// gets response
response = this.restHandler.GetResponse(request);
}
catch (IdsException ex)
{
IdsExceptionManager.HandleException(ex);
}
CoreHelper.CheckNullResponseAndThrowException(response);
// de serialize object
IntuitResponse restResponse = (IntuitResponse)CoreHelper.GetSerializer(this.serviceContext, false).Deserialize<IntuitResponse>(response);
this.serviceContext.IppConfiguration.Logger.CustomLogger.Log(Diagnostics.TraceLevel.Info, "Finished Executing Method Add.");
return (T)(restResponse.AnyIntuitObject as IEntity);
}
#endregion
#region Read
#region PDF
/// <summary>
/// Returns an entity as pdf bytes.
/// </summary>
/// <typeparam name="T">Generic Type T.</typeparam>
/// <param name="entity">Entity to be returned as pdf bytes (entities of type Sales Receipt, Invoice and Estimate are supported to be returned as pdf).</param>
/// <returns type="byte[]">Returns pdf as bytes</returns>
public byte[] GetPdf<T>(T entity) where T : IEntity
{
// Validate parameter
if (!ServicesHelper.IsTypeNull(entity))
{
IdsException exception = new IdsException(Resources.ParameterNotNullMessage, new ArgumentNullException(Resources.EntityString));
this.serviceContext.IppConfiguration.Logger.CustomLogger.Log(Diagnostics.TraceLevel.Error, string.Format(CultureInfo.InvariantCulture, Resources.ExceptionGeneratedMessage, exception.ToString()));
IdsExceptionManager.HandleException(exception);
}
this.serviceContext.IppConfiguration.Logger.CustomLogger.Log(Diagnostics.TraceLevel.Info, "Called Method GetPdf by " + entity.GetType().FullName);
string id = string.Empty;
string resourceString = entity.GetType().Name.ToLower(CultureInfo.InvariantCulture);
// Convert to role base to get the Id property which is required to Find the entity.
IntuitEntity intuitEntity = entity as IntuitEntity;
if (intuitEntity == null)
{
IdsException exception = new IdsException(Resources.EntityConversionFailedMessage);
this.serviceContext.IppConfiguration.Logger.CustomLogger.Log(Diagnostics.TraceLevel.Error, string.Format(CultureInfo.InvariantCulture, Resources.ExceptionGeneratedMessage, exception.ToString()));
IdsExceptionManager.HandleException(exception);
}
// Check whether the Id is null and throw an exception if it is null.
if (string.IsNullOrWhiteSpace(intuitEntity.Id) && (entity.GetType().Name != "Preferences"))
{
IdsException exception = new IdsException(Resources.EntityIdNotNullMessage, new ArgumentNullException(Resources.IdString));
this.serviceContext.IppConfiguration.Logger.CustomLogger.Log(Diagnostics.TraceLevel.Error, string.Format(CultureInfo.InvariantCulture, Resources.ExceptionGeneratedMessage, exception.ToString()));
IdsExceptionManager.HandleException(exception);
}
//check if the operation is allowed on the entity
CheckForPdfAllowedEntities(entity);
id = intuitEntity.Id;
//build the url to be called
string uri = string.Empty;
uri = string.Format(CultureInfo.InvariantCulture, "{0}/company/{1}/{2}/{3}/pdf", CoreConstants.VERSION, this.serviceContext.RealmId, resourceString, id);
// Creates request parameters
RequestParameters parameters;
if (this.serviceContext.IppConfiguration.Message.Request.SerializationFormat ==
Intuit.Ipp.Core.Configuration.SerializationFormat.Json)
{
parameters = new RequestParameters(uri, HttpVerbType.GET, CoreConstants.CONTENTTYPE_APPLICATIONJSON);
}
else
{
parameters = new RequestParameters(uri, HttpVerbType.GET, CoreConstants.CONTENTTYPE_APPLICATIONXML);
}
// Prepare request
HttpWebRequest request = this.restHandler.PrepareRequest(requestParameters: parameters, requestBody: null, includeRequestId: false);
request.Accept = CoreConstants.CONTENTTYPE_APPLICATIONPDF;
//Exception for Download, it does not accept "Accept" header
//request.Accept = null;
byte[] response = new byte[0];
try
{
// Gets response
response = this.restHandler.GetResponseStream(request);
}
catch (IdsException ex)
{
IdsExceptionManager.HandleException(ex);
}
return response;
}
#endregion
#region Email
/// <summary>
/// Call the synchronous methods to send entity of type T in an email.
/// </summary>
/// <typeparam name="T">Generic Type T.</typeparam>
/// <param name="entity">Instance of entity to be sent in an email. This is not the actual entity that will be emailed. This entity needs to be present on server and the entity on the server will be sent in an email.Any changes in the passed in entity must be committed to the server in order for it to reflect in the email. Entities of type Sales Receipt, Invoice and Estimate are supported to be sent in an email as pdf</param>
/// <param name="sendToEmail">Optional parameter to specify an email address</param>
/// <returns name="T">Retruns the entity sent in email</returns>
public T SendEmail<T>(T entity, string sendToEmail = null) where T : IEntity
{
// Validate parameter
if (!ServicesHelper.IsTypeNull(entity))
{
IdsException exception = new IdsException(Resources.ParameterNotNullMessage, new ArgumentNullException(Resources.EntityString));
this.serviceContext.IppConfiguration.Logger.CustomLogger.Log(Diagnostics.TraceLevel.Error, string.Format(CultureInfo.InvariantCulture, Resources.ExceptionGeneratedMessage, exception.ToString()));
IdsExceptionManager.HandleException(exception);
}
this.serviceContext.IppConfiguration.Logger.CustomLogger.Log(Diagnostics.TraceLevel.Info, "Called Method SendEmail by " + entity.GetType().FullName);
string id = string.Empty;
string resourceString = entity.GetType().Name.ToLower(CultureInfo.InvariantCulture);
// Convert to role base to get the Id property which is required to Find the entity.
IntuitEntity intuitEntity = entity as IntuitEntity;
if (intuitEntity == null)
{
IdsException exception = new IdsException(Resources.EntityConversionFailedMessage);
this.serviceContext.IppConfiguration.Logger.CustomLogger.Log(Diagnostics.TraceLevel.Error, string.Format(CultureInfo.InvariantCulture, Resources.ExceptionGeneratedMessage, exception.ToString()));
IdsExceptionManager.HandleException(exception);
}
// Check whether the Id is null and throw an exception if it is null.
if (string.IsNullOrWhiteSpace(intuitEntity.Id) && (entity.GetType().Name != "Preferences"))
{
IdsException exception = new IdsException(Resources.EntityIdNotNullMessage, new ArgumentNullException(Resources.IdString));
this.serviceContext.IppConfiguration.Logger.CustomLogger.Log(Diagnostics.TraceLevel.Error, string.Format(CultureInfo.InvariantCulture, Resources.ExceptionGeneratedMessage, exception.ToString()));
IdsExceptionManager.HandleException(exception);
}
//check if the operation is allowed on the entity
CheckForPdfAllowedEntities(entity);
//check if email address is valid
ProcessSendToEmail(sendToEmail);
id = intuitEntity.Id;
//build the url to be called
string uri = string.Empty;
//IF sendtoemail is specidfied that takes priority and is used to send the email to, if not specified it uses the email from BillEmail.Address from the entity saved on the server and not from the passes in entity
uri = String.IsNullOrWhiteSpace(sendToEmail) ? string.Format(CultureInfo.InvariantCulture, "{0}/company/{1}/{2}/{3}/send", CoreConstants.VERSION, this.serviceContext.RealmId, resourceString, id) : string.Format(CultureInfo.InvariantCulture, "{0}/company/{1}/{2}/{3}/send?sendTo={4}", CoreConstants.VERSION, this.serviceContext.RealmId, resourceString, id, sendToEmail);
// Creates request parameters
RequestParameters parameters;
if (this.serviceContext.IppConfiguration.Message.Request.SerializationFormat ==
Intuit.Ipp.Core.Configuration.SerializationFormat.Json)
{
parameters = new RequestParameters(uri, HttpVerbType.POST, CoreConstants.CONTENTTYPE_APPLICATIONJSON);
}
else
{
parameters = new RequestParameters(uri, HttpVerbType.POST, CoreConstants.CONTENTTYPE_APPLICATIONXML);
}
// Prepare request
HttpWebRequest request = this.restHandler.PrepareRequest(requestParameters: parameters, requestBody: null, includeRequestId: false);
request.ContentType = CoreConstants.CONTENTTYPE_APPLICATIONOCTETSTREAM;
string response = string.Empty;
try
{
// Gets response
response = this.restHandler.GetResponse(request);
}
catch (IdsException ex)
{
IdsExceptionManager.HandleException(ex);
}
CoreHelper.CheckNullResponseAndThrowException(response);
// De serialize object
IntuitResponse restResponse = (IntuitResponse)CoreHelper.GetSerializer(this.serviceContext, false).Deserialize<IntuitResponse>(response);
object value = restResponse.AnyIntuitObject;
if (value != null)
{
return (T)(value as IEntity);
}
else
{
return default(T);
}
}
private void ProcessSendToEmail(String sendToEmail)
{
//if email address is null return no need to check
if (String.IsNullOrWhiteSpace(sendToEmail)) return;
//check if the eamil address is empty or null
if (IsValidEmailAddress(sendToEmail)) return;
IdsException exception = new IdsException(Resources.EmailAddressNotValid,
new ArgumentNullException(Resources.IdString));
this.serviceContext.IppConfiguration.Logger.CustomLogger.Log(Diagnostics.TraceLevel.Error,
string.Format(
CultureInfo.InvariantCulture,
Resources.EmailAddressNotValidExceptionMessage,
exception.ToString()));
IdsExceptionManager.HandleException(exception);
}
private bool IsValidEmailAddress(String emailAddress)
{
return !String.IsNullOrWhiteSpace(emailAddress) && Regex.IsMatch(emailAddress,
@"^(?("")(""[^""]+?""@)|(([0-9a-z]((\.(?!\.))|[-!#\$%&'\*\+/=\?\^`\{\}\|~\w])*)(?<=[0-9a-z])@))"
+ @"(?(\[)(\[(\d{1,3}\.){3}\d{1,3}\])|(([0-9a-z][-\w]*[0-9a-z]*\.)+[a-z0-9]{2,17}))$",
RegexOptions.IgnoreCase);
}
#endregion
/// <summary>
/// Returns an entity under the specified realm. The realm must be set in the context.
/// </summary>
/// <typeparam name="T">Generic Type T.</typeparam>
/// <param name="entity"> Entity type to Find.</param>
/// <returns> Returns an entity of specified Id.</returns>
public T FindById<T>(T entity) where T : IEntity
{
this.serviceContext.IppConfiguration.Logger.CustomLogger.Log(Diagnostics.TraceLevel.Info, "Called Method FindById.");
// Validate parameter
if (!ServicesHelper.IsTypeNull(entity))
{
IdsException exception = new IdsException(Resources.ParameterNotNullMessage, new ArgumentNullException(Resources.EntityString));
this.serviceContext.IppConfiguration.Logger.CustomLogger.Log(Diagnostics.TraceLevel.Error, string.Format(CultureInfo.InvariantCulture, Resources.ExceptionGeneratedMessage, exception.ToString()));
IdsExceptionManager.HandleException(exception);
}
string id = string.Empty;
string resourceString = entity.GetType().Name.ToLower(CultureInfo.InvariantCulture);
// Convert to role base to get the Id property which is required to Find the entity.
IntuitEntity intuitEntity = entity as IntuitEntity;
if (intuitEntity == null)
{
IdsException exception = new IdsException(Resources.EntityConversionFailedMessage);
this.serviceContext.IppConfiguration.Logger.CustomLogger.Log(Diagnostics.TraceLevel.Error, string.Format(CultureInfo.InvariantCulture, Resources.ExceptionGeneratedMessage, exception.ToString()));
IdsExceptionManager.HandleException(exception);
}
// Check whether the Id is null and throw an exception if it is null.
if (string.IsNullOrWhiteSpace(intuitEntity.Id) && (entity.GetType().Name != "Preferences"))
{
IdsException exception = new IdsException(Resources.EntityIdNotNullMessage, new ArgumentNullException(Resources.IdString));
this.serviceContext.IppConfiguration.Logger.CustomLogger.Log(Diagnostics.TraceLevel.Error, string.Format(CultureInfo.InvariantCulture, Resources.ExceptionGeneratedMessage, exception.ToString()));
IdsExceptionManager.HandleException(exception);
}
id = intuitEntity.Id;
string uri = string.Empty;
if (resourceString.Equals("preferences"))
{
uri = string.Format(CultureInfo.InvariantCulture, "{0}/company/{1}/{2}", CoreConstants.VERSION, this.serviceContext.RealmId, resourceString);
}
else
{
uri = string.Format(CultureInfo.InvariantCulture, "{0}/company/{1}/{2}/{3}", CoreConstants.VERSION, this.serviceContext.RealmId, resourceString, id);
}
// Creates request parameters
RequestParameters parameters;
if (this.serviceContext.IppConfiguration.Message.Request.SerializationFormat ==
Intuit.Ipp.Core.Configuration.SerializationFormat.Json)
{
parameters = new RequestParameters(uri, HttpVerbType.GET, CoreConstants.CONTENTTYPE_APPLICATIONJSON);
}
else
{
parameters = new RequestParameters(uri, HttpVerbType.GET, CoreConstants.CONTENTTYPE_APPLICATIONXML);
}
// Prepares request
HttpWebRequest request = this.restHandler.PrepareRequest(parameters, null);
string response = string.Empty;
try
{
// Gets response
response = this.restHandler.GetResponse(request);
}
catch (IdsException ex)
{
IdsExceptionManager.HandleException(ex);
}
CoreHelper.CheckNullResponseAndThrowException(response);
// De serialize object
IntuitResponse restResponse =
(IntuitResponse)
CoreHelper.GetSerializer(this.serviceContext, false).Deserialize<IntuitResponse>(response);
object value = restResponse.AnyIntuitObject;
if (value != null)
{
return (T)(value as IEntity);
}
else
{
return default(T);
}
}
/// <summary>
/// Returns entities by the Parent Id specified, supported for TaxClassification only.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="entity"></param>
/// <returns></returns>
public ReadOnlyCollection<T> FindByParentId<T>(T entity) where T : IEntity
{
this.serviceContext.IppConfiguration.Logger.CustomLogger.Log(Diagnostics.TraceLevel.Info, "Called Method FindByParentId.");
ServicesHelper.ValidateEntity(entity, serviceContext);
ServicesHelper.ValidateEntityType(entity, "TaxClassification", serviceContext);
string parentId = string.Empty;
ReferenceType parentRef = ServicesHelper.PrepareByParentId(entity, serviceContext);
ServicesHelper.ValidateObject(parentRef, serviceContext);
parentId = parentRef.Value;
string resourceString = entity.GetType().Name.ToLower(CultureInfo.InvariantCulture);
// Convert to role base to get the Id property which is required to Find the entity.
IntuitEntity intuitEntity = entity as IntuitEntity;
ServicesHelper.ValidateIntuitEntity(intuitEntity, serviceContext);
// Check whether the Id is null and throw an exception if it is null.
ServicesHelper.ValidateId(parentId, serviceContext);
string uri = string.Empty;
uri = string.Format(CultureInfo.InvariantCulture, "{0}/company/{1}/{2}/{3}/children", CoreConstants.VERSION, this.serviceContext.RealmId, resourceString, parentId);
List<T> entities = PrepareAndExecuteHttpRequest<T>(uri);
this.serviceContext.IppConfiguration.Logger.CustomLogger.Log(Diagnostics.TraceLevel.Info, "Finished Executing Method FindByParentId.");
ReadOnlyCollection<T> readOnlyCollection = new ReadOnlyCollection<T>(entities);
return readOnlyCollection;
}
/// <summary>
/// Returns entities by the Level specified, supported for TaxClassification only.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="entity"></param>
/// <returns></returns>
public ReadOnlyCollection<T> FindByLevel<T>(T entity) where T : IEntity
{
this.serviceContext.IppConfiguration.Logger.CustomLogger.Log(Diagnostics.TraceLevel.Info, "Called Method FindByLevel.");
// Validate parameter
ServicesHelper.ValidateEntity(entity, serviceContext);
ServicesHelper.ValidateEntityType(entity, "TaxClassification", serviceContext);
string level = string.Empty;
level = ServicesHelper.PrepareByLevel(entity, serviceContext);
string resourceString = entity.GetType().Name.ToLower(CultureInfo.InvariantCulture);
// Convert to role base to get the Id property which is required to Find the entity.
IntuitEntity intuitEntity = entity as IntuitEntity;
ServicesHelper.ValidateIntuitEntity(intuitEntity, serviceContext);
// Check whether the Level is null and throw an exception if it is null.
ServicesHelper.ValidateId(level, serviceContext);
string uri = string.Empty;
uri = string.Format(CultureInfo.InvariantCulture, "{0}/company/{1}/{2}?level={3}", CoreConstants.VERSION, this.serviceContext.RealmId, resourceString, level);
List<T> entities = PrepareAndExecuteHttpRequest<T>(uri);
this.serviceContext.IppConfiguration.Logger.CustomLogger.Log(Diagnostics.TraceLevel.Info, "Finished Executing Method FindByLevel.");
ReadOnlyCollection<T> readOnlyCollection = new ReadOnlyCollection<T>(entities);
return readOnlyCollection;
}
/// <summary>
/// Returns a list of all entities of type T under the specified realm. The realm must be set in the context.
/// </summary>
/// <typeparam name="T">Generic Type T.</typeparam>
/// <param name="entity">The entity for which the data is required.</param>
/// <param name="startPosition">The start position to retrieve.</param>
/// <param name="maxResults">Maximum no. of results to retrieve</param>
/// <returns> Returns the list of entities.</returns>
public ReadOnlyCollection<T> FindAll<T>(T entity, int startPosition = 1, int maxResults = 500) where T : IEntity
{
this.serviceContext.IppConfiguration.Logger.CustomLogger.Log(Diagnostics.TraceLevel.Info, "Called Method FindAll.");
ServicesHelper.ValidateEntity(entity, serviceContext);
string resourceString = entity.GetType().Name;
List<T> entities = new List<T>();
if (resourceString == "TaxClassification")
{
string uri = string.Empty;
uri = string.Format(CultureInfo.InvariantCulture, "{0}/company/{1}/{2}", CoreConstants.VERSION, this.serviceContext.RealmId, resourceString.ToLower(CultureInfo.InvariantCulture));
entities = PrepareAndExecuteHttpRequest<T>(uri);
}
else
{
if (startPosition <= 0)
{
IdsException exception = new IdsException(Resources.ParameterZeroNegativeValueMessage, new ArgumentException(Resources.PageNumberString));
this.serviceContext.IppConfiguration.Logger.CustomLogger.Log(Diagnostics.TraceLevel.Error, string.Format(CultureInfo.InvariantCulture, Resources.ExceptionGeneratedMessage, exception.ToString()));
IdsExceptionManager.HandleException(exception);
}
if (maxResults <= 0)
{
IdsException exception = new IdsException(Resources.ParameterZeroNegativeValueMessage, new ArgumentException(Resources.PageSizeString));
this.serviceContext.IppConfiguration.Logger.CustomLogger.Log(Diagnostics.TraceLevel.Error, string.Format(CultureInfo.InvariantCulture, Resources.ExceptionGeneratedMessage, exception.ToString()));
IdsExceptionManager.HandleException(exception);
}
// Gets the resource name to be added to the resource Uri
string query = string.Format(CultureInfo.InvariantCulture, "select * from {0} startPosition {1} maxResults {2}", resourceString, startPosition, maxResults);
string uri = string.Format(CultureInfo.InvariantCulture, "{0}/company/{1}/query", CoreConstants.VERSION, this.serviceContext.RealmId);
// Creates request parameters
RequestParameters parameters = null;
parameters = new RequestParameters(uri, HttpVerbType.POST, CoreConstants.CONTENTTYPE_APPLICATIONTEXT);
// Prepares request
HttpWebRequest request = this.restHandler.PrepareRequest(parameters, query);
string response = string.Empty;
try
{
// Gets response