public async Task<dynamic> GetAll()
        {
            try
            {
                var dbRef = new DbConnection();
                var client = dbRef.GetClient();
                //Create the DB if it does not exist.
                if (client.Database.GetAsync().Result.Error == "not_found")
                {
                    await dbRef.CreateDB();
                    //load with initial data
                    await client.Documents.PostAsync("{\"text\":\"Sample 1\"}");
                    await client.Documents.PostAsync("{\"text\":\"Sample 2\"}");
                    await client.Documents.PostAsync("{\"text\":\"Sample 3\"}");
                }
                //Query for all docs including full content of the docs.
                var query = new QueryViewRequest("_all_docs").Configure(query1 => query1.IncludeDocs(true));

                //GET
                RawResponse response = await client.Views.QueryRawAsync(query);
                if (response.IsSuccess)
                {
                    return response.Content;
                }
                else
                {
                    return "{\"msg\": \"Failure to GET. Status Code: " + response.StatusCode + ". Reason: " + response.Reason + "\"}";
                }
            }
            catch (Exception e)
            {
                return "{\"msg\": \"Failure to GET: " + e + "\"}";
            }
        }
Example #2
0
		async  Task<ViewQueryResponse<string>> GetPersonListAsync ()
		{
			List<MyPerson> database = new List<MyPerson>();
			string sourceDirectory = @"/Users/chrisk/source/KiwiRest/RestFiles/App_Data/files";
			AfisEngine Afis = new AfisEngine();
			DateTime date1 = DateTime.Now;
			Console.WriteLine("Starting PersonList:  " + date1);
			WebClient client = new WebClient ();
			string uri = "http://localhost:5984/prints/_all_docs&include_docs=true";
			//			string data = client.DownloadString (uri);
			//			var fromJson = JsonSerializer.DeserializeFromString<AllDocs>(data);
			var myCouchClient = new MyCouch.MyCouchClient("http://localhost:5984/prints");
			ViewQueryResponse<string> result = null;
			try 
			{
				var queryView = new QueryViewRequest("_all_docs");
				queryView.Configure(query => query
					.IncludeDocs(true));
				result = await myCouchClient.Views.QueryAsync<string>(queryView);
			}
			catch (Exception e) {
			}

			return result;
		}
Example #3
0
        public ViewsFixture()
        {
            Artists = ClientTestData.Artists.CreateArtists(10);

            Client = IntegrationTestsRuntime.CreateNormalClient();

            var bulk = new BulkRequest();
            bulk.Include(Artists.Select(i => Client.Entities.Serializer.Serialize(i)).ToArray());

            var bulkResponse = Client.Documents.BulkAsync(bulk).Result;

            foreach (var row in bulkResponse.Rows)
            {
                var artist = Artists.Single(i => i.ArtistId == row.Id);
                Client.Entities.Reflector.RevMember.SetValueTo(artist, row.Rev);
            }

            var tmp = Client.Documents.PostAsync(ClientTestData.Views.ArtistsViews).Result;

            var touchView1 = new QueryViewRequest(ClientTestData.Views.ArtistsAlbumsViewId).Configure(q => q.Stale(Stale.UpdateAfter));
            var touchView2 = new QueryViewRequest(ClientTestData.Views.ArtistsNameNoValueViewId).Configure(q => q.Stale(Stale.UpdateAfter));
            var touchView3 = new QueryViewRequest(ClientTestData.Views.ArtistsTotalNumOfAlbumsViewId).Configure(q => q.Stale(Stale.UpdateAfter));

            Client.Views.QueryAsync(touchView1).Wait();
            Client.Views.QueryAsync(touchView2).Wait();
            Client.Views.QueryAsync(touchView3).Wait();
        }
        public async Task<ActionResult> GetResult(int measurePoint, int minutesAgo)
        {
            var viewModel = new TrafficQueryViewModel();
            using (var client = new MyCouchClient("http://db-couchdb.cloudapp.net:5984", "bekk4"))
            {
                var startTime = DateTime.Now.Subtract(new TimeSpan(0, minutesAgo, 0)).ToString("O");
                var startKey = new object[] {measurePoint, startTime};
                var endKey = new object[] {measurePoint, DateTime.Now.ToString("O")};
                var carCountQuery = new QueryViewRequest("stats", "count").Configure(x => x.StartKey(startKey).EndKey(endKey));
                var carCountResult = await client.Views.QueryAsync(carCountQuery);
                var averageSpeedQuery = new QueryViewRequest("stats", "speed").Configure(x => x.StartKey(startKey).EndKey(endKey));
                var averageSpeedResult = await client.Views.QueryAsync(averageSpeedQuery);
                viewModel.MeasurePoint = measurePoint;
                var carCount = carCountResult.Rows.FirstOrDefault();
                if (carCount != null)
                    viewModel.NumberOfCars = int.Parse(carCount.Value);
                var averageSpeed = averageSpeedResult.Rows.FirstOrDefault();
                if (averageSpeed != null)
                {
                    viewModel.AverageSpeed = float.Parse(averageSpeed.Value, CultureInfo.InvariantCulture);
                }
            }

            return PartialView(viewModel);
        } 
