Exemplo n.º 1
0
        private static async Task CreateDocumentCollectionIfNotExists(string databaseName, string collectionName)
        {
            try
            {
                await Client.ReadDocumentCollectionAsync(UriFactory.CreateDocumentCollectionUri(databaseName, collectionName));
            }
            catch (DocumentClientException de)
            {
                // If the document collection does not exist, create a new collection
                if (de.StatusCode == HttpStatusCode.NotFound)
                {
                    DocumentCollection collectionInfo = new DocumentCollection();
                    collectionInfo.Id = collectionName;

                    // Configure collections for maximum query flexibility including string range queries.
                    collectionInfo.IndexingPolicy = new IndexingPolicy(new RangeIndex(DataType.String) { Precision = -1 });

                    // Here we create a collection with 400 RU/s.
                    await Client.CreateDocumentCollectionAsync(
                        UriFactory.CreateDatabaseUri(databaseName),
                        collectionInfo,
                        new RequestOptions { OfferThroughput = 400 });
                }
                else
                {
                    throw;
                }
            }
        }
        public DocumentDBDataReader()
        {
            var dict = new Dictionary<HighchartsHelper.DocumentTypes, IEnumerable<Document>>();
            _documentClient = new DocumentClient(new Uri(ConfigurationManager.AppSettings["DocumentServiceEndpoint"]), ConfigurationManager.AppSettings["DocumentKey"]);

            _database = _documentClient.CreateDatabaseQuery().Where(db => db.Id == ConfigurationManager.AppSettings["DocumentDatabase"]).AsEnumerable().FirstOrDefault();

            if (_database == null)
                throw new ApplicationException("Error: DocumentDB database does not exist");

            // Check to verify a document collection with the id=FamilyCollection does not exist
            _documentCollection = _documentClient.CreateDocumentCollectionQuery(_database.CollectionsLink).Where(c => c.Id == ConfigurationManager.AppSettings["DocumentCollection"]).AsEnumerable().FirstOrDefault();

            if (_documentCollection == null)
                throw new ApplicationException("Error: DocumentDB collection does not exist");


            try
            {
                _documentClient.CreateUserDefinedFunctionAsync(_documentCollection.SelfLink, new UserDefinedFunction
                {
                    Id = "ISDEFINED",
                    Body = @"function ISDEFINED(doc, prop) {
                            return doc[prop] !== undefined;
                        }"
                });  
            }
            catch (Exception)
            {
                //fail silently for now..
            }
        }
Exemplo n.º 3
0
        private static void CreateDocumentCollection(DocumentClient documentClient)
        {
            // Create the database if it doesn't exist.

            try
            {
                documentClient.ReadDocumentCollectionAsync(UriFactory.CreateDocumentCollectionUri(DatabaseName, CollectionName))
                    .GetAwaiter()
                    .GetResult();
            }
            catch (DocumentClientException de)
            {
                // If the document collection does not exist, create it
                if (de.StatusCode == HttpStatusCode.NotFound)
                {
                    var collectionInfo = new DocumentCollection
                    {
                        Id = CollectionName,
                        IndexingPolicy = new IndexingPolicy(new RangeIndex(DataType.String) { Precision = -1 })
                    };

                    documentClient.CreateDocumentCollectionAsync(
                        UriFactory.CreateDatabaseUri(DatabaseName),
                        collectionInfo,
                        new RequestOptions { OfferThroughput = 400 }).GetAwaiter().GetResult();
                }
                else
                {
                    throw;
                }
            }
        }
        /// <summary>
        /// Initialize a HashPartitionResolver.
        /// </summary>
        /// <param name="partitionKeyPropertyName">The property name to be used as the partition Key.</param>
        /// <param name="client">The DocumentDB client instance to use.</param>
        /// <param name="database">The database to run the samples on.</param>
        /// <param name="collectionNames">The names of collections used.</param>
        /// <returns>The created HashPartitionResolver.</returns>
        public static async Task<HashPartitionResolver> InitializeHashResolver(string partitionKeyPropertyName, DocumentClient client, Database database, string[] collectionNames)
        {
            // Set local to input.
            string[] CollectionNames = collectionNames;
            int numCollectionNames = CollectionNames.Length;

            // Create array of DocumentCollections.
            DocumentCollection[] collections = new DocumentCollection[numCollectionNames];

            // Create string array of Self Links to Collections.
            string[] selfLinks = new string[numCollectionNames];

            //Create some collections to partition data.
            for (int i = 0; i < numCollectionNames; i++)
            {
                collections[i] = await DocumentClientHelper.GetCollectionAsync(client, database, CollectionNames[i]);
                selfLinks[i] = collections[i].SelfLink;
            }

            // Join Self Link Array into a comma separated string.
            string selfLinkString = String.Join(", ", selfLinks);

            //Initialize a partition resolver that users hashing, and register with DocumentClient. 
            //Uses User Id for PartitionKeyPropertyName, could also be TenantId, or any other variable.
            HashPartitionResolver hashResolver = new HashPartitionResolver(partitionKeyPropertyName, new[] { selfLinkString });
            client.PartitionResolvers[database.SelfLink] = hashResolver;

            return hashResolver;
        }
        private async Task<DocumentClient> GetDocumentDbClient()
        {
            var client = new DocumentClient(new Uri(_endPointUrl), _authorizationKKry);

            var database = client.CreateDatabaseQuery().
                Where(db => db.Id == DocumentDbId).AsEnumerable().FirstOrDefault();

            if (database == null)
            {
                database = await client.CreateDatabaseAsync(
                    new Database
                    {
                        Id = DocumentDbId
                    });    
            }

            DocumentCollection = client.CreateDocumentCollectionQuery
                ("dbs/" + database.Id).Where(c => c.Id == _collectionId).AsEnumerable().FirstOrDefault();

            if (DocumentCollection == null)
            {
                DocumentCollection = await client.CreateDocumentCollectionAsync("dbs/" + DocumentDbId,
                new DocumentCollection
                {
                    Id = _collectionId
                });

            }
           

            return client;
        }
