/// <summary>
        /// 
        /// </summary>
        /// <param name="queryResult"></param>
        public QueryResultEventArgs(IQueryResult queryResult)
        {
            if (queryResult == null)
                throw new ArgumentNullException("queryResult", "The queryResult object cannot be null.");

            this.queryResult = queryResult;
        }
Example #2
0
        public ChainedResult(IQueryResult basicResult, Func<Task<IQueryResult>> nextResult)
        {
            if (basicResult == null) throw new ArgumentNullException("basicResult");
            if (nextResult == null) throw new ArgumentNullException("nextResult");

            _basicResult = basicResult;
            _nextResult = nextResult;
        }
Example #3
0
		public void DoQuery (Query query, IQueryResult result, IQueryableChangeData change_data)
		{
			try {
				iqueryable.DoQuery (query, result, change_data);
			} catch (Exception ex) {
				Logger.Log.Warn (ex, "Caught exception calling DoQuery on '{0}'", Name);
			}
		}
		public void DoQuery (Query query, IQueryResult result, IQueryableChangeData data)
		{
			// Get rid of the standard UnixTransport so that we can
			// forward our local query to remote hosts.
			query.Transports.Clear ();

			List<string[]> network_services = Conf.Networking.GetListOptionValues (Conf.Names.NetworkServices);
			if (network_services != null) {
				foreach (string[] service in network_services)
					query.RegisterTransport (new HttpTransport (service [1]));
			}

			// Anonymous delegates cannot be un-registered ... hence
			Query.HitsAdded hits_added_handler;
			hits_added_handler = delegate (HitsAddedResponse response) {
								//Console.WriteLine ("Adding hits added response");
                                                                TransformResponse(response);
								result.Add (response.Hits, response.NumMatches);
						};

			Query.HitsSubtracted hits_subtracted_handler;
			hits_subtracted_handler = delegate (HitsSubtractedResponse response) {
								// Console.WriteLine ("Adding hits subtracted response");
								result.Subtract (response.Uris);
						    };

			Query.Finished finished_handler;
			finished_handler = delegate (FinishedResponse response) {
							//Console.WriteLine ("Adding finished response");
							// NO-OP
					    };

			// FIXME: ClosedEvent ? Should be handled by HttpTransport but should we do something more

			query.HitsAddedEvent += hits_added_handler;
			query.HitsSubtractedEvent += hits_subtracted_handler;
			query.FinishedEvent += finished_handler;

			Exception throw_me = null;

			try {
				query.SendAsyncBlocking ();
			} catch (Exception ex) {
				throw_me = ex;
			}

			// FIXME FIXME FIXME: Live query does not work!

			query.HitsAddedEvent -= hits_added_handler;
			query.HitsSubtractedEvent -= hits_subtracted_handler;
			query.FinishedEvent -= finished_handler;
			query.Transports.Clear ();

			if (throw_me != null)
				throw throw_me;

			return;
		}
Example #5
0
		public void DoQuery (Query query, IQueryResult result, IQueryableChangeData data)
		{
			string search = null;
			foreach (QueryPart qp in query.Parts) {
				if (qp is QueryPart_Text) {
					search = ((QueryPart_Text) qp).Text;
					break;
				}
			}

			if (String.IsNullOrEmpty (search))
				return;

			SafeProcess pc = new SafeProcess ();
			// Double the max-hits since it is hard to tell locate to ignore
			// hidden files and directories; so we prune them later.
			// So if hidden files are returned first, you are doomed
			pc.Arguments = new string[] { "locate", "-P", "-e", "-l", (2 * query.MaxHits).ToString (), search };
			pc.RedirectStandardOutput = true;
			pc.RedirectStandardError = false;
			pc.UseLangC = true;

			try {
				pc.Start ();
			} catch (Beagle.Util.SafeProcessException e) {
				Log.Error (e, "Error while running 'locate -P -e -l {0} {1}'", (2 * query.MaxHits), search);
				return;
			}

			string match = null;
			ArrayList result_batch = new ArrayList ();
			const int MAX_QUEUED_HITS = 25;
			Hit hit;
			int count = 0;

			using (StreamReader pout = new StreamReader (pc.StandardOutput)) {
				while (count < query.MaxHits && ! pout.EndOfStream) {
					match = pout.ReadLine ();
					hit = PathToHit (match);
					if (hit == null)
						continue;

					result_batch.Add (hit);

					if (result_batch.Count >= MAX_QUEUED_HITS) {
						result.Add (result_batch);
						result_batch.Clear ();
					}
					count ++;
				}
			}

			result.Add (result_batch, count);

			pc.Close ();
		}
Example #6
0
		public void DoQuery (Query query,
				     IQueryResult result,
				     IQueryableChangeData changeData)
		{
			Logger.Log.Debug ("Kicking off a bugzilla query");
			// FIXME - hard coding the url here
                        XmlDocument xml = GetBugzillaXml (query.QuotedText);
                        if (xml != null) {
				Hit hit = XmlBugToHit (xml, query.QuotedText);
				if (hit != null)
					result.Add (hit);
			}
		}
Example #7
0
 public ServiceQueryResult(IQueryResult myQueryResult)
 {
     this.Duration = myQueryResult.Duration;
     if (myQueryResult.Error != null)
         this.Error = myQueryResult.Error.Message;
     else
         this.Error = null;
     this.NameOfQueryLanguage = myQueryResult.NameOfQuerylanguage;
     this.NumberOfAffectedVertices = myQueryResult.NumberOfAffectedVertices;
     this.Query = myQueryResult.Query;
     if (myQueryResult.TypeOfResult == ResultType.Successful)
         this.TypeOfResult = ServiceResultType.Successful;
     else if (myQueryResult.TypeOfResult == ResultType.Failed)
         this.TypeOfResult = ServiceResultType.Failed;
     this.Vertices = myQueryResult.Vertices.Select(x => new ServiceVertexView(x)).ToList();
 }
		public IAsyncResult DoQuery (Query query,  IQueryResult result,
				     					IQueryableChangeData changeData)
		{
      		ICollection l;
     		
			SearchRequest sreq = new SearchRequest();

      		l = query.Text;
      		if ((l != null) && (l.Count > 0))
				sreq.text = ICollection2StringList(query.Text);
					
      		l = query.MimeTypes;
      		if ((l != null) && (l.Count > 0))					
				sreq.mimeType = ICollection2StringList(query.MimeTypes);

			l = query.Sources;
      		if ((l != null) && (l.Count > 0))						
				sreq.searchSources = ICollection2StringList(query.Sources);
				
			sreq.qdomain = QueryDomain.Global; //Caution: This Enables Cascaded NetBeagle searching !
			//sreq.qdomain = QueryDomain.System;
			
			//Cache the query request, get a unique searchId and include in network searchRequest:
			sreq.searchId = NetworkedBeagle.AddRequest(query);

			
			int hc = NetworkedBeagle.HopCount(query);
			sreq.hopCount = (hc > 0) ? hc:1;

			log.Info("NetBeagleHandler: Starting WebService Query for " + Hostname + ":" + Port);
			
			ReqContext rc = new ReqContext(wsp, result, netBeagleQueryable);
				
			IAsyncResult ar = wsp.BeginBeagleQuery(sreq, DoQueryResponseHandler, rc);

			// Return w/o waiting for Async query to complete.	
			// Return IAsynResult handle, to allow caller to control it, if required. 
					   				
			return ar;
		}
