private static void Main(string[] args)
        {
            var client = new DocumentClient(new Uri("https://url.com:443/"), "**********");

            var database = GetDatabase(client);
            var documentCollection = GetDocumentCollection(client, database);

            Test(
                "Via Linq lambda",
                 new[] { "en-GB", "nl-NL" },
                () =>
                {
                    var documentQuery = client
                        .CreateDocumentQuery<Document>(documentCollection.SelfLink)
                        .Where(x => x.Created > LastYear);

                    Console.WriteLine("  {0}", documentQuery);

                    documentQuery.ToList();
                });

            Test(
                "Via SqlQuerySpec query",
                 new[] { "en-GB", "nl-NL" },
                () =>
                {
                    var sqlQuerySpec = new SqlQuerySpec("SELECT * FROM root WHERE (root.created > @lastYear)");
                    sqlQuerySpec.Parameters = new SqlParameterCollection();
                    sqlQuerySpec.Parameters.Add(new SqlParameter("@lastYear", LastYear));

                    var documentQuery = client.CreateDocumentQuery(documentCollection.SelfLink, sqlQuerySpec);

                    Console.WriteLine("  {0}", documentQuery);

                    documentQuery.ToList();
                });

            Test(
                "Via custom generated query",
                 new[] { "en-GB", "nl-NL" },
                () =>
                {
                    var query = $"SELECT * FROM root WHERE (root.created > {LastYear:E10})";

                    var documentQuery = client.CreateDocumentQuery(documentCollection.SelfLink, query);

                    Console.WriteLine("  {0}", documentQuery);

                    documentQuery.ToList();
                });

            Console.ReadLine();
        }
        //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,
                });
            }
        }
Beispiel #3
0
        public static async Task UpdateDcAll(string endpointUrl, string authorizationKey)
        {
            DocumentClient client = new DocumentClient(new Uri(endpointUrl), authorizationKey);
            var database = await DocumentDB.GetDB(client);

            IEnumerable<DocumentCollection> dz = client.CreateDocumentCollectionQuery(database.SelfLink)
                .AsEnumerable();


            DocumentCollection origin = client.CreateDocumentCollectionQuery(database.SelfLink)
                .Where(c => c.Id == "LMSCollection")
                .AsEnumerable()
                .FirstOrDefault();

            //search collection
            var ds =
                from d in client.CreateDocumentQuery<DcAllocate>(origin.DocumentsLink)
                where d.Type == "DisList"
                select d;
            foreach (var d in ds)
            {
                if (d.District.Contains("tst-azhang14"))
                {
                    Console.WriteLine(d.DcName);
                }
            }

            /* foreach (var x in dz)
            {
                Console.WriteLine(x.Id + x.DocumentsLink);
                await UpdateDc(x, client, database, origin);
            }*/
        }
        private IQueryable <Document> GetDocumentQuery(string collectionId)
        {
            string      collectionLink = string.Concat("dbs/", _databaseId, "/colls/", collectionId);
            FeedOptions feedOptions    = new FeedOptions()
            {
                EnableCrossPartitionQuery = true
            };

            return(_database.CreateDocumentQuery(collectionLink, feedOptions));
        }
Beispiel #5
0
        static void Main(string[] args)
        {
            ConnectionPolicy policy = new ConnectionPolicy()
            {
                ConnectionMode = ConnectionMode.Direct,
                ConnectionProtocol = Protocol.Tcp
            };
            Uri endPoint = new Uri(EndpointUrl);
            using (DocumentClient client = new DocumentClient(endPoint, AuthKey, policy))
            {
                Database database =
                    client.CreateDatabaseQuery().Where(db => db.Id == DatabasebId).AsEnumerable().First();
                DocumentCollection collection =
                    client.CreateDocumentCollectionQuery(database.SelfLink)
                        .Where(c => c.Id == CollectionId)
                        .AsEnumerable()
                        .First();

                IEnumerable<DataClass> dataSet = GetDataObjects(100);

                Task<ResourceResponse<Document>>[] documentTasks =
                    dataSet.Select(d => client.CreateDocumentAsync(collection.DocumentsLink, d)).ToArray();

                Task.WaitAll(documentTasks);

                Document[] docs = documentTasks.Select(t => t.Result.Resource).ToArray();

                Document doc = docs.First();

                Task<ResourceResponse<Attachment>>[] attachmentTasks =
                    docs.Select(d => client.CreateAttachmentAsync(doc.AttachmentsLink, GetStream(1024))).ToArray();

                Task.WaitAll(attachmentTasks);

                DataClass[] data =
                    client.CreateDocumentQuery<DataClass>(collection.DocumentsLink).Select(d => d).ToArray();
                Attachment[] attachments = client.CreateAttachmentQuery(doc.AttachmentsLink).ToArray();

                string sql = "SELECT c.Name FROM c Where c.ObjectKey < 30 AND c.ObjectKey > 20";
                dynamic[] dataArray = client.CreateDocumentQuery(collection.DocumentsLink, sql).ToArray();
            }
        }
        public IEnumerable<Trip> Get()
        {
            var client = new DocumentClient(new Uri("https://etamanager.documents.azure.com:443/"), "HIgfJLkqRsemDoAv62MSn0/UFK2dC9RxtAopuV3rAa7f1tCqou/A2xbh1ShLDkKDaWOPLEsZ0sl7dGzjrEz36A==");
            return client.CreateDocumentQuery<Trip>("dbs/-gIgAA==/colls/-gIgALa0OwA=");

            //await client.CreateDocumentAsync("dbs/-gIgAA==/colls/-gIgALa0OwA=", new Trip("UKA0021", "EMA", "LHR", "DHL ECO GB", "FL62 ZWB", "25/07/2015 02:04:12", "03:00", "-00:55"));
            //return new[]
            //{
            //    new Trip("HDC1001", "HDC", "BRU", "NINATRANS", "NOGPS_Nina", string.Empty, "08:00", "NA"),
            //    new Trip("UKA0096", "EMA", "LHR", "DHL ECO GB", "LS14 HLK", "25/07/2015 01:36:11", "03:00", "-01:23"),
            //    new Trip("UKA0021", "EMA", "LHR", "DHL ECO GB", "FL62 ZWB", "25/07/2015 02:04:12", "03:00", "-00:55")
            //};
        }