Exemplo n.º 6
0
        private static RangePartitionResolver<long> GetUpdateResolver(RangePartitionResolver<long> oldResolver,
            DocumentCollection newDc)
        {
            var map = new Dictionary<Range<long>, string>();
            var vs = oldResolver.PartitionMap;
            if (vs.Count > 1)
            {
                foreach (var v in vs)
                {
                    if (map.Count < vs.Count - 1)
                    {
                        map.Add(new Range<long>(v.Key.Low, v.Key.High), v.Value);
                    }
                }
            }
            //Check Resolver
            var now = (long) (DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalMilliseconds;
            if (now < vs.LastOrDefault().Key.Low || now > vs.LastOrDefault().Key.High) return null;

            map.Add(new Range<long>(vs.LastOrDefault().Key.Low, now), vs.LastOrDefault().Value);
            map.Add(new Range<long>(now + 1, vs.LastOrDefault().Key.High), newDc.SelfLink);
            return new RangePartitionResolver<long>(
                u => ((PostMessage) u).Info.timestamp,
                map);
        }
Exemplo n.º 7
0
        public async Task CollectionTransfer(DocumentCollection dc1, DocumentCollection dc2)
        {
            var sp = await _iDBoperation.GetStoreProcedure(dc1.SelfLink, "BatchDelete");
            var sp2 = await _iDBoperation.GetStoreProcedure(dc1.SelfLink, "BatchInsert");

            var docs = _iDBoperation.GetDocumentByType(dc1.DocumentsLink, "Post");

            var l = docs.ToList();
            var cur = 0;
            int maxDoc = 400;
            while (cur < l.Count)
            {
                var s = new List<dynamic>();
                for (var i = cur; i < l.Count; i++)
                {
                    if (s.Count < maxDoc)
                    {
                        s.Add(l[i]);
                    }
                }
                var n = await BatchTransfer(sp2.SelfLink, sp.SelfLink, s);
                //Console.WriteLine(n + "----" + l.Count);
                cur = cur + n;
            }
        }
Exemplo n.º 8
0
 public DocumentCollection FetchAll()
 {
     DocumentCollection coll = new DocumentCollection();
     Query qry = new Query(Document.Schema);
     coll.LoadAndCloseReader(qry.ExecuteReader());
     return coll;
 }
        private static async Task<DocumentCollection> CreateDocumentCollection(DocumentClient client, Database database, string collectionId)
        {
            var collectionSpec = new DocumentCollection { Id = collectionId };
            var requestOptions = new RequestOptions { OfferType = "S1" };

            return await client.CreateDocumentCollectionAsync(database.SelfLink, collectionSpec, requestOptions);
        }
        //new add
        private static async Task GetStart()
        {
            var client = new DocumentClient(new Uri(EndpointURL), AuthorizationKey);
            
            database = client.CreateDatabaseQuery().Where(d => d.Id == "ppweict").AsEnumerable().FirstOrDefault();
            collection = client.CreateDocumentCollectionQuery(database.SelfLink).Where(c => c.Id == "Exam_Pool").AsEnumerable().FirstOrDefault();


            var EfDs = client.CreateDocumentQuery(collection.DocumentsLink, "SELECT * FROM Exam_pool f WHERE f.verify = \"true\" ");
            foreach (exam_pool EfD in EfDs)
            {
                Console.WriteLine(EfD);
                exams.Add(new exam_pool
                {
                    id = EfD.id,
                    exam_catrgory = EfD.exam_catrgory,
                    exam_level = EfD.exam_level,
                    questions = EfD.questions,
                    answer_A = EfD.answer_A,
                    answer_B = EfD.answer_B,
                    answer_C = EfD.answer_C,
                    answer_D = EfD.answer_D,
                    answer_E = EfD.answer_E,
                    C_answer = EfD.C_answer,
                    exam_link = EfD.exam_link,
                    lang = EfD.lang,
                    verify = EfD.verify,
                });
            }
        }
Exemplo n.º 11
0
 public ProcessMessage(DbService iDbService, QueueService iQueueService)
 {
     _documentClient = iDbService.GetDocumentClient();
     _client = iDbService.GetFirebaseClient();
     _documentCollection = iDbService.GetDc("LMSCollection", "LMSRegistry");
     _sp = iDbService.GetSp(_documentCollection, "Post");
     _queue = iQueueService.GetQueue("queue");
 }
Exemplo n.º 12
0
            public void Initialize()
            {
                tr = new AC_Transactions();
                DocColl = Application.DocumentManager;
                DocColl.DocumentCreated += DocColl_DocumentCreated;

                if (tr.AC_Doc != null){ findandLink(); }
            }
 private async Task CreateCollection(string collectionId)
 {
     collection = client.CreateDocumentCollectionQuery(database.SelfLink).Where(c => c.Id == collectionId).ToArray().FirstOrDefault();
     if (null == collection)
     {
         collection = await client.CreateDocumentCollectionAsync(database.SelfLink, new DocumentCollection { Id = collectionId });
     }
 }
Exemplo n.º 14
0
 public async static Task GoOnVacation(DocumentClient client, DocumentCollection collection, string jeffersons, bool left)
 {
     var family = GetFamily(client, collection, jeffersons);
     dynamic doc = GetDocumentById(client, collection,family.id);
     Family f = doc;
     f.IsHome = false;
     var task = await client.ReplaceDocumentAsync(doc.SelfLink, f);
     
 }
Exemplo n.º 15
0
        public async Task<DocumentCollection> GetCollection()
        {
            if (_documentCollection == null)
            {
                var db = await GetDatabase();
                _documentCollection = await GetCollection(_config["DocumentCollection"], db);
            }

            return _documentCollection;
        }
Exemplo n.º 16
0
 public async Task UpdateCurrentCollection(DocumentCollection newDc)
 {
     await _iDBoperation.DeleteDocById("CurrentCollection");
     var doc = new CurrentCollection
     {
         id = "CurrentCollection",
         name = newDc.Id
     };
     await _iDBoperation.CreateDocument(doc);
 }
Exemplo n.º 17
0
        static UsersController()
        {
            var address = CloudConfigurationManager.GetSetting("DocumentDbEndpointAddress");
            var authorizationKey = CloudConfigurationManager.GetSetting("DocumentDbAuthorizationKey");
            
            Client = new DocumentClient(new Uri(address), authorizationKey);

            var database = GetOrCreateDatabase(Client, "CloudCampDb");
            DocumentCollection = GetOrCreateCollection(Client, database.SelfLink, "Users");
        }
Exemplo n.º 18
0
        private async Task InitClient()
        {
            _client = new DocumentClient(new Uri(Uri), Key);
            _database = await _client.GetDatabase("reportdb");
            _documentCollection = await _client.GetCollection(_database, "reports");

            if (HasReports() == false)
            {
                await CreateDummyReportsAsync();
            }
        }
Exemplo n.º 19
0
 private static async Task DeletePost(DocumentCollection dc,string id)
 {
     var ds =
          from d in _client.CreateDocumentQuery(dc.DocumentsLink)
          where d.Id==id
          select d;
     foreach (var d in ds)
     {
         await _client.DeleteDocumentAsync(d.SelfLink);
     }
 }
        private async Task CreateCollectionIfNotExistsAsync(string collectionName)
        {
            _collection = (await _client.ReadDocumentCollectionFeedAsync(_database.CollectionsLink))
                .SingleOrDefault(c => c.Id == collectionName);

            if (_collection == null)
                _collection = await _client.CreateDocumentCollectionAsync(_database.SelfLink, new DocumentCollection
                {
                    Id = collectionName
                });
        }
Exemplo n.º 21
0
        private static async Task ReadOrCreateCollection(string databaseLink)
        {
            Collection = Client.CreateDocumentCollectionQuery(databaseLink).Where(col => col.Id == _collectionId).AsEnumerable().FirstOrDefault();

            if (Collection == null)
            {
                var collectionSpec = new DocumentCollection {Id = _collectionId};
                var requestOptions = new RequestOptions {OfferType = "S1"};

                Collection = await Client.CreateDocumentCollectionAsync(databaseLink, collectionSpec, requestOptions);
            }
        }
        public SpeakerAzureDocDbRepository(Settings settings)
        {
            _settings = settings;

            _client = new DocumentClient(new Uri(endpointUrl), authorizationKey);
            
            //Get, or Create, the Database
            _database = GetOrCreateDatabaseAsync(databaseId).Result;

            //Get, or Create, the Document Collection
            _collection = GetOrCreateCollectionAsync(_database.SelfLink, collectionId).Result;
        }
Exemplo n.º 23
0
    private async Task EnsureStoryCollectionAsync()
    {
      await EnsureDatabaseAsync();
      var coll = _client.CreateDocumentCollectionQuery(DatabaseLink)
        .Where(s => s.Id == STORYCOLLECTIONID)
        .AsEnumerable()
        .FirstOrDefault();

      if (coll == null)
      {
        _storyCollection = await _client.CreateDocumentCollectionAsync(_database.CollectionsLink, new DocumentCollection() { Id = STORYCOLLECTIONID });
      }
    }
Exemplo n.º 24
0
        internal static DocumentCollection ReadOrCreateCollection(DocumentClient client, string databaseLink, string collectionId)
        {
            var collections = client.CreateDocumentCollectionQuery(databaseLink)
                            .Where(col => col.Id == collectionId).ToArray();

            if (collections.Any())
            {
                return collections.First();
            }

            var collection = new DocumentCollection { Id = collectionId };
            return client.CreateDocumentCollectionAsync(databaseLink, collection).Result;
        }
        private async Task SetupCollection(string databaseLink)
        {
            _collection = Client.CreateDocumentCollectionQuery(databaseLink)
                .Where(c => c.Id == _collectionName)
                .AsEnumerable()
                .FirstOrDefault();

            if (_collection == null)
            {
                var collectionSpec = new DocumentCollection { Id = _collectionName };
                _collection = await Client.CreateDocumentCollectionAsync(databaseLink, collectionSpec);
            }
        }
        /// <summary>
        /// Initialize a RangePartitionResolver.
        /// </summary>
        /// <param name="partitionKeyPropertyName">The property name to be used as the partition Key.</param>
        /// <param name="client">The DocumentDB client instance to use.</param>
        /// <param name="database">The database to run the samples on.</param>
        /// <param name="collectionNames">The names of collections used.</param>
        /// <returns>The created HashPartitionResolver.</returns>
        public static async Task<RangePartitionResolver<string>> InitializeRangeResolver(string partitionKeyPropertyName, DocumentClient client, Database database, string[] collectionNames)
        {
            // Set local to input.
            string[] CollectionNames = collectionNames;
            int numCollectionNames = CollectionNames.Length;

            // Create array of DocumentCollections.
            DocumentCollection[] collections = new DocumentCollection[numCollectionNames];

            // Create string array of Self Links to Collections.
            string[] selfLinks = new string[numCollectionNames];

            //Create some collections to partition data.
            for (int i = 0; i < numCollectionNames; i++)
            {
                collections[i] = await DocumentClientHelper.GetCollectionAsync(client, database, CollectionNames[i]);
                selfLinks[i] = collections[i].SelfLink;
            }

            // Join Self Link Array into a comma separated string.
            string selfLinkString = String.Join(", ", selfLinks);

            // If each collection represents a range, it will have both a start and end point in its range, thus there are 2 rangeNames for each collection.
            string[] rangeNames = new string[numCollectionNames * 2];

            // Keeping track of where in the rangeNames array to add a new start/end of a range.
            int currentRangePosition = 0;

            for (int y = 0; y < numCollectionNames; y++)
            {
                string[] rangeTemp = collectionNames[y].Split('-');
                for (int z = 0; z < rangeTemp.Length; z++)
                {
                    rangeNames[currentRangePosition] = rangeTemp[z];
                    currentRangePosition++;
                }
            }

            // Dictionary needed to input into RangePartitionResolver with corresponding range and collection self link.
            Dictionary<Range<string>, string> rangeCollections = new Dictionary<Range<string>, string>();

            // TO DO:: Iterate through the ranges and add then to rangeCollections with the appropriate start/end point, with the corresponding collection self link.
            //rangeCollections.Add()
            
            RangePartitionResolver<string> rangeResolver = new RangePartitionResolver<string>(
                partitionKeyPropertyName,
                rangeCollections);

            client.PartitionResolvers[database.SelfLink] = rangeResolver;
            return rangeResolver;
        }
Exemplo n.º 27
0
        private static async Task BackupPostCollection(DocumentCollection dc, DocumentClient client)
        {
            Trace.TraceInformation("Collection '{0}' start.  Time: '{1}'", dc.Id,
                DateTime.Now.ToString(CultureInfo.CurrentCulture));
            try
            {
                var ds =
                    from d in client.CreateDocumentQuery<PostMessage>(dc.DocumentsLink)
                    where d.Type == "Post"
                    select d;

                TableBatchOperation batchOperation = new TableBatchOperation();
                List<dynamic> docList = new List<dynamic>();
                foreach (var d in ds)
                {
                    TablePost c = ModelService.TablePostData(d);
                    batchOperation.Insert(c);
                    docList.Add(d);

                    if (batchOperation.Count == 100)
                    {
                        var operation = batchOperation;
                        var res = await _retryPolicy.ExecuteAsync(
                            () => _table.ExecuteBatchAsync(operation));
                        batchOperation = new TableBatchOperation();
                        if (res.Count == operation.Count)
                        {
                            await _iDbService.DocumentDb.BatchDelete(dc, docList);
                            docList = new List<dynamic>();
                            Trace.TraceInformation("inserted");
                        }
                    }
                }
                if (batchOperation.Count > 0)
                {
                    var operation = batchOperation;
                    var res = await _retryPolicy.ExecuteAsync(
                        () => _table.ExecuteBatchAsync(operation));
                    if (res.Count == operation.Count)
                    {
                        await _iDbService.DocumentDb.BatchDelete(dc, docList);
                        Trace.TraceInformation("inserted");
                    }
                }
            }
            catch (Exception e)
            {
                Trace.TraceError("Error in BackupCollection " + e.Message);
            }
        }
Exemplo n.º 28
0
        private static async Task ReadOrCreateCollection(string databaseLink)
        {
            var collections = Client.CreateDocumentCollectionQuery(databaseLink)
                              .Where(col => col.Id == _collectionId).ToArray();

            if (collections.Any())
            {
                _collection = collections.First();
            }
            else
            {
                _collection = await Client.CreateDocumentCollectionAsync(databaseLink,
                    new DocumentCollection { Id = _collectionId });
            }
        }
 public  async Task<List<Order>> GetOrders()
 {
     List<Order> orderDetailsList = new List<Order>();
     if (null == client)
     {
         await InitializeDocumentDB();
     }
     collection = client.CreateDocumentCollectionQuery(database.SelfLink).Where(c => c.Id == "OrderDetails").ToArray().FirstOrDefault();
     //var query = client.CreateDocumentQuery(collection.SelfLink, "SELECT * FROM OrderDetails");
     var query = from ordr in client.CreateDocumentQuery<Order>(collection.SelfLink) select ordr;
     foreach (Order order in query.AsEnumerable())
     {
         orderDetailsList.Add(order);
     }
     return orderDetailsList;
 }
Exemplo n.º 30
0
 public UserStore(DocumentClient documentClient, DocumentCollection users) // DocumentCollection of TUser
 {
     _Client          = documentClient;
     _Users           = users;
     UsesPartitioning = _Users.PartitionKey?.Paths.Any() ?? false;
 }
Exemplo n.º 31
0
 /// <summary>
 /// Create a new document.
 /// </summary>
 /// <param name="collection">The document collection the entity belongs to.</param>
 /// <param name="entity">The document entity to create.</param>
 /// <returns>The async task.</returns>
 public async Task <ResourceResponse <Microsoft.Azure.Documents.Document> > CreateDocumentAsync(DocumentCollection collection, T entity)
 {
     return(await _client.CreateDocumentAsync(collection.SelfLink, entity));
 }
 public OrdreProfessionalGraphRepository(DocumentClient documentClient, DocumentCollection documentCollection) : base(documentClient, documentCollection)
 {
 }
Exemplo n.º 33
0
        /// <summary>
        /// Driver function for bulk import.
        /// </summary>
        /// <returns></returns>
        private async Task RunBulkImportAsync()
        {
            // Cleanup on start if set in config.

            DocumentCollection dataCollection = null;

            try
            {
                if (bool.Parse(ConfigurationManager.AppSettings["ShouldCleanupOnStart"]))
                {
                    Database database = Utils.GetDatabaseIfExists(client, DatabaseName);
                    if (database != null)
                    {
                        await client.DeleteDatabaseAsync(database.SelfLink);
                    }

                    Trace.TraceInformation("Creating database {0}", DatabaseName);
                    database = await client.CreateDatabaseAsync(new Database { Id = DatabaseName });

                    Trace.TraceInformation(String.Format("Creating collection {0} with {1} RU/s", CollectionName, CollectionThroughput));
                    dataCollection = await Utils.CreatePartitionedCollectionAsync(client, DatabaseName, CollectionName, CollectionThroughput);
                }
                else
                {
                    dataCollection = Utils.GetCollectionIfExists(client, DatabaseName, CollectionName);
                    if (dataCollection == null)
                    {
                        throw new Exception("The data collection does not exist");
                    }
                }
            }
            catch (Exception de)
            {
                Trace.TraceError("Unable to initialize, exception message: {0}", de.Message);
                throw;
            }

            // Prepare for bulk import.

            // Creating documents with simple partition key here.
            string partitionKeyProperty        = dataCollection.PartitionKey.Paths[0].Replace("/", "");
            long   numberOfDocumentsToGenerate = long.Parse(ConfigurationManager.AppSettings["NumberOfDocumentsToImport"]);

            // Set retry options high for initialization (default values).
            client.ConnectionPolicy.RetryOptions.MaxRetryWaitTimeInSeconds           = 30;
            client.ConnectionPolicy.RetryOptions.MaxRetryAttemptsOnThrottledRequests = 9;

            IBulkExecutor graphbulkExecutor = new GraphBulkExecutor(client, dataCollection);
            await graphbulkExecutor.InitializeAsync();

            // Set retries to 0 to pass control to bulk executor.
            client.ConnectionPolicy.RetryOptions.MaxRetryWaitTimeInSeconds           = 0;
            client.ConnectionPolicy.RetryOptions.MaxRetryAttemptsOnThrottledRequests = 0;

            var tokenSource = new CancellationTokenSource();
            var token       = tokenSource.Token;

            BulkImportResponse vResponse = null;
            BulkImportResponse eResponse = null;

            try
            {
                vResponse = await graphbulkExecutor.BulkImportAsync(
                    Utils.GenerateVertices(numberOfDocumentsToGenerate),
                    enableUpsert : true,
                    disableAutomaticIdGeneration : true,
                    maxConcurrencyPerPartitionKeyRange : null,
                    maxInMemorySortingBatchSize : null,
                    cancellationToken : token);

                eResponse = await graphbulkExecutor.BulkImportAsync(
                    Utils.GenerateEdges(numberOfDocumentsToGenerate),
                    enableUpsert : true,
                    disableAutomaticIdGeneration : true,
                    maxConcurrencyPerPartitionKeyRange : null,
                    maxInMemorySortingBatchSize : null,
                    cancellationToken : token);
            }
            catch (DocumentClientException de)
            {
                Trace.TraceError("Document client exception: {0}", de);
            }
            catch (Exception e)
            {
                Trace.TraceError("Exception: {0}", e);
            }

            Console.WriteLine("\nSummary for batch");
            Console.WriteLine("--------------------------------------------------------------------- ");
            Console.WriteLine(
                "Inserted {0} graph elements ({1} vertices, {2} edges) @ {3} writes/s, {4} RU/s in {5} sec)",
                vResponse.NumberOfDocumentsImported + eResponse.NumberOfDocumentsImported,
                vResponse.NumberOfDocumentsImported,
                eResponse.NumberOfDocumentsImported,
                Math.Round(
                    (vResponse.NumberOfDocumentsImported) /
                    (vResponse.TotalTimeTaken.TotalSeconds + eResponse.TotalTimeTaken.TotalSeconds)),
                Math.Round(
                    (vResponse.TotalRequestUnitsConsumed + eResponse.TotalRequestUnitsConsumed) /
                    (vResponse.TotalTimeTaken.TotalSeconds + eResponse.TotalTimeTaken.TotalSeconds)),
                vResponse.TotalTimeTaken.TotalSeconds + eResponse.TotalTimeTaken.TotalSeconds);
            Console.WriteLine(
                "Average RU consumption per insert: {0}",
                (vResponse.TotalRequestUnitsConsumed + eResponse.TotalRequestUnitsConsumed) /
                (vResponse.NumberOfDocumentsImported + eResponse.NumberOfDocumentsImported));
            Console.WriteLine("---------------------------------------------------------------------\n ");

            if (vResponse.BadInputDocuments.Count > 0 || eResponse.BadInputDocuments.Count > 0)
            {
                using (System.IO.StreamWriter file = new System.IO.StreamWriter(@".\BadVertices.txt", true))
                {
                    foreach (object doc in vResponse.BadInputDocuments)
                    {
                        file.WriteLine(doc);
                    }
                }

                using (System.IO.StreamWriter file = new System.IO.StreamWriter(@".\BadEdges.txt", true))
                {
                    foreach (object doc in eResponse.BadInputDocuments)
                    {
                        file.WriteLine(doc);
                    }
                }
            }

            // Cleanup on finish if set in config.
            if (bool.Parse(ConfigurationManager.AppSettings["ShouldCleanupOnFinish"]))
            {
                Trace.TraceInformation("Deleting Database {0}", DatabaseName);
                await client.DeleteDatabaseAsync(UriFactory.CreateDatabaseUri(DatabaseName));
            }

            Trace.WriteLine("\nPress any key to exit.");
            Console.ReadKey();
        }
Exemplo n.º 34
0
 public DocumentConnection(Database db, DocumentClient client, DocumentCollection collection)
 {
     Database   = db;
     Client     = client;
     Collection = collection;
 }
 public async Task CreateDocumentCollectionIfNotExistsAsync(Uri uri, DocumentCollection documentCollection)
 {
     await client.CreateDocumentCollectionIfNotExistsAsync(uri, documentCollection);
 }
Exemplo n.º 36
0
        /// <summary>
        /// Run the get started application.
        /// </summary>
        /// <param name="client">The DocumentDB client instance</param>
        /// <returns>A Task for asynchronous execuion.</returns>
        public async Task RunAsync(DocumentClient client)
        {
            Database database = await client.CreateDatabaseIfNotExistsAsync(new Database { Id = "graphdb" });

            DocumentCollection graph = await client.CreateDocumentCollectionIfNotExistsAsync(
                UriFactory.CreateDatabaseUri("graphdb"),
                new DocumentCollection { Id = "Persons" },
                new RequestOptions { OfferThroughput = 10000 });

            // Azure Cosmos DB supports the Gremlin API for working with Graphs. Gremlin is a functional programming language composed of steps.
            // Here, we run a series of Gremlin queries to show how you can add vertices, edges, modify properties, perform queries and traversals
            // For additional details, see https://aka.ms/gremlin for the complete list of supported Gremlin operators
            Dictionary <string, string> gremlinQueries = new Dictionary <string, string>
            {
                { "Cleanup", "g.V().drop()" },
                { "AddVertex 1", "g.addV('person').property('id', 'thomas').property('firstName', 'Thomas').property('age', 44)" },
                { "AddVertex 2", "g.addV('person').property('id', 'mary').property('firstName', 'Mary').property('lastName', 'Andersen').property('age', 39)" },
                { "AddVertex 3", "g.addV('person').property('id', 'ben').property('firstName', 'Ben').property('lastName', 'Miller')" },
                { "AddVertex 4", "g.addV('person').property('id', 'robin').property('firstName', 'Robin').property('lastName', 'Wakefield')" },
                { "AddEdge 1", "g.V('thomas').addE('knows').to(g.V('mary'))" },
                { "AddEdge 2", "g.V('thomas').addE('knows').to(g.V('ben'))" },
                { "AddEdge 3", "g.V('ben').addE('knows').to(g.V('robin'))" },
                { "UpdateVertex", "g.V('thomas').property('age', 44)" },
                { "CountVertices", "g.V().count()" },
                { "Filter Range", "g.V().hasLabel('person').has('age', gt(40))" },
                { "Project", "g.V().hasLabel('person').values('firstName')" },
                { "Sort", "g.V().hasLabel('person').order().by('firstName', decr)" },
                { "Traverse", "g.V('thomas').outE('knows').inV().hasLabel('person')" },
                { "Traverse 2x", "g.V('thomas').outE('knows').inV().hasLabel('person').outE('knows').inV().hasLabel('person')" },
                { "Loop", "g.V('thomas').repeat(out()).until(has('id', 'robin')).path()" },
                { "DropEdge", "g.V('thomas').outE('knows').where(inV().has('id', 'mary')).drop()" },
                { "CountEdges", "g.E().count()" },
                { "DropVertex", "g.V('thomas').drop()" },
            };

            foreach (KeyValuePair <string, string> gremlinQuery in gremlinQueries)
            {
                Console.WriteLine($"Running {gremlinQuery.Key}: {gremlinQuery.Value}");

                // The CreateGremlinQuery method extensions allow you to execute Gremlin queries and iterate
                // results asychronously
                IDocumentQuery <dynamic> query = client.CreateGremlinQuery <dynamic>(graph, gremlinQuery.Value);
                while (query.HasMoreResults)
                {
                    foreach (dynamic result in await query.ExecuteNextAsync())
                    {
                        Console.WriteLine($"\t {JsonConvert.SerializeObject(result)}");
                    }
                }

                Console.WriteLine();
            }

            // Data is returned in GraphSON format, which be deserialized into a strongly-typed vertex, edge or property class
            // The following snippet shows how to do this
            string gremlin = gremlinQueries["AddVertex 1"];

            Console.WriteLine($"Running Add Vertex with deserialization: {gremlin}");

            IDocumentQuery <Vertex> insertVertex = client.CreateGremlinQuery <Vertex>(graph, gremlinQueries["AddVertex 1"]);

            while (insertVertex.HasMoreResults)
            {
                foreach (Vertex vertex in await insertVertex.ExecuteNextAsync <Vertex>())
                {
                    // Since Gremlin is designed for multi-valued properties, the format returns an array. Here we just read
                    // the first value
                    string name = (string)vertex.GetVertexProperties("firstName").First().Value;
                    Console.WriteLine($"\t Id:{vertex.Id}, Name: {name}");
                }
            }

            Console.WriteLine();

            Console.WriteLine("Done. Press any key to exit...");
            Console.ReadLine();
        }
Exemplo n.º 37
0
        public static async Task <HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequestMessage req, TraceWriter log)
        {
            log.Info("C# HTTP trigger function processed a request.");

            string shipmasterId = req.GetQueryNameValuePairs()
                                  .FirstOrDefault(q => string.Compare(q.Key, "ShipmasterId", true) == 0)
                                  .Value;
            string shipmentId = req.GetQueryNameValuePairs()
                                .FirstOrDefault(q => string.Compare(q.Key, "ShipmentID", true) == 0)
                                .Value;


            if (string.IsNullOrEmpty(shipmasterId) || string.IsNullOrEmpty(shipmentId))
            {
                return(req.CreateErrorResponse(HttpStatusCode.BadRequest, "Input is Null or Empty"));
            }


            var Cosmosconnectionstring = Environment.GetEnvironmentVariable("NoSQLConnectionString");
            var ConnectionstrinG       = Environment.GetEnvironmentVariable("SQLConnectionString");
            var PrimaryKey             = Environment.GetEnvironmentVariable("NoSqlPrimaryKey");

            DocumentClient     client             = new DocumentClient(new Uri(Cosmosconnectionstring), PrimaryKey);
            FeedOptions        feedOptions        = new FeedOptions();
            Database           databaseInfo       = client.CreateDatabaseQuery().Where(x => x.Id == "TitanCosmosDB").AsEnumerable().FirstOrDefault();
            string             DB                 = databaseInfo.SelfLink;
            DocumentCollection documentCollection = new DocumentCollection {
                Id = "TitanTelemetryCollection"
            };

            var collectionlinK  = UriFactory.CreateDocumentCollectionUri("TitanCosmosDB", "TitanTelemetryCollection");
            var collectionAlert = UriFactory.CreateDocumentCollectionUri("TitanCosmosDB", "TitanAlertCollection");

            List <SensorDetails> sensorList = new List <SensorDetails>();

            var Connectionstring = Environment.GetEnvironmentVariable("SQLConnectionString");

            string SqlSelect = "SELECT DISTINCT [ObjectType],[ObjectId],[BeaconId],'NonAlert'As [BeaconStatus] FROM [Beacon_Object_Info] WHERE [ShipMasterId]=@ShipMasterId" +
                               " AND[BeaconId] not in (SELECT DISTINCT[BeaconID] from Alert_Process where [ShipmentID] = @ShipmentID and[Status] = 'Active')" +
                               " UNION " +
                               " SELECT DISTINCT[ObjectType],[ObjectId],[BeaconId],'Alert'As[BeaconStatus] FROM[Beacon_Object_Info] WHERE[ShipMasterId]=@ShipMasterId" +
                               " AND[BeaconId] in (SELECT DISTINCT [BeaconID] from Alert_Process where[ShipmentID] = @ShipmentID and[Status]='Active')";

            string cosmosTelemeterySelect = "";


            using (SqlConnection conn = new SqlConnection(Connectionstring))
            {
                using (SqlCommand cmd = new SqlCommand(SqlSelect, conn))
                {
                    cmd.Parameters.Add("@ShipMasterId", SqlDbType.Int).Value    = shipmasterId;
                    cmd.Parameters.Add("@ShipmentID", SqlDbType.NVarChar).Value = shipmentId;
                    conn.Open();
                    SqlDataReader reader = cmd.ExecuteReader();

                    while (reader.Read())
                    {
                        SensorDetails Sensor = new SensorDetails();
                        Sensor.ObjectType   = (string)reader["ObjectType"];
                        Sensor.ObjectId     = (string)reader["ObjectId"];
                        Sensor.BeaconId     = (string)reader["BeaconId"];
                        Sensor.BeaconStatus = (string)reader["BeaconStatus"];
                        TelemetryDetails objTelmetry = new TelemetryDetails();
                        cosmosTelemeterySelect = "SELECT TOP 1 c.temperature,c.humidity,f.current_system_time,c.humidity_alert,c.temperature_alert,c.tamper_alert,c.shock_alert " +
                                                 " FROM f JOIN c IN f.sensor_Values WHERE c.sensorID = '" + Sensor.BeaconId + "' order by f.current_system_time desc";
                        IQueryable <TelemetryDetails> cosTelemetry = client.CreateDocumentQuery <TelemetryDetails>(collectionlinK, cosmosTelemeterySelect);
                        objTelmetry = cosTelemetry.ToList().SingleOrDefault();


                        if (objTelmetry != null)
                        {
                            Sensor.Temperature         = objTelmetry.Temperature;
                            Sensor.Humidity            = objTelmetry.Humidity;
                            Sensor.BeaconTimestamp     = objTelmetry.current_system_time;
                            Sensor.HumidityAlert       = objTelmetry.humidity_alert;
                            Sensor.TamperAlert         = objTelmetry.tamper_alert;
                            Sensor.TemperatureAlert    = objTelmetry.temperature_alert;
                            Sensor.ShockVibrationAlert = objTelmetry.shock_alert;
                        }
                        sensorList.Add(Sensor);
                    }

                    reader.Close();
                    conn.Close();
                }
            }

            return(new HttpResponseMessage(HttpStatusCode.OK)
            {
                Content = new StringContent(JsonConvert.SerializeObject(sensorList, Formatting.Indented), Encoding.UTF8, "application/json")
            });
        }
        public async Task ContainerV2CompatTest()
        {
            string             containerId        = "SerializeContainerTest";
            DocumentCollection documentCollection = new DocumentCollection()
            {
                Id           = containerId,
                PartitionKey = new PartitionKeyDefinition()
                {
                    Paths = new Collection <string>()
                    {
                        "/pkPath"
                    }
                },
                IndexingPolicy = new IndexingPolicy()
                {
                    IncludedPaths = new Collection <IncludedPath>()
                    {
                        new IncludedPath()
                        {
                            Path = "/*"
                        }
                    },
                    CompositeIndexes = new Collection <Collection <CompositePath> >()
                    {
                        new Collection <CompositePath>()
                        {
                            new CompositePath()
                            {
                                Path  = "/address/test/*",
                                Order = CompositePathSortOrder.Ascending
                            },
                            new CompositePath()
                            {
                                Path  = "/address/test2/*",
                                Order = CompositePathSortOrder.Ascending
                            }
                        }
                    },
                    SpatialIndexes = new Collection <SpatialSpec>()
                    {
                        new SpatialSpec()
                        {
                            Path         = "/name/first/*",
                            SpatialTypes = new Collection <SpatialType>()
                            {
                                SpatialType.LineString
                            }
                        }
                    }
                },
            };


            string documentJsonString = null;

            using (MemoryStream memoryStream = new MemoryStream())
            {
                documentCollection.SaveTo(memoryStream);
                memoryStream.Position = 0;
                using (StreamReader sr = new StreamReader(memoryStream))
                {
                    documentJsonString = await sr.ReadToEndAsync();
                }
            }

            Assert.IsNotNull(documentJsonString);

            string cosmosJsonString = null;

            using (MemoryStream memoryStream = new MemoryStream())
            {
                documentCollection.SaveTo(memoryStream);
                memoryStream.Position = 0;

                CosmosJsonDotNetSerializer serializerCore      = new CosmosJsonDotNetSerializer();
                ContainerProperties        containerProperties = serializerCore.FromStream <ContainerProperties>(memoryStream);

                Assert.IsNotNull(containerProperties);
                Assert.AreEqual(containerId, containerProperties.Id);

                using (Stream stream = serializerCore.ToStream <ContainerProperties>(containerProperties))
                {
                    using (StreamReader sr = new StreamReader(stream))
                    {
                        cosmosJsonString = await sr.ReadToEndAsync();
                    }
                }
            }

            JObject jObjectDocumentCollection = JObject.Parse(documentJsonString);
            JObject jObjectContainer          = JObject.Parse(cosmosJsonString);

            Assert.IsTrue(JToken.DeepEquals(jObjectDocumentCollection, jObjectContainer), $"v2:{documentJsonString}; v3:{cosmosJsonString}");
        }
