public void NonZipQueryException() { QueryException err = new QueryException(QueryErrors.InvalidLatLon, "ERROR"); { this.weatherQuery.Setup(w => w.Cooldown).Returns(1 * 60 * 60); // 1 hour query cooldown. this.weatherQuery.Setup(w => w.QueryForWeather(It.Is <string>(s => s == zip))).Throws(err); Task <string> response = this.uut.QueryWeather(zip); response.Wait(); Assert.AreEqual(err.Message, response.Result); } { // Non-zip code error should not fill cache, we should // still query. this.weatherQuery.Setup(w => w.Cooldown).Returns(1 * 60 * 60); this.weatherQuery.Setup(w => w.QueryForWeather(It.Is <string>(s => s == zip))).Throws(err); Task <string> response = this.uut.QueryWeather(zip); response.Wait(); Assert.AreEqual(err.Message, response.Result); } }
public async Task TwoOperations_ShortHand_QueryException() { // arrange Schema schema = Schema.Create(@" type Query { a: String } ", c => { c.BindResolver(() => "hello world") .To("Query", "a"); }); var request = new QueryRequest("{ a } query a { a }").ToReadOnly(); var context = new QueryContext( schema, new EmptyServiceProvider(), request); context.Document = Parser.Default.Parse(request.Query); var middleware = new ResolveOperationMiddleware( c => Task.CompletedTask, null); // act Func <Task> func = () => middleware.InvokeAsync(context); // assert QueryException exception = await Assert.ThrowsAsync <QueryException>(func); Assert.Equal( "Only queries that contain one operation can be executed " + "without specifying the opartion name.", exception.Message); }
public async Task TwoOperations_WrongOperationName_QueryException() { // arrange Schema schema = Schema.Create(@" type Query { a: String } ", c => { c.BindResolver(() => "hello world") .To("Query", "a"); }); var request = new QueryRequest( "query a { a } query b { a }", "c") .ToReadOnly(); var context = new QueryContext( schema, new EmptyServiceProvider(), request); context.Document = Parser.Default.Parse(request.Query); var middleware = new ResolveOperationMiddleware( c => Task.CompletedTask, null); // act Func <Task> func = () => middleware.InvokeAsync(context); // assert QueryException exception = await Assert.ThrowsAsync <QueryException>(func); Assert.Equal( "The specified operation `c` does not exist.", exception.Message); }
public void FixtureSetup() { this.invalidZipException = new QueryException( QueryErrors.InvalidZip, "Error with one or more zip codes: Error: Zip code \"" + zip + "\" is not a valid US zip code" ); }
public async void NonZipQueryException() { QueryException err = new QueryException(QueryErrors.InvalidLatLon, "ERROR"); this.weatherQuery.ExceptionToThrowDuringQuery = err; this.weatherQuery.Cooldown = 1 * 60 * 60; // One hour. { string response = await this.uut.QueryWeather(zip); Assert.AreEqual(err.Message, response); // No value in cache, expect query. Assert.IsTrue(this.weatherQuery.WasQueried); } this.weatherQuery.ResetStates(); this.weatherQuery.ExceptionToThrowDuringQuery = err; this.weatherQuery.Cooldown = 1 * 60 * 60; // One hour. { string response = await this.uut.QueryWeather(zip); Assert.AreEqual(err.Message, response); // Non-zip code error should not fill cache, we should // still query. Assert.IsTrue(this.weatherQuery.WasQueried); } }
public void TestBadWeatherReport() { string xml = ReadFile(Path.Combine(testFilesLocation, "BadReport.xml")); QueryException error = Assert.Throws <QueryException>(() => XmlLoader.ParseWeatherReport(xml, defaultZip) ); Assert.AreEqual(QueryErrors.MissingForecast, error.ErrorCode); }
public void TestBadZipCode() { string xml = ReadFile(Path.Combine(testFilesLocation, "InvalidZipCode.xml")); QueryException error = Assert.Throws <QueryException>(() => XmlLoader.ParseLatitudeLongitude(xml, defaultZip) ); Assert.AreEqual(QueryErrors.InvalidZip, error.ErrorCode); }
public void Constructor_with_2_arguments_should_work() { var query = new BsonDocument("query", 1); var exception = new QueryException("message", query); exception.Message.Should().Be("message"); exception.InnerException.Should().BeNull(); exception.Query.Equals(query).Should().BeTrue(); exception.Result.Should().BeNull(); }
private static void CheckResponse(ElasticsearchResponse <string> response) { if (response?.Body == null || string.IsNullOrEmpty(response.Body)) { if (!string.IsNullOrEmpty(response?.DebugInformation)) { throw QueryException.MissingBody(Strings.MissingBody, new Exception(response.DebugInformation, response.OriginalException)); } throw QueryException.MissingBody(Strings.MissingBody, response?.OriginalException); } }
public void Constructor_with_4_arguments_should_work() { var query = new BsonDocument("query", 1); var result = new BsonDocument("result", 2); var innerException = new Exception("inner"); var exception = new QueryException("message", query, result, innerException); exception.Message.Should().Be("message"); exception.InnerException.Message.Should().Be("inner"); exception.Query.Equals(query).Should().BeTrue(); exception.Result.Equals(result).Should().BeTrue(); }
public async void Query(string bucket, string org) { string flux = $"from(bucket:\"{bucket}\") |> range(start: 0)"; var queryApi = client.GetQueryApi(); await queryApi.QueryAsync(flux, org, (cancellable, record) => { QueryComplete?.Invoke(this, new QueryCompleteEventArgs(record)); }, exception => { QueryException?.Invoke(this, new QueryExceptionEventArgs(exception)); }, () => { QuerySuccess?.Invoke(this, new QuerySuccessEventArgs()); }); }
public void TestZipErrorResponse() { string xml = ReadFile(Path.Combine(testFilesLocation, "SampleZipError.xml")); { QueryException error = Assert.Throws <QueryException>(() => XmlLoader.ParseLatitudeLongitude(xml, defaultZip) ); Assert.AreEqual(QueryErrors.InvalidZip, error.ErrorCode); } { QueryException error = Assert.Throws <QueryException>(() => XmlLoader.ParseWeatherReport(xml, defaultZip) ); Assert.AreEqual(QueryErrors.InvalidZip, error.ErrorCode); } }
public void Serialization_should_work() { var query = new BsonDocument("query", 1); var result = new BsonDocument("result", 2); var innerException = new Exception("inner"); var exception = new QueryException("message", query, result, innerException); var formatter = new BinaryFormatter(); using (var stream = new MemoryStream()) { formatter.Serialize(stream, exception); stream.Position = 0; var rehydrated = (QueryException)formatter.Deserialize(stream); rehydrated.Message.Should().Be("message"); rehydrated.InnerException.Message.Should().Be("inner"); rehydrated.Query.Equals(query).Should().BeTrue(); rehydrated.Result.Equals(result).Should().BeTrue(); } }
private void HandleException(QueryException ex, HttpContext context) { ApiException apiException; switch (ex) { case InvalidQueryException e: apiException = new ApiException(HttpStatusCode.BadRequest, e.Message, e); break; case ResourceNotFoundException e: apiException = new ApiException(HttpStatusCode.NotFound, e.Message, e); break; default: apiException = new ApiException(HttpStatusCode.InternalServerError, "Server error"); break; } HandleException(apiException, context); }
public static bool IsRetryable(this QueryException exception) { foreach (var error in exception.Errors) { switch (error.Code) { case 4040: case 4050: case 4070: return(true); case 5000: return(error.Message != null && error.Message.Contains(QueryClient.Error5000MsgQueryPortIndexNotFound)); default: continue; } } return(false); }
public static Error ToError(this QueryException exception) { return(new Error { Message = exception.Message, Details = GetDetails(exception) }); }
/// <summary> /// Initializes a new instance of the <see cref="HibernateQueryException"/> class. /// </summary> /// <param name="ex">The ex.</param> public HibernateQueryException(QueryException ex) : base(ex.Message, ex) { }
public void Constructor_WithInnerExceptionAndMessage_ConstructsQueryException() { var exc = new QueryException("test", new ArgumentException("test")); Assert.AreEqual(QueryException.QueryPhaseName, exc.PhaseName); }
public override int[] GetNamedParameterLocs(string name) { object o = namedParameters[name]; if (o == null) { QueryException qe = new QueryException("Named parameter does not appear in Query: " + name); qe.QueryString = queryString; throw qe; } if (o is int) { return new int[] {((int) o)}; } else { return ArrayHelper.ToIntArray((ArrayList) o); } }
public override int[] GetNamedParameterLocs(string name) { List<int> o; if (!namedParameters.TryGetValue(name, out o)) { QueryException qe = new QueryException("Named parameter does not appear in Query: " + name); qe.QueryString = queryString; throw qe; } return o.ToArray(); }
/// <summary> /// 导入数据到关系数据库 /// </summary> /// <param name="mode">导入模式</param> /// <param name="isNew">导入模式为更新模式的时候,进行实体类数据新旧比较的自定义方法,第一个参数为源实体,第二个参数为数据库的目标实体,返回源是否比目标新</param> /// <returns>导入的数据数量</returns> public ImportResult Import(ImportMode mode, Func <T, T, bool> isNew) { Type entityType = typeof(T); string importTableName = EntityFieldsCache.Item(entityType).TableName; ImportResult result = new ImportResult(); result.ImportTable = importTableName; result.IsCancel = true; //导出批次管理 string memDbPath = this.MemDB.Path; string pkgPath = memDbPath.Length > 255 ? memDbPath.Substring(memDbPath.Length - 255) : memDbPath; List <ExportBatchInfo> batchList = MemDB.Get <ExportBatchInfo>(); ExportBatchInfo currBatch = batchList.FirstOrDefault(p => p.ExportTableName == importTableName); if (currBatch == null) { result.Flag = ImportResultFlag.NoBatchInfo; return(result);//没有导入批次信息,不能导入 } //只有比数据库的导入批次数据新,才可以导入 currBatch.PackagePath = pkgPath; OQL q = OQL.From(currBatch) .Select() .Where(currBatch.ExportTableName, currBatch.PackagePath) .END; ExportBatchInfo dbBatch = this.CurrDbContext.QueryObject <ExportBatchInfo>(q); if (dbBatch == null) { currBatch.SetDefaultChanges(); this.CurrDbContext.Add <ExportBatchInfo>(currBatch); result.BatchNumber = currBatch.BatchNumber; } else { result.BatchNumber = currBatch.BatchNumber; if (currBatch.BatchNumber <= dbBatch.BatchNumber) { result.Flag = ImportResultFlag.IsOldData; return(result);//没有新数据需要导入 } currBatch.ID = dbBatch.ID; } //导入数据 int count = 0;// List <T> list = this.MemDB.Get <T>(); System.Diagnostics.Stopwatch watch = new System.Diagnostics.Stopwatch(); watch.Start(); if (list.Count > 0) { ImportEntityEventArgs <T> args = new ImportEntityEventArgs <T>(list, entityType, importTableName, currBatch.BatchNumber); if (BeforeImport != null) { BeforeImport(this, args); if (args.Cancel) { result.Flag = ImportResultFlag.UserCanceled; return(result); } } //处理不同的导入模式 if (mode == ImportMode.Append) { list.ForEach(item => { item.ResetChanges(true); }); count = this.CurrDbContext.AddList(list); } else if (mode == ImportMode.TruncateAndInsert) { string sql = "TRUNCATE TABLE [" + importTableName + "]"; this.CurrDbContext.CurrentDataBase.ExecuteNonQuery(sql); //list.ForEach(item => //{ // item.SetDefaultChanges(); //}); //count = this.CurrDbContext.AddList(list); list[0].ResetChanges(true); EntityQuery <T> eq = new EntityQuery <T>(this.CurrDbContext.CurrentDataBase); count = eq.QuickInsert(list); } else if (mode == ImportMode.Update) { if (isNew == null) { throw new ArgumentNullException("当 ImportMode 为Update 模式的时候,参数 isNew 不能为空。"); } foreach (T item in list) { T dbEntity = (T)item.Clone(); EntityQuery eq = new EntityQuery(this.CurrDbContext.CurrentDataBase); if (eq.FillEntity(dbEntity)) { if (isNew(item, dbEntity)) { item.ResetChanges(true);; //设置了更改状态,才可以更新到数据库 count += eq.Update(item); } } } } else if (mode == ImportMode.Merge) { /* * //下面的方式比较缓慢,改用先删除数据包对应的数据再快速插入的方式 * foreach (T item in list) * { * T dbEntity = (T)item.Clone(); * EntityQuery eq = new EntityQuery(this.CurrDbContext.CurrentDataBase); * if (eq.FillEntity(dbEntity)) * { * int changedCount = dbEntity.MapFrom(item, true); * if (changedCount > 0) * { * count+= eq.Update(dbEntity); * } * } * else * { * //没有Fill成功实体,说明数据库没有此数据,则添加数据到数据库 * item.SetDefaultChanges(); * count+= eq.Insert(item); * } * } * // */ var idList = list.Select(s => s[s.PrimaryKeys[0]]).ToList(); //每页大小 const int pageSize = 500; //页码 int pageNum = 0; T entity = new T(); list[0].ResetChanges(true); EntityQuery <T> eq = new EntityQuery <T>(this.CurrDbContext.CurrentDataBase); this.CurrDbContext.CurrentDataBase.BeginTransaction(); try { while (pageNum * pageSize < idList.Count) { var currIdList = idList.Skip(pageSize * pageNum).Take(pageSize); var deleteQ = OQL.From(entity) .Delete() .Where(cmp => cmp.Comparer(entity[entity.PrimaryKeys[0]], "in", currIdList.ToArray())) .END; int deleteCount = eq.ExecuteOql(deleteQ); pageNum++; } count = eq.QuickInsert(list); this.CurrDbContext.CurrentDataBase.Commit(); } catch (Exception ex) { count = 0; this.CurrDbContext.CurrentDataBase.Rollback(); result.IsCancel = true; result.Flag = ImportResultFlag.Error; result.ImportCount = count; result.ErrorMessage = ex.Message; if (ex.InnerException != null) { QueryException qe = ex.InnerException as QueryException; if (qe != null) { result.ErrorMessage += ":QueryException :" + qe.Message; } else { result.ErrorMessage += ":Error :" + ex.InnerException.Message; } } return(result); } } else { //自定义的处理方式,请在 BeforeImport 事件自行处理 } if (AfterImport != null) { args.Cancel = false; AfterImport(this, args); } }//end if //更新导入批次信息 currBatch.BatchNumber = result.BatchNumber; currBatch.LastExportDate = DateTime.Now; this.CurrDbContext.Update <ExportBatchInfo>(currBatch); watch.Stop(); result.Duration = Convert.ToInt64(watch.Elapsed.TotalSeconds); result.IsCancel = false; result.Flag = ImportResultFlag.Succeed; result.ImportCount = count; return(result); }
/// <summary> /// Compile the query (generate the SQL). /// </summary> protected void Compile() { log.Debug("compiling query"); try { ParserHelper.Parse( new PreprocessingParser(tokenReplacements), queryString, ParserHelper.HqlSeparators, this); RenderSql(); } catch (QueryException qe) { qe.QueryString = queryString; throw; } catch (MappingException) { throw; } catch (Exception e) { log.Debug("unexpected query compilation problem", e); QueryException qe = new QueryException("Incorrect query syntax", e); qe.QueryString = queryString; throw qe; } PostInstantiate(); compiled = true; }
public QueryDescriptor this[string name, string[] subNames, QueryPermission permission] { get { if (string.IsNullOrWhiteSpace(name)) { throw new ArgumentException($"{nameof(name)} is required", nameof(name)); } name = name.Trim().ToLower(); var notExistEx = new QueryException($"Query {name} does not exist", QueryErrorCode.QueryNotFound); if (!_dic.ContainsKey(name)) { throw notExistEx; } var unauthorizedEx = new QueryException($"Unauthorized, don't have permission to access query {name}", QueryErrorCode.Unauthorized); var descriptorDic = _dic[name]; if (subNames == null || subNames.Length == 0) { if (!descriptorDic.ContainsKey(_defaultSubName)) { throw notExistEx; } var query = descriptorDic[_defaultSubName]; if (!query.HasPermission(permission)) { throw unauthorizedEx; } return(query); } else { var subNameList = subNames.Select(p => p.Trim().ToLower()); var subEx = new QueryException($"Sub names of query {name} don't exist or don't have permission to access query", QueryErrorCode.UnauthorizedOrNotFound); QueryDescriptor query; foreach (var subName in subNameList) { if (!descriptorDic.ContainsKey(subName)) { continue; } query = descriptorDic[subName]; if (!query.HasPermission(permission)) { continue; } return(query); } if (!descriptorDic.ContainsKey(_defaultSubName)) { throw subEx; } query = descriptorDic[_defaultSubName]; if (!query.HasPermission(permission)) { throw subEx; } return(query); } } }