Beispiel #7
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);
            }
        }
        public void Start()
        {
            QueueUtility.Listen<EventController.Position>("PositionQueue", async position =>
            {
                var client = new DocumentClient(new Uri("https://etamanager.documents.azure.com:443/"), "HIgfJLkqRsemDoAv62MSn0/UFK2dC9RxtAopuV3rAa7f1tCqou/A2xbh1ShLDkKDaWOPLEsZ0sl7dGzjrEz36A==");
                var trip = client.CreateDocumentQuery<TripDocument>("dbs/-gIgAA==/colls/-gIgALa0OwA=").Where(t => t.Code == position.TripCode).AsEnumerable().FirstOrDefault();
                if (trip != null)
                {
                    trip.ExpectedArrival = position.DT;
                    await client.ReplaceDocumentAsync(trip.SelfLink, trip);
                }

                var update = new EventController.ETAUpdate { code = position.TripCode, expectedArrival = position.DT };
                QueueUtility.Send("ETAUpdateQueue", update);
            });
            QueueUtility.Listen<EventController.ETAUpdate>("ETAUpdateQueue", update => this.tripsHub.Clients.All.addNewMessageToPage(update));
        }
Beispiel #9
0
        private static async void RunQuery()
        {
            DocumentClient client = new DocumentClient(new Uri(CONST_EndPointUrl), CONST_AuthorizationKey);

            Database database = await GetDatabase(client);

            DocumentCollection documentCollection = await GetDocumentCollection(client, database);

            List<Course> coursesList = client.CreateDocumentQuery<Course>(documentCollection.DocumentsLink).Where(c => c.Name == "English").ToList();

            if (coursesList != null && coursesList.Count > 0)
            {
                foreach (var item in coursesList)
                {
                    Console.WriteLine(item.Name);
                }
            }
        }
        public async Task <List <TResult> > GetDocumentsAsync <T, TResult>(Func <IQueryable <T>, IQueryable <TResult> > query)
        {
            var feedOptions = new FeedOptions
            {
                PartitionKey = new PartitionKey("*")
            };
            var collectionUri = UriFactory.CreateDocumentCollectionUri(_dbSetting.DatabaseId, _dbSetting.CollectionId);
            var q             = _cosmosDBClient.CreateDocumentQuery <T>(collectionUri, feedOptions);
            var docQuery      = query(q).AsDocumentQuery();

            var results = new List <TResult>();
            FeedResponse <TResult> response = null;

            do
            {
                response = await docQuery.ExecuteNextAsync <TResult>();

                results.AddRange(response.ToList());
            }while (docQuery.HasMoreResults);
            return(results);
        }