Exemplo n.º 39
0
        static public void Plan2HoePrSelPolygonLayer()
        {
            try
            {
                if (!OpenHoePrPalette())
                {
                    return;
                }

                var      opts = Globs.TheHoePrOptions;
                Document doc  = Application.DocumentManager.MdiActiveDocument;

                using (DocumentLock m_doclock = doc.LockDocument())
                {
                    DocumentCollection dm = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager;
                    if (doc == null)
                    {
                        return;
                    }
                    Editor ed = doc.Editor;
#if NEWSETFOCUS
                    doc.Window.Focus();
#else
                    Autodesk.AutoCAD.Internal.Utils.SetFocusToDwgView(); // previous 2014 AutoCAD - Versions
#endif

                    PromptNestedEntityOptions peo = new PromptNestedEntityOptions("\nPolylinie wählen: ");
                    //peo.SetRejectMessage("\nDas gewählte Element ist keine Polylinie.");
                    //peo.AddAllowedClass(typeof(Polyline), true);
                    //peo.AddAllowedClass(typeof(Polyline2d), true);
                    //peo.AddAllowedClass(typeof(Polyline3d), true);

                    PromptEntityResult per = ed.GetNestedEntity(peo);

                    if (per.Status == PromptStatus.OK)
                    {
                        using (var tr = doc.TransactionManager.StartTransaction())
                        {
                            DBObject obj = tr.GetObject(per.ObjectId, OpenMode.ForRead);
                            Entity   ent = obj as Entity;
                            if (ent != null)
                            {
                                if (ent is Polyline || ent is Polyline2d || ent is Polyline3d)
                                {
                                    opts.SetPolygonLayer(ent.Layer);
                                }
                                else
                                {
                                    ed.WriteMessage("\nDas gewählte Element ist keine Polylinie.");
                                }
                            }

                            tr.Commit();
                        }
                    }
                }
            }
            catch (System.Exception ex)
            {
                Application.ShowAlertDialog(string.Format(CultureInfo.CurrentCulture, "Fehler in Plan2HoePrSelPolygonLayer aufgetreten! {0}", ex.Message));
            }
        }
        public async Task <DocumentCollection> CreateDocumentCollectionIfNotExistsAsync(Uri databaseUri, DocumentCollection documentCollection, RequestOptions options)
        {
            ResourceResponse <DocumentCollection> response = await _client.CreateDocumentCollectionIfNotExistsAsync(databaseUri, documentCollection, options);

            return(response.Resource);
        }
        private bool GetHeightFromVermBlocks(ref double height)
        {
            DocumentCollection dm  = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager;
            Document           doc = dm.MdiActiveDocument;
            Editor             ed  = doc.Editor;

#if NEWSETFOCUS
            doc.Window.Focus();
#else
            Autodesk.AutoCAD.Internal.Utils.SetFocusToDwgView(); // previous 2014 AutoCAD - Versions
#endif


            PromptEntityResult per = ed.GetEntity("\nErsten Vermessungsblock wählen: ");

            //DocumentLock loc = dm.MdiActiveDocument.LockDocument();
            //using (loc)
            //{
            //}

            bool   blockFound = false;
            double height1    = 0.0;
            double height2    = 0.0;
            if (per.Status == PromptStatus.OK)
            {
                Transaction tr = doc.TransactionManager.StartTransaction();
                using (tr)
                {
                    DBObject obj = tr.GetObject(per.ObjectId, OpenMode.ForRead);

                    BlockReference br = obj as BlockReference;
                    if (br == null)
                    {
                        return(false);
                    }

                    if (br.Name == "GEOINOVA")
                    {
                        blockFound = true;
                        height1    = br.Position.Z;
                        br.Highlight();
                    }

                    if (blockFound)
                    {
                        blockFound = false;
                        per        = ed.GetEntity("\nZweiten Vermessungsblock wählen: ");
                        if (per.Status == PromptStatus.OK)
                        {
                            obj = tr.GetObject(per.ObjectId, OpenMode.ForRead);
                            BlockReference br2 = obj as BlockReference;
                            if (br2 == null)
                            {
                                return(false);
                            }

                            if (br2.Name == "GEOINOVA")
                            {
                                blockFound = true;
                                height2    = br2.Position.Z;
                            }
                        }

                        if (blockFound)
                        {
                            height = Math.Abs(height1 - height2);
                        }

                        br.Unhighlight();
                    }

                    tr.Commit();
                }

                if (!blockFound)
                {
                    return(false);
                }
                return(true);
            }

            return(false);
        }
