示例#1
0
        public static async Task <string> GenerateHashAsync(Guid diagramId)
        {
            var result = string.Empty;

            using (DocumentDBContext docdb = new DocumentDBContext())
            {
                var id = diagramId.ToString().ToUpperInvariant();
                // var doc = await docdb.GetItemAsync<dynamic>(id, DiagramCollection);


                var input = string.Format("{0}{1}", Guid.NewGuid().ToString(), id.ToString());

                var sha        = new SHA256CryptoServiceProvider();
                var buffer     = Encoding.ASCII.GetBytes(input);
                var hash       = sha.ComputeHash(buffer);
                var hashString = string.Empty;
                foreach (var b in hash)
                {
                    hashString += b.ToString("X2");
                }
                var hashResult = new SharedDocumentResult()
                {
                    Id        = hashString,
                    DiagramId = id
                };
                var     json    = JsonConvert.SerializeObject(hashResult);
                dynamic success = await docdb.InsertOrUpdateItemAsync(DiagramCollection, json);

                result = hashResult.Id;
            }
            return(result);
        }
示例#2
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        static public async Task <List <dynamic> > GetUserDiagramsAsync(string userId)
        {
            List <dynamic> docs = new List <dynamic>();

            using (DocumentDBContext docdb = new DocumentDBContext(DiagramCollection))
            {
                var diagrams = (await docdb.GetItemsByPropertyAsync <dynamic>("userId", userId)).ToList();
                foreach (var diagram in diagrams)
                {
                    string name;
                    string ID;

                    try
                    {
                        name = diagram.name;
                    }
                    catch
                    {
                        name = "(blank)";
                    }
                    try {
                        ID = diagram.id;
                        docs.Add(new
                        {
                            name = name,
                            id   = ID
                        });
                    }
                    catch
                    {
                    }
                }
            }
            return(docs);
        }
示例#3
0
        private async Task <bool> tryDownloadSettings()
        {
            bool savedSettings = false;

            try
            {
                using (var dp = SimpleIoc.Default.GetInstance <IUnitOfWorkFactory>().CreateUnitOfWork())
                {
                    var syncedSettings = await DocumentDBContext.GetAllItemsAsync <SyncedSettings>(p => p.EntityType == EntityType.SETTING_SUMMARY);

                    var settingsToSave     = syncedSettings.FirstOrDefault();
                    var localSyncedSetting = dp.SyncedSettingsRepo.GetAll().FirstOrDefault();

                    settingsToSave.SyncedToCloud = true;
                    if (localSyncedSetting == null)
                    {
                        dp.SyncedSettingsRepo.Add(settingsToSave);
                    }
                    else
                    {
                        dp.SyncedSettingsRepo.Update(settingsToSave);
                    }
                    dp.SaveChanges();
                    savedSettings = true;
                }
            }
            catch (Exception exc)
            {
                Logging.Logger.Log(exc);
            }

            return(savedSettings);
        }
示例#4
0
        public async Task AddAsync_Creates_IfTrue_AndNotFound(string partitionKeyPath, int collectionThroughput)
        {
            // Arrange
            var mockService           = new Mock <IDocumentDBService>(MockBehavior.Strict);
            DocumentDBContext context = CreateContext(mockService.Object, partitionKeyPath: partitionKeyPath,
                                                      throughput: collectionThroughput, createIfNotExists: true);
            var collector = new DocumentDBAsyncCollector <Item>(context);

            mockService
            .SetupSequence(m => m.UpsertDocumentAsync(It.IsAny <Uri>(), It.IsAny <object>()))
            .Throws(DocumentDBTestUtility.CreateDocumentClientException(HttpStatusCode.NotFound))
            .Returns(Task.FromResult(new Document()));

            SetupDatabaseMock(mockService);
            SetupCollectionMock(mockService, partitionKeyPath, collectionThroughput);

            // Act
            await collector.AddAsync(new Item { Text = "hello!" });

            // Assert
            mockService.VerifyAll();

            // Verify that we upsert again after creation.
            mockService.Verify(m => m.UpsertDocumentAsync(It.IsAny <Uri>(), It.IsAny <object>()), Times.Exactly(2));
        }