Example #5
0
 public async static Task<ViewQueryResponse<PropertyType>> Get()
 {
     using (var db = Database.Connect())
     {
         var query = new QueryViewRequest("propertytypes", "all").Configure(q => q.Limit(300).Reduce(false));
         return await db.Views.QueryAsync<PropertyType>(query);
     }
 }
Example #6
0
 public async static Task<ViewQueryResponse<Property>> Get(string ReferenceCode)
 {
     using (var db = Database.Connect())
     {
         var query = new QueryViewRequest("properties", "all").Configure(q => q.Key<string>(ReferenceCode).Reduce(false));
         return await db.Views.QueryAsync<Property>(query);
     }
 }
 // GET api/values
 public IEnumerable<object> Get()
 {
     using (var client = new MyCouchClient("http://db-couchdb.cloudapp.net:5984", "bekk4"))
     {
         var query = new QueryViewRequest("test", "all").Configure(q => q.Reduce(false));
         var result = client.Views.QueryAsync(query).Result;
         return result.Rows.Select(row => row.Value);
     }
 }
 // GET: OverView
 public async Task<ActionResult> Index()
 {
     var viewModel = new OverviewViewModel();
     using (var client = new MyCouchClient("http://db-couchdb.cloudapp.net:5984", "bekk4"))
     {
         var query = new QueryViewRequest("test", "measurepoints").Configure(x => x.Group(true));
         var result = await client.Views.QueryAsync(query);
         viewModel.MeasurementPoints = result.Rows.Select(x => x.Key);
     }
     return View(viewModel);
 }
        public virtual HttpRequest Create(QueryViewRequest request)
        {
            Ensure.That(request, "request").IsNotNull();

            var httpRequest = request.HasKeys
                ? new HttpRequest(HttpMethod.Post, GenerateRelativeUrl(request)).SetJsonContent(GenerateRequestBody(request))
                : new HttpRequest(HttpMethod.Get, GenerateRelativeUrl(request));

            httpRequest.SetRequestTypeHeader(request.GetType());

            return httpRequest;
        }