Exemplo n.º 42
0
        public GivenACosmosConnection()
        {
            someDummyDocument = new DummyCosmosDocument
            {
                Id       = someDocumentId,
                Data     = someDocumentData,
                ETag     = someDocumentETag,
                SelfLink = someSelfLink
            };

            jsonSerializerSettings = new JsonSerializerSettings();
            someRequestOptions     = new RequestOptions();
            someFeedOptions        = new FeedOptions();

            someDocument = new Document();
            someDocument.LoadFrom(new JsonTextReader(new StringReader(JsonConvert.SerializeObject(someDummyDocument))), jsonSerializerSettings);

            someCollectionUri = UriFactory.CreateDocumentCollectionUri(someDatabaseId, someCollectionId);
            someDocumentUri   = UriFactory.CreateDocumentUri(someDatabaseId, someCollectionId, someDocumentId);

            connectionPolicy = new ConnectionPolicy();
            retryOptions     = new Mock <RetryOptions>();
            retryOptions.Object.MaxRetryAttemptsOnThrottledRequests = 9;
            retryOptions.Object.MaxRetryWaitTimeInSeconds           = 30;
            connectionPolicy.RetryOptions = retryOptions.Object;

            documentClient = new Mock <IDocumentClient>();
            documentClient.Setup(x => x.ConnectionPolicy).Returns(connectionPolicy);
            documentClient.Setup(x => x.CreateDocumentAsync(someCollectionUri, someDummyDocument, It.IsAny <RequestOptions>(), It.IsAny <bool>(), It.IsAny <CancellationToken>()))
            .Returns(Task.FromResult(new ResourceResponse <Document>(someDocument)));

            documentClient.Setup(x => x.CreateDocumentQuery <DummyCosmosDocument>(someCollectionUri, It.IsAny <FeedOptions>()))
            .Returns(new List <DummyCosmosDocument> {
                someDummyDocument
            }.AsQueryable().OrderBy(d => d.Id));

            documentClient.Setup(x => x.CreateDocumentQuery <DummyCosmosDocument>(someCollectionUri, It.IsAny <SqlQuerySpec>(), It.IsAny <FeedOptions>()))
            .Returns(new List <DummyCosmosDocument> {
                someDummyDocument
            }.AsQueryable().OrderBy(d => d.Id));

            databaseFactory = new Mock <IDatabaseFactory>();
            databaseFactory.Setup(x => x.DocumentClient()).Returns(documentClient.Object);

            someDocumentCollection = new DocumentCollection
            {
                Id = someCollectionId
            };

            bulkExecutor           = new Mock <IBulkExecutor>();
            bulkExecutorWrapper    = new Mock <IBulkExecutorWrapper>();
            someBulkImportResponse = new BulkImportResponse();

            bulkExecutor
            .Setup(b => b.BulkImportAsync(It.Is <IEnumerable <CosmosDocumentBase> >(l => l.Count() == 1), true, false, null, null, default))
            .Callback(() =>
            {
                someBulkImportResponse.GetType().GetProperty("NumberOfDocumentsImported").SetValue(someBulkImportResponse, 1);
                someBulkImportResponse.GetType().GetProperty("TotalRequestUnitsConsumed").SetValue(someBulkImportResponse, 1);
                someBulkImportResponse.GetType().GetProperty("TotalTimeTaken").SetValue(someBulkImportResponse, TimeSpan.FromSeconds(10));
            })
            .Returns(Task.FromResult(someBulkImportResponse));

            bulkExecutor
            .Setup(b => b.BulkImportAsync(It.Is <IEnumerable <CosmosDocumentBase> >(l => l.Count() == 2), true, false, null, null, default))
            .Callback(() =>
            {
                someBulkImportResponse.GetType().GetProperty("NumberOfDocumentsImported").SetValue(someBulkImportResponse, 2);
                someBulkImportResponse.GetType().GetProperty("TotalRequestUnitsConsumed").SetValue(someBulkImportResponse, 2);
                someBulkImportResponse.GetType().GetProperty("TotalTimeTaken").SetValue(someBulkImportResponse, TimeSpan.FromSeconds(20));
            })
            .Returns(Task.FromResult(someBulkImportResponse));

            someDatabaseUri = UriFactory.CreateDatabaseUri(someDatabaseId);

            documentClient.Setup(x => x.CreateDocumentCollectionQuery(someDatabaseUri, It.IsAny <FeedOptions>()))
            .Returns(new List <DocumentCollection> {
                someDocumentCollection
            }.AsQueryable().OrderBy(x => x.PartitionKey));
            databaseFactory.Setup(x => x.DocumentClient()).Returns(documentClient.Object);
            databaseFactory.Setup(x => x.BulkExecutor(documentClient.Object, someDocumentCollection)).Returns(bulkExecutor.Object);
            databaseFactory.Setup(x => x.BulkExecutorWrapper(bulkExecutor.Object)).Returns(bulkExecutorWrapper.Object);

            sut = new CosmosConnection(databaseFactory.Object, someDatabaseId, someBatchBulkSize);
        }