Example #9
0
        public string GenerateOutputResult(IQueryResult myQueryResult, Dictionary<String, String> myParams)
        {
            var result = new SchemaToClassesGenerator.Result();

            result.Version = IOInterfaceCompatibility.MaxVersion.ToString();

            result.Query = new Query() { Duration = myQueryResult.Duration, ResultType = Enum.GetName(typeof(ResultType), myQueryResult.TypeOfResult), Language = myQueryResult.NameOfQuerylanguage, Value = myQueryResult.Query, VerticesCount = myQueryResult.Vertices.LongCount(), Error = myQueryResult.Error == null ? null : HandleQueryExceptions(myQueryResult) };

            List<SchemaToClassesGenerator.VertexView> vertices = new List<SchemaToClassesGenerator.VertexView>();

            foreach (var aVertex in myQueryResult.Vertices)
            {
                vertices.Add(GenerateVertexView(aVertex));
            }

            result.VertexViews = vertices.ToArray();
            
            var stream = new MemoryStream();

            var writer = new System.Xml.Serialization.XmlSerializer(result.GetType());
            writer.Serialize(stream, result);

            return System.Text.Encoding.UTF8.GetString(stream.ToArray());
        }
Example #10
0
        /// <summary>
        /// generate link list needed for visual graph out of query result
        /// <param name="myQueryResult">The query result.</param>
        /// <param name="Links">out parameter returning list of NodeLink classes</param>
        /// </summary>
        private void GenerateLinkList( IQueryResult myQueryResult, List<string> Nodes, out List<NodeLink> Links)
        {
            Links = new List<NodeLink>();

            if (Nodes.Count() <= 0) return;

            GenerateLinkList_AnalyzeVertices(myQueryResult.Vertices, Nodes, ref Links);
        }
        public IQueryResult <RoleModel> Execute()
        {
            IQueryResult <RoleModel> result = null;
            RoleModel model = null;

            try
            {
                model = this.Build();
            }
            catch (Exception ex)
            {
                result = new QueryResult <RoleModel>()
                {
                    b_Successful   = false,
                    s_ErrorMessage = ex.Message,
                    i_AffectedRows = 0,
                    i_CountPages   = 0,
                    i_CountRecords = 0,
                    i_CountTotal   = 0,
                    i_InsertId     = 0,
                    o_Records      = null,
                    o_ScalarValue  = null
                };
                return(result);
            }
            switch (callingMethod)
            {
            case "create":
                result = providingController.Connection.Create <RoleModel>(model);
                break;

            case "retrieve":
                var rq = new QueryBuilder <RoleModel>();
                if (model.IsChanged(x => x.ID))
                {
                    rq.Where(x => x.ID, model.ID);
                }
                if (model.IsChanged(x => x.Name))
                {
                    rq.Where(x => x.Name, model.Name);
                }
                if (model.IsChanged(x => x.Description))
                {
                    rq.Where(x => x.Description, model.Description);
                }
                if (model.IsChanged(x => x.Mode))
                {
                    rq.Where(x => x.Mode, model.Mode);
                }
                result = providingController.Connection.Retrieve <RoleModel>(rq.Build());
                rq     = null;
                break;

            case "count":
                var cq = new QueryBuilder <RoleModel>();
                if (model.IsChanged(x => x.ID))
                {
                    cq.Where(x => x.ID, model.ID);
                }
                if (model.IsChanged(x => x.Name))
                {
                    cq.Where(x => x.Name, model.Name);
                }
                if (model.IsChanged(x => x.Description))
                {
                    cq.Where(x => x.Description, model.Description);
                }
                if (model.IsChanged(x => x.Mode))
                {
                    cq.Where(x => x.Mode, model.Mode);
                }
                result = providingController.Connection.Count <RoleModel>(cq.Build());
                cq     = null;
                break;

            case "find":
                var fq = new QueryBuilder <RoleModel>();
                if (model.IsChanged(x => x.ID))
                {
                    fq.Where(x => x.ID, model.ID, QueryComparisonOperators.IsLike);
                }
                if (model.IsChanged(x => x.Name))
                {
                    fq.Where(x => x.Name, model.Name, QueryComparisonOperators.IsLike);
                }
                if (model.IsChanged(x => x.Description))
                {
                    fq.Where(x => x.Description, model.Description, QueryComparisonOperators.IsLike);
                }
                if (model.IsChanged(x => x.Mode))
                {
                    fq.Where(x => x.Mode, model.Mode, QueryComparisonOperators.IsLike);
                }
                result = providingController.Connection.Retrieve <RoleModel>(fq.Build());
                rq     = null;
                break;

            case "update":
                var uq = new QueryBuilder <RoleModel>().Where(x => x.ID, model.ID).Build();
                result = providingController.Connection.Update <RoleModel>(uq, model);
                uq     = null;
                break;

            case "delete":
                var ud = new QueryBuilder <RoleModel>().Where(x => x.ID, model.ID).Build();
                result = providingController.Connection.Delete <RoleModel>(ud);
                ud     = null;
                break;
            }
            if (result == null)
            {
                throw new NotImplementedException(callingMethod + " not implemented for execution.");
            }
            return(result);
        }