Example #10
0
	     public static List<MyPerson> GetPersonList ()
		{
			List<MyPerson> database = new List<MyPerson>();
			string sourceDirectory = @"/Users/chrisk/source/KiwiRest/RestFiles/App_Data/files";
			AfisEngine Afis = new AfisEngine();
			DateTime date1 = DateTime.Now;
			Console.WriteLine("Starting PersonList:  " + date1);
			WebClient client = new WebClient ();
			string uri = "http://localhost:5984/prints/_all_docs&include_docs=true";
//			string data = client.DownloadString (uri);
//			var fromJson = JsonSerializer.DeserializeFromString<AllDocs>(data);
			var myCouchClient = new MyCouch.MyCouchClient("http://localhost:5984/prints");
			try 
			{
				var queryView = new QueryViewRequest("_all_docs");
				queryView.Configure(query => query
					.IncludeDocs(true));
			}
			catch (Exception e) {
			}

			try
			{
				var files = Directory.EnumerateFiles(sourceDirectory, "*.png");

				foreach (string currentFile in files)
				{
					DateTime date3 = DateTime.Now;
					Console.WriteLine("Processing " + currentFile + " at " + date3);
					string fileName = currentFile.Substring(sourceDirectory.Length + 1);
					//					Directory.Move(currentFile, Path.Combine(archiveDirectory, fileName));
					Guid g = Guid.NewGuid ();
					var guidStr = g.ToString ();
					MyPerson probe = SourceAfisIdentify.Enroll (currentFile, guidStr, Afis);
					Console.WriteLine("Adding " + guidStr);
					DateTime date4 = DateTime.Now;
					Console.WriteLine("Processed  " + currentFile + " at " + date4 + " uuid: " + guidStr);
					var diffInSeconds = (date4 - date3).TotalSeconds;
					Console.WriteLine("Finished " + guidStr + " at " + date4 + " Total time: " + diffInSeconds + " seconds");
					database.Add (probe);
				}
				DateTime date2 = DateTime.Now;
				var diffInSeconds2 = (date2 - date1).TotalSeconds;
				Console.WriteLine("Finished PersonList at " + date2 + " Total time: " + diffInSeconds2 + " seconds");
			}
			catch (Exception e)
			{
				Console.WriteLine(e.Message);
			}

			return database;
		}
        /// <summary>
        /// Returns all configured options of <see cref="QueryViewRequest"/> as key values.
        /// The values are formatted to JSON-compatible strings.
        /// </summary>
        /// <returns></returns>
        protected virtual IDictionary<string, string> GenerateJsonCompatibleKeyValues(QueryViewRequest request)
        {
            var kvs = new Dictionary<string, string>();

            if (request.IncludeDocs.HasValue)
                kvs.Add(KeyNames.IncludeDocs, Serializer.ToJson(request.IncludeDocs.Value));

            if (request.Descending.HasValue)
                kvs.Add(KeyNames.Descending, Serializer.ToJson(request.Descending.Value));

            if (request.Reduce.HasValue)
                kvs.Add(KeyNames.Reduce, Serializer.ToJson(request.Reduce.Value));

            if (request.InclusiveEnd.HasValue)
                kvs.Add(KeyNames.InclusiveEnd, Serializer.ToJson(request.InclusiveEnd.Value));

            if (request.UpdateSeq.HasValue)
                kvs.Add(KeyNames.UpdateSeq, Serializer.ToJson(request.UpdateSeq.Value));

            if (request.Group.HasValue)
                kvs.Add(KeyNames.Group, Serializer.ToJson(request.Group.Value));

            if (request.GroupLevel.HasValue)
                kvs.Add(KeyNames.GroupLevel, Serializer.ToJson(request.GroupLevel.Value));

            if (request.Stale.HasValue)
                kvs.Add(KeyNames.Stale, request.Stale.Value.AsString());

            if (request.Key != null)
                kvs.Add(KeyNames.Key, Serializer.ToJson(request.Key));

            if (request.StartKey != null)
                kvs.Add(KeyNames.StartKey, Serializer.ToJson(request.StartKey));

            if (!string.IsNullOrWhiteSpace(request.StartKeyDocId))
                kvs.Add(KeyNames.StartKeyDocId, request.StartKeyDocId);

            if (request.EndKey != null)
                kvs.Add(KeyNames.EndKey, Serializer.ToJson(request.EndKey));

            if (!string.IsNullOrWhiteSpace(request.EndKeyDocId))
                kvs.Add(KeyNames.EndKeyDocId, request.EndKeyDocId);

            if (request.Limit.HasValue)
                kvs.Add(KeyNames.Limit, Serializer.ToJson(request.Limit.Value));

            if (request.Skip.HasValue)
                kvs.Add(KeyNames.Skip, Serializer.ToJson(request.Skip.Value));

            return kvs;
        }
        protected virtual string GenerateRelativeUrl(QueryViewRequest request)
        {
            if (request.ViewIdentity is SystemViewIdentity)
            {
                return string.Format("/{0}{1}",
                    request.ViewIdentity.Name,
                    GenerateRequestUrlQueryString(request));
            }

            return string.Format("/_design/{0}/_view/{1}{2}",
                request.ViewIdentity.DesignDocument,
                request.ViewIdentity.Name,
                GenerateRequestUrlQueryString(request));
        }