Exemplo n.º 43
0
        private async Task GetStartedDemo()
        {
            this.client = new DocumentClient(new Uri(EndpointUri), PrimaryKey);

            try
            {
                await this.client.DeleteDatabaseAsync(UriFactory.CreateDatabaseUri(DatabaseName));
            }
            catch (DocumentClientException dce)
            {
                Console.WriteLine("Database not found!");
            }


            await this.client.CreateDatabaseIfNotExistsAsync(new Database { Id = DatabaseName });

            DocumentCollection collectionDefinition = new DocumentCollection
            {
                Id = CollectionName
            };

            collectionDefinition.IndexingPolicy.Automatic = true;

            collectionDefinition.DefaultTimeToLive = -1;        // switch on TTL but no default expiry time
            collectionDefinition.PartitionKey.Paths.Add("/moduleId");

            // performance / load testing on indexes
            collectionDefinition.IndexingPolicy.IncludedPaths.Add(
                new IncludedPath
            {
                Path    = "/*",
                Indexes = new Collection <Index>
                {
                    new RangeIndex(DataType.Number)
                    {
                        Precision = -1, DataType = DataType.Number
                    },
                    new RangeIndex(DataType.String)
                    {
                        Precision = -1, DataType = DataType.String
                    }
                }
            });

            collectionDefinition.IndexingPolicy.ExcludedPaths.Add(new ExcludedPath {
                Path = "/newObject/?"
            });
            collectionDefinition.IndexingPolicy.ExcludedPaths.Add(new ExcludedPath {
                Path = "/previousObject/?"
            });

            DocumentCollection auditCollection = await this.client.CreateDocumentCollectionIfNotExistsAsync(
                UriFactory.CreateDatabaseUri(DatabaseName),
                collectionDefinition,
                new RequestOptions { OfferThroughput = 20000 });

            List <AuditEvent> AuditEvents = AuditEventFactory.GeneratAuditEvents(10, 10, 5);

            await CreateAuditRecords(AuditEvents);

            ExecuteSimpleQuery();
            ExecuteTextSearch();
            ExecuteSqlStringSearch();
            ExecuteDateSearch();
        }