示例#5
0
        private static async Task DeleteCollection(string appDataPath)
        {
            try
            {
                string settingsFile    = appDataPath + "\\" + FolderConstants.GIN_APP_DATA_FOLDER + "\\settings.txt";
                string encryptedString = System.IO.File.ReadAllText(settingsFile);
                string decryptedString = CottonDBMS.Helpers.EncryptionHelper.Decrypt(encryptedString);
                var    parms           = Newtonsoft.Json.JsonConvert.DeserializeObject <TruckAppInstallParams>(decryptedString);

                if (!string.IsNullOrEmpty(parms.EndPoint) &&
                    !string.IsNullOrEmpty(parms.Key))
                {
                    DocumentDBContext.Initialize(parms.EndPoint, parms.Key);

                    //remove document tracking lists this truck has downloaded
                    //this allows them to be released for delete etc at the gin
                    await DocumentDBContext.DeleteCollectionAsync();
                }
                else
                {
                    Console.WriteLine("One or more settings null.");
                }
            }
            catch (Exception exc)
            {
                Console.WriteLine(exc.Message);
                Console.WriteLine(exc.StackTrace);
                Console.WriteLine("Press enter to continue.");
                Console.ReadLine();
            }
        }
示例#6
0
        public static async Task SyncTrucksTable(CancellationToken cToken, UnitOfWork uow)
        {
            var trucks = await DocumentDBContext.GetAllItemsAsync <TruckEntity>(p => p.EntityType == EntityType.TRUCK);

            var localTruckIds = uow.TruckRepository.GetAllIds();

            if (cToken.IsCancellationRequested)
            {
                return;
            }
            using (var addWork = new UnitOfWork())
            {
                addWork.DisableChangeTracking();
                AddRemoteEntitiesToLocalOfType <TruckEntity>(addWork, addWork.TruckRepository, cToken, trucks, localTruckIds);
            }

            if (cToken.IsCancellationRequested)
            {
                return;
            }

            using (var updateWork = new UnitOfWork())
            {
                updateWork.DisableChangeTracking();
                SyncHelper.UpdateRemoteEntitiesOnLocalOfType <TruckEntity>(updateWork, updateWork.TruckRepository, cToken, trucks, localTruckIds, true);
            }

            if (cToken.IsCancellationRequested)
            {
                return;
            }
            SyncHelper.DeleteEntitiesOfTypeNoSourceCheck <TruckEntity>(uow, uow.TruckRepository, cToken, trucks);
        }
示例#8
0
文件: DAL.cs 项目: masonch/AzureLens
 /// <summary>
 /// 
 /// </summary>
 /// <param name="userId"></param>
 /// <returns></returns>
 static public async Task<List<dynamic>> GetUserDiagramsAsync(string userId)
 {
     List<dynamic> docs = new List<dynamic>();
     using (DocumentDBContext docdb = new DocumentDBContext("Diagrams"))
     {
         docs = await docdb.GetItemsByPropertyAsync<dynamic>("userId", userId);
     }
     return docs;
 }
        private async Task CreateCollection()
        {
            var exists = await DocumentDBContext.CollectionExistsAsync();

            if (!exists)
            {
                await DocumentDBContext.CreateCollectionAsync();

                await DocumentDBContext.CreateStoredProceduresAsync();
            }
        }
示例#10
0
        public void Setup()
        {
            TestingContext = new DocumentDBContext()
            {
                DatabaseId   = "TestDb-" + Guid.NewGuid().ToString(),
                CollectionId = "TestItemRepositoryTests-" + Guid.NewGuid().ToString()
            };

            _testUserId = Guid.NewGuid().ToString();

            _repository = new TestItemRepository(TestingContext);
            _repository.CreateDatabaseAsync(TestingContext.DatabaseId).Wait();
            _repository.CreateCollectionAsync(TestingContext.DatabaseId, TestingContext.CollectionId).Wait();
        }
示例#11
0
文件: DAL.cs 项目: dranreb/AzureLens
        /// <summary>
        /// Load a list of JSON documents
        /// TODO: will need to filter the result set by User
        /// </summary>
        /// <returns></returns>
        public static List<dynamic> LoadDiagrams()
        {
            List<dynamic> docs = new List<dynamic>();
            using (DocumentDBContext docdb = new DocumentDBContext())
            {
                // test only - load the same JSON doc into a list
                dynamic doc = LoadDiagram(new Guid("b2aea850-eada-2e77-e074-6fe8f099ccf4"));
                docs.Add(doc);
                docs.Add(doc);
                docs.Add(doc);

                //docs = docdb.GetUserItemAsync<dynamic>("*****@*****.**", "AzureLensColl");
            }
            return docs;
        }