Example #13
0
        /// <summary>
        /// Retrieves all Submission ids for the comments in the comment database
        /// </summary>
        /// <returns>Set of all submission id strings</returns>
        public HashSet<string> fetchCommentSubmissions()
        {
            HashSet<string> hs = new HashSet<string>();

            Console.WriteLine("Querying view");
            var query1 = new QueryViewRequest("parentids", "all");
            //query1.Configure(cfg => cfg.Limit(5));

            ViewQueryResponse<string> result = client1.Views.QueryAsync<string>(query1).Result;

            foreach (var row in result.Rows) {
                hs.Add(row.KeyAsString());
            }

            Console.WriteLine(result.RowCount);
            return hs;
        }
Example #14
0
        /// <summary>
        /// Will return IndexEntry objects upto the specified limit. 
        /// </summary>
        /// <param name="limit"></param>
        /// <returns></returns>
        public List<IndexEntry> fetchIndex(int limit = 10000, int startIndex = 0)
        {
            List<IndexEntry> ids = new List<IndexEntry>();

            //Use the system view _all_docs to fetch the data
            var query = new QueryViewRequest("_all_docs");
            query.Limit = limit;
            query.Skip = startIndex;
            //Only the index will be returned otherwise
            query.IncludeDocs = true;
            var rData = CorpusIndexClient.Views.QueryAsync<dynamic>(query).Result;

            foreach (var row in rData.Rows) {
                IndexEntry ie = JsonConvert.DeserializeObject<IndexEntry>(row.IncludedDoc);
                ids.Add(ie);
            }

            return ids;
        }
        public virtual HttpRequest Create(QueryViewRequest request)
        {
            Ensure.That(request, "request").IsNotNull();

            var httpRequest = request.HasKeys
                ? new HttpRequest(HttpMethod.Post, GenerateRelativeUrl(request)).SetJsonContent(GenerateRequestBody(request))
                : new HttpRequest(HttpMethod.Get, GenerateRelativeUrl(request));

            httpRequest.SetRequestTypeHeader(request.GetType());

            if (request.HasAccepts)
                httpRequest.SetAcceptHeader(request.Accepts);
            else
            {
                if (!string.IsNullOrWhiteSpace(request.ListName))
                    httpRequest.SetAcceptHeader(HttpContentTypes.Json, HttpContentTypes.Html);
            }

            return httpRequest;
        }
        protected virtual string GenerateRelativeUrl(QueryViewRequest request)
        {
            if (request.ViewIdentity is SystemViewIdentity)
            {
                return string.Format("/{0}{1}",
                    new UrlSegment(request.ViewIdentity.Name),
                    GenerateRequestUrlQueryString(request));
            }

            if (!string.IsNullOrWhiteSpace(request.ListName))
                return string.Format("/_design/{0}/_list/{1}/{2}{3}",
                    new UrlSegment(request.ViewIdentity.DesignDocument),
                    new UrlSegment(request.ListName),
                    new UrlSegment(request.ViewIdentity.Name),
                    GenerateRequestUrlQueryString(request));

            return string.Format("/_design/{0}/_view/{1}{2}",
                new UrlSegment(request.ViewIdentity.DesignDocument),
                new UrlSegment(request.ViewIdentity.Name),
                GenerateRequestUrlQueryString(request));
        }
		public async Task<IEnumerable<TShirt>> GetAll()
		{
			Task<ViewQueryResponse<TShirt>> tshirtTask;
			ViewQueryResponse<TShirt> tshirtResult;
			List<TShirt> tshirts = null;

			// TODO: inject client or replace client with store
			using (var client = new MyCouchClient("http://localhost:5984", "cshirts")) {
				var query = new QueryViewRequest("getAllTshirts");
				tshirtTask = client.Views.QueryAsync<TShirt>(query);
			}

			tshirtResult = await tshirtTask;

			foreach (var row in tshirtResult.Rows) {				
				var tshirt = new TShirt ();
				tshirt = row.Value;
				tshirts.Add (tshirt);
			}
			Console.WriteLine (tshirts);
			return tshirts;
		}
        public async Task <User> Ask(FindByLogin criterion)
        {
            var query =
                new CouchRequest.QueryViewRequest(DbConsts.DesignDocumentName, DbConsts.ByLoginDocsViewName)
                .Configure(q => q.Key(criterion.Login));

            var viewResult = await _couchWrapper.GetResponseAsync(async (client) =>
            {
                return(await client.Views.QueryAsync <UserDto>(query));
            });

            if (viewResult.Rows.Length == 0)
            {
                return(null);
            }

            if (viewResult.Rows.Length > 1)
            {
                throw new Exception(String.Format("several records found by login {0}", criterion.Login));
            }

            return(_autoMapper.Map <User>(viewResult.Rows.Single().Value));
        }