Example #12
0
        public override IQueryResult Execute(IGraphDB myGraphDB, IGraphQL myGraphQL, GQLPluginManager myPluginManager, String myQuery, SecurityToken mySecurityToken, Int64 myTransactionToken)
        {
            Stopwatch sw = Stopwatch.StartNew();

            _query = myQuery;
            IQueryResult   result   = null;
            String         myAction = "";
            List <IVertex> myToBeUpdatedVertices = new List <IVertex>();

            //prepare
            var vertexType = myGraphDB.GetVertexType <IVertexType>(
                mySecurityToken,
                myTransactionToken,
                new RequestGetVertexType(_type),
                (stats, vtype) => vtype);

            if (_whereExpression != null)
            {
                //validate
                _whereExpression.Validate(myPluginManager, myGraphDB, mySecurityToken, myTransactionToken, vertexType);

                //calculate
                var expressionGraph = _whereExpression.Calculon(myPluginManager, myGraphDB, mySecurityToken, myTransactionToken, new CommonUsageGraph(myGraphDB, mySecurityToken, myTransactionToken), false);

                //extract
                myToBeUpdatedVertices = expressionGraph.Select(new LevelKey(vertexType.ID, myGraphDB, mySecurityToken, myTransactionToken), null, true).ToList();
            }

            switch (myToBeUpdatedVertices.Count)
            {
            case 0:

                //insert
                result = ProcessInsert(myGraphDB, myPluginManager, mySecurityToken, myTransactionToken);

                myAction = "Inserted";

                break;

            case 1:

                //delete
                ProcessDelete(myToBeUpdatedVertices[0], myGraphDB, myPluginManager, mySecurityToken, myTransactionToken);

                //insert
                result = ProcessInsert(myGraphDB, myPluginManager, mySecurityToken, myTransactionToken);

                myAction = "Replaced";

                break;

            default:
                //error
                throw new NotImplementedQLException("It's currenty not implemented to InsertOrReplace more than one vertex");
            }

            if (result.Error != null)
            {
                throw result.Error;
            }

            return(GenerateResult(sw.ElapsedMilliseconds, result, myAction));
        }
		////////////////////////////////////////////////////////////////

		public void DoQuery (Query               query,
				     IQueryResult        result,
				     ICollection         search_subset_uris, // should be internal uris
				     QueryPartHook       query_part_hook,
				     HitFilter           hit_filter)
		{
			if (Debug)
				Logger.Log.Debug ("###### {0}: Starting low-level queries", IndexName);

			Stopwatch total, a, b, c, d, e, f;

			total = new Stopwatch ();
			a = new Stopwatch ();
			b = new Stopwatch ();
			c = new Stopwatch ();
			d = new Stopwatch ();
			e = new Stopwatch ();
			f = new Stopwatch ();

			total.Start ();
			a.Start ();

			ArrayList primary_required_part_queries;
			ArrayList secondary_required_part_queries;

			LNS.BooleanQuery primary_prohibited_part_query;
			LNS.BooleanQuery secondary_prohibited_part_query;

			AndHitFilter all_hit_filters;

			ArrayList term_list;

			// Assemble all of the parts into a bunch of Lucene queries

			term_list = AssembleQuery (query,
				query_part_hook,
				hit_filter,
				out primary_required_part_queries,
				out secondary_required_part_queries,
				out primary_prohibited_part_query,
				out secondary_prohibited_part_query,
				out all_hit_filters);

			a.Stop ();
			if (Debug)
				Log.Debug ("###### {0}: Building queries took {1}", IndexName, a);

			// If we have no required parts, give up.
			if (primary_required_part_queries == null)
				return;

			b.Start ();
			
			//
			// Now that we have all of these nice queries, let's execute them!
			//

			IndexReader primary_reader;
			LNS.IndexSearcher primary_searcher;
			IndexReader secondary_reader;
			LNS.IndexSearcher secondary_searcher;

			// Create the searchers that we will need.
			if (! BuildSearchers (out primary_reader, out primary_searcher, out secondary_reader, out secondary_searcher))
				return;

			b.Stop ();
			if (Debug)
				Log.Debug ("###### {0}: Readers/searchers built in {1}", IndexName, b);

			// Build whitelists and blacklists for search subsets.
			c.Start ();

			// Possibly create our whitelists from the search subset.
			LuceneBitArray primary_whitelist, secondary_whitelist;
			CreateQueryWhitelists (search_subset_uris,
				primary_searcher,
				secondary_searcher,
				primary_prohibited_part_query,
				secondary_prohibited_part_query,
				out primary_whitelist,
				out secondary_whitelist);

			c.Stop ();
			if (Debug)
				Log.Debug ("###### {0}: Whitelists and blacklists built in {1}", IndexName, c);

			// Now run the low level queries against our indexes.
			d.Start ();

			BetterBitArray primary_matches = null;

			if (primary_required_part_queries != null) {

				if (secondary_searcher != null)
					primary_matches = DoRequiredQueries_TwoIndex (primary_searcher,
										      secondary_searcher,
										      primary_required_part_queries,
										      secondary_required_part_queries,
										      primary_whitelist,
										      secondary_whitelist);
				else
					primary_matches = DoRequiredQueries (primary_searcher,
									     primary_required_part_queries,
									     primary_whitelist);

			} 

			d.Stop ();
			if (Debug)
				Logger.Log.Debug ("###### {0}: Low-level queries finished in {1}", IndexName, d);

			e.Start ();
			// Only generate results if we got some matches
			if (primary_matches != null && primary_matches.ContainsTrue ()) {
				GenerateQueryResults (primary_reader,
						      secondary_reader,
						      primary_matches,
						      result,
						      term_list,
						      query.MaxHits,
						      new HitFilter (all_hit_filters.HitFilter),
						      IndexName);
			}

			e.Stop ();

			if (Debug)
				Log.Debug ("###### {0}: Query results generated in {1}", IndexName, e);

			//
			// Finally, we clean up after ourselves.
			//

			f.Start ();
			CloseSearchers (primary_reader, primary_searcher, secondary_reader, secondary_searcher);
			f.Stop ();
			
			if (Debug)
				Log.Debug ("###### {0}: Readers/searchers released in {1}", IndexName, f);

			total.Stop ();
			if (Debug) {
				Log.Debug ("###### {0}: Query time breakdown:", IndexName);
				Log.Debug ("###### {0}:    Build queries {1,6} ({2:0.0}%)", IndexName, a, 100 * a.ElapsedTime / total.ElapsedTime);
				Log.Debug ("###### {0}:      Got readers {1,6} ({2:0.0}%)", IndexName, b, 100 * b.ElapsedTime / total.ElapsedTime);
				Log.Debug ("###### {0}:       Whitelists {1,6} ({2:0.0}%)", IndexName, c, 100 * c.ElapsedTime / total.ElapsedTime);
				Log.Debug ("###### {0}:          Queries {1,6} ({2:0.0}%)", IndexName, d, 100 * d.ElapsedTime / total.ElapsedTime);
				Log.Debug ("###### {0}:    Gen'd Results {1,6} ({2:0.0}%)", IndexName, e, 100 * e.ElapsedTime / total.ElapsedTime);
				Log.Debug ("###### {0}:   Reader cleanup {1,6} ({2:0.0}%)", IndexName, f, 100 * f.ElapsedTime / total.ElapsedTime);
				Log.Debug ("###### {0}:            TOTAL {1,6}", IndexName, total);

				Logger.Log.Debug ("###### {0}: Total query run in {1}", IndexName, total);
			}

		}
Example #14
0
		private void AssertIDs(IQueryResult queryResult, int[] expectedIDs)
		{
			AssertIDs(queryResult, expectedIDs, false);
		}
Example #15
0
 /// <summary>
 /// Sorts a <see cref="IQueryResult"/> using an <see cref="IOrderCriteria"/>
 /// </summary>
 /// <param name="queryResult"></param>
 /// <param name="orderCriteria"></param>
 public void Sort(IQueryResult queryResult, IOrderCriteria orderCriteria)
 {
     queryResult.Rows.Sort(new RowComparer(orderCriteria, queryResult));
 }
Example #16
0
        public string GenerateOutputResult(IQueryResult myQueryResult, Dictionary<String, String> myParams)
        {
            // root element...
            var _Query = new JObject();
            // query --------------------------------
            _Query.Add(new JProperty("Query", myQueryResult.Query));
            // result -------------------------------
            _Query.Add(new JProperty("Result", myQueryResult.TypeOfResult.ToString()));
            // duration -----------------------------
            _Query.Add(new JProperty("Duration", new JArray(myQueryResult.Duration, "ms")));
            // warnings -----------------------------
            // currently not in 2.0
            //_Query.Add(new JProperty("warnings", new JArray(
            //    from _Warning in myQueryResult.Warnings
            //    select new JObject(
            //             new JProperty("code", _Warning.GetType().ToString()),
            //             new JProperty("description", _Warning.ToString())
            //           ))));
            // errors -------------------------------
            if (myQueryResult.Error != null)
            {
                _Query.Add(new JProperty("Errors", new JArray(
                             new JObject(
                             new JProperty("Code", myQueryResult.Error.GetType().ToString()),
                             new JProperty("Description", HandleQueryExceptions(myQueryResult))
                           ))));
            }
            // results ------------------------------
            JArray _resultsArray = new JArray();
            // fill the results array
            if (myQueryResult.Vertices != null)
            {
                foreach (IVertexView _vertex in myQueryResult.Vertices)
                {
                    _resultsArray.Add(GenerateVertexViewJSON(_vertex));
                }
            }
            // add the results to the query....
            _Query.Add(new JProperty("Results", _resultsArray));

            return _Query.ToString();
        }
 public void SubscriptionEventResult(SubscriptionEventContext context, IQueryResult result)
 {
 }