Exemplo n.º 44
0
 public GraphObjectGraphRepository(DocumentClient documentClient, DocumentCollection documentCollection) : base(documentClient, documentCollection)
 {
 }
        public async static Task PopulateLimitedIndexesCollection(List <DgProvider> narrowProviders)
        {
            Uri uri = UriFactory.CreateDocumentCollectionUri(BhProvidersDatabaseDa.DatabaseName, BhProvidersDatabaseDa.CollectionNames.LimtedIndexes.ToString());
            //Delete collection if exists
            bool exists = BhProvidersDatabaseDa.DocumentClient.CreateDocumentCollectionQuery(BhProvidersDatabaseDa.DatabaseUri)
                          .ToList()
                          .Exists(c => c.Id == BhProvidersDatabaseDa.CollectionNames.LimtedIndexes.ToString());

            if (exists)
            {
                await BhProvidersDatabaseDa.DocumentClient.DeleteDocumentCollectionAsync(uri);
            }

            //Set throughput and partition key
            int    reservedRUs  = 9000;
            string partitionKey = "/locations[0].zip";

            PartitionKeyDefinition partitionKeyDefinition = new PartitionKeyDefinition();

            partitionKeyDefinition.Paths.Add(partitionKey); //Weird.  Cannot have more than one partition key...

            RequestOptions requestOptions = new RequestOptions {
                OfferThroughput = reservedRUs
            };
            DocumentCollection limitedIndexesCollection = new DocumentCollection {
                Id = BhProvidersDatabaseDa.CollectionNames.LimtedIndexes.ToString()
            };

            limitedIndexesCollection.IndexingPolicy.IncludedPaths = new System.Collections.ObjectModel.Collection <IncludedPath>();
            limitedIndexesCollection.IndexingPolicy.IncludedPaths.Add
                (new IncludedPath
            {
                Indexes = new System.Collections.ObjectModel.Collection <Index>
                {
                    new HashIndex(DataType.String)
                    {
                        Precision = -1
                    },
                    new RangeIndex(DataType.String)
                    {
                        Precision = -1
                    }
                },
                Path = "/whateverPath/*"
            });
            limitedIndexesCollection.IndexingPolicy.IndexingMode = IndexingMode.Lazy;
            ResourceResponse <DocumentCollection> response = await BhProvidersDatabaseDa.DocumentClient.CreateDocumentCollectionAsync(
                BhProvidersDatabaseDa.DatabaseUri,
                new DocumentCollection
            {
                Id           = BhProvidersDatabaseDa.CollectionNames.LimtedIndexes.ToString(),
                PartitionKey = partitionKeyDefinition
            },
                requestOptions
                );

            DocumentCollection collection = response.Resource;
            DocumentCollection narrowProviderCollection = new DocumentCollection {
                Id = BhProvidersDatabaseDa.CollectionNames.DgNarrowProviders.ToString()
            };

            narrowProviderCollection.IndexingPolicy.IndexingMode = IndexingMode.Lazy;

            /*            Index index = new Index();
             *          narrowProviderCollection.IndexingPolicy.IncludedPaths = new System.Collections.ObjectModel.Collection<IncludedPath>()
             *          {
             *              new IncludedPath
             *              {
             *                  Indexes = new System.Collections.ObjectModel.Collection<Index>()
             *                  { new  ;
             */
            await BhProvidersDatabaseDa.CreateCollection(BhProvidersDatabaseDa.CollectionNames.DgNarrowProviders);

            foreach (DgProvider provider in filteredProviders)
            {
                DataModels.Narrow.DgProvider        narrow = provider;
                Task <ResourceResponse <Document> > task   = BhProvidersDatabaseDa.DocumentClient.CreateDocumentAsync(uri, narrow);
            }
            Console.WriteLine($"Received {filteredProviders.Count}");
        }
        public void ContainerSettingsWithIndexingPolicyTest()
        {
            string id     = Guid.NewGuid().ToString();
            string pkPath = "/partitionKey";

            // Two equivalent definitions
            ContainerProperties cosmosContainerSettings = new ContainerProperties(id, pkPath);

            cosmosContainerSettings.IndexingPolicy.Automatic = true;
            cosmosContainerSettings.IndexingPolicy.IncludedPaths.Add(new Cosmos.IncludedPath()
            {
                Path = "/id1/*"
            });

            Cosmos.UniqueKey cuk1 = new Cosmos.UniqueKey();
            cuk1.Paths.Add("/u1");
            cosmosContainerSettings.UniqueKeyPolicy.UniqueKeys.Add(cuk1);

            DocumentCollection collection = new DocumentCollection()
            {
                Id           = id,
                PartitionKey = new PartitionKeyDefinition()
                {
                    Paths = new Collection <string>()
                    {
                        pkPath
                    },
                }
            };

            collection.IndexingPolicy.Automatic = true;
            collection.IndexingPolicy.IncludedPaths.Add(new Documents.IncludedPath()
            {
                Path = "/id1/*"
            });

            Documents.UniqueKey duk1 = new Documents.UniqueKey();
            duk1.Paths.Add("/u1");
            collection.UniqueKeyPolicy.UniqueKeys.Add(duk1);

            string cosmosSerialized = SettingsContractTests.CosmosSerialize(cosmosContainerSettings);
            string directSerialized = SettingsContractTests.DirectSerialize(collection);

            // Swap de-serialize and validate
            ContainerProperties containerDeserSettings = SettingsContractTests.CosmosDeserialize <ContainerProperties>(directSerialized);
            DocumentCollection  collectionDeser        = SettingsContractTests.DirectDeSerialize <DocumentCollection>(cosmosSerialized);

            Assert.AreEqual(collection.Id, containerDeserSettings.Id);
            Assert.AreEqual(collection.PartitionKey.Paths[0], containerDeserSettings.PartitionKeyPath);
            Assert.AreEqual(collection.IndexingPolicy.Automatic, containerDeserSettings.IndexingPolicy.Automatic);
            Assert.AreEqual(collection.IndexingPolicy.IncludedPaths.Count, containerDeserSettings.IndexingPolicy.IncludedPaths.Count);
            Assert.AreEqual(collection.IndexingPolicy.IncludedPaths[0].Path, containerDeserSettings.IndexingPolicy.IncludedPaths[0].Path);
            Assert.AreEqual(collection.IndexingPolicy.IncludedPaths[0].Indexes.Count, containerDeserSettings.IndexingPolicy.IncludedPaths[0].Indexes.Count);
            Assert.AreEqual(collection.UniqueKeyPolicy.UniqueKeys.Count, containerDeserSettings.UniqueKeyPolicy.UniqueKeys.Count);
            Assert.AreEqual(collection.UniqueKeyPolicy.UniqueKeys[0].Paths.Count, containerDeserSettings.UniqueKeyPolicy.UniqueKeys[0].Paths.Count);
            Assert.AreEqual(collection.UniqueKeyPolicy.UniqueKeys[0].Paths[0], containerDeserSettings.UniqueKeyPolicy.UniqueKeys[0].Paths[0]);

            Assert.AreEqual(cosmosContainerSettings.Id, collectionDeser.Id);
            Assert.AreEqual(cosmosContainerSettings.PartitionKeyPath, collectionDeser.PartitionKey.Paths[0]);
            Assert.AreEqual(cosmosContainerSettings.IndexingPolicy.Automatic, collectionDeser.IndexingPolicy.Automatic);
            Assert.AreEqual(cosmosContainerSettings.IndexingPolicy.IncludedPaths.Count, collectionDeser.IndexingPolicy.IncludedPaths.Count);
            Assert.AreEqual(cosmosContainerSettings.IndexingPolicy.IncludedPaths[0].Path, collectionDeser.IndexingPolicy.IncludedPaths[0].Path);
            Assert.AreEqual(cosmosContainerSettings.IndexingPolicy.IncludedPaths[0].Indexes.Count, collectionDeser.IndexingPolicy.IncludedPaths[0].Indexes.Count);
            Assert.AreEqual(cosmosContainerSettings.UniqueKeyPolicy.UniqueKeys.Count, collectionDeser.UniqueKeyPolicy.UniqueKeys.Count);
            Assert.AreEqual(cosmosContainerSettings.UniqueKeyPolicy.UniqueKeys[0].Paths.Count, collectionDeser.UniqueKeyPolicy.UniqueKeys[0].Paths.Count);
            Assert.AreEqual(cosmosContainerSettings.UniqueKeyPolicy.UniqueKeys[0].Paths[0], collectionDeser.UniqueKeyPolicy.UniqueKeys[0].Paths[0]);
        }
Exemplo n.º 47
0
 public CosmicGraphClient(DocumentClient documentClient, DocumentCollection collection)
 {
     this.documentClient = documentClient;
     this.collection     = collection;
 }
Exemplo n.º 48
0
 public static Uri ToDocumentCollectionUri(this DocumentCollection documentCollection) =>
 UriFactory.CreateDocumentCollectionUri("BryceMountainPatrol", documentCollectionMap[documentCollection]);
Exemplo n.º 49
0
        public async Task <IEnumerable <string> > buildDB()
        {
            var results = new List <string>();

            Microsoft.Azure.Documents.Database database = await client.CreateDatabaseIfNotExistsAsync(new Database { Id = "graphdb" });

            DocumentCollection graph = await client.CreateDocumentCollectionIfNotExistsAsync(
                UriFactory.CreateDatabaseUri("graphdb"),
                new DocumentCollection { Id = "Persons" },
                new RequestOptions { OfferThroughput = 400 });

            Dictionary <string, string> gremlinQueries = new Dictionary <string, string>
            {
                { "Cleanup", "g.V().drop()" },
                { "AddAdam", "g.addV('person').property('id', 'Adam').property('Name', 'Adam')" },
                { "AddEve", "g.addV('person').property('id', 'Eve').property('Name', 'Eve')" },
                { "AddCain", "g.addV('person').property('id', 'Cain').property('Name', 'Cain')" },
                { "AddAbel", "g.addV('person').property('id', 'Abel').property('Name', 'Abel')" },
                { "AddSeth", "g.addV('person').property('id', 'Seth').property('Name', 'Seth')" },
                { "AddEnosh", "g.addV('person').property('id', 'Enosh').property('Name', 'Enosh')" },

                { "AddAdam+Eve", "g.V('Adam').addE('Married').to(g.V('Eve'))" },

                { "AddCain->Abel", "g.V('Cain').addE('Brother').to(g.V('Abel'))" },
                { "AddCain->Seth", "g.V('Cain').addE('Brother').to(g.V('Seth'))" },
                { "AddAbel->Seth", "g.V('Abel').addE('Brother').to(g.V('Seth'))" },

                { "AddEve->Abel", "g.V('Eve').addE('Mother').to(g.V('Abel'))" },
                { "AddEve->Cain", "g.V('Eve').addE('Mother').to(g.V('Cain'))" },
                { "AddEve->Seth", "g.V('Eve').addE('Mother').to(g.V('Seth'))" },

                { "AddAdam->Abel", "g.V('Adam').addE('Father').to(g.V('Abel'))" },
                { "AddAdam->Cain", "g.V('Adam').addE('Father').to(g.V('Cain'))" },
                { "AddAdam->Seth", "g.V('Adam').addE('Father').to(g.V('Seth'))" },
                { "AddSeth->Enosh", "g.V('Seth').addE('Father').to(g.V('Enosh'))" },

                { "UpdateAbel1", "g.V('Abel').property('Profession', 'Shepherd')" },
                { "UpdateCain1", "g.V('Cain').property('Profession', 'Farmer')" },

                { "UpdateAdam", "g.V('Adam').property('Max Age', '930').property('Born', '4026 BCE').property('Died', '3096 BCE').property('Name Means', 'Earthling Man; Mankind; Humankind; from a root meaning \"red\"')" },
                { "UpdateAdamFatherAge", "g.V('Adam').outE('Father').as('e').inV().has('Name', 'Seth').select('e').property('Age', '130')" }
            };

            foreach (KeyValuePair <string, string> gremlinQuery in gremlinQueries)
            {
                results.Add($"Running {gremlinQuery.Key}: {gremlinQuery.Value}");

                // The CreateGremlinQuery method extensions allow you to execute Gremlin queries and iterate
                // results asychronously
                IDocumentQuery <dynamic> query = client.CreateGremlinQuery <dynamic>(graph, gremlinQuery.Value);
                while (query.HasMoreResults)
                {
                    foreach (dynamic result in await query.ExecuteNextAsync())
                    {
                        results.Add($"\t {JsonConvert.SerializeObject(result)}");
                    }
                }

                results.Add("");
            }

            return(results);
        }
