Beispiel #1
0
        async void CreatePermissionAsync(object resource, RequestOptions requestOptions)
        {
            try
            {
                var permission = JsonSerializable.LoadFrom <Permission>(new MemoryStream(Encoding.UTF8.GetBytes(resource as string)));

                ResourceResponse <Permission> newtpermission;
                using (PerfStatus.Start("CreatePermission"))
                {
                    newtpermission = await _client.CreatePermissionAsync((Parent.Tag as Resource).GetLink(_client), permission, requestOptions);
                }
                Nodes.Add(new ResourceNode(_client, newtpermission.Resource, ResourceType.Permission));

                // set the result window
                var json = newtpermission.Resource.ToString();

                Program.GetMain().SetResultInBrowser(json, null, false, newtpermission.ResponseHeaders);
            }
            catch (AggregateException e)
            {
                Program.GetMain().SetResultInBrowser(null, e.InnerException.ToString(), true);
            }
            catch (Exception e)
            {
                Program.GetMain().SetResultInBrowser(null, e.ToString(), true);
            }
        }
        public async Task Create(JObject data)
        {
            var bytes = Encoding.UTF8.GetBytes(data.ToString());

            using (var ms = new MemoryStream(bytes))
            {
                await _client.CreateDocumentAsync(
                    UriFactory.CreateDocumentCollectionUri(_database, _collection),
                    JsonSerializable.LoadFrom <Document>(ms));
            }
        }
Beispiel #3
0
        private static T DirectDeSerialize <T>(string payload) where T : JsonSerializable, new()
        {
            using (MemoryStream ms = new MemoryStream())
            {
                StreamWriter sw = new StreamWriter(ms, new UTF8Encoding(false, true), 1024, leaveOpen: true);
                sw.Write(payload);
                sw.Flush();

                ms.Position = 0;
                return(JsonSerializable.LoadFrom <T>(ms));
            }
        }
        public override void ReplaceEvent(object docId, AuditEvent auditEvent)
        {
            var      client = GetClient();
            var      docUri = UriFactory.CreateDocumentUri(_database, _collection, docId.ToString());
            Document doc;

            using (var ms = new MemoryStream(Encoding.UTF8.GetBytes(auditEvent.ToJson())))
            {
                doc    = JsonSerializable.LoadFrom <Document>(ms);
                doc.Id = docId.ToString();
            }
            client.ReplaceDocumentAsync(docUri, doc).Wait();
        }
Beispiel #5
0
 // This function will get triggered/executed when a new message is written in the servicebus output queue
 public static void ProcessQueueMessage([ServiceBusTrigger("outputqueue", AccessRights.Listen)] BrokeredMessage message, TextWriter log)
 {
     try
     {
         var stream   = message.GetBody <Stream>();
         var document = JsonSerializable.LoadFrom <Document>(stream);
         Client.CreateDocumentAsync(UriFactory.CreateDocumentCollectionUri(DbName, CollectionName), document).Wait();
     }
     catch (Exception e)
     {
         log.WriteLine(e.Message);
     }
 }
Beispiel #6
0
        public override async Task ReplaceEventAsync(object docId, AuditEvent auditEvent)
        {
            var      client = GetClient(auditEvent);
            var      docUri = UriFactory.CreateDocumentUri(DatabaseBuilder?.Invoke(auditEvent), CollectionBuilder?.Invoke(auditEvent), docId.ToString());
            Document doc;

            using (var ms = new MemoryStream(Encoding.UTF8.GetBytes(auditEvent.ToJson())))
            {
                doc    = JsonSerializable.LoadFrom <Document>(ms);
                doc.Id = docId.ToString();
            }
            await client.ReplaceDocumentAsync(docUri, doc);
        }
Beispiel #7
0
        public override async Task ReplaceEventAsync(object docId, AuditEvent auditEvent)
        {
            var      client = GetClient();
            var      docUri = UriFactory.CreateDocumentUri(DatabaseBuilder?.Invoke(), ContainerBuilder?.Invoke(), docId.ToString());
            Document doc;

            using (var ms = new MemoryStream(Encoding.UTF8.GetBytes(auditEvent.ToJson())))
            {
                doc = JsonSerializable.LoadFrom <Document>(ms);
            }
            doc.Id = docId.ToString();
            await client.ReplaceDocumentAsync(docUri, doc, new RequestOptions()
            {
                JsonSerializerSettings = Core.Configuration.JsonSettings
            });
        }