示例#12
0
        public async Task CreateIfNotExist_Succeeds_IfDbAndCollectionExist()
        {
            // Arrange
            var mockService           = new Mock <IDocumentDBService>(MockBehavior.Strict);
            DocumentDBContext context = CreateContext(mockService.Object);

            SetupDatabaseMock(mockService, databaseExists: true);
            SetupCollectionMock(mockService, collectionExists: true);

            // Act
            await DocumentDBAsyncCollector <Item> .CreateIfNotExistAsync(context);

            // Assert
            mockService.VerifyAll();
        }
示例#13
0
文件: DAL.cs 项目: dranreb/AzureLens
 public static bool SaveDiagram(string doc)
 {
     dynamic rtnValue = false;
     try
     {
         using (DocumentDBContext docdb = new DocumentDBContext())
         {
             rtnValue = docdb.InsertOrUpdateItemAsync("AzureLensColl", doc);
         }
     }
     catch
     {
         // handle exception...
     }
     return rtnValue;
 }
示例#14
0
 static public async Task<bool> DeleteDiagramAsync(string diagramId)
 {
     var rtnValue = false;
     try
     {
         using (DocumentDBContext docdb = new DocumentDBContext())
         {
             rtnValue = await docdb.DeleteItemAsync(DiagramCollection, diagramId);
         }
     }
     catch
     {
         // handle exception...                
     }
     return rtnValue;
 }
示例#15
0
        public Repository(string collectionName, string databaseId = null, Expression <Func <T, object> > idNameFactory = null)
        {
            DocumentDBContext documentDBDataContext = new DocumentDBContext();

            _client = documentDBDataContext.Client;

            _databaseId = databaseId == null ? ConfigurationManager.AppSettings["DatabaseName"] : databaseId;

            _database = new AsyncLazy <Database>(async() => await GetOrCreateDatabaseAsync());

            _collection = new AsyncLazy <DocumentCollection>(async() => await GetOrCreateCollectionAsync());

            _collectionName = collectionName;

            _repositoryIdentityProperty = TryGetIdProperty(idNameFactory);
        }
示例#16
0
 /// <summary>
 /// Updates an existing diagram in the Diagrams collection
 /// NOTE: the Diagram JSON must have the id attribute or an exception will occur
 /// </summary>
 /// <param name="id"></param>
 /// <param name="diagram"></param>
 /// <returns></returns>
 static public async Task<string> UpdateDiagramAsync(string diagram)
 {
     string diagramId = string.Empty;
     try
     {
         using (DocumentDBContext docdb = new DocumentDBContext())
         {
             diagramId = await docdb.InsertOrUpdateItemAsync(DiagramCollection, diagram);
         }
     }
     catch
     {
         // handle exception...                
     }
     return diagramId;
 }
示例#17
0
        static public async Task <bool> DeleteDiagramAsync(string diagramId)
        {
            var rtnValue = false;

            try
            {
                using (DocumentDBContext docdb = new DocumentDBContext())
                {
                    rtnValue = await docdb.DeleteItemAsync(DiagramCollection, diagramId);
                }
            }
            catch
            {
                // handle exception...
            }
            return(rtnValue);
        }
示例#18
0
        /// <summary>
        /// Updates an existing diagram in the Diagrams collection
        /// NOTE: the Diagram JSON must have the id attribute or an exception will occur
        /// </summary>
        /// <param name="id"></param>
        /// <param name="diagram"></param>
        /// <returns></returns>
        static public async Task <string> UpdateDiagramAsync(string diagram)
        {
            string diagramId = string.Empty;

            try
            {
                using (DocumentDBContext docdb = new DocumentDBContext())
                {
                    diagramId = await docdb.InsertOrUpdateItemAsync(DiagramCollection, diagram);
                }
            }
            catch
            {
                // handle exception...
            }
            return(diagramId);
        }
示例#19
0
文件: DAL.cs 项目: dranreb/AzureLens
 //static public bool UpdateDiagram(Guid diagramId, string doc)
 //{
 //    using (DocumentDBContext docdb = new DocumentDBContext())
 //    {
 //        dynamic x = docdb.InsertOrUpdateItemAsync("AzureLensColl", doc);
 //    }
 //    return true;
 //}
 public static dynamic LoadDiagram(Guid diagramId)
 {
     dynamic doc = null;
     try
     {
         dynamic id = diagramId.ToString();
         using (DocumentDBContext docdb = new DocumentDBContext())
         {
             doc = docdb.GetItemAsync<dynamic>(id, "AzureLensColl");
         }
     }
     catch
     {
         // handle exception...
     }
     return doc.Result;
 }