Beispiel #11
0
        static void Main(string[] args)
        {
            var query = "SELECT * FROM c";

            using (var client = new DocumentClient(new Uri(endpoint), authKey))
            {
                var collLink = UriFactory.CreateDocumentCollectionUri(databaseId, collectionId);
                var querySpec = new SqlQuerySpec { QueryText = query };

                var itr = client.CreateDocumentQuery(collLink, querySpec).AsDocumentQuery();
                var response = itr.ExecuteNextAsync<Document>().Result;
                var charge = response.RequestCharge;
                Console.WriteLine("Request charge: {0}", charge);

                foreach (var doc in response.AsEnumerable())
                {
                    Console.WriteLine(doc.ToString());
                }
            }

            Console.ReadLine();
        }
        // GET /api/search/?criterias=TOTO
        public List<FeedItem> Get([FromUri]string criterias = "")
        {
            // si criterias = LAST10 -> renvoyé les dix derniere articles

            var client = new DocumentClient(new Uri(EndpointUrl), AuthorizationKey);

            Database database = client.CreateDatabaseQuery()
                .Where(db => db.Id == databaseId)
                .AsEnumerable()
                .FirstOrDefault();

            DocumentCollection collectionPosts = client.CreateDocumentCollectionQuery(database.CollectionsLink)
                .Where(doccoll => doccoll.Id == collectionIdPost)
                .AsEnumerable()
                .FirstOrDefault();

            var posts  = (
                from b in client.CreateDocumentQuery<FeedItem>(collectionPosts.SelfLink)
                where b.Year == 2015 && b.Month >= 1 && b.Day >= 8
                select b).ToList();

            return posts;
        }
Beispiel #13
0
        private static async Task DeleteAll(DocumentClient client, Database database,
            DocumentCollection documentCollection)
        {
            IEnumerable<DocumentCollection> dz = client.CreateDocumentCollectionQuery(database.SelfLink)
                .AsEnumerable();

            foreach (var z in dz)
            {
                var families =
                    from f in client.CreateDocumentQuery(z.DocumentsLink)
                    select f;


                foreach (var family in families)
                {
                    dynamic d = JsonConvert.DeserializeObject(family.ToString());
                    //Console.WriteLine(d.Path.school);  
                    try
                    {
                        //var res = await client.DeleteDocumentAsync(family.SelfLink);
                        var family1 = family;
                        var response = await _iDbService.ExecuteWithRetries(5, () => client.DeleteDocumentAsync(family1.SelfLink));
                    }
                    catch (DocumentClientException e)
                    {
                        /* if (e.RetryAfter.TotalMilliseconds>0)
                            {
                                Console.WriteLine(e.RetryAfter.TotalMilliseconds);
                                Thread.Sleep((int) e.RetryAfter.TotalMilliseconds);
                                client.DeleteDocumentAsync(family.SelfLink).Wait();
                            }
                            else
                            {*/
                        Console.WriteLine(e.Message);
                        // }
                    }

                    Console.WriteLine(family.SelfLink);
                }
            }
        }
        private static async Task GetStartedDemo()
        {
            // Create a new instance of the DocumentClient
            var client = new DocumentClient(new Uri(EndpointUrl), AuthorizationKey);

            // Check to verify a database with the id=FamilyRegistry does not exist
            Database database = client.CreateDatabaseQuery().Where(db => db.Id == "FamilyRegistry").AsEnumerable().FirstOrDefault();

            // If the database does not exist, create a new database
            if (database == null)
            {
                database = await client.CreateDatabaseAsync(
                    new Database
                    {
                        Id = "FamilyRegistry"
                    });

                WriteMessage("Created dbs/FamilyRegistry");
            }

            // Check to verify a document collection with the id=FamilyCollection does not exist
            DocumentCollection documentCollection = client.CreateDocumentCollectionQuery("dbs/" + database.Id).Where(c => c.Id == "FamilyCollection").AsEnumerable().FirstOrDefault();

            // If the document collection does not exist, create a new collection
            if (documentCollection == null)
            {
                documentCollection = await client.CreateDocumentCollectionAsync("dbs/" + database.Id,
                    new DocumentCollection
                    {
                        Id = "FamilyCollection"
                    });

                WriteMessage("Created dbs/FamilyRegistry/colls/FamilyCollection");
            }

            // Check to verify a document with the id=AndersenFamily does not exist
            Document document = client.CreateDocumentQuery("dbs/" + database.Id + "/colls/" + documentCollection.Id).Where(d => d.Id == "AndersenFamily").AsEnumerable().FirstOrDefault();

            // If the document does not exist, create a new document
            if (document == null)
            {
                // Create the Andersen Family document
                Family andersonFamily = new Family
                {
                    Id = "AndersenFamily",
                    LastName = "Andersen",
                    Parents = new Parent[] {
                        new Parent { FirstName = "Thomas" },
                        new Parent { FirstName = "Mary Kay"}
                    },
                    Children = new Child[] {
                        new Child
                        { 
                            FirstName = "Henriette Thaulow", 
                            Gender = "female", 
                            Grade = 5, 
                            Pets = new Pet[] {
                                new Pet { GivenName = "Fluffy" } 
                            }
                        } 
                    },
                    Address = new Address { State = "WA", County = "King", City = "Seattle" },
                    IsRegistered = true
                };

                // id based routing for the first argument, "dbs/FamilyRegistry/colls/FamilyCollection"
                await client.CreateDocumentAsync("dbs/" + database.Id + "/colls/" + documentCollection.Id, andersonFamily);

                WriteMessage("Created dbs/FamilyRegistry/colls/FamilyCollection/docs/AndersenFamily");
            }

            // Check to verify a document with the id=AndersenFamily does not exist
            document = client.CreateDocumentQuery("dbs/" + database.Id + "/colls/" + documentCollection.Id).Where(d => d.Id == "WakefieldFamily").AsEnumerable().FirstOrDefault();

            if (document == null)
            {
                // Create the WakeField document
                Family wakefieldFamily = new Family
                {
                    Id = "WakefieldFamily",
                    Parents = new Parent[] {
                        new Parent { FamilyName= "Wakefield", FirstName= "Robin" },
                        new Parent { FamilyName= "Miller", FirstName= "Ben" }
                    },
                    Children = new Child[] {
                        new Child {
                            FamilyName= "Merriam", 
                            FirstName= "Jesse", 
                            Gender= "female", 
                            Grade= 8,
                            Pets= new Pet[] {
                                new Pet { GivenName= "Goofy" },
                                new Pet { GivenName= "Shadow" }
                            }
                        },
                        new Child {
                            FamilyName= "Miller", 
                            FirstName= "Lisa", 
                            Gender= "female", 
                            Grade= 1
                        }
                    },
                    Address = new Address { State = "NY", County = "Manhattan", City = "NY" },
                    IsRegistered = false
                };

                // id based routing for the first argument, "dbs/FamilyRegistry/colls/FamilyCollection"
                await client.CreateDocumentAsync("dbs/" + database.Id + "/colls/" + documentCollection.Id, wakefieldFamily);

                WriteMessage("Created dbs/FamilyRegistry/colls/FamilyCollection/docs/WakefieldFamily");
            }

            // Query the documents using DocumentDB SQL for the Andersen family
            var families = client.CreateDocumentQuery("dbs/" + database.Id + "/colls/" + documentCollection.Id,
                "SELECT * " +
                "FROM Families f " +
                "WHERE f.id = \"AndersenFamily\"");

            foreach (var family in families)
            {
                Console.WriteLine("\tRead {0} from SQL", family);
            }

            // Query the documents using LINQ for the Andersen family
            families =
                from f in client.CreateDocumentQuery("dbs/" + database.Id + "/colls/" + documentCollection.Id)
                where f.Id == "AndersenFamily"
                select f;

            foreach (var family in families)
            {
                Console.WriteLine("Read {0} from LINQ", family);
            }

            // Query the documents using LINQ lambdas for the Andersen family
            families = client.CreateDocumentQuery("dbs/" + database.Id + "/colls/" + documentCollection.Id)
                .Where(f => f.Id == "AndersenFamily")
                .Select(f => f);

            foreach (var family in families)
            {
                Console.WriteLine("\tRead {0} from LINQ query", family);
            }

            // Clean up/delete the database and client
            await client.DeleteDatabaseAsync("dbs/" + database.Id);
            client.Dispose();
        }