Example #18
0
        /// <summary>
        /// Sends a N1QL query to the server to be executed using the <see cref="IQueryRequest"/> object using async/await.
        /// </summary>
        /// <typeparam name="T">The Type T of the body of each result row.</typeparam>
        /// <param name="queryRequest">The <see cref="IQueryRequest"/> object to send to the server.</param>
        /// <param name="cancellationToken">Token which can cancel the query.</param>
        /// <returns>An <see cref="Task{IQueryResult}"/> object to be awaited on that is the result of the query.</returns>
        /// <exception cref="ServiceNotSupportedException">The cluster does not support Query services.</exception>
        public override async Task <IQueryResult <T> > SendWithRetryAsync <T>(IQueryRequest queryRequest, CancellationToken cancellationToken)
        {
            IQueryResult <T> queryResult = null;

            try
            {
                //Is the cluster configured for Query services?
                if (!ConfigInfo.IsQueryCapable)
                {
                    throw new ServiceNotSupportedException(
                              ExceptionUtil.GetMessage(ExceptionUtil.ServiceNotSupportedMsg, "Query"));
                }

                queryRequest.Lifespan = new Lifespan
                {
                    CreationTime = DateTime.UtcNow,
                    Duration     = ConfigInfo.ClientConfig.QueryRequestTimeout
                };

                using (var timeoutCancellationTokenSource = new CancellationTokenSource(ConfigInfo.ClientConfig.ViewRequestTimeout))
                {
                    // If we received a functional cancellationToken (not just CancellationToken.None),
                    // then combine with the timeout token source
                    var cancellationTokenSource = cancellationToken.CanBeCanceled
                        ? CancellationTokenSource.CreateLinkedTokenSource(cancellationToken, timeoutCancellationTokenSource.Token)
                        : timeoutCancellationTokenSource;

                    using (cancellationTokenSource)
                    {
                        // Note: it is safe to dispose the same CTS twice, so this using statement is safe

                        queryResult = await RetryQueryEveryAsync(async (e, c) =>
                        {
                            var attempts = 0;
                            IServer server;
                            while ((server = c.GetQueryNode()) == null)
                            {
                                if (attempts++ > 10)
                                {
                                    throw new TimeoutException("Could not acquire a server.");
                                }
                                await Task.Delay((int)Math.Pow(2, attempts), cancellationTokenSource.Token).ContinueOnAnyContext();
                            }

                            // Don't forward our new cancellation token to the query layer,
                            // it has its own timeout implementation.  Just forward the cancellation token
                            // which was passed as a parameter.
                            var result = await server.SendAsync <T>(queryRequest, cancellationToken).ContinueOnAnyContext();
                            if (!result.Success)
                            {
                                //if this is too loose, we may need to constrain it to HttpRequestException or another exception later on
                                var exception = result.Exception;
                                if (exception != null && !(exception is TaskCanceledException))
                                {
                                    lock (_syncObj)
                                    {
                                        Log.Trace("Request failed checking config:", exception);
                                        UpdateConfig();
                                    }
                                }
                            }
                            return(result);
                        },
                                                                 queryRequest, ConfigInfo, cancellationTokenSource.Token).ConfigureAwait(false);
                    }
                }
            }
            catch (Exception e)
            {
                Log.Info(e);
                const string message = "The Query request failed, check Error and Exception fields for details.";
                queryResult = new QueryResult <T>
                {
                    Message   = message,
                    Status    = QueryStatus.Fatal,
                    Success   = false,
                    Exception = e
                };
            }
            return(queryResult);
        }