示例#20
0
        private static async Task pushModules(IUnitOfWork uow, IModuleRepository repo, CancellationToken cToken, IEnumerable <ModuleEntity> remoteEntities, params string[] includes)
        {
            try
            {
                Logging.Logger.Log("INFO", "Pushing entities of type Module");
                //var remoteIds = remoteEntities.Select(t => t.Id).ToList();

                //only push modules if they are not already in cloud, they were created on the truck, and they are not on the unassigned list
                //TODO PICKUP LIST ID
                var newEntities = repo.FindMatching(t => t.Source == InputSource.TRUCK && t.PickupListId != GUIDS.UNASSIGNED_LIST_ID, includes).ToList();

                int count = 1;
                foreach (var entity in newEntities /*.Where(t => !remoteIds.Contains(t.Id))*/)
                {
                    Console.WriteLine("Pushing entity: " + entity.Name);

                    if (cToken.IsCancellationRequested)
                    {
                        return;
                    }
                    await DocumentDBContext.UpsertItemAsync <ModuleEntity>(entity);

                    var remoteEntity = remoteEntities.SingleOrDefault(m => m.Id == entity.Id);
                    if (remoteEntity != null)
                    {
                        remoteEntity.PickupListId = entity.PickupListId;
                        remoteEntity.FieldId      = entity.FieldId;
                    }

                    repo.Update(entity, true);
                    count++;
                    if (count == 100)
                    {
                        count = 1;
                        Console.WriteLine("Saving changes");
                        uow.SaveChanges();
                    }
                }
                Console.WriteLine("Saving changes");
                uow.SaveChanges();
            }
            catch (Exception exc)
            {
                Logging.Logger.Log(exc);
            }
        }
示例#21
0
        static public async Task <dynamic> LoadDiagram(Guid diagramId)
        {
            dynamic doc = null;

            try
            {
                var id = diagramId.ToString();
                using (DocumentDBContext docdb = new DocumentDBContext())
                {
                    doc = await docdb.GetItemAsync <dynamic>(id, DiagramCollection);
                }
            }
            catch
            {
                // handle exception...
            }
            return(doc);
        }
示例#22
0
        private static DocumentDBItemValueBinder <T> CreateBinder <T>(out Mock <IDocumentDBService> mockService, string partitionKey = null) where T : class
        {
            mockService = new Mock <IDocumentDBService>(MockBehavior.Strict);

            DocumentDBAttribute attribute = new DocumentDBAttribute(DatabaseName, CollectionName)
            {
                Id           = Id,
                PartitionKey = partitionKey
            };

            var context = new DocumentDBContext
            {
                ResolvedAttribute = attribute,
                Service           = mockService.Object
            };

            return(new DocumentDBItemValueBinder <T>(context));
        }
示例#23
0
        public static async Task SyncLoadScans(UnitOfWork uow, CancellationToken token)
        {
            try
            {
                if (token.IsCancellationRequested)
                {
                    return;
                }

                Logging.Logger.Log("INFO", "Push load scans to cloud.");
                //var cutOffTime = DateTime.UtcNow.AddMinutes(-30);

                var newEntities = uow.LoadScanRepository.FindMatching(t => t.Source == InputSource.TRUCK && t.SyncedToCloud == false && t.Updated.HasValue && !t.GinTagLoadNumber.StartsWith("AUTO"));
                foreach (var entity in newEntities)
                {
                    try
                    {
                        if (token.IsCancellationRequested)
                        {
                            return;
                        }

                        await DocumentDBContext.UpsertItemAsync <LoadScanEntity>(entity);

                        uow.LoadScanRepository.Update(entity, true);
                        uow.SaveChanges();
                    }
                    catch (Exception excInner)
                    {
                        Logging.Logger.Log(excInner);
                    }
                }

                if (token.IsCancellationRequested)
                {
                    return;
                }
            }
            catch (Exception exc)
            {
                Logging.Logger.Log(exc);
            }
        }