Beispiel #15
0
 private SiteClassification InternalGetSiteClassificationByName(DocumentClient client, string collectionLink, string name)
 {
     var _siteClassification = from record in client.CreateDocumentQuery<SiteClassification>(collectionLink)
                    where record.Key == name
                    select record;
     return _siteClassification.ToList().FirstOrDefault();
 }
Beispiel #16
0
 private List<SiteClassification> InternalGetAvailableSiteClassifcations(DocumentClient client, string collectionLink)
 {
     List<SiteClassification> _returnResults = new List<SiteClassification>();
     var _siteClassifications = from record in client.CreateDocumentQuery<SiteClassification>(collectionLink)
                      where record.Enabled == true
                      select record;
     _returnResults = _siteClassifications.ToList();
     return _returnResults;
 }
Beispiel #17
0
        private static async Task sp2(DocumentCollection dc, DocumentClient client, Database database)
        {
            DocumentCollection dc2 = client.CreateDocumentCollectionQuery(database.SelfLink)
                .Where(c => c.Id == "LMSCollection1444075919174")
                .AsEnumerable()
                .FirstOrDefault();
            await client.OpenAsync();
            //await _iDbService.CollectionTransfer(client, dc2, dc);
            var mn=await client.ReadDatabaseAsync(database.SelfLink);

          /*  await client.CreateDocumentAsync(dc.SelfLink, new CurrentCollection
            {
                id = "CurrentCollection",
                name=dc.Id
            });*/
          /*  var resolver = _iDbService.GetResolver(client, dc);
            foreach (var d in resolver.PartitionMap)
            {
                Console.WriteLine(d.Value);
                Offer offer = client.CreateOfferQuery()
                                      .Where(r => r.ResourceLink == d.Value)
                                      .AsEnumerable()
                                      .SingleOrDefault();
            }*/




           /* HashPartitionResolver hashResolver = new HashPartitionResolver(
                u => ((PostMessage) u).Path.District,
                new string[] {dc.SelfLink, dc2.SelfLink});

            client.PartitionResolvers[database.SelfLink] = hashResolver;*/

            var rangeResolver = _iDbService.GetResolver(client);
            client.PartitionResolvers[database.SelfLink] = rangeResolver;

            
            var created = await _iDbService.InitResolver("");
          
            
            while (true)
            {
                var re2 = await _iDbService.UpdateResolver(dc2);
                var p = re2;
                await Task.Delay(TimeSpan.FromSeconds(4));
            }

            var z1 = rangeResolver.GetPartitionKey(new PostMessage
                    {
                        Type = "Post",
                        Info = new Info
                        {
                            user = "******",
                            uid = "1210808",
                            message = "java",
                            timestamp = 7
                        },
                        Path = new PostPath
                        {
                            District = "tst-azhang" 
                        }
                    });

            //search global
            IQueryable<PostMessage> query = client.CreateDocumentQuery<PostMessage>(database.SelfLink)
                .Where(u => u.Info.timestamp>1);

            var now = (long)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalMilliseconds;

            //search on partition

            var t1 = DateTime.Now;
            var query2 = client.CreateDocumentQuery<PostMessage>(database.SelfLink, new FeedOptions
            {
                MaxItemCount = 1200
            }, now);
            var query3 = client.CreateDocumentQuery<PostMessage>(dc2.SelfLink).AsDocumentQuery();



            var t2 = DateTime.Now;
            Console.WriteLine(t2-t1);
              //.Where(u => u.Path.District=="tst-azhang");
          
            foreach (PostMessage a in query2)
            {
                Console.WriteLine(a.Info.timestamp);
            }

          /*  double totalRequestCharge = 0;
            
            while (query3.HasMoreResults)
            {
                FeedResponse<dynamic> queryResponse = await query3.ExecuteNextAsync<dynamic>();
                Console.WriteLine("Query batch consumed {0} request units {1} doc", queryResponse.RequestCharge, queryResponse.Count);
                totalRequestCharge += queryResponse.RequestCharge;
            }
            Console.WriteLine(DateTime.Now - t2);
            Console.WriteLine("Query consumed {0} request units in total", totalRequestCharge);*/
            Console.ReadLine();
       

            int n = 19;
            try
            {
                while (n < 10)
                {
                    n++;
                    var timestamp=(long) (DateTime.UtcNow.AddHours(-1).Subtract(new DateTime(1970, 1, 1))).TotalMilliseconds;
                    PostMessage x = new PostMessage
                    {
                        Type = "Post",
                        Info = new Info
                        {
                            user = "******",
                            uid = "1210808",
                            message = "java",
                            timestamp = timestamp
                        },
                        Path = new PostPath
                        {
                            District = "tst-azhang" 
                        }
                    };

                    await client.CreateDocumentAsync(database.SelfLink, x);
                }
            }
            catch (Exception e)
            {
                var t = e;
            }

            var z = 4;
        }
