private async void DeleteButton_Click(object sender, RoutedEventArgs e) { using (var store = new MyCouchStore("http://*****:*****@localhost:5984", "tv-series")) { //Delete a document using user given ID await store.DeleteAsync(SearchIDTxt.Text); SearchIDTxt.Clear(); ReadTxt.Clear(); SearchIDTxt.IsEnabled = true; MessageBox.Show("Document Successfully Deleted", "TV-Series", MessageBoxButton.OK, MessageBoxImage.Exclamation); } // Refreshes the number of tv-serie documents when one is removed. using (var client = new MyCouchClient("http://*****:*****@localhost:5984", "tv-series")) { var personQuery = new QueryViewRequest("series", "CountNoTvSeries").Configure(query2 => query2 .Reduce(false)); ViewQueryResponse result2 = await client.Views.QueryAsync(personQuery); NoTvSeriesTxt.Text = result2.RowCount.ToString(); } }
public async void DeleteObject(string _id, string _rev) { using (var db = new MyCouchStore("http://localhost:5984", "cars")) { var response = await db.DeleteAsync(_id, _rev); } }
public async Task <string> Spam([Author] Member author, MyCouchStore db, ISocketMessageChannel channel, SocketUserMessage message, [Rest] string youtubeUrl) { if (message.Author is SocketGuildUser discordAuthor && discordAuthor.VoiceChannel != null) { Spammable spammable; try { spammable = await Spammable.Create(youtubeUrl); } catch (Exception exception) { Console.WriteLine(exception); return("Could not download youtube video. Maybe try a different video?"); } var bbpCost = spammable.Length * 100 / 60; var walletCost = new Wallet(bbpCost + " BBP"); author.Wallet.Subtract(walletCost); try { await channel.SendMessageAsync($"{author.Name} has triggered a mic spam for {walletCost}."); var client = await discordAuthor.VoiceChannel.ConnectAsync(); if (!await spammable.Spam(client)) { return("Could not play youtube video in voice channel. Maybe try a different video."); } else { await db.StoreAsync(author); return(null); } } finally { await discordAuthor.VoiceChannel.DisconnectAsync(); } }
public async Task <CreateContractCommandContext> Execute(CreateContractCommandContext commandContext) { using (var store = new MyCouchStore("http://*****:*****@cm-ylng-msk-03:5984", "cmas")) { var query = new QueryViewRequest("contracts", "empty"); var viewResult = await store.Client.Views.QueryAsync(query); var firstRow = viewResult.Rows.FirstOrDefault(); if (firstRow != null) { commandContext.id = firstRow.Id; } else { var doc = new ContractDto(); doc.UpdatedAt = DateTime.Now; doc.CreatedAt = DateTime.Now; doc.Status = "empty"; var result = await store.Client.Entities.PostAsync(doc); commandContext.id = result.Id; } return(commandContext); } }
//ToDo inject my couch client public RecipesCouchRepository(IOptions <ConnectionStrings> connectionStrings, LanguageService languageService, ILogger <RecipesCouchRepository> logger) { this.languageService = languageService; this.logger = logger; this.store = new MyCouchStore(connectionStrings.Value.CouchDb, "recipes"); }
/// <summary> /// Returns Id of created document /// </summary> private string CreateDocument(string document) { using (var c = new MyCouchStore(_uri)) { var header = c.StoreAsync(document).Result; return header.Id; } }
public static async Task <IEnumerable <T> > GetAllAsync <T>(this MyCouchStore db) where T : class { var query = new Query(SystemViewIdentity.AllDocs).Configure(config => config.IncludeDocs(true)); return((await db.QueryAsync <dynamic, T>(query)) .Where(row => !row.Id.StartsWith("_")) .Select(row => row.IncludedDoc as T)); }
public async Task <Car> GetObject(string id) { using (var db = new MyCouchStore("http://localhost:5984", "cars")) { var response = await db.GetByIdAsync <Car>(id); return(response); } }
public async Task <DeleteContractCommandContext> Execute(DeleteContractCommandContext commandContext) { using (var store = new MyCouchStore("http://*****:*****@cm-ylng-msk-03:5984", "cmas")) { await store.DeleteAsync(commandContext.id); return(commandContext); } }
public static void Main(string[] args) { //this give me this error: //System.IO.FileNotFoundException: Could not load file or assembly 'EnsureThat, Version=2.0.0.39118, Culture=neutral, PublicKeyToken=null' or one of its dependencies. //File name: 'EnsureThat, Version=2.0.0.39118, Culture=neutral, PublicKeyToken=null' var client = new MyCouchStore("http://localhost:5984/test"); Console.WriteLine("Hello World"); Console.ReadLine(); }
public IEnumerable<MovieRating> GetAllMovieRatings() { using (var c = new MyCouchStore(_uri)) { var query = new Query("views", "allRatings"); query.Reduce = false; var result = c.QueryAsync<MovieRating>(query).Result; return result.Select(x => x.Value); } }
public async Task<IEnumerable<MovieInformationRow>> GetAllMovieInformation() { using (var c = new MyCouchStore(_uri)) { var query = new Query("views", "movies"); query.Group = true; var result = await c.QueryAsync<MovieInformationRow>(query); return result.Select(x => x.Value); } }
/// <summary> /// Temp function, will be removed when datamodel is consistent /// </summary> public async Task<IEnumerable<AllRatingsRow>> GetAllMovieRatings2() { using (var c = new MyCouchStore(_uri)) { var query = new Query("views", "allRatings"); query.Reduce = false; var result = await c.QueryAsync<AllRatingsRow>(query); return result.Select(x => x.Value); } }
public static async Task <Member> GetMember(this MyCouchStore db, ulong id) { if (await db.ExistsAsync(id.ToString())) { return(await db.GetByIdAsync <Member>(id.ToString())); } else { throw new CommandFailedException($"User with id {id} is not in the backend database... Go ask Keith about it"); } }
private string GetRev(MyCouchStore store, Guid id) { var doc = store.GetByIdAsync(id.ToString()).Result; if (doc == null) { return(null); } var retrieved = store.GetByIdAsync <BookOrderDto>(id.ToString()).Result; return(retrieved._rev); }
/// <summary> /// /// </summary> public CouchDbStore(string couchDbUrl) { if (string.IsNullOrEmpty(couchDbUrl)) { throw new ArgumentException($"couchDbUrl parameter must not be null or empty."); } var dbConnectionInfo = new DbConnectionInfo(couchDbUrl, EntityName); Client = new MyCouchClient(dbConnectionInfo); CouchServerClient = new MyCouchServerClient(couchDbUrl); Store = new MyCouchStore(Client); }
public static async Task <Member> GetMember(this MyCouchStore db, string name) { var members = await db.GetAllAsync <Member>(); var result = members.FirstOrDefault(member => member.Name.ToLower() == name.ToLower()); if (result == null) { throw new CommandFailedException($"User with name {name} is not in the backend database... Go ask Keith about it"); } else { return(result); } }
public CouchDbStoreBase(string database) { _database = database; using (var client = new MyCouchServerClient(SERVER)) { var d = client.Databases.PutAsync(_database).Result; if (!client.Databases.HeadAsync(_database).Result.IsSuccess) { throw new Exception($"Database '{_database}' not found!"); } } Store = new MyCouchStore(SERVER, _database); }
public static MyCouchStore Create(CouchDbConnection cn, string dbName) { // configure the JSON serializers to include the $type field in the JSON to support deserializing to the // concrete classes where we used inheritance and interfaces / base classes. var bootstrapper = new MyCouchClientBootstrapper(); bootstrapper.SerializationConfigurationFn = () => { var cfg = new SerializationConfiguration(new SerializationContractResolver()); cfg.Settings.TypeNameHandling = TypeNameHandling.Objects; return(cfg); }; var client = new MyCouchClient(CouchDbConnection.Current.ServerUrl, dbName, bootstrapper); var store = new MyCouchStore(client); return(store); }
public BookOrder Get(Guid id) { BookOrderDto retrieved; using (var store = new MyCouchStore(_databaseUri, _databaseName)) { var doc = store.GetByIdAsync(id.ToString()).Result; if (doc == null) { return(null); } retrieved = JsonConvert.DeserializeObject <BookOrderDto>(doc); } return(BookOrderMapper.MapFrom(retrieved)); }
public CommentService() { using (var client = new MyCouchServerClient(SERVER)) { var d = client.Databases.PutAsync(DATABASE).Result; if (!client.Databases.HeadAsync(DATABASE).Result.IsSuccess) { throw new Exception($"Database '{DATABASE}' not found!"); } } using (var client = new MyCouchClient(SERVER, DATABASE)) { if (!client.Documents.HeadAsync("_design/comments").Result.IsSuccess) { var assembly = Assembly.GetExecutingAssembly(); var docName = "SocketComment.DesignDocuments.Comments.json"; using (Stream stream = assembly.GetManifestResourceStream(docName)) using (StreamReader reader = new StreamReader(stream)) { string docString = reader.ReadToEnd(); if (string.IsNullOrWhiteSpace(docString)) { throw new Exception("Failed to load document json file"); } var doc = client.Documents.PostAsync(docString).Result; if (!doc.IsSuccess) { throw new Exception("Failed to setup default view document"); } } } } _commentStore = new MyCouchStore(SERVER, DATABASE); _commentCache = CacheFactory.Build <Comment>(settings => { settings.WithMicrosoftMemoryCacheHandle(); }); }
private static void EnsureViewsAreUpToDate(DatabaseHeaderResponse karinsFilmerDb) { using (var c = new MyCouchStore(karinsFilmerDb.RequestUri)) { JObject viewJson = ReadViewFileFromSolution(); string viewJsonString = viewJson.ToString(Formatting.None); string jsonFromDb = c.GetByIdAsync("_design/views").Result; if (jsonFromDb != null) { var o = JsonConvert.DeserializeObject<JObject>(jsonFromDb); o.Remove("_rev"); jsonFromDb = o.ToString(Formatting.None); } if (viewJsonString != jsonFromDb) { c.SetAsync("_design/views", viewJsonString).Wait(); } } }
private async void ReadButton_Click(object sender, RoutedEventArgs e) { using (var store = new MyCouchStore("http://*****:*****@localhost:5984", "tv-series")) { //Get User given document ID with MyCouch. var retrieved = await store.GetByIdAsync(SearchIDTxt.Text); ReadTxt.Text = retrieved; //Aligning the text to be in JSON structure. ReadTxt.Text = ReadTxt.Text.Replace(",", "," + System.Environment.NewLine + " "); ReadTxt.Text = ReadTxt.Text.Replace("{", "{" + System.Environment.NewLine + " "); ReadTxt.Text = ReadTxt.Text.Replace("}", System.Environment.NewLine + "}"); ReadTxt.Text = ReadTxt.Text.Replace(":", ": "); ReadTxt.Text = ReadTxt.Text.Replace("[", " [" + System.Environment.NewLine + " "); ReadTxt.Text = ReadTxt.Text.Replace("]", System.Environment.NewLine + " " + "]"); SearchIDTxt.IsEnabled = false; ReadButton.IsEnabled = false; } }
public void Store(BookOrder bookOrder) { using (var store = new MyCouchStore(_databaseUri, _databaseName)) { // HACK: Concurrency support, lets just get the latest rev // Don't do this in production environments !! Implement concurrency properly all the way // to the client !! string rev = GetRev(store, bookOrder.Id); BookOrderDto bookOrderDto = BookOrderMapper.MapTo(bookOrder, rev); if (rev == null) { store.StoreAsync(bookOrderDto).Wait(); } else { bookOrderDto._rev = rev; store.StoreAsync(bookOrderDto).Wait(); } } }
public void ExportAllDataFromCouchToFiles() { string connectionString = ConfigurationManager.ConnectionStrings["CouchDb"].ConnectionString; using (var c = new MyCouchStore(connectionString)) { var query = new Query("_all_docs") {IncludeDocs = true}; var result = c.QueryAsync(query).Result; var jsonFileParts = new List<string>(); foreach (var obj in result) { var doc = JsonConvert.DeserializeObject<JObject>(obj.IncludedDoc); JToken type; if (doc.TryGetValue("type", out type) && type.ToString() == "MovieRating") jsonFileParts.Add(obj.IncludedDoc); } var json = "[\n" + String.Join(",\n", jsonFileParts) + "\n]"; File.WriteAllText("TestData.json", json); } }
public void ImportTestData() { // Remove the old database string connectionString = ConfigurationManager.ConnectionStrings["CouchDb"].ConnectionString; var uri = new Uri(connectionString); var dbName = uri.LocalPath.Substring(1); using (var s = new MyCouchServerClient(uri.Scheme + "://" + uri.Authority)) { s.Databases.DeleteAsync(dbName).Wait(); } // Create new database CouchConfig.SetupCouchDb(); // Fill it with test data using (var c = new MyCouchStore(connectionString)) { foreach (var testData in GetTestData()) { c.StoreAsync(testData).Wait(); } } }
static void WorkTimerCallback(object state) { MyCouchClient couch = (MyCouchClient) state; List<ADAITask> taskList = new List<ADAITask>(); Console.Write("Getting settings..."); Task<GetEntityResponse<Settings>> settingsTask = couch.Entities.GetAsync<Settings>("settings"); settingsTask.Wait(); Settings settings; if (settingsTask.Result.IsSuccess) { settings = settingsTask.Result.Content; Console.WriteLine("done"); } else { settings = new Settings(); Console.WriteLine("error - using defaults"); } Console.WriteLine("Current settings: autoWatch = " + settings.autoWatch); Console.Write("Polling tasklist..."); QueryViewRequest req = new QueryViewRequest("tasks", "tasks").Configure(q => q.IncludeDocs(true)); Task<ViewQueryResponse<string, ADAITask>> queryTask = couch.Views.QueryAsync<string, ADAITask>(req); queryTask.Wait(); Console.WriteLine("done - " + queryTask.Result.TotalRows + " tasks fetched"); if (queryTask.Result.TotalRows == 0 && !settings.autoWatch) { Console.WriteLine("Finished! Waiting for next polling interval..."); return; } Console.Write("Connecting to " + DB + "..."); OracleConnection conn = null; try { conn = new OracleConnection(connString); conn.Open(); // Open session OracleCommand cmdOpenSession = new OracleCommand("e.env_session_intf#.open_session", conn); cmdOpenSession.CommandType = System.Data.CommandType.StoredProcedure; cmdOpenSession.ExecuteNonQuery(); Console.WriteLine("done"); OracleCommand cmd = new OracleCommand(); cmd.Connection = conn; cmd.CommandType = System.Data.CommandType.Text; // Copy task IDs to a list that we then use in an OracleParameter for the IN clause foreach (ViewQueryResponse<string, ADAITask>.Row row in queryTask.Result.Rows) { //taskIdList.Add(row.IncludedDoc.TaskID); OracleParameter par = new OracleParameter(":t" + cmd.Parameters.Count, OracleDbType.Int32); par.Value = row.IncludedDoc.TaskID; cmd.Parameters.Add(par); } StringBuilder inClause = new StringBuilder(); foreach (OracleParameter par in cmd.Parameters) { inClause.AppendFormat("{0},", par.ParameterName); } if (inClause.Length > 0) { inClause.Remove(inClause.Length - 1, 1); // Remove trailing comma } else { inClause.Append("null"); } StringBuilder q = new StringBuilder(); q.AppendLine("select env_task.id, env_task.name, env_wfc_status.name, env_release.user_id"); q.AppendLine(" from e.env_task, e.env_wfc_status, e.env_release, env_user"); q.AppendLine(" where env_task.env_wfc_status_id = env_wfc_status.id"); q.AppendLine(" and env_task.env_release_id = env_release.id"); q.AppendLine(" and env_task.resp_env_user_id = env_user.id"); q.AppendFormat(" and (env_task.id in ({0})", inClause); q.AppendLine(); // Also include new tasks not already watched? if (settings.autoWatch) { OracleParameter parUser = new OracleParameter(); parUser.OracleDbType = OracleDbType.Varchar2; parUser.ParameterName = ":oracle_user"; parUser.Value = username.ToUpper(); cmd.Parameters.Add(parUser); q.AppendFormat(" or env_user.oracle_user = {0}", parUser.ParameterName); q.AppendLine(); q.AppendLine(" and env_task.env_wfc_status_id in (2018 /* Integration Test Running */, 2015 /* Ready to Integrate */)"); } q.AppendLine(")"); cmd.CommandText = q.ToString(); Console.Write("Running query..."); Debug.WriteLine(cmd.CommandText); OracleDataReader reader = cmd.ExecuteReader(); Console.WriteLine("done"); foreach (ViewQueryResponse<string, ADAITask>.Row row in queryTask.Result.Rows) { taskList.Add(row.IncludedDoc); } while (reader.Read()) { ADAITask t = null; if (taskList.Exists(m => m.TaskID == reader.GetInt32(0))) { t = queryTask.Result.Rows.Where(e => e.IncludedDoc.TaskID == reader.GetInt32(0)).Single().IncludedDoc; } else { t = new ADAITask(reader.GetInt32(0)); taskList.Add(t); } t.TaskName = reader.GetString(1); t.TaskStatus = reader.GetString(2); t.TaskRelease = reader.GetString(3); t.LastUpdated = DateTime.Now; Debug.WriteLine("Task ID: " + t.TaskID + ", Task Name: " + t.TaskName + ", Task Status: " + t.TaskStatus + ", Task Release: " + t.TaskRelease); } reader.Close(); } catch (OracleException e) { Console.WriteLine(e.Message); return; } finally { if (conn != null) { conn.Close(); } } MyCouchStore store = new MyCouchStore(couch); foreach (ADAITask t in taskList) { Console.Write("Updating doc for task " + t.TaskID + "..."); Task<ADAITask> storeTask = store.StoreAsync<ADAITask>(t); storeTask.Wait(); Console.WriteLine("done"); } Console.WriteLine("Finished! Waiting for next polling interval..."); //GetChangesRequest getChangesRequest = new GetChangesRequest //{ // Feed = ChangesFeed.Normal //}; //Task<ChangesResponse> changesTask = store.Client.Changes.GetAsync(getChangesRequest); //changesTask.Wait(); //changeObserver.SetIgnoreUntilSeqNr(changesTask.Result.LastSeq); }
public CouchDbMobileProductRepository() { _store = MyCouchStoreFactory.Create(CouchDbConnection.Current, _dbName); }
public CouchDbLeadTypeRepository() { _store = MyCouchStoreFactory.Create(CouchDbConnection.Current, _dbName); }
static void WorkTimerCallback(object state) { MyCouchClient couch = (MyCouchClient)state; List <ADAITask> taskList = new List <ADAITask>(); Console.Write("Getting settings..."); Task <GetEntityResponse <Settings> > settingsTask = couch.Entities.GetAsync <Settings>("settings"); settingsTask.Wait(); Settings settings; if (settingsTask.Result.IsSuccess) { settings = settingsTask.Result.Content; Console.WriteLine("done"); } else { settings = new Settings(); Console.WriteLine("error - using defaults"); } Console.WriteLine("Current settings: autoWatch = " + settings.autoWatch); Console.Write("Polling tasklist..."); QueryViewRequest req = new QueryViewRequest("tasks", "tasks").Configure(q => q.IncludeDocs(true)); Task <ViewQueryResponse <string, ADAITask> > queryTask = couch.Views.QueryAsync <string, ADAITask>(req); queryTask.Wait(); Console.WriteLine("done - " + queryTask.Result.TotalRows + " tasks fetched"); if (queryTask.Result.TotalRows == 0 && !settings.autoWatch) { Console.WriteLine("Finished! Waiting for next polling interval..."); return; } Console.Write("Connecting to " + DB + "..."); OracleConnection conn = null; try { conn = new OracleConnection(connString); conn.Open(); // Open session OracleCommand cmdOpenSession = new OracleCommand("e.env_session_intf#.open_session", conn); cmdOpenSession.CommandType = System.Data.CommandType.StoredProcedure; cmdOpenSession.ExecuteNonQuery(); Console.WriteLine("done"); OracleCommand cmd = new OracleCommand(); cmd.Connection = conn; cmd.CommandType = System.Data.CommandType.Text; // Copy task IDs to a list that we then use in an OracleParameter for the IN clause foreach (ViewQueryResponse <string, ADAITask> .Row row in queryTask.Result.Rows) { //taskIdList.Add(row.IncludedDoc.TaskID); OracleParameter par = new OracleParameter(":t" + cmd.Parameters.Count, OracleDbType.Int32); par.Value = row.IncludedDoc.TaskID; cmd.Parameters.Add(par); } StringBuilder inClause = new StringBuilder(); foreach (OracleParameter par in cmd.Parameters) { inClause.AppendFormat("{0},", par.ParameterName); } if (inClause.Length > 0) { inClause.Remove(inClause.Length - 1, 1); // Remove trailing comma } else { inClause.Append("null"); } StringBuilder q = new StringBuilder(); q.AppendLine("select env_task.id, env_task.name, env_wfc_status.name, env_release.user_id"); q.AppendLine(" from e.env_task, e.env_wfc_status, e.env_release, env_user"); q.AppendLine(" where env_task.env_wfc_status_id = env_wfc_status.id"); q.AppendLine(" and env_task.env_release_id = env_release.id"); q.AppendLine(" and env_task.resp_env_user_id = env_user.id"); q.AppendFormat(" and (env_task.id in ({0})", inClause); q.AppendLine(); // Also include new tasks not already watched? if (settings.autoWatch) { OracleParameter parUser = new OracleParameter(); parUser.OracleDbType = OracleDbType.Varchar2; parUser.ParameterName = ":oracle_user"; parUser.Value = username.ToUpper(); cmd.Parameters.Add(parUser); q.AppendFormat(" or env_user.oracle_user = {0}", parUser.ParameterName); q.AppendLine(); q.AppendLine(" and env_task.env_wfc_status_id in (2018 /* Integration Test Running */, 2015 /* Ready to Integrate */)"); } q.AppendLine(")"); cmd.CommandText = q.ToString(); Console.Write("Running query..."); Debug.WriteLine(cmd.CommandText); OracleDataReader reader = cmd.ExecuteReader(); Console.WriteLine("done"); foreach (ViewQueryResponse <string, ADAITask> .Row row in queryTask.Result.Rows) { taskList.Add(row.IncludedDoc); } while (reader.Read()) { ADAITask t = null; if (taskList.Exists(m => m.TaskID == reader.GetInt32(0))) { t = queryTask.Result.Rows.Where(e => e.IncludedDoc.TaskID == reader.GetInt32(0)).Single().IncludedDoc; } else { t = new ADAITask(reader.GetInt32(0)); taskList.Add(t); } t.TaskName = reader.GetString(1); t.TaskStatus = reader.GetString(2); t.TaskRelease = reader.GetString(3); t.LastUpdated = DateTime.Now; Debug.WriteLine("Task ID: " + t.TaskID + ", Task Name: " + t.TaskName + ", Task Status: " + t.TaskStatus + ", Task Release: " + t.TaskRelease); } reader.Close(); } catch (OracleException e) { Console.WriteLine(e.Message); return; } finally { if (conn != null) { conn.Close(); } } MyCouchStore store = new MyCouchStore(couch); foreach (ADAITask t in taskList) { Console.Write("Updating doc for task " + t.TaskID + "..."); Task <ADAITask> storeTask = store.StoreAsync <ADAITask>(t); storeTask.Wait(); Console.WriteLine("done"); } Console.WriteLine("Finished! Waiting for next polling interval..."); //GetChangesRequest getChangesRequest = new GetChangesRequest //{ // Feed = ChangesFeed.Normal //}; //Task<ChangesResponse> changesTask = store.Client.Changes.GetAsync(getChangesRequest); //changesTask.Wait(); //changeObserver.SetIgnoreUntilSeqNr(changesTask.Result.LastSeq); }
public UserCouchRepository(IOptions <ConnectionStrings> connectionStrings, LanguageService languageService) { this.languageService = languageService; this.store = new MyCouchStore(connectionStrings.Value.CouchDb, "recipes"); }
public IngredientsRepository(IOptions <ConnectionStrings> connectionStrings) { this.store = new MyCouchStore(connectionStrings.Value.CouchDb, "recipes"); }
public async Task <string> Give([Author] Member author, Member reciever, [Rest] string amountText, MyCouchStore db) { if (author.Id == reciever.Id) { throw new CommandFailedException("You can't give to yourself."); } var amount = new Wallet(amountText); author.Wallet.Subtract(amount); reciever.Wallet.Add(amount); await db.StoreAsync(author); await db.StoreAsync(reciever); return($"{author} has given {reciever} {amount.ToString()}."); }
public bool LoadFrom(string couchdb_host, string db_name, string config_name = null, bool track_changes = false) { using (var couch_store = new MyCouchStore(couchdb_host, db_name)) { config_name = config_name ?? ((this.Config != null) ? this.Config.Id : typeof(T).Name); var task = couch_store.GetByIdAsync <T>(config_name); task.Wait(); if (task.Result != null) { if (task.Result.PreLoad()) { task.Result.OnLoad(); this.Config = task.Result; Logger.InfoFormat("Configuration is loaded from {0}/{1}/{2} successfully:\n\r{3}", couchdb_host, db_name, config_name, couch_store.Client.Serializer.Serialize(task.Result)); } else { Logger.InfoFormat("Failed to load configuration from {0}/{1}/{2}", couchdb_host, db_name, config_name); return(false); } } else { if (this.Config != null) { try { var write_task = couch_store.StoreAsync <T>(this.Config); write_task.Wait(); Logger.InfoFormat("Configuration does not exist on {0}/{1}/{2}. So wrote back {3}:\n\r{4}", couchdb_host, db_name, config_name, write_task.Result, couch_store.Client.Serializer.Serialize(this.Config)); } catch (Exception ex) { Logger.Warn("Failed to store back defaut configuration", ex); return(false); } } } } if (false == track_changes) { return(true); } throw new NotImplementedException("configuration tracking is not available now"); /* * var getChangesRequest = new GetChangesRequest * { * Feed = ChangesFeed.Continuous, * Heartbeat = 1000, * }; * * _couch_client = new MyCouchClient(couchdb_host, db_name); * _cancellation = new CancellationTokenSource(); * _couch_client.Changes.GetAsync(getChangesRequest, data => this.FeedData(data), _cancellation.Token); * * return true; */ }