示例#24
0
        public async Task CreateIfNotExist_Throws_IfExceptionIsNotConflict()
        {
            // Arrange
            var mockService           = new Mock <IDocumentDBService>(MockBehavior.Strict);
            DocumentDBContext context = CreateContext(mockService.Object);

            SetupDatabaseMock(mockService);

            // overwrite the default setup with one that throws
            mockService
            .Setup(m => m.CreateDatabaseAsync(It.Is <Database>(d => d.Id == DatabaseName)))
            .ThrowsAsync(DocumentDBTestUtility.CreateDocumentClientException(HttpStatusCode.BadRequest));

            // Act
            await Assert.ThrowsAsync <DocumentClientException>(
                () => DocumentDBAsyncCollector <Item> .CreateIfNotExistAsync(context));

            // Assert
            mockService.VerifyAll();
        }
示例#25
0
        public static async Task SyncPBIScans(UnitOfWork uow, DateTime lastSyncTime, CancellationToken token)
        {
            try
            {
                if (token.IsCancellationRequested)
                {
                    return;
                }

                Logging.Logger.Log("INFO", "Push PBI scans to cloud.");

                var newEntities = uow.BaleScanRepository.FindMatching(t => t.Source == InputSource.TRUCK && t.SyncedToCloud == false);
                foreach (var entity in newEntities)
                {
                    try
                    {
                        if (token.IsCancellationRequested)
                        {
                            return;
                        }
                        await DocumentDBContext.UpsertItemAsync <BaleScanEntity>(entity);

                        uow.BaleScanRepository.Update(entity, true);
                        uow.SaveChanges();
                    }
                    catch (Exception excInner)
                    {
                        Logging.Logger.Log(excInner);
                    }
                }

                if (token.IsCancellationRequested)
                {
                    return;
                }
            }
            catch (Exception exc)
            {
                Logging.Logger.Log(exc);
            }
        }
示例#26
0
        public async Task SetAsync_Updates_IfPropertyChanges()
        {
            // Arrange
            var mockService = new Mock <IDocumentDBService>(MockBehavior.Strict);

            Item original = new Item
            {
                Id   = "abc123",
                Text = "hello"
            };

            Item updated = new Item
            {
                Id   = "abc123",
                Text = "goodbye"
            };

            mockService
            .Setup(m => m.ReplaceDocumentAsync(_expectedUri, updated))
            .ReturnsAsync(new Document());

            DocumentDBAttribute attribute = new DocumentDBAttribute(DatabaseName, CollectionName)
            {
                Id = Id
            };

            var context = new DocumentDBContext
            {
                Service           = mockService.Object,
                ResolvedAttribute = attribute
            };

            JObject clonedOrig = DocumentDBItemValueBinder <object> .CloneItem(original);

            // Act
            await DocumentDBItemValueBinder <Item> .SetValueInternalAsync(clonedOrig, updated, context);

            // Assert
            mockService.VerifyAll();
        }
示例#27
0
        public async Task DoSync()
        {
            var newSyncTime = DateTime.UtcNow;

            try
            {
                if (!SyncHelper.HasConnection())
                {
                    return;
                }

                using (var uow = new UnitOfWork())
                {
                    var documentDbSetting = uow.SettingsRepository.FindSingle(x => x.Key == BridgeSettingKeys.DOCUMENT_DB_KEY);
                    var endpointSetting   = uow.SettingsRepository.FindSingle(x => x.Key == BridgeSettingKeys.DOCUMENTDB_ENDPOINT);
                    DocumentDBContext.Initialize(endpointSetting.Value, documentDbSetting.Value);
                    if (DocumentDBContext.Initialized)
                    {
                        try
                        {
                            var lastSyncTime = DateTime.Parse(uow.SettingsRepository.GetSettingWithDefault(BridgeSettingKeys.LAST_SYNC_TIME, "01/01/2019"));
                            lastSyncTime = lastSyncTime.AddMinutes(-1);

                            await ExecuteSteps(uow, lastSyncTime);

                            uow.SettingsRepository.UpsertSetting(BridgeSettingKeys.LAST_SYNC_TIME, newSyncTime.ToString());
                            uow.SaveChanges();
                        }
                        catch (Exception exc)
                        {
                            Logging.Logger.Log(exc);
                        }
                    }
                }
            }
            catch (Exception outerExc)
            {
                Logging.Logger.Log(outerExc);
            }
        }
