-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathDocumentDBDomainManager.cs
333 lines (269 loc) · 10.7 KB
/
DocumentDBDomainManager.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
using Microsoft.Azure.Documents;
using Microsoft.Azure.Documents.Client;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Azure.Documents.Linq;
using System.Web.Http;
using System.Configuration;
using System.IO;
using System.Net;
using Newtonsoft.Json;
using System.Web.Http.OData;
using Microsoft.Azure.Mobile.Server.Tables;
namespace MobileAppDocDBOfflineSyncSampleService.Helpers
{
public class DocumentDBDomainManager<TDocument> :IDomainManager<TDocument> where TDocument : DocumentResource , new()
{
public HttpRequestMessage Request { get; set; }
//public ApiServices Services { get; set; }
private string _collectionId;
private string _databaseId;
private Database _database;
private DocumentCollection _collection;
private DocumentClient _client;
public DocumentDBDomainManager(string collectionId, string databaseId, HttpRequestMessage request)//, ApiServices services)
{
Request = request;
//Services = services;
_collectionId = collectionId;
_databaseId = databaseId;
}
// public DocumentDBDomainManager(HttpRequestMessage request, ApiServices services)
//{
// var attribute = typeof(TDocument).GetCustomAttributes(typeof(DocumentAttribute), true).FirstOrDefault() as DocumentAttribute;
// if (attribute == null)
// throw new ArgumentException("the model class must be decorated with the Document attribute");
// Request = request;
// Services = services;
// _collectionId = attribute.CollectionId;
// _databaseId = attribute.DatabaseId;
//}
public async Task<bool> DeleteAsync(string id)
{
try
{
var doc = GetDocument(id);
if (doc == null)
{
return false;
}
await Client.DeleteDocumentAsync(doc.SelfLink);
return true;
}
catch (Exception ex)
{
//Services.Log.Error(ex);
throw new HttpResponseException(System.Net.HttpStatusCode.InternalServerError);
}
}
public Task<TDocument> InsertAsync(TDocument data)
{
try
{
data.CreatedAt = DateTimeOffset.UtcNow;
data.UpdatedAt = DateTimeOffset.UtcNow;
return Client.CreateDocumentAsync(Collection.SelfLink, data)
.ContinueWith<TDocument>(t=> GetDocFromResponse(t));
}
catch (Exception ex)
{
//Services.Log.Error(ex);
throw new HttpResponseException(System.Net.HttpStatusCode.InternalServerError);
}
}
private TDocument GetDocFromResponse(Task<ResourceResponse<Document>> source)
{
if (source.IsFaulted)
{
new InvalidOperationException("Parent task is faulted.",source.Exception);
}
return GetDocEntity(source.Result.Resource);
}
private TDocument GetDocEntity(Document source)
{
if (source == null)
{
new ArgumentNullException("source");
}
return JsonConvert.DeserializeObject<TDocument>(JsonConvert.SerializeObject(source));
}
public SingleResult<TDocument> Lookup(string id)
{
var qry = this.Query().Where(d => d.Id == id)
.Select<TDocument, TDocument>(d => d);
var result = qry.ToList<TDocument>();
return SingleResult.Create<TDocument>(result.AsQueryable());
}
public Task<SingleResult<TDocument>> LookupAsync(string id)
{
try
{
return Task<SingleResult<TDocument>>.Run(()=> Lookup(id));
}
catch (Exception ex)
{
//Services.Log.Error(ex);
throw new HttpResponseException(System.Net.HttpStatusCode.InternalServerError);
}
}
public IQueryable<TDocument> Query()
{
try
{
var qry = Client
.CreateDocumentQuery<TDocument>(Collection.DocumentsLink)
.ToList()
.AsQueryable();
return qry;
}
catch (Exception ex)
{
//Services.Log.Error(ex);
throw new HttpResponseException(System.Net.HttpStatusCode.InternalServerError);
}
}
public Task<IEnumerable<TDocument>> QueryAsync()
{
throw new NotImplementedException();
}
public Task<TDocument> UpdateAsync(string id, Delta<TDocument> patch)
{
if (id == null)
{
throw new ArgumentNullException("id");
}
if (patch == null)
{
throw new ArgumentNullException("patch");
}
var doc = this.GetDocument(id);
if (doc == null)
{
//Services.Log.Error(string.Format( "Resource with id {0} not found", id));
throw new HttpResponseException(System.Net.HttpStatusCode.NotFound);
}
TDocument current = this.GetDocEntity(doc);
patch.Patch(current);
this.VerifyUpdatedKey(id, current);
current.UpdatedAt = DateTimeOffset.UtcNow;
try
{
return Client.ReplaceDocumentAsync(current.SelfLink, current)
.ContinueWith<TDocument>(t => GetDocFromResponse(t));
}
catch (Exception ex)
{
//Services.Log.Error(ex);
throw new HttpResponseException(System.Net.HttpStatusCode.InternalServerError);
}
}
public Task<TDocument> ReplaceAsync(string id, TDocument data)
{
if (id == null)
{
throw new ArgumentNullException("id");
}
if (data == null)
{
throw new ArgumentNullException("data");
}
this.VerifyUpdatedKey(id, data);
data.CreatedAt = DateTimeOffset.UtcNow;
try
{
return Client.ReplaceDocumentAsync(data.SelfLink, data)
.ContinueWith<TDocument>(t => GetDocFromResponse(t));
}
catch (Exception ex)
{
//Services.Log.Error(ex);
throw new HttpResponseException(System.Net.HttpStatusCode.InternalServerError);
}
}
private Document GetDocument(string id)
{
return Client.CreateDocumentQuery<Document>(Collection.DocumentsLink)
.Where(d => d.Id == id)
.AsEnumerable()
.FirstOrDefault();
}
private void VerifyUpdatedKey(string id, TDocument data)
{
if (data == null || data.Id != id)
{
HttpResponseMessage badKey = this.Request.CreateErrorResponse(HttpStatusCode.BadRequest, "The keys don't match");
throw new HttpResponseException(badKey);
}
}
#region DocumentDBClient
private DocumentClient Client
{
get
{
if (_client == null)
{
string endpoint = ConfigurationManager.AppSettings["endpoint"];
string authKey = ConfigurationManager.AppSettings["authKey"];
Uri endpointUri = new Uri(endpoint);
_client = new DocumentClient(endpointUri, authKey);
}
return _client;
}
}
private DocumentCollection Collection
{
get
{
if (_collection == null)
{
_collection = ReadOrCreateCollection(Database.SelfLink);
}
return _collection;
}
}
private Database Database
{
get
{
if (_database == null)
{
_database = ReadOrCreateDatabase();
}
return _database;
}
}
private DocumentCollection ReadOrCreateCollection(string databaseLink)
{
var col = Client.CreateDocumentCollectionQuery(databaseLink)
.Where(c => c.Id == _collectionId)
.AsEnumerable()
.FirstOrDefault();
if (col == null)
{
col = Client.CreateDocumentCollectionAsync(databaseLink, new DocumentCollection { Id = _collectionId }).Result;
}
return col;
}
private Database ReadOrCreateDatabase()
{
var db = Client.CreateDatabaseQuery()
.Where(d => d.Id == _databaseId)
.AsEnumerable()
.FirstOrDefault();
if (db == null)
{
db = Client.CreateDatabaseAsync(new Database { Id = _databaseId }).Result;
}
return db;
}
#endregion
public Task<IEnumerable<TDocument>> QueryAsync(System.Web.Http.OData.Query.ODataQueryOptions query)
{
throw new NotImplementedException();
}
}
}