Example #19
0
        /// <summary>
        /// Creates and Serves vector tiles
        /// </summary>
        /// <param name="boundVariables"></param>
        /// <param name="operationInput"></param>
        /// <param name="outputFormat"></param>
        /// <param name="requestProperties"></param>
        /// <param name="responseProperties"></param>
        /// <returns></returns>
        private byte[] VectorTileHandler(NameValueCollection boundVariables,
                                         JsonObject operationInput,
                                         string outputFormat,
                                         string requestProperties,
                                         out string responseProperties)
        {
            //responseProperties = null;
            responseProperties = null; //"Content-Type:application/json";
            ESRI.ArcGIS.SOESupport.AutoTimer timer = new AutoTimer();

            const string methodName = "VectorTileHandler";

            try
            {
                long?      layerIndex;
                long?      zoom;
                long?      row;
                long?      col;
                string     jsonFormatParam;
                TileFormat jsonFormat = TileFormat.EsriJson; // Defaulting to EsriJson
                if (!operationInput.TryGetAsLong("l", out layerIndex))
                {
                    throw new ArgumentNullException("layer");
                }
                if (!operationInput.TryGetAsLong("z", out zoom))
                {
                    throw new ArgumentNullException("zoom");
                }
                if (!operationInput.TryGetAsLong("y", out row))
                {
                    throw new ArgumentNullException("row");
                }
                if (!operationInput.TryGetAsLong("x", out col))
                {
                    throw new ArgumentNullException("col");
                }
                if (operationInput.TryGetString("jf", out jsonFormatParam))
                {
                    if (!string.IsNullOrEmpty(jsonFormatParam))
                    {
                        jsonFormatParam = jsonFormatParam.ToLower().Trim();
                        Enum.GetNames(typeof(TileFormat)).ToList().ForEach(n =>
                        {
                            if (n.ToLower() == jsonFormatParam)
                            {
                                jsonFormat = (TileFormat)Enum.Parse(typeof(TileFormat), jsonFormatParam, true);
                            }
                        });
                    }
                }


                //System.Diagnostics.Debug.WriteLine(string.Format("l:{0}, r:{1}, c:{2}", zoom, row, col));

                // Check to see if the tile exists on disk...
                //  <cache-root>\<layerId>\<zoom>\<row>\<col>.esrijson;
                //i.e. to be consistent with Esri tile caching structure
                string tilePath = string.Format(@"{0}\{1}\{2}\{3}\{4}.{5}",
                                                _vectorCacheRootDirectory, layerIndex, zoom.Value,
                                                row.Value, col.Value, jsonFormat.ToString().ToLower());
                if (File.Exists(tilePath))
                {
                    // Fetch tile contents from disk
                    _dtsLogger.LogInfo(soe_name, methodName, "Time: " + timer.Elapsed.ToString());
                    logger.LogMessage(ServerLogger.msgType.infoSimple, methodName, -1, "Time: " + timer.Elapsed.ToString());
                    return(this.ReadTileFile(tilePath));
                }
                else
                {
                    // Write new files to disk

                    IMapServer3 mapServer = serverObjectHelper.ServerObject as IMapServer3;
                    if (mapServer == null)
                    {
                        throw new InvalidOperationException("Unable to access the map server.");
                    }

                    // Get the bbox. Returns an envelope in WGS84 (4326).
                    IEnvelope env102100 = TileUtil.GetEnvelopeFromZoomRowCol((int)zoom.Value, (int)row.Value, (int)col.Value);
                    //_dtsLogger.LogInfo(soe_name, methodName, this.GeometryToXml(env4326));


                    // Convert envelope to polygon b/c QueryData does not support spatialfilter geometry using envelope
                    IPolygon polygon102100 = this.CreatePolygonFromEnvelope(env102100);

                    // Use QueryData and generalize result geometries based on zoom level
                    IQueryResultOptions resultOptions = new QueryResultOptionsClass();
                    // i.e; IRecordSet to support BOTH json and geojson
                    resultOptions.Format = esriQueryResultFormat.esriQueryResultRecordSetAsObject;
                    IMapTableDescription tableDescription =
                        this.GetTableDescription(mapServer, (int)layerIndex, (int)zoom);

                    // Create spatial filter
                    ISpatialFilter spatialFilter = new SpatialFilterClass();
                    spatialFilter.Geometry      = polygon102100;
                    spatialFilter.GeometryField = "Shape";
                    spatialFilter.SpatialRel    = esriSpatialRelEnum.esriSpatialRelIntersects;
                    //TODO:  Subfields should be configurable
                    spatialFilter.SubFields = "*";

                    // Execute query
                    IQueryResult result = mapServer.QueryData(mapServer.DefaultMapName,
                                                              tableDescription, spatialFilter, resultOptions);

                    byte[] json = null;

                    // TODO:  Support writing tiles for no data
                    // Need a way to do this for GeoJson; parse Esri JSON recordset into GeoJson
                    if (result == null || !this.RecordsetHasFeatures(result.Object as IRecordSet))
                    {
                        // Write "no data" tile
                        if (jsonFormat == TileFormat.EsriJson)
                        {
                            resultOptions.Format = esriQueryResultFormat.esriQueryResultJsonAsMime;
                            result = mapServer.QueryData(mapServer.DefaultMapName, tableDescription, spatialFilter, resultOptions);
                            json   = result.MimeData;
                        }
                        else
                        {
                            json = StrToByteArray(NO_DATA_GEOJSON);
                        }
                    }
                    else
                    {
                        //We have features...
                        IRecordSet features = result.Object as IRecordSet;

                        // Get geometry type for query layer
                        esriGeometryType geometryType = this.GetLayerGeometryType(mapServer.GetServerInfo(mapServer.DefaultMapName).MapLayerInfos, (int)layerIndex);
                        switch (geometryType)
                        {
                        case esriGeometryType.esriGeometryPoint:
                            // Do nothing... already intersected
                            json = ESRI.ArcGIS.SOESupport.Conversion.ToJson(features);
                            break;

                        case esriGeometryType.esriGeometryPolyline:
                            // Polylines must be clipped to envelope
                            IFeatureCursor cursor = null;
                            this.ClipFeaturesToTile(ref cursor, ref features, env102100);
                            json = ESRI.ArcGIS.SOESupport.Conversion.ToJson(features);
                            this.ReleaseComObject(cursor);
                            break;

                        case esriGeometryType.esriGeometryMultipoint:
                        case esriGeometryType.esriGeometryPolygon:
                            // Get IDs of features whose centroid is contained by tile envelope
                            List <int> ids = this.GetIdsOfContainedFeatureCentroids(features, polygon102100);
                            if (ids.Count == 0)
                            {
                                // Write no data tile
                                if (jsonFormat == TileFormat.EsriJson)
                                {
                                    // Query to get empty featureset and serialize to disk
                                    resultOptions.Format = esriQueryResultFormat.esriQueryResultJsonAsMime;
                                    IQueryFilter queryFilter = new QueryFilterClass();
                                    queryFilter.SubFields   = "*";
                                    queryFilter.WhereClause = "1=2";
                                    result = mapServer.QueryData(mapServer.DefaultMapName, tableDescription, queryFilter, resultOptions);
                                    json   = result.MimeData;
                                }
                                else
                                {
                                    json = StrToByteArray(NO_DATA_GEOJSON);
                                }
                            }
                            else
                            {
                                // Execute new query for IDs
                                IQueryFilter queryFilter = new QueryFilterClass();
                                queryFilter.SubFields = "*";
                                // TODO:  Account for sql query syntax based on datasource
                                //      FGDB/Shapefile then "OBJECTID"; quotes required
                                //      PGDB then [OBJECTID]; brackets required
                                //      SDE then OBJECTID; nothing but the fieldname
                                queryFilter.WhereClause = string.Format("\"OBJECTID\" IN({0})", ids.ToDelimitedString <int>(","));    // FGDB
                                result   = mapServer.QueryData(mapServer.DefaultMapName, tableDescription, queryFilter, resultOptions);
                                features = result.Object as IRecordSet;
                                // Do some checking here...
                                var featureCount = this.GetRecordsetFeatureCount(features);
                                if (featureCount != ids.Count)
                                {
                                    System.Diagnostics.Debug.WriteLine(string.Format("Query Problem:  ID search results IS NOT EQUAL to contained IDs count - [{0}:{1}]", featureCount, ids.Count));
                                    System.Diagnostics.Debug.WriteLine("Query:  " + queryFilter.WhereClause);
                                }
                                json = ESRI.ArcGIS.SOESupport.Conversion.ToJson(features);
                            }

                            break;


                        default:
                            throw new NotSupportedException(string.Format("Geometry type {0} is not supported by {1}", geometryType.ToString(), soe_name));
                        }
                    }


                    //store the json to disk
                    this.WriteTileFile(json, tilePath, (int)layerIndex, (int)zoom, (int)row);
                    _dtsLogger.LogInfo(soe_name, methodName, "Time: " + timer.Elapsed.ToString());
                    logger.LogMessage(ServerLogger.msgType.infoSimple, methodName, -1, "Time: " + timer.Elapsed.ToString());
                    return(json);
                }
            }
            catch (Exception ex)
            {
                // Log the error
                _dtsLogger.LogError(soe_name, methodName, "n/a", ex);
                logger.LogMessage(ServerLogger.msgType.error, methodName, 9999, ex.StackTrace);
                return(StrToByteArray("{}"));
            }
        }
Example #20
0
 public bool Equals(IQueryResult obj)
 {
     return(obj != null && obj.GetType() == GetType() &&
            Equals((GoogleResult)obj));
 }
Example #21
0
 public Task <T> Execute <T>(IQueryResult <T> query)
 {
     return(Execute(() => query.Execute(_queryableProvider), _dbContext, query));
 }
Example #22
0
 /// <summary>
 /// generates information needed for visual graph out of query result
 /// <param name="myQueryResult">The query result.</param>
 /// <param name="Nodes">out parameter returning list of nodes</param>
 /// <param name="Links">out parameter returning list of NodeLink classes</param>
 /// </summary>
 private void GenerateVisGraph(IQueryResult myQueryResult, out List<string> Nodes, out List<NodeLink> Links)
 {
     GenerateNodeList(myQueryResult, out Nodes);
     GenerateLinkList(myQueryResult, Nodes, out Links);
 }
Example #23
0
 public RowComparer(IOrderCriteria orderCriteria, IQueryResult queryResult)
 {
     _orderCriteria = orderCriteria;
     _queryResult   = queryResult;
 }
 internal void Serialize(IQueryResult result, IBufferWriter <byte> writer)
 {
     using var jsonWriter = new Utf8JsonWriter(writer, _options);
     WriteResult(jsonWriter, result);
     jsonWriter.Flush();
 }