示例#28
0
        private static async Task ClearDownloadedListsData(string appDataPath)
        {
            try
            {
                Console.WriteLine("Releasing downloaded lists...");
                string settingsFile    = appDataPath + "\\Truck\\settings.txt";
                string encryptedString = System.IO.File.ReadAllText(settingsFile);
                string decryptedString = CottonDBMS.Helpers.EncryptionHelper.Decrypt(encryptedString);
                var    parms           = Newtonsoft.Json.JsonConvert.DeserializeObject <TruckAppInstallParams>(decryptedString);

                if (!string.IsNullOrEmpty(parms.EndPoint) &&
                    !string.IsNullOrEmpty(parms.Key) &&
                    !string.IsNullOrEmpty(parms.TruckID))
                {
                    DocumentDBContext.Initialize(parms.EndPoint, parms.Key);

                    Console.WriteLine("Looking for downloaded lists...");
                    var docs = await DocumentDBContext.GetAllItemsAsync <TruckListsDownloaded>(p => p.Id == "TRUCKDOWNLOADS_" + parms.TruckID);

                    if (docs.Count() > 0)
                    {
                        Console.WriteLine("Releasing lists...");
                        //remove document tracking lists this truck has downloaded
                        //this allows them to be released for delete etc at the gin
                        await DocumentDBContext.DeleteItemAsync <TruckListsDownloaded>("TRUCKDOWNLOADS_" + parms.TruckID);
                    }
                }
                else
                {
                    Console.WriteLine("One or more settings null.");
                }
            }
            catch (Exception exc)
            {
                Console.WriteLine(exc.Message);
                Console.WriteLine(exc.StackTrace);
                Console.WriteLine("Press enter to continue.");
                Console.ReadLine();
            }
        }
示例#29
0
        private static async Task processDeletedDocuments(IUnitOfWork uow, CancellationToken cToken, string thisTruckID, List <TruckPickupListRelease> truckReleaseDocuments)
        {
            if (cToken.IsCancellationRequested)
            {
                return;
            }
            try
            {
                var docsDeleted = new List <DocumentToProcess>();

                foreach (var d in uow.DocumentsToProcessRepository.GetAll())
                {
                    if (d.EntityType == EntityType.PICKUPLIST)
                    {
                        var releaseDoc = new TruckPickupListRelease();
                        releaseDoc.Id            = Guid.NewGuid().ToString();
                        releaseDoc.Source        = InputSource.TRUCK;
                        releaseDoc.SyncedToCloud = true;
                        releaseDoc.Name          = "LIST_RELEASE_" + thisTruckID + "_" + d.Id;
                        releaseDoc.TruckID       = thisTruckID;
                        releaseDoc.PickupListID  = d.Id;
                        truckReleaseDocuments.Add(releaseDoc);
                    }
                    docsDeleted.Add(d);
                }

                if (truckReleaseDocuments.Count() > 0)
                {
                    await DocumentDBContext.BulkUpsert <TruckPickupListRelease>(truckReleaseDocuments, 500);
                }

                uow.DocumentsToProcessRepository.BulkDelete(docsDeleted);
                uow.SaveChanges();
            }
            catch (Exception exc)
            {
                Logging.Logger.Log(exc);
            }
        }
        private async Task <bool> CreateDatabase()
        {
            DocumentDBContext.Initialize(tbAzureCosmosEndpoint.Text.Trim(), tbAzureKey.Text.Trim());
            bool exists = await DocumentDBContext.DatabaseExistsAsync();

            bool createSucceded = true;

            if (!exists)
            {
                try
                {
                    await DocumentDBContext.CreateDatabaseAsync();
                }
                catch (Exception exc)
                {
                    Logging.Logger.Log(exc);
                    createSucceded = false;
                }
            }

            return(createSucceded);
        }
示例#31
0
        public MessageProcessorSpec()
        {
            var configuration = Substitute.For <IConfigurationRoot>();

            configuration[Constants.DocumentDb.PrimaryKey].Returns(PrimaryKey);
            configuration[Constants.DocumentDb.EndpointUrl].Returns(EndpointUrl);
            configuration[Constants.Storage.ConnectionString].Returns(StorageConnectionString);

            _container = new ContainerBuilder()
                         .AddTranscient <IRepositoryFactory, DocumentDbFactory>()
                         .AddTranscient <IMessageProcessor, MessageProcessor>()
                         .AddTranscient <IPoisonMessageRepository, PoisonMessageRepository>()
                         .AddTranscient <IPolicyRegistry, PolicyRegistry>()
                         .AddInstance(Substitute.For <ILogger>())
                         .AddInstance(configuration)
                         .Build();

            _dbContext = new DocumentDBContext(new Uri(EndpointUrl), PrimaryKey,
                                               Constants.DocumentDb.DatabaseId, Constants.DocumentDb.CollectionId);

            _tableContext = new TableContext(StorageConnectionString, Constants.Storage.PoisonTableName);
        }