Beispiel #8
0
        public async Task DocumentDB(string collectionName, string resp, TraceWriter llog)
        {
            try
            {
                var azureServiceTokenProvider = new AzureServiceTokenProvider();
                var keyVaultClient            = new KeyVaultClient(new KeyVaultClient.AuthenticationCallback(azureServiceTokenProvider.KeyVaultTokenCallback));
                var EndpointUrlKV             = await keyVaultClient.GetSecretAsync("https://Demo-KV001.vault.azure.net/secrets/EndpointUrlKV")
                                                .ConfigureAwait(false);

                var PrimaryKeyKV = await keyVaultClient.GetSecretAsync("https://Demo-KV001.vault.azure.net/secrets/PrimaryKeyKV")
                                   .ConfigureAwait(false);

                var databaseNameKV = await keyVaultClient.GetSecretAsync("https://Demo-KV001.vault.azure.net/secrets/databasenameKV")
                                     .ConfigureAwait(false);


                client = new DocumentClient(new Uri(EndpointUrlKV.Value), PrimaryKeyKV.Value);

                await client.CreateDatabaseIfNotExistsAsync(new Database { Id = databaseNameKV.Value });

                try
                {
                    await client.CreateDocumentCollectionIfNotExistsAsync(UriFactory.CreateDatabaseUri(databaseNameKV.Value), new DocumentCollection { Id = collectionName }, new RequestOptions { OfferThroughput = 400 });
                }
                catch (Exception e)
                {
                    llog.Info("DocumentClientException: " + e.Message.ToString());
                }

                using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(resp)))
                {
                    var doc = JsonSerializable.LoadFrom <Document>(ms);
                    doc.Id = DateTime.Now.ToLongTimeString() + " " + DateTime.Now.ToLongDateString();

                    var docDBresp = await client.CreateDocumentAsync(UriFactory.CreateDocumentCollectionUri(databaseNameKV.Value, collectionName), doc);

                    /*while (docDBresp.IsCompleted == false)
                     * { }*/
                }
            }
            catch (Exception e)
            {
                llog.Info("General Exception: " + e.Message.ToString());
            }
        }
        public Task PutAsync(HttpMonitor httpMonitor)
        {
            if (httpMonitor == null)
            {
                throw new ArgumentNullException(nameof(httpMonitor));
            }

            var documentCollectionUri = _configs.DocumentCollectionUri;

            var jObject = JObject.FromObject(httpMonitor, JsonSerializer.Create(Constants.JsonSerializerSettings));

            // add type
            jObject.Add("_type", JValue.CreateString(DocumentType));

            var document = JsonSerializable.LoadFrom <Document>(new MemoryStream(Encoding.UTF8.GetBytes(jObject.ToString())));

            return(_client.UpsertDocumentAsync(documentCollectionUri, document, null, true));
        }
        public static SerializableNameValueCollection LoadFromString(string value)
        {
            if (!string.IsNullOrEmpty(value))
            {
                using (MemoryStream ms = new MemoryStream())
                {
                    using (StreamWriter writer = new StreamWriter(ms))
                    {
                        writer.Write(value);
                        writer.Flush();
                        ms.Position = 0;
                        return(JsonSerializable.LoadFrom <SerializableNameValueCollection>(ms));
                    }
                }
            }

            return(new SerializableNameValueCollection());
        }
        public async Task Run(string input)
        {
            var updatedCount = 0;

            var query = _documentClient.CreateDocumentQuery <dynamic>(
                UriFactory.CreateDocumentCollectionUri(_configuration.DatabaseId, _configuration.VenuesCollectionName),
                "select * from venues c where is_defined(c.LATITUDE) or is_defined(c.LONGITUDE) or is_defined(c.ID)")
                        .AsDocumentQuery();

            await query.ProcessAll(async chunk =>
            {
                foreach (Document doc in chunk)
                {
                    var jObj = JObject.Parse(doc.ToString());

                    if (jObj.ContainsKey("ID"))
                    {
                        jObj.Remove("ID");
                    }

                    if (jObj.ContainsKey("LATITUDE"))
                    {
                        jObj["Latitude"] = jObj["LATITUDE"];
                        jObj.Remove("LATITUDE");
                    }

                    if (jObj.ContainsKey("LONGITUDE"))
                    {
                        jObj["Longitude"] = jObj["LONGITUDE"];
                        jObj.Remove("LONGITUDE");
                    }

                    var jsonStream = new MemoryStream(Encoding.UTF8.GetBytes(jObj.ToString()));
                    var updatedDoc = JsonSerializable.LoadFrom <Document>(jsonStream);

                    await _documentClient.ReplaceDocumentAsync(updatedDoc);

                    updatedCount++;
                }
            });

            _logger.LogInformation($"Updated {updatedCount} venues.");
        }