Example #25
0
 /// <summary>
 /// Determines whether a prepared query's plan stale.
 /// </summary>
 /// <param name="queryResult">The N1QL query result.</param>
 /// <returns>
 ///   <c>true</c> if query plan is stale; otherwise, <c>false</c>.
 /// </returns>
 public static bool IsQueryPlanStale <T>(this IQueryResult <T> queryResult)
 {
     return(StaleStatuses.Contains(queryResult.MetaData.Status) &&
            queryResult.Errors.Any(error => StaleErrorCodes.Contains(error.Code)));
 }
		private static void GenerateQueryResults (IndexReader       primary_reader,
							  IndexReader       secondary_reader,
							  BetterBitArray    primary_matches,
							  IQueryResult      result,
							  ICollection       query_term_list,
							  int               max_results,
							  HitFilter         hit_filter,
							  string            index_name)
		{
			int num_hits;

			if (Debug)
				Logger.Log.Debug (">>> {0}: Initially handed {1} matches", index_name, primary_matches.TrueCount);

			if (primary_matches.TrueCount <= max_results) {
				if (Debug)
					Logger.Log.Debug (">>> {0}: Initial count is within our limit of {1}", index_name, max_results);
				num_hits = primary_matches.TrueCount;
			} else {
				if (Debug)
					Logger.Log.Debug (">>> {0}: Number of hits is capped at {1}", index_name, max_results);
				num_hits = max_results;
			}

			Stopwatch total, d, e;
			total = new Stopwatch ();
			d = new Stopwatch ();
			e = new Stopwatch ();

			total.Start ();

			ArrayList final_list_of_hits = null;

			// This is used only for scoring
			Dictionary<int, Hit> hits_by_id = new Dictionary<int, Hit> (num_hits);

			int total_number_of_matches = primary_matches.TrueCount;

			if (primary_matches.TrueCount > max_results)
				final_list_of_hits = ScanRecentDocs (primary_reader,
					secondary_reader,
					primary_matches,
					hits_by_id,
					max_results,
					ref total_number_of_matches,
					hit_filter,
					index_name);

			if (final_list_of_hits == null)
				final_list_of_hits = FindRecentResults (primary_reader,
					secondary_reader,
					primary_matches,
					hits_by_id,
					max_results,
					ref total_number_of_matches,
					hit_filter,
					index_name);

			d.Start ();

			ScoreHits (hits_by_id, primary_reader, query_term_list);
			hits_by_id = null;

			d.Stop ();

			if (Debug)
				Log.Debug (">>> {0}: Scored hits in {1}", index_name, d);

			e.Start ();

			// 25 hits seems to be the sweet spot: anything lower
			// and serialization overhead gets us, higher takes
			// longer to send out.
			const int MAX_QUEUED_HITS = 25;
			int sent_index = 0;

			// Break up the hits into reasonably sized chunks for
			// sending over the wire.
			for (int i = 0; i < final_list_of_hits.Count; ++i) {
				// Flush our hits
				if (i > 0 && i % MAX_QUEUED_HITS == 0) {
					result.Add (final_list_of_hits.GetRange (0, MAX_QUEUED_HITS));
					final_list_of_hits.RemoveRange (0, MAX_QUEUED_HITS);
					i -= MAX_QUEUED_HITS;
				}
			}

			// Flush the remaining hits
			result.Add (final_list_of_hits, total_number_of_matches);
			final_list_of_hits = null;

			e.Stop ();

			if (Debug)
				Log.Debug (">>> {0}: Hit filters executed and results sent in {1}", index_name, e);

			total.Stop ();

			if (Debug) {
				Logger.Log.Debug (">>> {0}: GenerateQueryResults time statistics:", index_name);
				//Logger.Log.Debug (">>> {0}:   Short circuit {1,6} ({2:0.0}%)", index_name, a == null ? "N/A" : a.ToString (), a == null ? 0.0 : 100 * a.ElapsedTime / total.ElapsedTime);
				//Logger.Log.Debug (">>> {0}:     Create docs {1,6} ({2:0.0}%)", index_name, b, 100 * b.ElapsedTime / total.ElapsedTime);
				//Logger.Log.Debug (">>> {0}:    Hit assembly {1,6} ({2:0.0}%)", index_name, c, 100 * c.ElapsedTime / total.ElapsedTime);
				Logger.Log.Debug (">>> {0}:     Scored hits {1,6} ({2:0.0}%)", index_name, d, 100 * d.ElapsedTime / total.ElapsedTime);
				Logger.Log.Debug (">>> {0}:    Results sent {1,6} ({2:0.0}%)", index_name, e, 100 * e.ElapsedTime / total.ElapsedTime);
				Logger.Log.Debug (">>> {0}:           TOTAL {1,6}", index_name, total);
			}
		}
Example #27
0
        public static Exception ThrowExceptionOnError <T>(this IQueryResult <T> result, QueryErrorContext context)
        {
            foreach (var error in result.Errors)
            {
                if (error.Code == 3000)
                {
                    throw new ParsingFailureException(context);
                }

                if (PreparedErrorCodes.Contains(error.Code))
                {
                    throw new PreparedStatementException(context);
                }

                if (error.Code == 4300 && error.Message.Contains("index") &&
                    error.Message.Contains("already exists"))
                {
                    throw new IndexExistsException(context);
                }

                if (error.Code >= 4000 && error.Code < 5000)
                {
                    throw new PlanningFailureException(context);
                }

                if (error.Code == 12004 || error.Code == 12016 ||
                    error.Code == 5000 && error.Message.Contains("index") && error.Message.Contains("not found"))
                {
                    throw new IndexNotFoundException(context);
                }

                if (error.Code == 5000 && error.Message.Contains("index") && error.Message.Contains("already exists"))
                {
                    throw new IndexExistsException(context);
                }

                if (error.Code >= 5000 && error.Code < 6000)
                {
                    throw new InternalServerFailureException();
                }

                if (error.Code == 12009)
                {
                    throw new CasMismatchException(context);
                }

                if (error.Code >= 10000 && error.Code < 11000)
                {
                    throw new AuthenticationFailureException("Could not authenticate query.")
                          {
                              Context = context
                          }
                }
                ;

                if (error.Code >= 12000 && error.Code < 13000 || error.Code >= 14000 && error.Code < 15000)
                {
                    throw new IndexFailureException(context);
                }
            }

            throw new CouchbaseException(context);
        }
Example #28
0
 private void Sort(IQueryResult result)
 {
     if (_orderings != null)
     {
         if (result.Size() == 0)
         {
             return;
         }
         result.SortIds(NewSodaQueryComparator());
     }
     if (_comparator != null)
     {
         if (result.Size() == 0)
         {
             return;
         }
         result.Sort(_comparator);
     }
 }
Example #29
0
        public FormPersonnelArchiveList(AuthorityFlag authFlag, HR_PersonnelArchiveChange personnelChange,
                                        HR_PersonnelArchive personnelArchive, string allowTime, string starTime, string endTime, IQueryResult result)
        {
            InitializeComponent();

            if (personnelChange != null)
            {
                m_personnelArchive = personnelArchive;
                m_personnelChange  = personnelChange;
                m_queryResult      = result;
                m_authFlag         = authFlag;
                AuthorityControl(m_authFlag);

                添加toolStripButton1.Visible  = false;
                新建toolStripButton1.Visible  = false;
                toolStripSeparator4.Visible = false;
                toolStripSeparator1.Visible = false;

                txtAllowTime.Text = allowTime;
                txtStarTime.Text  = starTime;
                txtEndTime.Text   = endTime;

                BindControl();

                FaceAuthoritySetting.SetVisibly(this.Controls, result.HideFields);
            }
            else
            {
                修改toolStripButton1.Visible  = false;
                toolStripSeparator1.Visible = false;

                txtCard.ReadOnly           = false;
                txtName.ReadOnly           = false;
                txtWorkID.ReadOnly         = false;
                txtPostAmount.ReadOnly     = false;
                txtTrainingAmount.ReadOnly = false;
                txtChangeAmount.ReadOnly   = false;
                dtpBirthday.Value          = ServerTime.Time;
                dtpJoinDate.Value          = ServerTime.Time;
                dtpBecomeDate.Value        = ServerTime.Time;
                dtpTakeJobDate.Value       = ServerTime.Time;
                dtpDimissionDate.Value     = ServerTime.Time;
            }

            toolStrip1.Visible = true;
        }