Example #19
0
//		async  Task<ViewQueryResponse<string>> GetPersonListAsync ()
		async  Task GetPersonListAsync (Container container)
		{
			//List<MyPerson> database = new List<MyPerson>();
			//List<MyPerson> database = FilesService.Database;

			//string sourceDirectory = @"/Users/chrisk/source/KiwiRest/RestFiles/App_Data/files";
			//AfisEngine Afis = new AfisEngine();
			DateTime date1 = DateTime.Now;
			Console.WriteLine("Starting FingerprintDatabase:  " + date1);
//			WebClient client = new WebClient ();
			//string uri = "http://localhost:5984/prints/_all_docs&include_docs=true";
			//			string data = client.DownloadString (uri);
			//			var fromJson = JsonSerializer.DeserializeFromString<AllDocs>(data);
			var myCouchClient = new MyCouch.MyCouchClient("http://localhost:5984/prints");
			ViewQueryResponse<string> result = null;
			try 
			{
				var queryView = new QueryViewRequest("_all_docs");
				queryView.Configure(query => query
					.IncludeDocs(true));
				result = await myCouchClient.Views.QueryAsync<string>(queryView);
				var rows = result.Rows;

//				foreach (ViewQueryResponse<SimpleFingerprint> row in rows)
				foreach (ViewQueryResponse<string,string>.Row row in rows)
				{
					Console.WriteLine("Lookin' at " + row);
					string doc = row.IncludedDoc;
					var person = new MyPerson ();
//					SimpleFingerprint print = TypeSerializer.DeserializeFromString<SimpleFingerprint>(doc);
					var jsonObj = JsonSerializer.DeserializeFromString<JsonObject>(doc);
					person._id = jsonObj["_id"];
					var jsonFingerprints = jsonObj["simpleFingerprint"];
					//var Filename = jsonObj["Filename"];
//					var serialFingerprints = JsonSerializer.DeserializeFromString<List<JsonObject>>(jsonFingerprints);
					var serialFingerprints = JsonArrayObjects.Parse(jsonFingerprints);
					//var fps = JsonSerializer.DeserializeFromString<Dictionary<string, string>>(jsonFingerprints);
					//var fp = JsonSerializer.DeserializeFromString<JsonObject>(jsonObj["simpleFingerprint"]);
					//SimpleFingerprint sf = JsonSerializer.DeserializeFromString<SimpleFingerprint>(jsonObj["simpleFingerprint"]);
					List<Fingerprint> fingerprints = new List<Fingerprint> ();
					foreach (KeyValuePair<string,string> pair in serialFingerprints[0]) {
						Fingerprint simpleFingerprint = new Fingerprint ();
						String value = pair.Value;
						if (value != null)
						{
							char[] delimiterChars = { ':' };
							string[] printPair = value.Split(delimiterChars);
							if (printPair[0] == "Base64Template")
							{
								byte[] printArray = System.Convert.FromBase64String(printPair[1]);
								simpleFingerprint.Template = printArray;
								fingerprints.Add(simpleFingerprint);
							}
						}
						//var print = printPair[1];
						//byte[] printArray = System.Convert.FromBase64String(print);
						//simpleFingerprint.Template = printArray;
//						simpleFingerprint.Filename = Filename;
						//fingerprints.Add(simpleFingerprint);
//						foreach (KeyValuePair<string,string> pair in fprint) {
//							SimpleFingerprint simpleFingerprint = new SimpleFingerprint ();
//							var strBase64Template = JsonSerializer.DeserializeFromString<string>(pair.Key);
////							simpleFingerprint.Base64Template = strBase64Template["Base64Template"];
//							fingerprints.Add(simpleFingerprint);
//						}

					}
//					foreach (KeyValuePair<string,string> pair in serialFingerprints)
//					{
//						var prints = JsonSerializer.DeserializeFromString<JsonObject>(pair.Key);
//						foreach (KeyValuePair<string,string> print in prints)
//						{
//							SimpleFingerprint simpleFingerprint = new SimpleFingerprint ();
//							var strBase64Template = JsonSerializer.DeserializeFromString<string>(print.Key);
////							simpleFingerprint.Base64Template = print["Base64Template"];
//							fingerprints.Add(simpleFingerprint);
//						}
//					}
					person.Fingerprints = fingerprints;
					//person.Filename = jsonObj["Filename"];
					person.Uuid = jsonObj["Uuid"];
					//database.Add(person);
					FingerprintDatabase.AddData(person);
					Console.WriteLine("Added person to FingerprintDatabase.");
				}
				//container.Register(database);

			}
			catch (Exception e) {
				Console.WriteLine("Error: " + e);
			}

//			return result;
		}