示例#32
0
        private static async Task RunAsync()
        {
            Console.WriteLine("Start Create Database");
            var documentDB = await DocumentDBContext.CreateDatabaseIfNotExistAsync(DatabaseName);

            Console.WriteLine("End Create Database");

            Console.WriteLine("Start Create Collection");
            var collection = await DocumentDBContext.CreateCollection(DatabaseName, CollectionName);

            Console.WriteLine("End Create Collection");

            client        = DocumentDBContext.GetClient();
            collectionUri = DocumentDBContext.CreateDocumentCollectionUri(DatabaseName, CollectionName);

            Console.WriteLine("Start Inicialize Collection");
            await DocumentDBContext.InicializeCollection(DatabaseName, CollectionName);

            Console.WriteLine("End Inicialize Collection");

            ContinueProcess();

            Console.WriteLine("Start Get All documents from collection");
            QueryAllDocuments();
            Console.WriteLine("End Get All documents from collection");

            ContinueProcess();

            Console.WriteLine("Start Query wiht Joins");
            QueryWithJoins();
            Console.WriteLine("End Query wiht Joins");

            ContinueProcess();

            Console.WriteLine("Start Query wiht Joins And filter");
            QueryWithTwoJoinsAndFilter();
            Console.WriteLine("End Query wiht Joins And filter");
        }
示例#33
0
        public async Task SetAsync_Poco_SkipsUpdate_IfSame()
        {
            // Arrange
            var mockService = new Mock <IDocumentDBService>(MockBehavior.Strict);

            Item original = new Item
            {
                Id   = "abc123",
                Text = "hello"
            };

            Item updated = new Item
            {
                Id   = "abc123",
                Text = "hello"
            };

            DocumentDBAttribute attribute = new DocumentDBAttribute(DatabaseName, CollectionName)
            {
                Id = Id
            };

            var context = new DocumentDBContext
            {
                Service           = mockService.Object,
                ResolvedAttribute = attribute
            };

            JObject clonedOrig = DocumentDBItemValueBinder <object> .CloneItem(original);

            // Act
            await DocumentDBItemValueBinder <Item> .SetValueInternalAsync(clonedOrig, updated, context);

            // Assert

            // nothing on the client should be called
            mockService.VerifyAll();
        }
示例#34
0
        public async Task SetAsync_Poco_Throws_IfIdChanges()
        {
            // Arrange
            var mockService = new Mock <IDocumentDBService>(MockBehavior.Strict);

            Item original = new Item
            {
                Id = "abc123",
            };

            Item updated = new Item
            {
                Id = "def456",
            };

            DocumentDBAttribute attribute = new DocumentDBAttribute(DatabaseName, CollectionName)
            {
                Id = Id
            };

            var context = new DocumentDBContext
            {
                Service           = mockService.Object,
                ResolvedAttribute = attribute
            };

            var originalJson = JObject.FromObject(original);

            // Act
            var ex = await Assert.ThrowsAsync <InvalidOperationException>(
                () => DocumentDBItemValueBinder <Item> .SetValueInternalAsync(originalJson, updated, context));

            // Assert
            Assert.Equal("Cannot update the 'Id' property.", ex.Message);
            mockService.Verify();
        }
示例#35
0
        public static async Task SyncModuleOwnershipTable(UnitOfWork uow, DateTime lastSyncTime, CancellationToken token)
        {
            //Sync module ownership table
            //get only modules updated or created
            var remoteModuleOwnerships = await DocumentDBContext.GetAllItemsAsync <ModuleOwnershipEntity>(p => p.EntityType == EntityType.MODULE_OWNERSHIP && (p.Created > lastSyncTime ||
                                                                                                                                                               (p.Updated.HasValue && p.Updated > lastSyncTime)));

            if (token.IsCancellationRequested)
            {
                return;
            }

            var localModuleOwnershipIds = uow.ModuleOwnershipRepository.GetAllIds();

            if (token.IsCancellationRequested)
            {
                return;
            }

            using (var addWork = new UnitOfWork())
            {
                addWork.DisableChangeTracking();
                AddRemoteEntitiesToLocalOfType <ModuleOwnershipEntity>(addWork, addWork.ModuleOwnershipRepository, token, remoteModuleOwnerships, localModuleOwnershipIds);
            }

            if (token.IsCancellationRequested)
            {
                return;
            }

            using (var updateWork = new UnitOfWork())
            {
                updateWork.DisableChangeTracking();
                UpdateRemoteEntitiesOnLocalOfType <ModuleOwnershipEntity>(updateWork, updateWork.ModuleOwnershipRepository, token, remoteModuleOwnerships, localModuleOwnershipIds, false);
            }
        }