Example #30
0
		private void AssertIDs(IQueryResult queryResult, int[] expectedIDs, bool ignoreUnexpected
			)
		{
			ExpectingVisitor expectingVisitor = new ExpectingVisitor(IntArrays4.ToObjectArray
				(expectedIDs), false, ignoreUnexpected);
			IIntIterator4 i = queryResult.IterateIDs();
			while (i.MoveNext())
			{
				expectingVisitor.Visit(i.CurrentInt());
			}
			expectingVisitor.AssertExpectations();
		}
Example #31
0
        private IQueryResult GenerateResult(double myElapsedTotalMilliseconds, IQueryResult myResult, String myAction)
        {
            List<IVertexView> view = new List<IVertexView>();

            if(myResult != null)
            {
                foreach (var item in myResult.Vertices)
                {
                    var dict = new Dictionary<string, object>();

                    if(item.HasProperty("VertexID"))
                        dict.Add("VertexID", item.GetProperty<IComparable>("VertexID"));

                    if(item.HasProperty("VertexTypeID"))
                        dict.Add("VertexTypeID", item.GetProperty<IComparable>("VertexTypeID"));

                    dict.Add("Action", myAction);

                    view.Add(new VertexView(dict, null));
                }
            }

            return QueryResult.Success(_query, SonesGQLConstants.GQL, view, Convert.ToUInt64(myElapsedTotalMilliseconds));
        }
 public AnswerResult(IQueryResult queryResult, bool isCorrect, IOption<string> hint)
 {
     m_QueryResult = queryResult;
     m_IsCorrect = isCorrect;
     m_Hint = hint;
 }
Example #33
0
        public string GenerateOutputResult(IQueryResult myQueryResult, Dictionary<String, String> myParams)
        {
            StringBuilder Output = new StringBuilder();
            Output.AppendLine("Query:\t\t"+myQueryResult.Query);
            Output.AppendLine("Result:\t\t"+myQueryResult.TypeOfResult.ToString());
            Output.AppendLine("Duration:\t"+myQueryResult.Duration+" ms");

            if (myQueryResult.Error != null)
            {
                Output.AppendLine("Error: \t\t"+myQueryResult.Error.GetType().ToString() + " - " + HandleQueryExceptions(myQueryResult));
            }

            if (myQueryResult.Vertices != null)
            {
                Output.AppendLine("Vertices:");

                foreach (IVertexView _vertex in myQueryResult.Vertices)
                {
                    Output.Append(GenerateVertexViewText("\t\t",_vertex));
                }
            }

            return Output.ToString();
        }
Example #34
0
        /// <summary>
        /// This private method analyses the QueryResult, shows the ResultType and Errors if existing.
        /// </summary>
        /// <param name="myQueryResult">The result of a query.</param>
        private bool CheckResult(IQueryResult myQueryResult)
        {
            if (myQueryResult.Error != null)
            {
                if (myQueryResult.Error.InnerException != null)
                    Console.WriteLine(myQueryResult.Error.InnerException.Message);
                else
                    Console.WriteLine(myQueryResult.Error.Message);

                return false;
            }
            else
            {
                Console.WriteLine("Query " + myQueryResult.TypeOfResult);

                return true;
            }
        }
Example #35
0
        public static System.Collections.Generic.IList <Extent> WrapQueryResult <Extent>(Db4objects.Db4o.Query.IQuery query)
        {
            IQueryResult queryResult = ((QQuery)query).GetQueryResult();

            return(new GenericObjectSetFacade <Extent>(queryResult));
        }
Example #36
0
		public StatefulQueryResult(IQueryResult queryResult)
		{
			_delegate = queryResult;
			_iterable = new Iterable4Adaptor(queryResult);
		}
 private string ExpectError(IQueryResult result)
 {
     return result.Map(
         table => { throw new ApplicationException("Expected error"); },
         error => error
     );
 }
Example #38
0
        public string GenerateOutputResult( IQueryResult myQueryResult, Dictionary<String, String> myParams)
        {
            StringBuilder Output = new StringBuilder();
            bool bShowEdgeNames = false;

            if (myParams.ContainsKey(_OptionStrings.ShowEdgeNames.name))
            {
                if (StringComparer.InvariantCultureIgnoreCase.Compare(myParams[_OptionStrings.ShowEdgeNames.name], _OptionStrings.ShowEdgeNames.show) == 0)
                {
                    bShowEdgeNames = true;
                }
                else if (StringComparer.InvariantCultureIgnoreCase.Compare(myParams[_OptionStrings.ShowEdgeNames.name], _OptionStrings.ShowEdgeNames.hide) == 0)
                {
                    bShowEdgeNames = false;
                }
            }

            if (myQueryResult.Error != null)
            {
                Output.Append(ConvertString2WebShellOut(HandleQueryExceptions(myQueryResult)));
                return Output.ToString();
            }

            List<string> Nodes;
            List<NodeLink> Links;
            GenerateVisGraph(myQueryResult, out Nodes, out Links);

            if (Nodes.Count == 0)
            {
                Output.Append(ConvertString2WebShellOut("Graph Visualisation Plugin:"));
                Output.Append(ConvertString2WebShellOut("Error: No vertex with property \"node\" found!"));
                Output.Append(ConvertString2WebShellOut("Please change your query string using \"as node\" for returned vertices"));
                Output.Append(ConvertString2WebShellOut("If you use WebShell and want to use another output format plugin,"));
                Output.Append(ConvertString2WebShellOut("enter e.g. format json for JSON output!"));
                return Output.ToString();
            }
            else
            {
                Output.AppendLine("var w = 960,");
                Output.AppendLine("h = 500;");
                Output.AppendLine("var vis = d3.select(\"#output\")");
                Output.AppendLine(".append(\"svg:svg\")");
                Output.AppendLine(".attr(\"width\", w)");
                Output.AppendLine(".attr(\"height\", h);");

                Output.AppendLine("var nodes = new Array();");
                Output.AppendLine("var links = new Array();");

                foreach (var Node in Nodes)
                {
                    Output.AppendLine("var node = new Object();");
                    Output.AppendLine("node.name=\"" + Node + "\";");
                    Output.AppendLine("nodes.push(node);");
                }

                foreach (var Link in Links)
                {
                    Output.AppendLine("var link = new Object();");
                    Output.AppendLine("link.source=" + Link.source + ";");
                    Output.AppendLine("link.target=" + Link.target + ";");
                    Output.AppendLine("link.name=\"" + Link.name + "\";");
                    Output.AppendLine("links.push(link);");
                }

                Output.AppendLine("var force = self.force = d3.layout.force()");
                Output.AppendLine(".nodes(nodes)");
                Output.AppendLine(".links(links)");
                Output.AppendLine(".gravity(.05)");
                Output.AppendLine(".distance(100)");
                Output.AppendLine(".charge(-100)");
                Output.AppendLine(".size([w, h])");
                Output.AppendLine(".start();");

                Output.AppendLine("var linkgroup = vis.selectAll(\"g.link\")");
                Output.AppendLine(".data(links)");
                Output.AppendLine(".enter().append(\"svg:g\");");

                Output.AppendLine("var link = linkgroup.append(\"svg:line\")");
                Output.AppendLine(".attr(\"class\", \"graphlink\");");

                if (bShowEdgeNames)
                {
                    Output.AppendLine("var linkname = linkgroup.append(\"svg:text\")");
                    Output.AppendLine(".attr(\"class\", \"graphlinktext\")");
                    Output.AppendLine(".text(function(d) { return d.name; });");
                }

                Output.AppendLine("var node = vis.selectAll(\"g.node\")");
                Output.AppendLine(".data(nodes)");
                Output.AppendLine(".enter().append(\"svg:g\")");
                Output.AppendLine(".attr(\"class\", \"node\")");
                Output.AppendLine(".call(force.drag);");

                Output.AppendLine("node.append(\"svg:image\")");
                Output.AppendLine(".attr(\"class\", \"circle\")");
                Output.AppendLine(".attr(\"xlink:href\", \"favicon.ico\")");
                Output.AppendLine(".attr(\"x\", \"-8px\")");
                Output.AppendLine(".attr(\"y\", \"-8px\")");
                Output.AppendLine(".attr(\"width\", \"16px\")");
                Output.AppendLine(".attr(\"height\", \"16px\");");

                Output.AppendLine("node.append(\"svg:text\")");
                Output.AppendLine(".attr(\"class\", \"nodetext\")");
                Output.AppendLine(".attr(\"dx\", 12)");
                Output.AppendLine(".attr(\"dy\", \".35em\")");
                Output.AppendLine(".text(function(d) { return d.name });");

                Output.AppendLine("force.on(\"tick\", function() {");
                Output.AppendLine("link.attr(\"x1\", function(d) { return d.source.x; })");
                Output.AppendLine(".attr(\"y1\", function(d) { return d.source.y; })");
                Output.AppendLine(".attr(\"x2\", function(d) { return d.target.x; })");
                Output.AppendLine(".attr(\"y2\", function(d) { return d.target.y; });");
                if (bShowEdgeNames)
                {
                    Output.AppendLine("linkname.attr(\"x\", function(d) { return (d.source.x + d.target.x) / 2; })");
                    Output.AppendLine(".attr(\"y\", function(d) { return (d.source.y + d.target.y) / 2; });");
                }
                Output.AppendLine("node.attr(\"transform\", function(d) { return \"translate(\" + d.x + \",\" + d.y + \")\"; });");
                Output.AppendLine("});");

                return Output.ToString();
            }
        }
		public void DoQuery (Query query, IQueryResult result, IQueryableChangeData data)
		{
		}