Beispiel #12
0
        public async Task DocumentDB(string collectionName, string resp)
        {
            try
            {
                //use managed service identity to obtain key vault access
                var azureServiceTokenProvider = new AzureServiceTokenProvider();
                var keyVaultClient            = new KeyVaultClient(new KeyVaultClient.AuthenticationCallback(azureServiceTokenProvider.KeyVaultTokenCallback));

                //read CosmosDB creds from key vault
                var EndpointUrlKV = await keyVaultClient.GetSecretAsync("https://Demo-KV001.vault.azure.net/secrets/EndpointUrlKV")
                                    .ConfigureAwait(false);

                var PrimaryKeyKV = await keyVaultClient.GetSecretAsync("https://Demo-KV001.vault.azure.net/secrets/PrimaryKeyKV")
                                   .ConfigureAwait(false);

                var databaseNameKV = await keyVaultClient.GetSecretAsync("https://Demo-KV001.vault.azure.net/secrets/databasenameKV")
                                     .ConfigureAwait(false);


                client = new DocumentClient(new Uri(EndpointUrlKV.Value), PrimaryKeyKV.Value);

                await client.CreateDatabaseIfNotExistsAsync(new Database { Id = databaseNameKV.Value });

                await client.CreateDocumentCollectionIfNotExistsAsync(UriFactory.CreateDatabaseUri(databaseNameKV.Value), new DocumentCollection { Id = collectionName });

                using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(resp)))
                {
                    var doc = JsonSerializable.LoadFrom <Document>(ms);
                    doc.Id = DateTime.Now.ToLongTimeString() + " " + DateTime.Now.ToLongDateString();

                    var docDBresp = await client.CreateDocumentAsync(UriFactory.CreateDocumentCollectionUri(databaseNameKV.Value, collectionName), doc);

                    /*while (docDBresp.IsCompleted == false)
                     * { }*/
                }
            }
            catch (DocumentClientException de)
            {
                Console.WriteLine("DocumentClientException: {0}", de.Message);
                Console.ReadKey();
            }
        }
        public Task CreateAsync(IAlertContact alertContact)
        {
            if (alertContact == null)
            {
                throw new ArgumentNullException(nameof(alertContact));
            }

            var documentcollectionUri = _configs.DocumentCollectionUri;

            var jObject = JObject.FromObject(alertContact, JsonSerializer.Create(Constants.JsonSerializerSettings));

            // add type
            jObject.Add("_type", JValue.CreateString(DocumentType));

            var json = jObject.ToString();

            var document = JsonSerializable.LoadFrom <Document>(new MemoryStream(Encoding.UTF8.GetBytes(json)));

            return(_client.CreateDocumentAsync(documentcollectionUri, document, null, true));
        }
Beispiel #14
0
        public Document GetNextDocument()
        {
            var data = _streamReader.ReadLine();

            if (data != null)
            {
                // build a Document instance from JSON text
                Document document = null;
                using (var memoryStream = new MemoryStream(Encoding.UTF8.GetBytes(data)))
                {
                    document = JsonSerializable.LoadFrom <Document>(memoryStream);
                }
                return(document);
            }
            else
            {
                // we've reached the end of the file
                return(null);
            }
        }