示例#36
0
        public static async Task <Guid?> GetIdFromHashAsync(string hash)
        {
            Guid?id = null;

            if (!string.IsNullOrWhiteSpace(hash))
            {
                using (DocumentDBContext docdb = new DocumentDBContext())
                {
                    var doc = await docdb.GetItemAsync <dynamic>(hash, DiagramCollection);

                    if (doc != null)
                    {
                        string diagramId = doc.diagramId;
                        Guid   parsedId;
                        if (Guid.TryParse(diagramId, out parsedId))
                        {
                            id = parsedId;
                        }
                    }
                }
            }

            return(id);
        }
示例#37
0
 static public async Task<dynamic> LoadDiagram(Guid diagramId)
 {
     dynamic doc = null;
     try
     {
         var id = diagramId.ToString();
         using (DocumentDBContext docdb = new DocumentDBContext())
         {
             doc = await docdb.GetItemAsync<dynamic>(id, DiagramCollection);
         }
     }
     catch
     {
         // handle exception...                
     }
     return doc;
 }
示例#38
0
        /// <summary>
        /// 
        /// </summary>
        /// <param name="userId"></param>
        /// <returns></returns>
        static public async Task<List<dynamic>> GetUserDiagramsAsync(string userId)
        {
            List<dynamic> docs = new List<dynamic>();
            using (DocumentDBContext docdb = new DocumentDBContext(DiagramCollection))
            {
                var diagrams = (await docdb.GetItemsByPropertyAsync<dynamic>("userId", userId)).ToList();
               foreach (var diagram in diagrams)
                {
                    string name;
                    string ID;

                    try
                    {
                        name = diagram.name;
                    }
                    catch
                    {
                        name = "(blank)";
                    }
                    try {
                        ID = diagram.id;
                        docs.Add(new
                        {
                            name = name,
                            id = ID
                        });

                    }
                    catch
                    {

                    }
                }

            }
            return docs;
        }
示例#39
0
        public static async Task<string> GenerateHashAsync(Guid diagramId)
        {
            var result = string.Empty;
            using (DocumentDBContext docdb = new DocumentDBContext())
            {
                var id = diagramId.ToString().ToUpperInvariant();
              // var doc = await docdb.GetItemAsync<dynamic>(id, DiagramCollection);

              
                    var input = string.Format("{0}{1}", Guid.NewGuid().ToString(), id.ToString());

                    var sha = new SHA256CryptoServiceProvider();
                    var buffer = Encoding.ASCII.GetBytes(input);
                    var hash = sha.ComputeHash(buffer);
                    var hashString = string.Empty;
                    foreach (var b in hash)
                    {
                        hashString += b.ToString("X2");
                    }
                    var hashResult = new SharedDocumentResult()
                    {
                        Id = hashString,
                        DiagramId = id
                    };
                    var json = JsonConvert.SerializeObject(hashResult);
                    dynamic success = await docdb.InsertOrUpdateItemAsync(DiagramCollection, json);
                   
                        result = hashResult.Id;
                    
              
            }
            return result;
        }
示例#40
0
        public static async Task<Guid?> GetIdFromHashAsync(string hash)
        {
            Guid? id = null;

            if (!string.IsNullOrWhiteSpace(hash))
            {
                using (DocumentDBContext docdb = new DocumentDBContext())
                {
                    var doc = await docdb.GetItemAsync<dynamic>(hash, DiagramCollection);
                    if (doc != null)
                    {
                        string diagramId = doc.diagramId;
                        Guid parsedId;
                        if (Guid.TryParse(diagramId, out parsedId))
                        {
                            id = parsedId;
                        }
                    }
                }
            }

            return id;
        }