Example #40
0
        /// <summary>
        /// generate node list needed for visual graph out of query result
        /// <param name="myQueryResult">The query result.</param>
        /// <param name="Nodes">out parameter returning list of nodes</param>
        /// </summary>
        private void GenerateNodeList(IQueryResult myQueryResult, out List<string> Nodes)
        {
            Nodes = new List<string>();

            GenerateNodeList_AnalyzeVertices(myQueryResult.Vertices, ref Nodes);
        }
 public ObjectSetFacade(IQueryResult qr)
 {
     _delegate = new StatefulQueryResult(qr);
 }
Example #42
0
        /// <summary>
        /// Handles query exceptions.
        /// </summary>
        /// <param name="queryresult">The query result.</param>
        /// <returns>The exception string.</returns>
        private String HandleQueryExceptions( IQueryResult queryresult)
        {
            StringBuilder SB = new StringBuilder();

            SB.Append(queryresult.Error.ToString());
            if (queryresult.Error.InnerException != null)
                SB.Append(" InnerException: " + queryresult.Error.InnerException.Message);

            return SB.ToString();
        }
Example #43
0
        private void DoGMailQuery(string query, int maxhits, IQueryResult result)
        {
            Log.Debug("GMailSearchDriver: Searching for [{0}]", query);
            MessageSet results = imap_client.Search(query, false);

            if (results == null)
            {
                return;
            }

            Log.Debug("Recvd {0} messages", results.Messages.Count);

            // Get the messages in reverse order; latest first
            ArrayList matched_ids = new ArrayList(results.Messages);

            matched_ids.Reverse();

            const int MAX_QUEUED_HITS = 25;
            int       left            = Math.Min(maxhits, matched_ids.Count);
            ArrayList result_batch    = new ArrayList(MAX_QUEUED_HITS);

            MailCollection emails;

            GMime.StreamMem stream;
            GMime.Parser    parser;
            GMime.Message   message;
            Hit             hit;

            foreach (string id in matched_ids)
            {
                if (left-- == 0)
                {
                    break;
                }
                Log.Debug("Fetching headers for message id {0}", id);

                emails = imap_client.FetchMessages(id, id, false, true, false);
                if (emails == null || emails.Count == 0)
                {
                    Log.Error("IMAP error: {0}", imap_client.LastError);
                    continue;
                }

                foreach (Mail m in emails)
                {
                    hit = null;

                    using (stream = new GMime.StreamMem(m.Header))
                        using (parser = new GMime.Parser(stream))
                            using (message = parser.ConstructMessage())
                                hit = MessageToHit(message);

                    if (hit == null)
                    {
                        Log.Error("Bad IMAP email {0}: no msg-id", id);
                        continue;
                    }
                    else
                    {
                        result_batch.Add(hit);
                    }
                }

                if (result_batch.Count >= MAX_QUEUED_HITS)
                {
                    result.Add(result_batch);
                    result_batch.Clear();
                }
            }

            result.Add(result_batch, matched_ids.Count);
        }
 private object QueryResultToJson(IQueryResult result)
 {
     return result.Map(QueryResultTableToJson, FailureToJson);
 }
Example #45
0
        /// <summary>
        /// generate bar chart data dictionary out of query result by searching recursively
        /// </summary>
        /// <param name="myQueryResult">query result</param>
        /// <returns>dictionary containing bar chart data</returns>
        private Dictionary<String, object> GenerateBarChart(IQueryResult myQueryResult)
        {
            Dictionary<String, object> barchart = new Dictionary<string, object>();

            foreach (var aVertex in myQueryResult.Vertices)
            {
                AnalyzeProperties(aVertex.GetAllProperties(), ref barchart);
                AnalyzeEdges(aVertex.GetAllEdges(), ref barchart);
            }

            return barchart;
        }
		public ReqContext(BeagleWebService wsp, IQueryResult result, IQueryable iq)
		{
			this.wsp = wsp;
			this.result = result;
			this.iq = iq;
			this.reqProcessed = false;
		}
        /// <summary>
        /// Internal Error handler for the top level Execution process.
        /// </summary>
        /// <returns></returns>
        protected virtual async Task HandleGraphQLErrorResponseAsync(HttpContext httpContext, HttpStatusCode statusCode, IQueryResult errorResult)
        {
            // in any case we will have a valid GraphQL result at this point that can be written
            // to the HTTP response stream.
            Debug.Assert(errorResult != null, "No GraphQL result was created.");

            await this.AzureFunctionsMiddlewareProxy.WriteResultAsync(
                httpContext.Response,
                errorResult,
                statusCode,
                httpContext.RequestAborted
                );
        }