Beispiel #15
0
        public void DocumentDB(string collectionName, string resp)
        {
            try
            {
                //use managed service identity to obtain key vault access
                AzureServiceTokenProvider azureServiceTokenProvider = new AzureServiceTokenProvider();
                KeyVaultClient            keyVaultClient            = new KeyVaultClient(new KeyVaultClient.AuthenticationCallback(azureServiceTokenProvider.KeyVaultTokenCallback));

                //read CosmosDB creds from key vault
                string endpointUrlKV  = keyVaultClient.GetSecretAsync("https://Demo-KV001.vault.azure.net/secrets/EndpointUrlKV").Result.Value;
                string primaryKeyKV   = keyVaultClient.GetSecretAsync("https://Demo-KV001.vault.azure.net/secrets/PrimaryKeyKV").Result.Value;
                string databaseNameKV = keyVaultClient.GetSecretAsync("https://Demo-KV001.vault.azure.net/secrets/DbNameKV").Result.Value;


                client = new DocumentClient(new Uri(endpointUrlKV), primaryKeyKV);

                client.CreateDatabaseIfNotExistsAsync(new Database {
                    Id = databaseNameKV
                }).GetAwaiter().GetResult();
                client.CreateDocumentCollectionIfNotExistsAsync(UriFactory.CreateDatabaseUri(databaseNameKV), new DocumentCollection {
                    Id = collectionName
                }).GetAwaiter().GetResult();

                using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(resp)))
                {
                    var doc = JsonSerializable.LoadFrom <Document>(ms);
                    doc.Id = DateTime.Now.ToLongTimeString() + " " + DateTime.Now.ToLongDateString();

                    client.CreateDocumentAsync(UriFactory.CreateDocumentCollectionUri(databaseNameKV, collectionName), doc).GetAwaiter().GetResult();
                }
            }
            catch (DocumentClientException de)
            {
                /* Console.WriteLine("DocumentClientException: {0}", de.Message);
                 * Console.ReadKey();*/
            }
        }
Beispiel #16
0
        public override async Task SendAsync(EventMessage message)
        {
            AuditRecord record = null;

            byte[] payload = null;
            queue.Enqueue(message);
            try
            {
                while (!queue.IsEmpty)
                {
                    arrayIndex = arrayIndex.RangeIncrement(0, clientCount - 1);
                    bool isdequeued = queue.TryDequeue(out EventMessage msg);

                    if (!isdequeued)
                    {
                        continue;
                    }

                    payload = GetPayload(message);
                    if (payload == null)
                    {
                        await logger?.LogWarningAsync(
                            $"Subscription '{metadata.SubscriptionUriString}' message not written to cosmos db sink because message is null.");

                        continue;
                    }

                    await using MemoryStream stream = new MemoryStream(payload)
                                {
                                    Position = 0
                                };
                    if (message.ContentType.Contains("json"))
                    {
                        await storageArray[arrayIndex].CreateDocumentAsync(collection.SelfLink,
                                                                           JsonSerializable.LoadFrom <Document>(stream));
                    }
                    else
                    {
                        dynamic documentWithAttachment = new {
                            Id        = Guid.NewGuid().ToString(),
                            Timestamp = DateTime.UtcNow
                        };

                        Document doc = await storageArray[arrayIndex]
                                       .CreateDocumentAsync(collection.SelfLink, documentWithAttachment);
                        string slug = GetSlug(documentWithAttachment.Id, message.ContentType);
                        await  storageArray[arrayIndex].CreateAttachmentAsync(doc.AttachmentsLink, stream,
                                                                              new MediaOptions {
                            ContentType = message.ContentType, Slug = slug
                        });
                    }

                    if (message.Audit)
                    {
                        record = new MessageAuditRecord(message.MessageId,
                                                        uri.Query.Length > 0 ? uri.ToString().Replace(uri.Query, "") : uri.ToString(),
                                                        "CosmosDB", "CosmoDB", payload.Length, MessageDirectionType.Out, true, DateTime.UtcNow);
                    }
                }
            }
            catch (Exception ex)
            {
                await logger?.LogErrorAsync(ex,
                                            $"Subscription '{metadata.SubscriptionUriString}' message not written to cosmos db sink.");

                record = new MessageAuditRecord(message.MessageId,
                                                uri.Query.Length > 0 ? uri.ToString().Replace(uri.Query, "") : uri.ToString(), "CosmosDB",
                                                "CosmosDB", payload.Length, MessageDirectionType.Out, false, DateTime.UtcNow, ex.Message);
            }
            finally
            {
                if (record != null && message.Audit)
                {
                    await auditor?.WriteAuditRecordAsync(record);
                }
            }
        }