Exemplo n.º 50
0
        public async Task <IHttpActionResult> GetInfo(string info)
        {
            DocumentCollection graph = await client.CreateDocumentCollectionIfNotExistsAsync(
                UriFactory.CreateDatabaseUri("graphdb"),
                new DocumentCollection { Id = "Persons" },
                new RequestOptions { OfferThroughput = 400 });

            string grem = $"g.V('{info}')";
            IDocumentQuery <dynamic> query = client.CreateGremlinQuery <dynamic>(graph, grem);
            var vert   = new List <dynamic>();
            var eMe    = new List <dynamic>();
            var eOther = new List <dynamic>();

            while (query.HasMoreResults)
            {
                foreach (dynamic result in await query.ExecuteNextAsync())
                {
                    vert.Add(result);
                }
            }

            grem  = $"g.V('{info}').outE()";
            query = client.CreateGremlinQuery <dynamic>(graph, grem);

            while (query.HasMoreResults)
            {
                string inV = "", label = "", outV = "";
                foreach (dynamic result in await query.ExecuteNextAsync())
                {
                    foreach (KeyValuePair <string, JToken> child in (result as JObject))
                    {
                        if (child.Key == "inV")
                        {
                            inV = (child.Value as JToken).Value <string>();
                        }
                        else if (child.Key == "label")
                        {
                            label = (child.Value as JToken).Value <string>();
                        }
                        else if (child.Key == "outV")
                        {
                            outV = (child.Value as JToken).Value <string>();
                        }
                    }
                    eMe.Add(new { outV, label, inV });
                }
            }
            grem  = $"g.V('{info}').inE()";
            query = client.CreateGremlinQuery <dynamic>(graph, grem);

            while (query.HasMoreResults)
            {
                string inV = "", label = "", outV = "";
                foreach (dynamic result in await query.ExecuteNextAsync())
                {
                    foreach (KeyValuePair <string, JToken> child in (result as JObject))
                    {
                        if (child.Key == "inV")
                        {
                            inV = (child.Value as JToken).Value <string>();
                        }
                        else if (child.Key == "label")
                        {
                            label = (child.Value as JToken).Value <string>();
                        }
                        else if (child.Key == "outV")
                        {
                            outV = (child.Value as JToken).Value <string>();
                        }
                    }
                    eOther.Add(new { inV, label, outV });
                }
            }
            string         marriedTo = "";
            List <dynamic> family    = new List <dynamic>();

            if (eMe.Any(z => z.label == "Married"))
            {
                marriedTo = eMe.First(z => z.label == "Married").inV;
                eMe.Remove(eMe.First(z => z.label == "Married"));
            }
            else if (eOther.Any(z => z.label == "Married"))
            {
                marriedTo = eOther.First(z => z.label == "Married").outV;
                eOther.Remove(eOther.First(z => z.label == "Married"));
            }
            if (eMe.Any(z => z.label == "Father"))
            {
                family.AddRange(eMe.Where(z => z.label == "Father").Select(z => new { type = "Child", name = (string)z.inV }).ToList());
                eMe.RemoveAll((z) => { return(z.label == "Father"); });
            }
            else if (eMe.Any(z => z.label == "Mother"))
            {
                family.AddRange(eMe.Where(z => z.label == "Mother").Select(z => new { type = "Child", name = (string)z.inV }).ToList());
                eMe.RemoveAll((z) => { return(z.label == "Mother"); });
            }

            if (eOther.Any(z => z.label == "Father"))
            {
                family.AddRange(eOther.Where(z => z.label == "Father").Select(z => new { type = "Father", name = (string)z.outV }).ToList());
                eOther.RemoveAll((z) => { return(z.label == "Father"); });
            }
            if (eOther.Any(z => z.label == "Mother"))
            {
                family.AddRange(eOther.Where(z => z.label == "Mother").Select(z => new { type = "Mother", name = (string)z.outV }).ToList());
                eOther.RemoveAll((z) => { return(z.label == "Mother"); });
            }

            if (eMe.Any(z => z.label == "Sister"))
            {
                family.AddRange(eMe.Where(z => z.label == "Sister").Select(z => new { type = "Sister", name = (string)z.outV }).ToList());
                eMe.RemoveAll((z) => { return(z.label == "Sister"); });
            }
            else if (eMe.Any(z => z.label == "Brother"))
            {
                family.AddRange(eMe.Where(z => z.label == "Brother").Select(z => new { type = "Brother", name = (string)z.outV }).ToList());
                eMe.RemoveAll((z) => { return(z.label == "Brother"); });
            }
            if (eOther.Any(z => z.label == "Sister"))
            {
                family.AddRange(eOther.Where(z => z.label == "Sister").Select(z => new { type = "Sister", name = (string)z.inV }).ToList());
                eOther.RemoveAll((z) => { return(z.label == "Sister"); });
            }
            else if (eOther.Any(z => z.label == "Brother"))
            {
                family.AddRange(eOther.Where(z => z.label == "Brother").Select(z => new { type = "Brother", name = (string)z.inV }).ToList());
                eOther.RemoveAll((z) => { return(z.label == "Brother"); });
            }

            return(Ok(new { vert, eMe, eOther, marriedTo, family }));
        }
        public void TestSetup()
        {
            databaseName              = ConfigurationManager.AppSettings["DatabaseAccountId"];
            collectionName            = Guid.NewGuid().ToString();
            partitionedCollectionName = Guid.NewGuid().ToString();

            databaseUri              = UriFactory.CreateDatabaseUri(databaseName);
            collectionUri            = UriFactory.CreateDocumentCollectionUri(databaseName, collectionName);
            partitionedCollectionUri = UriFactory.CreateDocumentCollectionUri(databaseName, partitionedCollectionName);

            Database database = documentClient.CreateDatabaseIfNotExistsAsync(new Database()
            {
                Id = databaseName
            }).Result.Resource;

            DocumentCollection newCollection = new DocumentCollection()
            {
                Id = collectionName
            };

            try
            {
                documentClient.CreateDocumentCollectionAsync(databaseUri, newCollection, new RequestOptions {
                    OfferThroughput = 400
                }).Wait();
            }
            catch (DocumentClientException ex)
            {
                if (ex.StatusCode == System.Net.HttpStatusCode.ServiceUnavailable)
                {
                    // Emulator con sometimes fail under load, so we retry
                    Task.Delay(1000);
                    documentClient.CreateDocumentCollectionAsync(databaseUri, newCollection, new RequestOptions {
                        OfferThroughput = 400
                    }).Wait();
                }
            }

            DocumentCollection partitionedCollection = new DocumentCollection()
            {
                Id           = partitionedCollectionName,
                PartitionKey = new PartitionKeyDefinition()
                {
                    Paths = new Collection <string> {
                        "/pk"
                    },
                }
            };

            try
            {
                documentClient.CreateDocumentCollectionAsync(databaseUri, partitionedCollection, new RequestOptions {
                    OfferThroughput = 10000
                }).Wait();
            }
            catch (DocumentClientException ex)
            {
                if (ex.StatusCode == System.Net.HttpStatusCode.ServiceUnavailable)
                {
                    // Emulator con sometimes fail under load, so we retry
                    Task.Delay(1000);
                    documentClient.CreateDocumentCollectionAsync(databaseUri, partitionedCollection, new RequestOptions {
                        OfferThroughput = 10000
                    }).Wait();
                }
            }
        }
Exemplo n.º 52
0
        public override void Load(string contentId, ScaleSettingsNodeViewModel node, Connection connection, DocumentCollection collection)
        {
            IsLoading = true;

            ContentId  = contentId;
            Node       = node;
            Title      = node.Name;
            Header     = node.Name;
            Connection = connection;
            Collection = collection;

            var split = Collection.AltLink.Split(new char[] { '/' });

            ToolTip = $"{split[1]}>{split[3]}";

            AccentColor = Connection.AccentColor;

            SetInformation();

            IsLoading = false;
        }
Exemplo n.º 53
0
        public void ScreenShotCommand() // This method can have any name
        {
            DocumentCollection acDocMgr = cadApplication.DocumentManager;
            Document           document = cadApplication.DocumentManager.MdiActiveDocument;


            string fileName = string.Empty;

            if (acDocMgr.Count > 1)
            {
                MessageBox.Show("已经有编辑的源文件在编辑,请手动关闭当前编辑的文件!");
                return;
            }
            else if (acDocMgr.Count == 1)
            {
                string[] args = Environment.GetCommandLineArgs();

                if (args.Length < 5)
                {
                    cadApplication.ShowAlertDialog("参数传递错误!");
                    return;
                }

                fileName = args[1];
                Environment.SetEnvironmentVariable("fileName", fileName);


                /// 如果是只有一个文档的话,且为源文件的话
                string curDocName = document.Name;

                if (curDocName.Contains(fileName))
                {
                    if (File.Exists(curDocName) &&
                        curDocName.IndexOf(orgDwgextesion) > -1)
                    {
                        string fName = curDocName.Replace(orgDwgextesion, dwgExtesion);
                        if (File.Exists(fName))
                        {
                            File.Delete(fName);
                        }
                    }
                    else if (File.Exists(curDocName) &&
                             curDocName.IndexOf(orgDwgextesion) < 0)
                    {
                        string fName = curDocName.Replace(dwgExtesion, orgDwgextesion);
                        if (File.Exists(fName))
                        {
                            File.Delete(fName);
                        }
                    }
                }
            }
            string newFileName = fileName.Replace(dwgExtesion, orgDwgextesion);

            Database db = HostApplicationServices.WorkingDatabase;
            Editor   ed = cadApplication.DocumentManager.MdiActiveDocument.Editor;


            /// 当前最新位置的Polyline
            ObjectId objId = new ObjectId();
            Polyline pl    = (Polyline)AutoCADHelper.GetObjFromDic(ref objId, "redId", db, ed);

            if (pl == null)
            {
                return;
            }

            ///保留剪切前的文件
            if (!File.Exists(fileName))
            {
                db.SaveAs(fileName, DwgVersion.Current);
            }
            else
            {
                db.SaveAs(newFileName, DwgVersion.Current);
            }
            //MessageBox.Show(newFileName);
            ///实行剪切操作
            AutoCADHelper.TrimMap(pl);

            /// 矩形右上角的点
            Point2d pThird = pl.GetPoint2dAt(2);
            /// 矩形左下角的点
            Point2d pFirst = pl.GetPoint2dAt(0);



            PromptSelectionResult result = ed.SelectCrossingWindow(
                new Point3d(pFirst.X + 10, pFirst.Y + 10, 0),
                new Point3d(pThird.X - 10, pThird.Y - 10, 0));


            if (result.Status == PromptStatus.Error)
            {
                cadApplication.ShowAlertDialog("没有选中坐标点!");
            }
            else if (result.Status == PromptStatus.OK)
            {
                ///剪切一些没有剪切干净的图形
                ///选中所有的实体对象
                PromptSelectionResult resultAll = ed.SelectAll();

                using (Transaction trans = document.TransactionManager.StartTransaction())
                {
                    ObjectId[]      sIds = result.Value.GetObjectIds();
                    List <ObjectId> oIds = sIds.ToList <ObjectId>();
                    foreach (ObjectId pid in resultAll.Value.GetObjectIds())
                    {
                        if (!oIds.Contains(pid))
                        {
                            Entity ent = trans.GetObject(pid, OpenMode.ForWrite) as Entity;
                            if (ent == null)
                            {
                                continue;
                            }
                            ent.Erase();
                        }
                    }
                    trans.Commit();
                }
                //if (!File.Exists(fileName))
                //{
                //    db.SaveAs(fileName, DwgVersion.Current);
                //}
                //else
                //{
                //    CADTools.RunCommand(true, "_qsave", "");
                //}
            }
        }