Beispiel #18
0
        /// <summary>
        /// Internal Member to Return a Site Request By Status
        /// </summary>
        /// <param name="client"></param>
        /// <param name="collectionLink"></param>
        /// <param name="status"></param>
        /// <returns></returns>
        private List<SiteInformation> GetSiteRequestsByStatus(DocumentClient client, string collectionLink, SiteRequestStatus status)
        {
            List<SiteInformation> _returnResults = new List<SiteInformation>();
            var siteRequests = from record in client.CreateDocumentQuery<SiteInformation>(collectionLink)
                               where record.RequestStatus == status.ToString()
                               select record;

            _returnResults = siteRequests.ToList();

            return _returnResults;
        }
Beispiel #19
0
        private static async Task DeleteAll(DocumentClient client, Database database,
            DocumentCollection dc)
        {
            IEnumerable<DocumentCollection> dz = client.CreateDocumentCollectionQuery(database.SelfLink)
                .AsEnumerable();
            var nnn = 0;
            foreach (var z in dz)
            {
                var families =
                    from f in client.CreateDocumentQuery(z.SelfLink)
                    select f;

                try
                {
                    var mn = 0;
                    List<dynamic> batch = new List<dynamic>();

                    foreach (var family in families)
                    {
                        nnn++;

                        if (mn < 100)
                        {
                            batch.Add(family);
                            mn++;
                        }
                        else
                        {
                            await _iDbService.DocumentDb.BatchDelete(z, batch);
                            mn = 0;
                            batch = new List<dynamic>();
                        }

                        /* dynamic d = JsonConvert.DeserializeObject(family.ToString());
                            //Console.WriteLine(d.Path.school);  
                            try
                            {
                                //var res = await client.DeleteDocumentAsync(family.SelfLink);
                                var family1 = family;
                                var response =
                                    await
                                        _iDbService.ExecuteWithRetries(5,
                                            () => client.DeleteDocumentAsync(family1.SelfLink));
                            }
                            catch (DocumentClientException e)
                            {
                                Console.WriteLine(e.Message);
                            }

                            Console.WriteLine(family.SelfLink);*/
                    }
                    await _iDbService.DocumentDb.BatchDelete(z, batch);
                }
                catch (Exception eee)
                {
                    Console.WriteLine(eee.Message);
                }
            }

            Console.WriteLine(nnn);
        }