Beispiel #17
0
        public async Task InsertDocument()
        {
            string             databaseName   = "";
            DocumentCollection collectionName = null;

            if (!InsertCollAndDatabase(ref databaseName, ref collectionName))
            {
                Warning("Collection >>> " + collectionName + " <<< don't exist.");
                collectionName = await _collectionRepository.CreateCollection(databaseName, collectionName.Id);

                ProgramHelper.Wait();
            }

            WriteLine("1. New document from file");
            WriteLine("2. New document from anonymous type");
            WriteLine("3. New document from model");

            InsertOptionEnum option = (InsertOptionEnum)ProgramHelper.EnterInt("");

            switch (option)
            {
            case InsertOptionEnum.FromFile:
            {
                using (StreamReader file = new StreamReader(@"Scripts\zips.json"))
                {
                    string line;
                    int    count = 0;
                    while ((line = file.ReadLine()) != null && count != 100)
                    {
                        byte[] byteArray = Encoding.UTF8.GetBytes(line);
                        using (MemoryStream stream = new MemoryStream(byteArray))
                        {
                            Document newDocument = await _repository.InsertDocument(UriFactory.CreateDocumentCollectionUri(databaseName, collectionName.Id), JsonSerializable.LoadFrom <Document>(stream));

                            Success(++count + ", document import.");
                        }
                    }
                }

                break;
            }

            case InsertOptionEnum.FromAnonymous:
            {
                var newDocument = new
                {
                    firstName = "Ratomir",
                    lastName  = "Vukadin",
                    bookmarks = new[]
                    {
                        new { url = "https://try.dot.net/", name = "Try dot net" },
                        new { url = "https://dotnetfiddle.net/", name = "Dot net fiddle" }
                    },
                    city  = "TORONTO",
                    loc   = new Point(-80.632504, 40.473298),
                    pop   = 11981,
                    state = "OH"
                };

                Document createdNewDocument = await _repository.InsertDocument(UriFactory.CreateDocumentCollectionUri(databaseName, collectionName.Id), newDocument);

                Success("New document successfully created.");
                break;
            }

            case InsertOptionEnum.FromModel:
            {
                EmailModel emailModel = new EmailModel()
                {
                    Bcc = new List <string>()
                    {
                        "*****@*****.**"
                    },
                    Cc = new List <string>()
                    {
                        "*****@*****.**"
                    },
                    Ctype      = "text/plain; charset=us-ascii",
                    Date       = DateTime.Now,
                    Fname      = "Ratomir",
                    Folder     = "_inbox",
                    Fpath      = "enron_mail_20110402/maildir/lay-k/_sent/81.",
                    Mid        = "33068967.1075840285147.JavaMail.evans@thyme",
                    Recipients = new List <string>()
                    {
                        "*****@*****.**", "*****@*****.**", "*****@*****.**"
                    },
                    Replyto = null,
                    Sender  = "*****@*****.**",
                    Subject = "Re: EXECUTIVE COMMITTEE MEETING - MONDAY, JULY 10",
                    Text    = "Katherine:\n\nMr.Lay is planning on attending in person.\n\nTori\n\n\n\nKatherine Brown\n07 / 05 / 2000 01:15 PM\n\n\nTo: James M Bannantine / ENRON_DEVELOPMENT@ENRON_DEVELOPMENT, Cliff \nBaxter / HOU / ECT@ECT, Sanjay Bhatnagar/ ENRON_DEVELOPMENT@ENRON_DEVELOPMENT, \nRick Buy/ HOU / ECT@ECT, Richard Causey/ Corp / Enron@ENRON, Diomedes \nChristodoulou / SA / Enron@Enron, David W Delainey / HOU / ECT@ECT, James \nDerrick / Corp / Enron@ENRON, Andrew S Fastow / HOU / ECT@ECT, Peggy_Fowler @pgn.com, \nMark Frevert/ NA / Enron@Enron, Ben F Glisan / HOU / ECT@ECT, Kevin Hannon/ Enron \nCommunications @Enron Communications, David \nHaug / ENRON_DEVELOPMENT@ENRON_DEVELOPMENT, Joe Hirko/ Enron \nCommunications @Enron Communications, Stanley Horton/ Corp / Enron@Enron, Larry L \nIzzo / ENRON_DEVELOPMENT@ENRON_DEVELOPMENT, Steven J Kean / HOU / EES@EES, Mark \nKoenig / Corp / Enron@ENRON, Kenneth Lay/ Corp / Enron@ENRON, Rebecca P \nMark / HOU / AZURIX@AZURIX, Mike McConnell/ HOU / ECT@ECT, Rebecca \nMcDonald / ENRON_DEVELOPMENT@ENRON_DEVELOPMENT, Jeffrey McMahon/ HOU / ECT@ECT, J \nMark Metts/ NA / Enron@Enron, Cindy Olson/ Corp / Enron@ENRON, Lou L \nPai / HOU / EES@EES, Ken Rice/ Enron Communications @Enron Communications, Jeffrey \nSherrick / Corp / Enron@ENRON, John Sherriff/ LON / ECT@ECT, Jeff \nSkilling / Corp / Enron@ENRON, Joseph W \nSutton / ENRON_DEVELOPMENT@ENRON_DEVELOPMENT, Greg Whalley/ HOU / ECT@ECT, Thomas \nE White/ HOU / EES@EES, Brenda Garza-Castillo / NA / Enron@Enron, Marcia \nManarin / SA / Enron@Enron, Susan Skarness/ HOU / ECT@ECT, Stacy \nGuidroz / ENRON_DEVELOPMENT@ENRON_DEVELOPMENT, Beena \nPradhan / ENRON_DEVELOPMENT@ENRON_DEVELOPMENT, Karen K Heathman / HOU / ECT@ECT, \nSharron Westbrook/ Corp / Enron@ENRON, Kay Chapman/ HOU / ECT@ECT, Molly \nBobrow / NA / Enron@Enron, Rosane Fabozzi/ SA / Enron@Enron, Stephanie \nHarris / Corp / Enron@ENRON, Bridget Maronge/ HOU / ECT@ECT, Mary_trosper @pgn.com, \nNicki Daw/ NA / Enron@Enron, Inez Dauterive/ HOU / ECT@ECT, Carol Ann Brown / Enron \nCommunications @Enron Communications, Elaine \nRodriguez / ENRON_DEVELOPMENT@ENRON_DEVELOPMENT, Nancy Young/ Enron \nCommunications @Enron Communications, Ann Joyner/ Corp / Enron@ENRON, Cindy \nStark / Corp / Enron@ENRON, Mary E Garza / ENRON_DEVELOPMENT@ENRON_DEVELOPMENT, \nMaureen McVicker/ HOU / EES@EES, Joannie Williamson/ Corp / Enron@ENRON, Rosalee \nFleming / Corp / Enron@ENRON, Vanessa Groscrand/ Corp / Enron@ENRON, Marsha \nLindsey / HOU / AZURIX@AZURIX, Cathy Phillips/ HOU / ECT@ECT, Loretta \nBrelsford / ENRON_DEVELOPMENT@ENRON_DEVELOPMENT, Sue Ford/ HOU / ECT@ECT, Dolores \nFisher / NA / Enron@Enron, Karen Owens/ HOU / EES@EES, Dorothy Dalton/ Enron \nCommunications @Enron Communications, Jewel Meeks/ Enron Communications @Enron \nCommunications, Christina Grow/ Corp / Enron@ENRON, Lauren Urquhart/ LON / ECT@ECT, \nSherri Sera/ Corp / Enron@ENRON, Katherine Brown/ Corp / Enron@ENRON, Pam \nBenson / ENRON_DEVELOPMENT@ENRON_DEVELOPMENT, Jana Mills/ HOU / ECT@ECT, Liz M \nTaylor / HOU / ECT@ECT, Judy G Smith / HOU / EES@EES, Bobbie Power/ Corp / Enron@ENRON\ncc: Suzanne Danz/ Corp / Enron@ENRON, Videoconference @enron, Vanessa \nGroscrand / Corp / Enron@ENRON \nSubject: EXECUTIVE COMMITTEE MEETING - MONDAY, JULY 10\n\n\nExecutive Committee Weekly Meeting\nDate: Monday, July 10\nTime: 11:00 a.m. (CDT)\nLocation: 50th Floor Boardroom\nVideo: Connections will be established with remote locations upon request.\nConf call: AT & T lines have been reserved.  Please contact Sherri Sera \n(713 / 853 - 5984) \n or Katherine Brown(713 / 345 - 7774) for the weekly dial -in number and \npasscode.\n\nPlease indicate below whether or not you plan to attend this meeting and \nthrough what medium. \n\n Yes, I will attend in person _______\n\n By video conference from _______\n\n By conference call  _______\n\n No, I will not attend  _______\n\n * **\n\nPlease return this e - mail to me with your response by 12:00 p.m., Friday, \nJuly 7.\n\nThank you, \nKatherine\n\n",
                    To      = new List <string>()
                    {
                        "*****@*****.**"
                    }
                };

                Document newDocument = await _repository.InsertDocument(databaseName, collectionName.Id, emailModel);

                emailModel.Id = newDocument.Id;
                Success("New document successfully created.");
                Info("New Email model id: " + emailModel.Id);

                break;
            }

            default:
                break;
            }
        }
        async void ReplaceResourceAsync(object resource, RequestOptions requestOptions)
        {
            try
            {
                string json = null;
                if (_resourceType == ResourceType.Document)
                {
                    var text     = resource as string;
                    var doc      = (Document)JsonConvert.DeserializeObject(text, typeof(Document));
                    var tagAsDoc = (Tag as Document);
                    doc.SetReflectedPropertyValue("AltLink", tagAsDoc.GetAltLink());
                    ResourceResponse <Document> rr;
                    var hostName = _client.ServiceEndpoint.Host;
                    using (PerfStatus.Start("ReplaceDocument"))
                    {
                        rr = await _client.ReplaceDocumentAsync(doc.GetLink(_client), doc, requestOptions);
                    }
                    json = rr.Resource.ToString();

                    Tag = rr.Resource;

                    Text = _customDocumentListDisplayManager.GetDisplayText(rr.Resource, hostName, _documentCollectionId, _databaseId);
                    // set the result window
                    SetResultInBrowser(DocumentHelper.RemoveInternalDocumentValues(json), null, false, rr.ResponseHeaders);
                }
                else if (_resourceType == ResourceType.StoredProcedure)
                {
                    var input = resource as StoredProcedure;
                    var sp    = Tag as StoredProcedure;
                    sp.Body = input.Body;
                    if (!string.IsNullOrEmpty(input.Id))
                    {
                        sp.Id = input.Id;
                    }
                    ResourceResponse <StoredProcedure> rr;
                    using (PerfStatus.Start("ReplaceStoredProcedure"))
                    {
                        rr = await _client.ReplaceStoredProcedureExAsync(sp, requestOptions);
                    }
                    json = rr.Resource.ToString();
                    Tag  = rr.Resource;
                    Text = rr.Resource.Id;
                    // set the result window
                    SetResultInBrowser(json, null, false, rr.ResponseHeaders);
                }
                else if (_resourceType == ResourceType.User)
                {
                    var text = resource as string;
                    var sp   = (User)JsonConvert.DeserializeObject(text, typeof(User));
                    sp.SetReflectedPropertyValue("AltLink", (Tag as User).GetAltLink());
                    ResourceResponse <User> rr;
                    using (PerfStatus.Start("ReplaceUser"))
                    {
                        rr = await _client.ReplaceUserExAsync(sp, requestOptions);
                    }
                    json = rr.Resource.ToString();
                    Tag  = rr.Resource;
                    Text = rr.Resource.Id;
                    // set the result window
                    SetResultInBrowser(json, null, false, rr.ResponseHeaders);
                }
                else if (_resourceType == ResourceType.Trigger)
                {
                    var input = resource as Trigger;
                    var sp    = Tag as Trigger;
                    sp.Body = input.Body;
                    if (!string.IsNullOrEmpty(input.Id))
                    {
                        sp.Id = input.Id;
                    }
                    ResourceResponse <Trigger> rr;
                    using (PerfStatus.Start("ReplaceTrigger"))
                    {
                        rr = await _client.ReplaceTriggerExAsync(sp, requestOptions);
                    }
                    json = rr.Resource.ToString();
                    Tag  = rr.Resource;
                    Text = rr.Resource.Id;
                    // set the result window
                    SetResultInBrowser(json, null, false, rr.ResponseHeaders);
                }
                else if (_resourceType == ResourceType.UserDefinedFunction)
                {
                    var input = resource as UserDefinedFunction;
                    var sp    = Tag as UserDefinedFunction;
                    sp.Body = input.Body;
                    if (!string.IsNullOrEmpty(input.Id))
                    {
                        sp.Id = input.Id;
                    }
                    ResourceResponse <UserDefinedFunction> rr;
                    using (PerfStatus.Start("ReplaceUDF"))
                    {
                        rr = await _client.ReplaceUserDefinedFunctionExAsync(sp, requestOptions);
                    }
                    json = rr.Resource.ToString();
                    Tag  = rr.Resource;
                    Text = rr.Resource.Id;
                    // set the result window
                    SetResultInBrowser(json, null, false, rr.ResponseHeaders);
                }
                else if (_resourceType == ResourceType.Permission)
                {
                    var text = resource as string;
                    var sp   = JsonSerializable.LoadFrom <Permission>(new MemoryStream(Encoding.UTF8.GetBytes(text)));
                    sp.SetReflectedPropertyValue("AltLink", (Tag as Permission).GetAltLink());
                    ResourceResponse <Permission> rr;
                    using (PerfStatus.Start("ReplacePermission"))
                    {
                        rr = await _client.ReplacePermissionExAsync(sp, requestOptions);
                    }
                    json = rr.Resource.ToString();
                    Tag  = rr.Resource;
                    Text = rr.Resource.Id;
                    // set the result window
                    SetResultInBrowser(json, null, false, rr.ResponseHeaders);
                }
                else if (_resourceType == ResourceType.Attachment)
                {
                    var text = resource as string;
                    var sp   = (Attachment)JsonConvert.DeserializeObject(text, typeof(Attachment));
                    sp.SetReflectedPropertyValue("AltLink", (Tag as Attachment).GetAltLink());
                    ResourceResponse <Attachment> rr;

                    var document   = ((Document)Parent.Tag);
                    var collection = ((DocumentCollection)Parent.Parent.Tag);

                    if (collection.PartitionKey != null && collection.PartitionKey.Paths.Count > 0)
                    {
                        requestOptions.PartitionKey = new PartitionKey(DocumentAnalyzer.ExtractPartitionKeyValue(document, collection.PartitionKey));
                    }

                    using (PerfStatus.Start("ReplaceAttachment"))
                    {
                        rr = await _client.ReplaceAttachmentExAsync(sp, requestOptions);
                    }

                    json = rr.Resource.ToString();
                    Tag  = rr.Resource;
                    Text = rr.Resource.Id;
                    // set the result window
                    SetResultInBrowser(json, null, false, rr.ResponseHeaders);
                }
            }
            catch (AggregateException e)
            {
                SetResultInBrowser(null, e.InnerException.ToString(), true);
            }
            catch (Exception e)
            {
                SetResultInBrowser(null, e.ToString(), true);
            }
        }