Exemplo n.º 54
0
        public void ProcessBlock()
        {
            double   insPnt_X = 0d;
            double   insPnt_Y = 0d;
            Document bDwg     = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager.MdiActiveDocument;

            Autodesk.AutoCAD.DatabaseServices.TransactionManager bTransMan = bDwg.TransactionManager;
            Editor ed   = bDwg.Editor;
            string path = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);

            string[] familyFiles = Directory.GetFiles(path + "\\fixtures", "*.dwg", SearchOption.TopDirectoryOnly);
            ed.WriteMessage("\nUsing directory {0}", path + "\\fixtures");

            try
            {
                DocumentCollection acDocMgr = Application.DocumentManager;
                foreach (string familyFile in familyFiles)
                {
                    string   equipmentNumber = Path.GetFileNameWithoutExtension(familyFile);
                    Document doc             = acDocMgr.Open(familyFile, false);
                    if (doc != null)
                    {
                        doc.LockDocument();
                        ed.WriteMessage("\nProcessing {0}", equipmentNumber);
                        ExplodeBlockByNameCommand(ed, doc, equipmentNumber);
                        doc.CloseAndSave(familyFile);
                        doc.Dispose();
                    }
                    else
                    {
                        ed.WriteMessage("\nCould not open {0}", equipmentNumber);
                    }

                    using (bDwg.LockDocument())
                        using (Transaction bTrans = bTransMan.StartTransaction())
                        {
                            Database blkDb = new Database(false, true);
                            blkDb.ReadDwgFile(familyFile, System.IO.FileShare.Read, true, ""); //Reading block source file
                            string   name = Path.GetFileNameWithoutExtension(familyFile);
                            ObjectId oid  = bDwg.Database.Insert(name, blkDb, true);

                            using (BlockReference acBlkRef = new BlockReference(new Point3d(insPnt_X, insPnt_Y, 0), oid))
                            {
                                BlockTableRecord acCurSpaceBlkTblRec;
                                acCurSpaceBlkTblRec = bTrans.GetObject(bDwg.Database.CurrentSpaceId, OpenMode.ForWrite) as BlockTableRecord;

                                acCurSpaceBlkTblRec.AppendEntity(acBlkRef);
                                bTrans.AddNewlyCreatedDBObject(acBlkRef, true);
                            }
                            bTrans.Commit();
                        }
                    insPnt_X += 240d;
                    if (insPnt_X > 2400)
                    {
                        insPnt_X  = 0;
                        insPnt_Y += 240d;
                    }
                }
            }
            catch (System.Exception err)
            {
                ed.WriteMessage("\nSomething went wrong in main process.");
                File.AppendAllText(Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory) + "\\error_main.log", err.ToString());
            }
            finally
            {
            }
        }
 public RestaurantRegisteredEventHandler(DocumentCollection documentCollection,
                                         ITableDataProvider tableDataProvider)
 {
     _documentCollection = documentCollection;
     _tableDataProvider  = tableDataProvider;
 }
Exemplo n.º 56
0
 public ConseillerGraphRepository(DocumentClient documentClient, DocumentCollection documentCollection) : base(documentClient, documentCollection)
 {
 }
Exemplo n.º 57
0
        public async Task <IEnumerable <KeyValuePair <string, Document> > > GetAllDocumentsAsync(DocumentCollection keysCollection, BucketNamespace bucketNamespace)
        {
            if (keysCollection.Total == 0)
            {
                return(null);
            }

            try
            {
                string @namespace = GetNamespaceAsString(bucketNamespace);

                var pairsCollection = new List <KeyValuePair <string, Document> >();

                foreach (var key in keysCollection.Items)
                {
                    var command = new Command
                    {
                        Id     = EnvelopeId.NewId(),
                        To     = Node.Parse("*****@*****.**"),
                        Uri    = new LimeUri($"/{@namespace}/{key}"),
                        Method = CommandMethod.Get
                    };

                    var envelopeResult = await RunCommandAsync(command);

                    var document = envelopeResult.Resource;

                    pairsCollection.Add(new KeyValuePair <string, Document>(key.ToString(), document));
                }

                return(pairsCollection);
            }
            catch (HttpRequestException e)
            {
                Console.WriteLine("\nException Caught!");
                Console.WriteLine("Message :{0} ", e.Message);
                return(null);
            }
        }
Exemplo n.º 58
0
        public void Execute()
        {
            CheckDisposed();

            // Configure with defaults if not already configured
            if (_configurator == null)
            {
                Configure();
            }

            // Create the input and output folders if they don't already exist
            if (!Directory.Exists(InputFolder))
            {
                Directory.CreateDirectory(InputFolder);
            }
            if (!Directory.Exists(OutputFolder))
            {
                Directory.CreateDirectory(OutputFolder);
            }

            try
            {
                Stopwatch engineStopwatch = Stopwatch.StartNew();
                using (Trace.WithIndent().Information("Executing {0} pipelines", _pipelines.Count))
                {
                    // Setup (clear the document collection and reset cache counters)
                    DocumentCollection.Clear();
                    ExecutionCacheManager.ResetEntryHits();

                    // Enumerate pipelines and execute each in order
                    int c = 1;
                    foreach (Pipeline pipeline in _pipelines.Pipelines)
                    {
                        Stopwatch pipelineStopwatch = Stopwatch.StartNew();
                        using (Trace.WithIndent().Information("Executing pipeline \"{0}\" ({1}/{2}) with {3} child module(s)", pipeline.Name, c, _pipelines.Count, pipeline.Count))
                        {
                            pipeline.Execute();
                            pipelineStopwatch.Stop();
                            Trace.Information("Executed pipeline \"{0}\" ({1}/{2}) in {3} ms resulting in {4} output document(s)",
                                              pipeline.Name, c++, _pipelines.Count, pipelineStopwatch.ElapsedMilliseconds,
                                              DocumentCollection.FromPipeline(pipeline.Name).Count());
                        }
                    }

                    // Clean up (clear unhit cache entries, dispose documents)
                    // Note that disposing the documents immediately after engine execution will ensure write streams get flushed and released
                    // but will also mean that callers (and tests) can't access documents and document content after the engine finishes
                    // Easiest way to access content after engine execution is to add a final Meta module and copy content to metadata
                    ExecutionCacheManager.ClearUnhitEntries(this);
                    foreach (Pipeline pipeline in _pipelines.Pipelines)
                    {
                        pipeline.ResetClonedDocuments();
                    }

                    engineStopwatch.Stop();
                    Trace.Information("Executed {0} pipelines in {1} ms",
                                      _pipelines.Count, engineStopwatch.ElapsedMilliseconds);
                }
            }
            catch (Exception ex)
            {
                Trace.Verbose("Exception while executing pipelines: {0}", ex);
                throw;
            }
        }
Exemplo n.º 59
0
        static public void Plan2HoePrSelHkBlockAndAtt()
        {
            try
            {
                if (!OpenHoePrPalette())
                {
                    return;
                }

                var      opts = Globs.TheHoePrOptions;
                Document doc  = Application.DocumentManager.MdiActiveDocument;

                using (DocumentLock m_doclock = doc.LockDocument())
                {
                    DocumentCollection dm = Autodesk.AutoCAD.ApplicationServices.Application.DocumentManager;
                    if (doc == null)
                    {
                        return;
                    }
                    Editor ed = doc.Editor;
#if NEWSETFOCUS
                    doc.Window.Focus();
#else
                    Autodesk.AutoCAD.Internal.Utils.SetFocusToDwgView(); // previous 2014 AutoCAD - Versions
#endif

                    PromptNestedEntityResult per = ed.GetNestedEntity("\nHöhenkotenblock wählen: ");

                    if (per.Status == PromptStatus.OK)
                    {
                        using (var tr = doc.TransactionManager.StartTransaction())
                        {
                            DBObject       obj = tr.GetObject(per.ObjectId, OpenMode.ForRead);
                            BlockReference br  = obj as BlockReference;
                            if (br == null)
                            {
                                br = Plan2Ext.Globs.GetBlockFromItsSubentity(tr, per);
                                if (br == null)
                                {
                                    return;
                                }
                            }

                            opts.SetHKBlockname(br.Name);

                            tr.Commit();
                        }

                        per = ed.GetNestedEntity("\nHöhen-Attribut wählen: ");
                        if (per.Status != PromptStatus.OK)
                        {
                            return;
                        }
                        using (var tr = doc.TransactionManager.StartTransaction())
                        {
                            DBObject           obj = tr.GetObject(per.ObjectId, OpenMode.ForRead);
                            AttributeReference ar  = obj as AttributeReference;
                            if (ar == null)
                            {
                                return;
                            }

                            opts.SetHoehenAtt(ar.Tag);

                            tr.Commit();
                        }
                    }
                }
            }
            catch (System.Exception ex)
            {
                Application.ShowAlertDialog(string.Format(CultureInfo.CurrentCulture, "Fehler in Plan2HoePrSelHkBlockAndAtt aufgetreten! {0}", ex.Message));
            }
        }
Exemplo n.º 60
-1
        private static async Task DeleteCourse(Guid guid, DocumentCollection documentCollection)
        {
            DocumentClient documentClient = new DocumentClient(new Uri("https://schooltest.documents.azure.com:443/"),
                "Of414DnEibhmqeSTB0pKShdQtR6dxxfXP8uT93pggxoumKthJGzuECCUJZ27Pqf846VUkFfOrraMTQ74PZaywA==");

            Course course = documentClient.CreateDocumentQuery<Course>(documentCollection.DocumentsLink,
                new SqlQuerySpec(string.Format("SELECT * FROM c WHERE c.CourseId = '{0}'", guid))).AsEnumerable().FirstOrDefault();

            if (course == null)
                return;

            await documentClient.DeleteDocumentAsync(course.SelfLink);
        }