Example #20
0
        private static void ClearAllDocuments(string dbName)
        {
            using (var client = CreateDbClient(dbName))
            {
                if (client.Database.HeadAsync().Result.StatusCode == HttpStatusCode.NotFound)
                    return;

                var query = new QueryViewRequest(SystemViewIdentity.AllDocs).Configure(q => q.Stale(Stale.UpdateAfter));
                var response = client.Views.QueryAsync<dynamic>(query).Result;

                BulkDelete(client, response);

                response = client.Views.QueryAsync<dynamic>(query).Result;

                BulkDelete(client, response);
            }
        }
 protected virtual string GenerateRequestBody(QueryViewRequest request)
 {
     return request.HasKeys
         ? Serializer.Serialize(new { keys = request.Keys })
         : "{}";
 }
        protected virtual string GenerateRequestUrlQueryString(QueryViewRequest request)
        {
            var p = GenerateQueryStringParams(request);

            return string.IsNullOrEmpty(p) ? string.Empty : string.Concat("?", p);
        }
        private async Task StartRebuildViews(MyCouchClient client, SiaqodbDocument crObjForUpdateViews)
        {
            //force building the index at Store time avoiding to wait on Query time
            if (crObjForUpdateViews.Tags != null)
            {
                foreach (string tagName in crObjForUpdateViews.Tags.Keys)
                {
                    string viewName = "tags_" + tagName;
                    QueryViewRequest query = new QueryViewRequest(viewName, viewName);
                    query.Stale = Stale.UpdateAfter;
                    query.Limit = 1;
                    var res = await client.Views.QueryAsync(query);

                }
            }
        }
Example #24
0
        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);
        }
        private async Task CheckTagsViews(MyCouchClient client, string bucketName, Dictionary<string, object> tags)
        {
            if (tags != null && tags.Count > 0)
            {
                HashSet<string> viewsCache = new HashSet<string>();


                QueryViewRequest query = new QueryViewRequest("_all_docs");
                query.StartKey = "_design/";
                query.EndKey = "_design0";

                var all =await client.Views.QueryAsync(query);
                if (!all.IsSuccess)
                    CheckBucketNotFound(bucketName, all);
                if (all.Rows != null)
                {
                    foreach (var row in all.Rows)
                    {
                        string viewName = row.Key.ToString().Replace("_design/", "");
                        viewsCache.Add(viewName);

                    }
                }


                foreach (string tagName in tags.Keys)
                {
                    string viewName = "tags_" + tagName;
                    if (!viewsCache.Contains(viewName) && tags[tagName] != null)
                    {

                        string viewJSON = @"{""_id"":""_design/" + viewName + @""",""language"":""javascript"",""views"":{""" + viewName + @""":{""map"":
                            ""function(doc) {if(doc.tags." + tagName + @"!=null)emit(doc.tags." + tagName + @", null);}""}}}";
                        var getJson = await client.Documents.PostAsync(viewJSON);
                        if (!getJson.IsSuccess)
                            CheckBucketNotFound(bucketName, getJson);
                        viewsCache.Add(viewName);



                    }
                }

            }


        }
 protected virtual string GenerateQueryStringParams(QueryViewRequest request)
 {
     return string.Join("&", GenerateJsonCompatibleKeyValues(request)
         .Select(kv => string.Format("{0}={1}", kv.Key, Uri.EscapeDataString(kv.Value))));
 }