forked from Sage/SDataCSharpClientLib
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSDataService.cs
More file actions
703 lines (627 loc) · 26.1 KB
/
Copy pathSDataService.cs
File metadata and controls
703 lines (627 loc) · 26.1 KB
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
using System;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Net;
using System.Xml;
using Sage.SData.Client.Atom;
using Sage.SData.Client.Common;
using Sage.SData.Client.Extensions;
using Sage.SData.Client.Framework;
using Sage.SData.Client.Metadata;
namespace Sage.SData.Client.Core
{
/// <summary>
/// Service class for processing SData Request
/// </summary>
/// <example>
/// <code lang="cs" title="The following code example demonstrates the usage of the SDataService class.">
/// <code
/// source=".\Example.cs"
/// region="SDataService Configuration"
/// />
/// </code>
/// </example>
public class SDataService : ISDataService, ISDataRequestSettings
{
private readonly SDataUri _uri;
/// <summary>
/// Flag set when Service is initialized
/// </summary>
[Obsolete("Explicit initialization is no longer required.")]
public bool Initialized
{
get { return true; }
}
/// <remarks>
/// Creates the service with predefined values for the url
/// </remarks>
public string Url
{
get { return _uri.ToString(); }
set { _uri.Uri = new Uri(value); }
}
/// <summary>
/// Accessor method for protocol,
/// </summary>
/// <remarks>HTTP is the default but can be HTTPS</remarks>
public string Protocol
{
get { return _uri.Scheme; }
set { _uri.Scheme = value; }
}
/// <remarks>
/// IP address is also allowed (192.168.1.1).
/// Can be followed by port number. For example www.example.com:5493.
/// 5493 is the recommended port number for SData services that are not exposed on the Internet.
/// </remarks>
public string ServerName
{
get { return _uri.Host; }
set
{
if (_uri.Host != value)
{
if (value != null)
{
var pos = value.IndexOf(':');
int port;
if (pos >= 0 && int.TryParse(value.Substring(pos + 1), out port))
{
value = value.Substring(0, pos);
_uri.Port = port;
}
}
_uri.Host = value;
}
}
}
/// <summary>
/// Gets or sets the port.
/// </summary>
public int? Port
{
get { return _uri.Port; }
set { _uri.Port = value ?? 80; }
}
/// <summary>
/// Accessor method for virtual directory
/// </summary>
/// <remarks>Must be sdata, unless the technical framework imposes something different.
///</remarks>
public string VirtualDirectory
{
get { return _uri.Server; }
set { _uri.Server = value; }
}
/// <summary>
/// Gets or sets the name of the application.
/// </summary>
/// <value>The name of the application.</value>
/// <remarks>
/// The <see cref="ApplicationName"/> is used to identify users specific to an application. That is, the same syndication resource can exist in the data store
/// for multiple applications that specify a different <see cref="ApplicationName"/>. This enables multiple applications to use the same data store to store resource
/// information without running into duplicate syndication resource conflicts. Alternatively, multiple applications can use the same syndication resource data store
/// by specifying the same <see cref="ApplicationName"/>. The <see cref="ApplicationName"/> can be set programmatically or declaratively in the configuration for the application.
/// </remarks>
public string ApplicationName
{
get { return _uri.Product; }
set { _uri.Product = value; }
}
/// <summary>
/// Accessor method for contractName
/// </summary>
/// <remarks>An SData service can support several “integration contracts” side-by-side.
/// For example, a typical Sage ERP service will support a crmErp contract which exposes
/// the resources required by CRM integration (with schemas imposed by the CRM/ERP contract)
/// and a native or default contract which exposes all the resources of the ERP in their native format.
/// </remarks>
public string ContractName
{
get { return _uri.Contract; }
set { _uri.Contract = value; }
}
/// <summary>
/// Accessor method for dataSet
/// </summary>
/// <remarks>Identifies the dataset when the application gives access to several datasets, such as several companies and production/test datasets.
/// If the application can only handle a single dataset, or if it can be configured with a default dataset,
/// a hyphen can be used as a placeholder for the default dataset.
/// For example, if prod is the default dataset in the example above, the URL could be shortened as:
/// http://www.example.com/sdata/sageApp/test/-/accounts?startIndex=21&count=10
/// If several parameters are required to specify the dataset (for example database name and company id),
/// they should be formatted as a single segment in the URL. For example, sageApp/test/demodb;acme/accounts -- the semicolon separator is application specific, not imposed by SData.
///</remarks>
public string DataSet
{
get { return _uri.CompanyDataset; }
set { _uri.CompanyDataset = value; }
}
/// <summary>
/// Get set for the user name to authenticate with
/// </summary>
public string UserName { get; set; }
/// <summary>
/// Get/set for the password to authenticate with
/// </summary>
public string Password { get; set; }
/// <summary>
/// Gets or sets the timeout in milliseconds used during requests.
/// </summary>
public int Timeout { get; set; }
/// <summary>
/// Gets the cookie collection associated with all requests to the server.
/// </summary>
public CookieContainer Cookies { get; set; }
/// <summary>
/// Gets or sets the user agent passed during requests.
/// </summary>
public string UserAgent { get; set; }
/// <summary>
/// Adds a new syndication resource to the data source.
/// </summary>
/// <param name="request">The request that identifies the resource within the syndication data source.</param>
/// <param name="feed"></param>
public virtual AtomFeed CreateFeed(SDataBaseRequest request, AtomFeed feed)
{
string eTag;
return CreateFeed(request, feed, out eTag);
}
/// <summary>
/// Adds a new syndication resource to the data source.
/// </summary>
/// <param name="request"></param>
/// <param name="feed"></param>
/// <param name="eTag"></param>
/// <returns></returns>
public virtual AtomFeed CreateFeed(SDataBaseRequest request, AtomFeed feed, out string eTag)
{
Guard.ArgumentNotNull(request, "request");
Guard.ArgumentNotNull(feed, "feed");
try
{
var requestUrl = request.ToString();
var operation = new RequestOperation(HttpMethod.Post, feed);
var response = ExecuteRequest(requestUrl, operation, MediaType.Atom, MediaType.Xml);
eTag = response.ETag;
return (AtomFeed) response.Content;
}
catch (Exception ex)
{
throw new SDataClientException(ex.Message, ex);
}
}
/// <summary>
/// Adds a new syndication resource to the data source.
/// </summary>
/// <param name="request">The request that identifies the resource within the syndication data source.</param>
/// <param name="entry">The entry that should be created.</param>
public virtual AtomEntry CreateEntry(SDataBaseRequest request, AtomEntry entry)
{
Guard.ArgumentNotNull(request, "request");
var requestUrl = request.ToString();
return CreateEntry(requestUrl, entry);
}
private AtomEntry CreateEntry(string url, AtomEntry entry)
{
Guard.ArgumentNotNull(entry, "entry");
try
{
var batchItem = new SDataBatchRequestItem
{
Url = url,
Method = HttpMethod.Post,
Entry = entry
};
if (BatchProcess.Instance.AddToBatch(batchItem))
{
return null;
}
var operation = new RequestOperation(HttpMethod.Post, entry);
var response = ExecuteRequest(url, operation, MediaType.AtomEntry, MediaType.Xml);
var result = response.Content as AtomEntry;
if (result == null)
{
var feedResult = response.Content as AtomFeed;
if (feedResult != null)
{
result = feedResult.Entries.FirstOrDefault();
}
}
if (!string.IsNullOrEmpty(response.ETag) && result != null)
{
result.SetSDataHttpETag(response.ETag);
}
return result;
}
catch (Exception ex)
{
throw new SDataClientException(ex.Message, ex);
}
}
/// <summary>
/// Asynchronous PUT to the server
/// </summary>
/// <param name="request">The request that identifies the resource within the syndication data source.</param>
/// <param name="resource">The resource that should be created asynchronously.</param>
public virtual AsyncRequest CreateAsync(SDataBaseRequest request, ISyndicationResource resource)
{
Guard.ArgumentNotNull(request, "request");
Guard.ArgumentNotNull(resource, "resource");
try
{
var requestUrl = new SDataUri(request.ToString()) {TrackingId = Guid.NewGuid().ToString()}.ToString();
var operation = new RequestOperation(HttpMethod.Post, resource);
var response = ExecuteRequest(requestUrl, operation, MediaType.Xml);
var tracking = (Tracking) response.Content;
return new AsyncRequest(this, response.Location, tracking);
}
catch (Exception ex)
{
throw new SDataClientException(ex.Message, ex);
}
}
/// <summary>
/// Generic delete from server
/// </summary>
/// <param name="url">the url for the operation</param>
/// <returns><b>true</b> returns true if the operation was successful</returns>
public virtual bool Delete(string url)
{
Guard.ArgumentNotNull(url, "url");
try
{
var operation = new RequestOperation(HttpMethod.Delete);
var response = ExecuteRequest(url, operation, MediaType.Xml);
return response.StatusCode == HttpStatusCode.OK;
}
catch (Exception ex)
{
throw new SDataClientException(ex.Message, ex);
}
}
/// <summary>
/// Removes a resource from the syndication data source.
/// </summary>
/// <param name="request"></param>
/// <returns></returns>
public virtual bool DeleteEntry(SDataBaseRequest request)
{
return DeleteEntry(request, null);
}
/// <summary>
/// Removes a resource from the syndication data source.
/// </summary>
/// <param name="request">The request from the syndication data source for the resource to be removed.</param>
/// <param name="entry">the resource that is being deleted</param>
/// <returns><b>true</b> if the syndication resource was successfully deleted; otherwise, <b>false</b>.</returns>
public virtual bool DeleteEntry(SDataBaseRequest request, AtomEntry entry)
{
Guard.ArgumentNotNull(request, "request");
return DeleteEntry(request.ToString(), entry);
}
private bool DeleteEntry(string url, AtomEntry entry)
{
try
{
var eTag = entry != null ? entry.GetSDataHttpETag() : null;
var batchItem = new SDataBatchRequestItem
{
Url = url,
Method = HttpMethod.Delete,
ETag = eTag
};
if (BatchProcess.Instance.AddToBatch(batchItem))
{
return true;
}
var operation = new RequestOperation(HttpMethod.Delete) {ETag = eTag};
var response = ExecuteRequest(url, operation, MediaType.AtomEntry, MediaType.Xml);
return response.StatusCode == HttpStatusCode.OK;
}
catch (Exception ex)
{
throw new SDataClientException(ex.Message, ex);
}
}
/// <summary>
/// generic read from the specified url
/// </summary>
/// <param name="url">url to read from </param>
/// <returns>string response from server</returns>
public virtual object Read(string url)
{
Guard.ArgumentNotNull(url, "url");
try
{
var operation = new RequestOperation(HttpMethod.Get);
var response = ExecuteRequest(url, operation);
if (response.Content is string && response.ContentType == MediaType.Xml)
{
try
{
return ReadSchema(response);
}
catch (XmlException)
{
}
catch (InvalidOperationException)
{
}
}
return response.Content;
}
catch (Exception ex)
{
throw new SDataClientException(ex.Message, ex);
}
}
public void ReadAsync(string url, object userState)
{
Guard.ArgumentNotNull(url, "url");
var operation = new RequestOperation(HttpMethod.Get);
var request = new SDataRequest(url, operation)
{
UserName = UserName,
Password = Password,
Timeout = Timeout,
Cookies = Cookies,
UserAgent = UserAgent
};
request.BeginGetResponse(
asyncResult =>
{
try
{
var response = request.EndGetResponse(asyncResult);
if (ReadCompleted != null)
{
var content = response.Content;
if (content is string && response.ContentType == MediaType.Xml)
{
try
{
content = ReadSchema(response);
}
catch (XmlException)
{
}
catch (InvalidOperationException)
{
}
}
ReadCompleted(this, new ReadCompletedEventArgs(content, null, false, userState));
}
}
catch (Exception ex)
{
if (ReadCompleted != null)
{
ReadCompleted(this, new ReadCompletedEventArgs(null, ex, false, userState));
}
}
}, null);
}
public event EventHandler<ReadCompletedEventArgs> ReadCompleted;
/// <summary>
/// Reads resource information from the data source based on the URL.
/// </summary>
/// <param name="request">request for the syndication resource to get information for.</param>
/// <returns>AtomFeed <see cref="AtomFeed"/> populated with the specified resources's information from the data source.</returns>
public virtual AtomFeed ReadFeed(SDataBaseRequest request)
{
string eTag = null;
return ReadFeed(request, ref eTag);
}
/// <summary>
/// Reads resource information from the data source based on the URL and the specified ETag.
/// </summary>
/// <param name="request"></param>
/// <param name="eTag"></param>
/// <returns></returns>
public virtual AtomFeed ReadFeed(SDataBaseRequest request, ref string eTag)
{
Guard.ArgumentNotNull(request, "request");
try
{
var requestUrl = request.ToString();
var operation = new RequestOperation(HttpMethod.Get) {ETag = eTag};
var response = ExecuteRequest(requestUrl, operation, MediaType.Atom, MediaType.Xml);
eTag = response.ETag;
return (AtomFeed) response.Content;
}
catch (Exception ex)
{
throw new SDataClientException(ex.Message, ex);
}
}
/// <summary>
/// Reads resource information from the data source based on the URL.
/// </summary>
/// <param name="request">Request for the syndication resource to get information for.</param>
/// <returns>An <see cref="AtomEntry"/> populated with the specified resources' information from the data source.</returns>
public virtual AtomEntry ReadEntry(SDataBaseRequest request)
{
return ReadEntry(request, null);
}
/// <summary>
/// Reads resource information from the data source based on the URL and the ETag of the specified entry.
/// </summary>
/// <param name="request"></param>
/// <param name="entry"></param>
/// <returns></returns>
public virtual AtomEntry ReadEntry(SDataBaseRequest request, AtomEntry entry)
{
Guard.ArgumentNotNull(request, "request");
try
{
var requestUrl = request.ToString();
var eTag = entry != null ? entry.GetSDataHttpETag() : null;
var batchItem = new SDataBatchRequestItem
{
Url = requestUrl,
Method = HttpMethod.Get,
ETag = eTag
};
if (BatchProcess.Instance.AddToBatch(batchItem))
{
return null;
}
var operation = new RequestOperation(HttpMethod.Get) {ETag = eTag};
var response = ExecuteRequest(requestUrl, operation, MediaType.AtomEntry, MediaType.Xml);
entry = (AtomEntry) response.Content;
if (!string.IsNullOrEmpty(response.ETag))
{
entry.SetSDataHttpETag(response.ETag);
}
return entry;
}
catch (Exception ex)
{
throw new SDataClientException(ex.Message, ex);
}
}
/// <summary>
/// Reads xsd from a $schema request
/// </summary>
/// <param name="request">url for the syndication resource to get information for.</param>
/// <returns>SDataSchema</returns>
public virtual SDataSchemaObject ReadSchema(SDataResourceSchemaRequest request)
{
Guard.ArgumentNotNull(request, "request");
try
{
var requestUrl = request.ToString();
var operation = new RequestOperation(HttpMethod.Get);
var response = ExecuteRequest(requestUrl, operation, MediaType.Xml);
return ReadSchema(response);
}
catch (Exception ex)
{
throw new SDataClientException(ex.Message, ex);
}
}
private static SDataSchemaObject ReadSchema(ISDataResponse response)
{
using (var reader = new StringReader((string) response.Content))
{
var schema = SDataSchema.Read(reader);
if (!string.IsNullOrEmpty(response.Location))
{
var targetElementName = new Uri(response.Location).Fragment.TrimStart('#');
if (!string.IsNullOrEmpty(targetElementName))
{
var resource = schema.ResourceTypes[targetElementName];
if (resource != null)
{
return resource;
}
}
}
return schema;
}
}
/// <summary>
/// Updates information about a syndication resource in the data source.
/// </summary>
/// <param name="request">The url from the syndication data source for the resource to be updated.</param>
/// <param name="entry">
/// An object that implements the <see cref="ISyndicationResource"/> interface that represents the updated information for the resource.
/// </param>
public virtual AtomEntry UpdateEntry(SDataBaseRequest request, AtomEntry entry)
{
Guard.ArgumentNotNull(request, "request");
return UpdateEntry(request.ToString(), entry);
}
private AtomEntry UpdateEntry(string url, AtomEntry entry)
{
Guard.ArgumentNotNull(entry, "entry");
try
{
var eTag = entry.GetSDataHttpETag();
var batchItem = new SDataBatchRequestItem
{
Url = url,
Method = HttpMethod.Put,
Entry = entry,
ETag = eTag
};
if (BatchProcess.Instance.AddToBatch(batchItem))
{
return null;
}
var operation = new RequestOperation(HttpMethod.Put, entry) {ETag = eTag};
var response = ExecuteRequest(url, operation, MediaType.AtomEntry, MediaType.Xml);
entry = (AtomEntry) response.Content;
if (!string.IsNullOrEmpty(response.ETag))
{
entry.SetSDataHttpETag(response.ETag);
}
return entry;
}
catch (Exception ex)
{
throw new SDataClientException(ex.Message, ex);
}
}
/// <summary>
/// Initialises a new instance of the <see cref="SDataService"/> class.
/// </summary>
public SDataService()
: this(null)
{
}
/// <summary>
/// Initialises a new instance of the <see cref="SDataService"/> class, initialized with a target url.
/// </summary>
/// <param name="url"></param>
public SDataService(string url)
: this(url, null, null)
{
}
/// <summary>
/// Initialises a new instance of the <see cref="SDataService"/> class, initialized with a target url, user name and password.
/// </summary>
/// <param name="url"></param>
/// <param name="userName">user name used for credentials</param>
/// <param name="password">password for user</param>
public SDataService(string url, string userName, string password)
{
_uri = url != null
? new SDataUri(url)
: new SDataUri
{
Server = "sdata",
Product = "-",
Contract = "-",
CompanyDataset = "-"
};
UserName = userName;
Password = password;
Timeout = 120000;
UserAgent = "Sage";
}
/// <summary>
/// Initializes the <see cref="SDataService"/>
/// </summary>
/// <remarks>Set the User Name and Password to authenticate with and build the url</remarks>
[Obsolete("Explicit initialization is no longer required.")]
public void Initialize()
{
}
protected virtual ISDataResponse ExecuteRequest(string url, RequestOperation operation, params MediaType[] accept)
{
var request = new SDataRequest(url, operation)
{
Accept = accept,
UserName = UserName,
Password = Password,
Timeout = Timeout,
Cookies = Cookies,
UserAgent = UserAgent
};
return request.GetResponse();
}
}
}