Beispiel #20
0
 private static Family GetFamily(DocumentClient client, DocumentCollection collection, string needle)
 {
     return client.CreateDocumentQuery<Family>(collection.DocumentsLink).Where(w => w.Name == needle).AsEnumerable().FirstOrDefault();
 }
Beispiel #21
0
        private static async Task Resolver(DocumentCollection dc, DocumentClient client, Database database)
        {
            //transfer collection data
            DocumentCollection dc2 = client.CreateDocumentCollectionQuery(database.SelfLink)
                .Where(c => c.Id == "LMSCollection1444075919174")
                .AsEnumerable()
                .FirstOrDefault();
            //await _iDbService.CollectionTransfer(dc2, dc);
   
            /*await client.CreateDocumentAsync(dc.SelfLink, new CurrentCollection
            {
                id = "CurrentCollection",
                name = dc.Id
            });*/

            //resolver
            /*HashPartitionResolver hashResolver = new HashPartitionResolver(
                u => ((PostMessage) u).Path.District,
                new string[] {dc.SelfLink, dc2.SelfLink});

            client.PartitionResolvers[database.SelfLink] = hashResolver;

            var rangeResolver = _iDbService.RangePartitionResolver().GetResolver();
            client.PartitionResolvers[database.SelfLink] = rangeResolver;
            var z1 = rangeResolver.GetPartitionKey(new PostMessage
            {
                Type = "Post",
                Info = new Info
                {
                    user = "******",
                    uid = "1210808",
                    message = "java",
                    timestamp = 7
                },
                Path = new PostPath
                {
                    District = "tst-azhang"
                }
            });*/

            var created = await _iDbService.DocumentDb.InitResolver();


            if (dc != null)
            {
                while (true)
                {
                    var re2 = await _iDbService.DocumentDb.UpdateResolver(dc2);
                    var p = re2;
                    await Task.Delay(TimeSpan.FromSeconds(4));
                }
            }


            //search global
            IQueryable<PostMessage> query = client.CreateDocumentQuery<PostMessage>(database.SelfLink)
                .Where(u => u.Info.timestamp > 1);


            //search on partition
            var partitionKey = (long) (DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalMilliseconds;
            var query2 = client.CreateDocumentQuery<PostMessage>(database.SelfLink, new FeedOptions
            {
                MaxItemCount = 1200
            }, partitionKey);

            foreach (PostMessage a in query2)
            {
                Console.WriteLine(a.Info.timestamp);
            }


            //check search RU
            /*  double totalRequestCharge = 0;
            var query3 = client.CreateDocumentQuery<PostMessage>(dc2.SelfLink).AsDocumentQuery();
            while (query3.HasMoreResults)
            {
                FeedResponse<dynamic> queryResponse = await query3.ExecuteNextAsync<dynamic>();
                Console.WriteLine("Query batch consumed {0} request units {1} doc", queryResponse.RequestCharge, queryResponse.Count);
                totalRequestCharge += queryResponse.RequestCharge;
            }
            Console.WriteLine("Query consumed {0} request units in total", totalRequestCharge);*/

            //await AddTestData(client,database,5);

            Console.ReadLine();
        }
Beispiel #22
0
        private static void ReadData(DocumentClient client, DocumentCollection documentCollection)
        {
            /*// Query the documents using LINQ.
            var families =
                from f in client.CreateDocumentQuery(documentCollection.DocumentsLink)
                where f.Id == "AndersenFamily"
                select f;

            foreach (var family in families)
            {
                Console.WriteLine("\tRead {0} from LINQ", family);
            }

            families = client.CreateDocumentQuery(documentCollection.DocumentsLink)
                .Where(f => f.Id == "AndersenFamily")
                .Select(f => f);

            foreach (var family in families)
            {
                Console.WriteLine("\tRead {0} from LINQ query", family);
            }
*/

            // Query the documents using DocumentSQL with one join.
            var items = client.CreateDocumentQuery<dynamic>(documentCollection.DocumentsLink,
                "SELECT f.id, c.FirstName AS child " +
                "FROM Families f " +
                "JOIN c IN f.Children");

            foreach (var item in items.ToList())
            {
                Console.WriteLine(item);
            }

            // Query the documents using LINQ with one join.
            /*var items = client.CreateDocumentQuery<Family>(documentCollection.DocumentsLink)
                .SelectMany(family => family.Parents
                    .Select(person => new
                    {
                        family = family.Id,
                        parent = person.FirstName
                    })
                );

            foreach (var item in items.ToList())
            {
                Console.WriteLine(item);
            }


            foreach (var pet in
                client.CreateDocumentQuery<Family>(documentCollection.DocumentsLink)
                    .SelectMany(f => f.Children)
                    .SelectMany(c => c.Pets
                        .Select(p => new
                        {
                            pet = p.GivenName
                        })))

            {
                Console.WriteLine(pet);
            }*/
        }
Beispiel #23
0
        private static async Task SaveDisList(Hashtable newList, Hashtable oldList,
            DocumentCollection origin, DocumentCollection oldDc,
            DocumentCollection newDc, DocumentClient client)
        {
            var t = (long) (DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalMilliseconds;
            var allow = new DcAllocate
            {
                Type = "DisList",
                DcName = newDc.Id,
                DcSelfLink = newDc.SelfLink,
                District = new List<string>()
            };

            foreach (DictionaryEntry i in newList)
            {
                allow.District.Add(i.Key.ToString());
            }
            await client.CreateDocumentAsync(origin.DocumentsLink, allow);


            var ds =
                from d in client.CreateDocumentQuery<DcAllocate>(origin.DocumentsLink)
                where d.Type == "DisList" && d.DcName == oldDc.Id
                select d;

            var l = ds.ToList().FirstOrDefault();

            if (l != null) await client.DeleteDocumentAsync(l._self);


            var allow2 = new DcAllocate
            {
                Type = "DisList",
                DcName = oldDc.Id,
                DcSelfLink = oldDc.SelfLink,
                District = new List<string>(),
            };

            foreach (DictionaryEntry i in oldList)
            {
                allow2.District.Add(i.Key.ToString());
            }
            await client.CreateDocumentAsync(origin.DocumentsLink, allow2);
        }
Beispiel #24
0
        /// <summary>
        /// Internal Member to Update Request and Status properties Azure DocumentDB by url 
        /// </summary>
        /// <param name="client"></param>
        /// <param name="selfLink"></param>
        /// <param name="request"></param>
        /// <param name="status"></param>
        /// <param name="message"></param>
        /// <returns></returns>
        private Document UpdateSiteRequestStatusByUrl(DocumentClient client, string selfLink, SiteInformation request, SiteRequestStatus status, string message)
        {
            dynamic _requestDocument = client.CreateDocumentQuery<Document>(selfLink).Where(d => d.Id == request.Id).AsEnumerable().FirstOrDefault();
            Document _d = _requestDocument; //Cast to Document to get the Selflink property
            Document _dReturnResult = null;
            SiteInformation _requestToUpdate = _requestDocument;
            if(!string.IsNullOrEmpty(message))
            {
                _requestToUpdate.RequestStatusMessage = message;
            }
            _requestToUpdate.EnumStatus = status;
            var savedRequestTask = Task.FromResult(client.ReplaceDocumentAsync(_d.SelfLink, _requestToUpdate));

            if (!savedRequestTask.Result.IsFaulted)
            {
                _dReturnResult = savedRequestTask.Result.Result;
            }
            return _dReturnResult;
        }
Beispiel #25
0
 public static Document GetDocumentById(DocumentClient client, DocumentCollection collection, string id)
 {
     return client.CreateDocumentQuery(collection.DocumentsLink).Where(w => w.Id == id).AsEnumerable().FirstOrDefault();
 }
Beispiel #26
0
 private static async Task TransferDc(DocumentCollection oldDc, DocumentCollection newDc, DocumentClient client,
     Database database, Hashtable newList)
 {
     foreach (DictionaryEntry dis in newList)
     {
         var tempDis = dis;
         var items =
             from d in client.CreateDocumentQuery<PostMessage>(oldDc.DocumentsLink)
             where d.Type == "Post" && d.Path.District == tempDis.Key.ToString()
             select d;
         foreach (var item in items)
         {
             try
             {
                 await client.DeleteDocumentAsync(item._self);
             }
             catch (Exception)
             {
                 Thread.Sleep(200);
                 client.DeleteDocumentAsync(item._self).Wait();
             }
             try
             {
                 await client.CreateDocumentAsync(newDc.DocumentsLink, item);
             }
             catch (Exception)
             {
                 Thread.Sleep(200);
                 client.CreateDocumentAsync(newDc.DocumentsLink, item).Wait();
             }
         }
     }
 }
Beispiel #27
0
        private static void RetrieveSessions(DocumentClient client)
        {
            var startsAt = new DateTime(2016, 10, 4, 12, 0, 0).ToString("s");
            // Construct the query operation for all sessions for the first day of the TechDays event.

            var query =
                from s in client.CreateDocumentQuery<Session>(UriFactory.CreateDocumentCollectionUri(DatabaseName, CollectionName))
                where s.StartsAt == startsAt
                select s;

            // Print the fields for each session.
            foreach (Session entity in query)
            {
                Console.WriteLine($"Day: {entity.StartsAt}, ID:{entity.SessionID}\tName:{entity.Name}\tPresenter:{entity.Presenter.FirstName} {entity.Presenter.LastName}");
            }
        }
Beispiel #28
0
        private static async Task UpdateDc(DocumentCollection oldDc, DocumentClient client,
            Database database, DocumentCollection origin)
        {
            var res = await client.ReadDocumentCollectionAsync(oldDc.SelfLink);
            var size = res.CollectionSizeUsage;
            var totalSize = res.CollectionSizeQuota;
            if (size > totalSize*2/100000)
            {
                var ds =
                    from d in client.CreateDocumentQuery<PostMessage>(oldDc.DocumentsLink)
                    where d.Type == "Post"
                    select d;

                Hashtable hs = new Hashtable();
                var n = ds.ToList().Count;
                foreach (var d in ds)
                {
                    if (!hs.ContainsKey(d.Path.District))
                    {
                        hs.Add(d.Path.District, 1);
                    }
                    else
                    {
                        hs[d.Path.District] = (int) hs[d.Path.District] + 1;
                    }
                }
                Hashtable newList = new Hashtable();
                Hashtable oldList = new Hashtable();

                foreach (DictionaryEntry h in hs)
                {
                    var c = 0;
                    foreach (DictionaryEntry hh in newList)
                    {
                        c = c + (int) hh.Value;
                    }
                    if (c < n*0.45 && (c + (int) h.Value < n*0.55))
                    {
                        newList.Add(h.Key, h.Value);
                    }
                    else
                    {
                        oldList.Add(h.Key, h.Value);
                    }
                }


                if (newList.Count > 0)
                {
                    //create new collection
                    /*var t = (long) (DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1))).TotalMilliseconds;
                  DocumentCollection newDc=await client.CreateDocumentCollectionAsync(database.CollectionsLink,
                                                        new DocumentCollection
                                                        {
                                                            Id = "LMSCollection"+t
                                                        });*/

                    //search collection
                    DocumentCollection newDc = client.CreateDocumentCollectionQuery(database.SelfLink)
                        .Where(c => c.Id == "LMSCollection1444075919174")
                        .AsEnumerable()
                        .FirstOrDefault();

                    await SaveDisList(newList, oldList, origin, oldDc, newDc, client);

                    await TransferDc(oldDc, newDc, client, database, newList);
                }
            }
        }
Beispiel #29
0
        private List<SiteInformation> GetSiteRequestsbyEmail(DocumentClient client, string collectionLink, string email)
        {
            List<SiteInformation> _returnResults = new List<SiteInformation>();
            var siteRequests = from record in client.CreateDocumentQuery<SiteInformation>(collectionLink)
                               where record.SiteOwner.Name == email
                               select record;

            _returnResults = siteRequests.ToList();

            return _returnResults;
        }
        private static async Task LogDocumentCountsPerCollection(DocumentClient client, Database database)
        {
            foreach (DocumentCollection collection in await client.ReadDocumentCollectionFeedAsync(database.SelfLink))
            {
                int numDocuments = 0;
                foreach (int document in client.CreateDocumentQuery<int>(collection.SelfLink, "SELECT VALUE 1 FROM ROOT", new FeedOptions { MaxItemCount = -1 }))
                {
                    numDocuments++;
                }

                Console.WriteLine("Collection {0}: {1} documents", collection.Id, numDocuments);
            }
        }
Beispiel #31
0
        /// <summary>
        /// Internal Member to get a site Request by Url
        /// </summary>
        /// <param name="client"></param>
        /// <param name="collectionLink"></param>
        /// <param name="url"></param>
        /// <returns></returns>
        private SiteInformation GetSiteRequestByUrl(DocumentClient client, string collectionLink, string url)
        { 
            var siteRequests  = from record in client.CreateDocumentQuery<SiteInformation>(collectionLink)
                           where record.Url == url
                           select record;

            return siteRequests.ToList().FirstOrDefault();
        }
Beispiel #32
-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);
        }