public override object InvokeInstance(object instance, params object[] args) { if (_target.IsStatic) { try { return(_target.Invoke(null, args)); } catch (TargetInvocationException e) { throw ExceptionHelpers.UpdateForRethrow(e.InnerException); } } try { return(_target.Invoke(instance, args)); } catch (TargetInvocationException e) { throw ExceptionHelpers.UpdateForRethrow(e.InnerException); } }
public ResourceType GetResourceType(object resourceObject) { TraceHelper.Current.MethodCall0("DataServiceQueryProvider", "GetResourceType"); object[] objArray = new object[2]; objArray[0] = "resourceObject"; objArray[1] = "DataServiceQueryProvider.GetResourceType"; resourceObject.ThrowIfNull("resourceObject", new ParameterExtensions.MessageLoader(DataServiceQueryProvider.GetInputVariableToODataMethodNullMessage), objArray); DSResource dSResource = resourceObject as DSResource; if (dSResource != null) { return(dSResource.ResourceType); } else { object[] assemblyQualifiedName = new object[3]; assemblyQualifiedName[0] = "resourceObject"; assemblyQualifiedName[1] = resourceObject.GetType().AssemblyQualifiedName; assemblyQualifiedName[2] = typeof(DSResource).AssemblyQualifiedName; string exceptionMessage = ExceptionHelpers.GetExceptionMessage(Resources.InvalidArgClrType, assemblyQualifiedName); throw new ArgumentException(exceptionMessage, "resourceObject"); } }
private object InvokeWorker(params object[] args) { if (_target.IsStatic) { try { return(_target.Invoke(null, args)); } catch (TargetInvocationException e) { throw ExceptionHelpers.UpdateForRethrow(e.InnerException); } } try { return(_target.Invoke(args[0], GetNonStaticArgs(args))); } catch (TargetInvocationException e) { throw ExceptionHelpers.UpdateForRethrow(e.InnerException); } }
public static object Factory(Dictionary <string, object> properties) { object obj = null; object obj1 = null; properties.TryGetValue("UserName", out obj); properties.TryGetValue("Password", out obj1); if (obj != null || obj1 != null) { if (obj != null) { return(new PSCredential((string)obj, WellKnownTypes.CreateSecureString(obj1 as string))); } else { throw new InvalidCastException(ExceptionHelpers.GetExceptionMessage(Resources.FieldParameterNullOrEmpty, new object[0])); } } else { return(null); } }
public void Constructor_uses_given_message_and_inner_exception_and_sets_up_serialization() { var innerException = new Exception("I'm in here."); var exception = new EntitySqlException("I knoweth not, good sir.", innerException); Assert.Equal("I knoweth not, good sir.", exception.Message); Assert.Same(innerException, exception.InnerException); Assert.Equal(HResultInvalidQuery, GetHResult(exception)); Assert.Equal("", exception.ErrorContext); Assert.Equal("", exception.ErrorDescription); Assert.Equal(0, exception.Line); Assert.Equal(0, exception.Column); exception = ExceptionHelpers.SerializeAndDeserialize(exception); Assert.Equal("I knoweth not, good sir.", exception.Message); Assert.Equal(innerException.Message, exception.InnerException.Message); Assert.Equal(HResultInvalidQuery, GetHResult(exception)); Assert.Equal("", exception.ErrorContext); Assert.Equal("", exception.ErrorDescription); Assert.Equal(0, exception.Line); Assert.Equal(0, exception.Column); }
/// <summary> /// Sets the Wallpaper Image using a file within the Application Storage /// </summary> /// <param name="localStorageFile">A file within the Application Storage</param> /// <returns>If the Wallpaper Image was successfully Set</returns> public override async Task <bool> SetImage(StorageFile localStorageFile) { if (!IsSupported) { return(false); } if (localStorageFile == null) { return(false); } try { bool success = await UserProfilePersonalizationSettings.Current.TrySetWallpaperImageAsync(localStorageFile); return(success); } catch (Exception e) { ExceptionHelpers.PrintOutException(e, "Wallpaper: Set Image"); return(false); } }
private void ExecuteAsync_doesnt_retry_on_transient_exceptions(Func <IExecutionStrategy, Func <Task <int> >, Task> executeAsync) { var executionStrategy = new DefaultSqlExecutionStrategy(); var executionCount = 0; var exception = Assert.Throws <EntityException>( () => ExceptionHelpers.UnwrapAggregateExceptions( () => executeAsync( executionStrategy, () => { executionCount++; throw new TimeoutException(); }).Wait())); Assert.IsType <TimeoutException>(exception.InnerException); exception.ValidateMessage( TestBase.EntityFrameworkSqlServerAssembly, "TransientExceptionDetected", "System.Data.Entity.SqlServer.Properties.Resources.SqlServer"); Assert.Equal(1, executionCount); }
public static void ValidateException(Exception expectedException, Exception actualException) { if ((expectedException == null) && (actualException == null)) { return; } if ((expectedException == null) ^ (actualException == null)) { //Log.TraceInternal("Expected exception: {0}\n", expectedException == null ? "null" : expectedException.ToString()); //Log.TraceInternal("Actual exception: {0}\n", actualException == null ? "null" : actualException.ToString()); throw new Exception("Actual exception and expected exceptiond do not match!"); } //Log.TraceInternal(string.Format("Expected exception: {0}", expectedException.ToString())); //Log.TraceInternal(string.Format("Actual exception: {0}", actualException.ToString())); Dictionary <string, string> dict = new Dictionary <string, string>() { { "Message", actualException.Message } }; // throws when validation fails. ExceptionHelpers.ValidateException(expectedException, actualException.GetType(), dict); }
private static string s_path = string.Empty; //DirectoryAssistance.GetTestBinsDirectory("TempFile.txt"); public static void ValidateExpressionXaml <T>(TestExpression te) { Activity expectedActivity = null, actualActivity = null; Expression <Func <ActivityContext, T> > lambdaExpression = null; lambdaExpression = (Expression <Func <ActivityContext, T> >)te.CreateLambdaExpresson <T>(); //Log.TraceInternal("Expression: {0}", lambdaExpression.ToString()); expectedActivity = te.CreateExpectedActivity() as Activity; if (te.ExpectedConversionException != null) { ExceptionHelpers.CheckForException( te.ExpectedConversionException.GetType(), te.ExpectedConversionException.Message, () => { actualActivity = ExpressionServices.Convert(lambdaExpression); }, true); } else { actualActivity = ExpressionServices.Convert(lambdaExpression); ValidateActivity(expectedActivity, actualActivity); } }
private void ExecuteAsync_throws_on_invalid_delay(Func <DbExecutionStrategy, Func <Task <int> >, Task> executeAsync) { var executionStrategyMock = new Mock <DbExecutionStrategy> { CallBase = true }; executionStrategyMock.Setup(m => m.GetNextDelay(It.IsAny <Exception>())).Returns <Exception>( e => TimeSpan.FromTicks(-1)); executionStrategyMock.Protected().Setup <bool>("ShouldRetryOn", ItExpr.IsAny <Exception>()).Returns <Exception>( e => e is ExternalException); var executionCount = 0; Assert.Equal( Strings.ExecutionStrategy_NegativeDelay(TimeSpan.FromTicks(-1)), Assert.Throws <InvalidOperationException>( () => ExceptionHelpers.UnwrapAggregateExceptions( () => executeAsync( executionStrategyMock.Object, () => { if (executionCount++ < 3) { throw new ExternalException(); } else { Assert.True(false); return(Task.FromResult(0)); } }).Wait())).Message); Assert.Equal(1, executionCount); }
public void Move(string OldDirectoryFullName, string OldFileName, string NewDirectoryFullName, string NewFileName) { if (_ProtocolV3 == null) { throw new NFSConnectionException("NFS Client not connected!"); } if (_MountProtocolV3 == null) { throw new NFSMountConnectionException("NFS Device not connected!"); } NFSAttributes OldDirectory = GetItemAttributes(OldDirectoryFullName); NFSAttributes NewDirectory = GetItemAttributes(NewDirectoryFullName); RenameArguments dpArgRename = new RenameArguments(); dpArgRename.From = new ItemOperationArguments(); dpArgRename.From.Directory = new NFSHandle(OldDirectory.Handle, V3.RPC.NFSv3Protocol.NFS_V3); dpArgRename.From.Name = new Name(OldFileName); dpArgRename.To = new ItemOperationArguments(); dpArgRename.To.Directory = new NFSHandle(NewDirectory.Handle, V3.RPC.NFSv3Protocol.NFS_V3); dpArgRename.To.Name = new Name(NewFileName); ResultObject <RenameAccessOK, RenameAccessFAIL> pRenameRes = _ProtocolV3.NFSPROC3_RENAME(dpArgRename); if (pRenameRes == null || pRenameRes.Status != NFSStats.NFS_OK) { if (pRenameRes == null) { throw new NFSGeneralException("NFSPROC3_WRITE: failure"); } ExceptionHelpers.ThrowException(pRenameRes.Status); } }
public void TestExecuteWithErrorReportingThrowOperationCanceledException() { bool finallyExecuted = false; Action a = () => { try { throw new OperationCanceledException(); } finally { finallyExecuted = true; } }; try { try { a(); } catch (Exception e) if (ExceptionHelpers.CrashUnlessCanceled(e)) { throw ExceptionUtilities.Unreachable; } Assert.True(false, "Should not get here because an exception should be thrown before this point."); } catch (OperationCanceledException) { Assert.True(finallyExecuted); return; } Assert.True(false, "Should have returned in the catch block before this point."); }
/// <summary> /// Get a metadata reference to this compilation info's compilation with respect to /// another project. For cross language references produce a skeletal assembly. If the /// compilation is not available, it is built. If a skeletal assembly reference is /// needed and does not exist, it is also built. /// </summary> internal async Task <MetadataReference> GetMetadataReferenceAsync( Solution solution, ProjectState fromProject, ProjectReference projectReference, CancellationToken cancellationToken) { try { Compilation compilation; // if we already have the compilation and its right kind then use it. if (this.ProjectState.LanguageServices == fromProject.LanguageServices && this.TryGetCompilation(out compilation)) { return(compilation.ToMetadataReference(projectReference.Aliases, projectReference.EmbedInteropTypes)); } // If same language then we can wrap the other project's compilation into a compilation reference if (this.ProjectState.LanguageServices == fromProject.LanguageServices) { // otherwise, base it off the compilation by building it first. compilation = await this.GetCompilationAsync(solution, cancellationToken).ConfigureAwait(false); return(compilation.ToMetadataReference(projectReference.Aliases, projectReference.EmbedInteropTypes)); } else { // otherwise get a metadata only image reference that is built by emitting the metadata from the referenced project's compilation and re-importing it. return(await this.GetMetadataOnlyImageReferenceAsync(solution, projectReference, cancellationToken).ConfigureAwait(false)); } } catch (Exception e) if (ExceptionHelpers.CrashUnlessCanceled(e)) { throw ExceptionUtilities.Unreachable; } }
private bool IsNullValueAllowedForField(string fieldName) { Func <ResourceProperty, bool> func = null; if (this.entityType == null) { return(true); } else { ReadOnlyCollection <ResourceProperty> properties = this.entityType.Properties; if (func == null) { func = (ResourceProperty item) => item.Name == fieldName; } ResourceProperty resourceProperty = properties.FirstOrDefault <ResourceProperty>(func); if (resourceProperty != null) { if (!resourceProperty.ResourceType.IsPrimitive() || resourceProperty.ResourceType.IsNullable()) { return(true); } else { return(false); } } else { object[] name = new object[2]; name[0] = fieldName; name[1] = this.entityType.Name; throw new ArgumentException(ExceptionHelpers.GetExceptionMessage(Resources.PropertyNotFoundInODataResource, name)); } } }
public void Load(XDocument doc) { var r = doc.Root; var c = control; var a = control.airportInfoControl; var w = control.weatherInfoControl; // The order is important. E.g. "pressUnit" has to be // loaded before "pressure", due to events handlers attached // to pressure.TextChanged. Action[] actions = { () => a.airportTxtBox.Text = r.GetString(airportIcao), () => a.rwyComboBox.Text = r.GetString(rwy), () => a.lengthUnitComboBox.Text = r.GetString(lengthUnit), () => w.windDirTxtBox.Text = r.GetString(windDir), () => w.windSpdTxtBox.Text = r.GetString(windSpeed), () => w.tempUnitComboBox.Text = r.GetString(tempUnit), () => w.oatTxtBox.Text = r.GetString(oat), () => w.pressUnitComboBox.Text = r.GetString(pressUnit), () => w.pressTxtBox.Text = r.GetString(pressure), () => w.surfCondComboBox.Text = r.GetString(surfCond), () => c.acListComboBox.Text = r.GetString(aircraft), () => c.wtUnitComboBox.Text = r.GetString(wtUnit), () => c.weightTxtBox.Text = r.GetString(toWt), () => c.flapsComboBox.Text = r.GetString(flaps), () => c.thrustRatingComboBox.Text = r.GetString(thrustRating), () => c.antiIceComboBox.Text = r.GetString(antiIce), () => c.packsComboBox.Text = r.GetString(packs) }; foreach (var action in actions) { ExceptionHelpers.IgnoreException(action); } }
internal void GenerateViewComponents() { this.EnsureExtentIsFullyMapped(this._usedViews); this.GenerateCaseStatements(this._domainMap.ConditionMembers(this._extentPath.Extent), this._usedViews); this.AddTrivialCaseStatementsForConditionMembers(); if (this._usedViews.Count == 0 || this._errorLog.Count > 0) { ExceptionHelpers.ThrowMappingException(this._errorLog, this._config); } this._topLevelWhereClause = this.GetTopLevelWhereClause(this._usedViews); int viewTarget = (int)this._context.ViewTarget; this._usedCells = this.RemapFromVariables(); this._basicView = new BasicViewGenerator(this._context.MemberMaps.ProjectedSlotMap, this._usedCells, this._domainQuery, this._context, this._domainMap, this._errorLog, this._config).CreateViewExpression(); if (this._context.LeftFragmentQP.IsContainedIn(this._basicView.LeftFragmentQuery, this._domainQuery)) { this._topLevelWhereClause = BoolExpression.True; } if (this._errorLog.Count <= 0) { return; } ExceptionHelpers.ThrowMappingException(this._errorLog, this._config); }
public void WhenExceptionActionPassed_ThenItShouldBeInvokedOnException() { var system = new ActorSystem(); IBus bus = null; system.Add(new ThrowingHandler(), ctx => { bus = ctx.Bus; }); Exception ex = null; var wait = new ManualResetEventSlim(false); system.Start(e => { ex = e; wait.Set(); }); var msg = new Message(); bus.Publish(ref msg); Assert.True(wait.Wait(TimeSpan.FromSeconds(10))); ExceptionHelpers.ExceptionOrAggregateWithOne(ex, ThrowingHandler.Exception); }
/// <summary> /// Overrides the brake settings of CalculatorData. /// </summary> /// <exception cref="RunwayTooShortException"></exception> /// <exception cref="Exception"></exception> public static LandingReport LandingReport(CalculatorData d) { var p = d.Parameters; var t = d.Table; var all = t.AllBrakes().Select(b => { return(ExceptionHelpers.DefaultIfThrows(() => { var dis = LandingDistanceMeter(d, null, b); return new ReportRow() { BrakeSetting = b, RequiredDistanceMeter = RoundToInt(dis), RemainingDistanceMeter = RoundToInt(p.RwyLengthMeter - dis) }; }, null)); }).ToList(); var selected = all[p.BrakeIndex]; if (selected == null) { throw new Exception("Unexpected error occurred."); } if (selected.RemainingDistanceMeter < 0) { throw new RunwayTooShortException(); } return(new LandingReport() { SelectedBrake = selected, AllBrakes = all }); }
private void ExecuteAsync_retries_until_limit_is_reached(Func <DbExecutionStrategy, Func <Task <int> >, Task> executeAsync) { var executionCount = 0; var executionStrategyMock = new Mock <DbExecutionStrategy> { CallBase = true }; executionStrategyMock.Setup(m => m.GetNextDelay(It.IsAny <Exception>())).Returns <Exception>( e => executionCount < 3 ? (TimeSpan?)TimeSpan.FromTicks(0) : null); executionStrategyMock.Protected().Setup <bool>("ShouldRetryOn", ItExpr.IsAny <Exception>()).Returns <Exception>( e => e is ExternalException); Assert.IsType <ExternalException>( Assert.Throws <RetryLimitExceededException>( () => ExceptionHelpers.UnwrapAggregateExceptions( () => executeAsync( executionStrategyMock.Object, () => { if (executionCount++ < 3) { throw new ExternalException(); } else { Assert.True(false); return(Task.FromResult(0)); } }).Wait())).InnerException); Assert.Equal(3, executionCount); }
public InitialSessionStateManager(string pssessionConfigurationAssembly, string pssessionConfigurationTypeName) { try { Type type = TypeLoader.LoadType(pssessionConfigurationAssembly, pssessionConfigurationTypeName); if (type != null) { this.sessionConfiguration = type.Assembly.CreateInstance(type.FullName) as PSSessionConfiguration; if (this.sessionConfiguration == null) { throw new ArgumentException(ExceptionHelpers.GetExceptionMessage(Resources.PSSessionConfigurationCreationFailed, new object[0])); } } else { object[] objArray = new object[2]; objArray[0] = pssessionConfigurationTypeName; objArray[1] = pssessionConfigurationAssembly; throw new ArgumentException(ExceptionHelpers.GetExceptionMessage(Resources.TypeLoadFromAssebmlyFailed, objArray), "pssessionConfigurationTypeName"); } } catch (Exception exception1) { Exception exception = exception1; TraceHelper.Current.PSSessionConfigurationLoadingFailed(pssessionConfigurationAssembly, exception.ToTraceMessage("Exception")); if (!exception.IsSevereException()) { throw new TypeLoadException(pssessionConfigurationTypeName, pssessionConfigurationAssembly, Utils.GetBaseBinDirectory(pssessionConfigurationAssembly), exception); } else { throw; } } TraceHelper.Current.PSSessionConfigurationLoadedSuccessfully(pssessionConfigurationTypeName); }
public EntityUpdate(CommandType commandType, UserContext userContext, ResourceType type, EntityMetadata metadata, IQueryable query, string membershipId) { ExceptionHelpers.ThrowArgumentExceptionIf("commandType", commandType != CommandType.Update, Resources.InternalErrorOccurred, new object[0]); this.query = query; this.userContext = userContext; this.membershipId = membershipId; this.resourceType = type; this.metadata = metadata; this.commandType = commandType; this.propertyUpdates = new SortedDictionary <string, object>(); this.updatedResource = null; this.resolveResource = null; CommandArgumentVisitor commandArgumentVisitor = new CommandArgumentVisitor(this); commandArgumentVisitor.Visit(query.Expression); if (this.AreAllKeyFieldsSpecified()) { return; } else { throw new ArgumentException(ExceptionHelpers.GetExceptionMessage(Resources.KeysMissingInQuery, new object[0])); } }
public static bool FindMappingErrors( ViewgenContext context, MemberDomainMap domainMap, ErrorLog errorLog) { if (context.ViewTarget == ViewTarget.QueryView && !context.Config.IsValidationEnabled) { return(false); } ErrorPatternMatcher errorPatternMatcher = new ErrorPatternMatcher(context, domainMap, errorLog); errorPatternMatcher.MatchMissingMappingErrors(); errorPatternMatcher.MatchConditionErrors(); errorPatternMatcher.MatchSplitErrors(); if (errorPatternMatcher.m_errorLog.Count == errorPatternMatcher.m_originalErrorCount) { errorPatternMatcher.MatchPartitionErrors(); } if (errorPatternMatcher.m_errorLog.Count > errorPatternMatcher.m_originalErrorCount) { ExceptionHelpers.ThrowMappingException(errorPatternMatcher.m_errorLog, errorPatternMatcher.m_viewgenContext.Config); } return(false); }
private void SaveDocumentText(DocumentId id, string fullPath, SourceText newText, Encoding encoding) { try { using (ExceptionHelpers.SuppressFailFast()) { var dir = Path.GetDirectoryName(fullPath); if (!Directory.Exists(dir)) { Directory.CreateDirectory(dir); } Debug.Assert(encoding != null); using (var writer = new StreamWriter(fullPath, append: false, encoding: encoding)) { newText.Write(writer); } } } catch (IOException exception) { this.OnWorkspaceFailed(new DocumentDiagnostic(WorkspaceDiagnosticKind.Failure, exception.Message, id)); } }
/// <summary> /// This method will delete the automatic created Resiliency key. PowerPoint uses this registry key /// to make entries to corrupted presentations. If there are to many entries under this key PowerPoint will /// get slower and slower to start. To prevent this we just delete this key when it exists /// </summary> private void DeleteResiliencyKeys() { Logger.WriteToLog("Deleting PowerPoint resiliency keys from the registry"); try { // HKEY_CURRENT_USER\Software\Microsoft\Office\14.0\PowerPoint\Resiliency\DocumentRecovery var key = $@"Software\Microsoft\Office\{_versionNumber}.0\PowerPoint\Resiliency"; if (Registry.CurrentUser.OpenSubKey(key, false) != null) { Registry.CurrentUser.DeleteSubKeyTree(key); Logger.WriteToLog("Resiliency keys deleted"); } else { Logger.WriteToLog("There are no keys to delete"); } } catch (Exception exception) { Logger.WriteToLog($"Failed to delete resiliency keys, error: {ExceptionHelpers.GetInnerException(exception)}"); } }
public async Task <(AppProduct, PurchaseResults)> Purchase(string id) { var license = GetLicense(id); // If the product does not exist, exit with null if (license == null) { Debug.WriteLine("This product does not exist"); throw new ArgumentException($"A product by ProductID of {id} does not exist", nameof(AppProduct.ProductID)); //return (null, null); } // If the license is valid, but we don't have the product, create the product var product = GetAppProductByProductID(id); if (product == null) { product = new AppProduct(id, id, false); AppProducts.Add(product); } // If the license is already active, simply return the product if (license.IsActive) { Debug.WriteLine("User already owns this product"); return(product, null); } try { PurchaseResults purchaseResults; if (DebugHelpers.DebugMode) { Debug.WriteLine("Debug mode active, Simulating product purchase"); purchaseResults = await CurrentAppSimulator.RequestProductPurchaseAsync(id); Debug.WriteLine("Finished Simulating"); } else { Debug.WriteLine("Requesting Product Purchase"); purchaseResults = await CurrentApp.RequestProductPurchaseAsync(id); Debug.WriteLine("User finished interacting with purchase screen"); } switch (purchaseResults.Status) { case ProductPurchaseStatus.AlreadyPurchased: Debug.WriteLine("User already owns this product"); MarkProductPurchased(product); break; case ProductPurchaseStatus.Succeeded: Debug.WriteLine("User now owns this product"); MarkProductPurchased(product); break; case ProductPurchaseStatus.NotPurchased: Debug.WriteLine("User chose to not purchase the product"); product.Purchased = false; if (DebugHelpers.DebugMode) { Debug.WriteLine("Simulating Purchase"); MarkProductPurchased(product); } break; case ProductPurchaseStatus.NotFulfilled: Debug.WriteLine("A previous purchase was not fulfilled"); MarkProductPurchased(product); break; default: Debug.WriteLine("An unknown response occurred. Please try again later"); break; } return(product, purchaseResults); } catch (Exception ex) { ExceptionHelpers.PrintOutException(ex, $"Product Purchase Error ({id})"); } return(product, null); }
private void InternalStart() { var readTaskEvent = default(AutoResetEvent); var writeTaskEvent = default(AutoResetEvent); var cancel = CancellationTokenSource.CreateLinkedTokenSource(this.Cancel, _close.Token).Token; try { if (this.Client == null) { using (var connectTaskEvent = new AutoResetEvent(false)) { this.Client = new TcpClient(); var connectTask = this.Client.ConnectAsync(IPAddress.Parse(this.HostName), this.Port).ContinueWithEvent(connectTaskEvent); while (!cancel.IsCancellationRequested) { if (connectTask.IsFaulted) { this.Logger?.LogError(0, connectTask.Exception, this.LogPrefix(this.Name) + "Exception Connecting TCP End"); return; } else if (connectTask.IsCompleted) { this.Logger?.LogInformation(this.LogPrefix(this.Name) + $"Connected from {this.Client.Client.LocalEndPoint} to {this.Client.Client.RemoteEndPoint}"); break; } var waitResult = WaitHandle.WaitAny(new WaitHandle[] { cancel.WaitHandle, connectTaskEvent }, TimeSpan.FromSeconds(0.1)); if (waitResult == 0) { if (_close.IsCancellationRequested) { this.Logger?.LogInformation(this.LogPrefix(this.Name) + "Got close event."); } else { this.Logger?.LogInformation(this.LogPrefix(this.Name) + "Got cancel event."); } return; } } } } else { this.Logger?.LogInformation(this.LogPrefix(this.Name) + $"Already connected from {this.Client.Client.LocalEndPoint} to {this.Client.Client.RemoteEndPoint}"); } var stream = this.Client.GetStream(); var readBuffer = new byte[8192]; var writeBuffer = default(byte[]); var readTask = default(Task <int>); var writeTask = default(Task); readTaskEvent = new AutoResetEvent(false); writeTaskEvent = new AutoResetEvent(false); while (!cancel.IsCancellationRequested) { if (readTask == null) { readTask = stream.ReadAsync(readBuffer, 0, readBuffer.Length).ContinueWithEvent(readTaskEvent); } if (readTask.IsCompleted) { var read = readTask.Result; if (read == 0) { this.Logger?.LogInformation(this.LogPrefix(this.Name) + $"Got 0 length read, quitting."); return; } this.Outgoing.AddRange(readBuffer.Take(read)); readTask = null; } if (writeTask == null) { var writeData = this.Incoming.Take(1024); if (writeData.Any()) { writeBuffer = writeData.ToArray(); writeTask = stream.WriteAsync(writeBuffer, 0, writeBuffer.Length).ContinueWith((t) => ExceptionHelpers.WrapObjectDisposedException(() => writeTaskEvent.Set())); } } if ((writeTask != null) && writeTask.IsCompleted) { writeTask = null; } var waitResult = WaitHandle.WaitAny(new WaitHandle[] { cancel.WaitHandle, readTaskEvent, writeTaskEvent, this.Incoming.Added }, TimeSpan.FromSeconds(0.1)); if (waitResult == 0) { if (_close.IsCancellationRequested) { this.Logger?.LogInformation(this.LogPrefix(this.Name) + "Got close event."); } else { this.Logger?.LogInformation(this.LogPrefix(this.Name) + "Got cancel event."); } return; } } } catch (Exception ex) { this.Logger?.LogError(0, ex, this.LogPrefix(this.Name) + "Got Exception"); } finally { this.OtherEnd?.Close(); this.Client?.Dispose(); readTaskEvent?.Dispose(); writeTaskEvent?.Dispose(); } }
public static DSConfiguration GetSection(Configuration config) { DSConfiguration section; DSConfiguration dSConfiguration; try { if (config == null) { section = ConfigurationManager.GetSection("managementOdata") as DSConfiguration; } else { section = config.GetSection("managementOdata") as DSConfiguration; } if (section != null) { var hasErrors = false; // section.ElementInformation.Errors != null -- Not Implemeted; if (hasErrors) { IEnumerator enumerator = section.ElementInformation.Errors.GetEnumerator(); try { if (enumerator.MoveNext()) { Exception current = (Exception)enumerator.Current; throw new InvalidConfigurationException(Resources.ConfigError, current); } } finally { IDisposable disposable = enumerator as IDisposable; if (disposable != null) { disposable.Dispose(); } } } section.Trace(); TraceHelper.Current.ValidDataServiceConfiguration(); dSConfiguration = section; } else { if (config != null) { TraceHelper.Current.DebugMessage(string.Concat("Configuration file ", config.FilePath, " does not contain managementOdata section.")); } object[] objArray = new object[1]; objArray[0] = "managementOdata"; string exceptionMessage = ExceptionHelpers.GetExceptionMessage(Resources.ConfigMissing, objArray); throw new InvalidConfigurationException(exceptionMessage); } } catch (ConfigurationErrorsException configurationErrorsException1) { ConfigurationErrorsException configurationErrorsException = configurationErrorsException1; throw new InvalidConfigurationException(Resources.ConfigError, configurationErrorsException); } return(dSConfiguration); }
internal MemberDomainMap( ViewTarget viewTarget, bool isValidationEnabled, IEnumerable <Cell> extentCells, EdmItemCollection edmItemCollection, ConfigViewGenerator config, Dictionary <EntityType, Set <EntityType> > inheritanceGraph) { m_conditionDomainMap = new Dictionary <MemberPath, CellConstantSet>(MemberPath.EqualityComparer); m_edmItemCollection = edmItemCollection; Dictionary <MemberPath, CellConstantSet> domainMap = null; if (viewTarget == ViewTarget.UpdateView) { domainMap = Domain.ComputeConstantDomainSetsForSlotsInUpdateViews(extentCells, m_edmItemCollection); } else { domainMap = Domain.ComputeConstantDomainSetsForSlotsInQueryViews(extentCells, m_edmItemCollection, isValidationEnabled); } foreach (var cell in extentCells) { var cellQuery = cell.GetLeftQuery(viewTarget); // Get the atoms from cellQuery and only keep the ones that // are condition members foreach (var condition in cellQuery.GetConjunctsFromWhereClause()) { // Note: TypeConditions are created using OneOfTypeConst and // scalars are created using OneOfScalarConst var memberPath = condition.RestrictedMemberSlot.MemberPath; Debug.Assert( condition is ScalarRestriction || condition is TypeRestriction, "Unexpected restriction"); // Take the narrowed domain from domainMap, if any CellConstantSet domainValues; if (!domainMap.TryGetValue(memberPath, out domainValues)) { domainValues = Domain.DeriveDomainFromMemberPath(memberPath, edmItemCollection, isValidationEnabled); } //Don't count conditions that are satisfied through IsNull=false if (!domainValues.Contains(Constant.Null)) { //multiple values of condition represent disjunction in conditions (not currently supported) // if there is any condition constant that is NotNull if (condition.Domain.Values.All(conditionConstant => (conditionConstant.Equals(Constant.NotNull)))) { continue; } //else there is atleast one condition value that is allowed, continue view generation } //------------------------------------------ //| Nullable | IsNull | Test case | //| T | T | T | //| T | F | T | //| F | T | F | //| F | F | T | //------------------------------------------ //IsNull condition on a member that is non nullable is an invalid condition if (domainValues.Count <= 0 || (!domainValues.Contains(Constant.Null) && condition.Domain.Values.Contains(Constant.Null))) { var message = Strings.ViewGen_InvalidCondition(memberPath.PathToString(false)); var record = new ErrorLog.Record(ViewGenErrorCode.InvalidCondition, message, cell, String.Empty); ExceptionHelpers.ThrowMappingException(record, config); } if (memberPath.IsAlwaysDefined(inheritanceGraph) == false) { domainValues.Add(Constant.Undefined); } AddToDomainMap(memberPath, domainValues); } } // Fill up the domains for the remaining slots as well m_nonConditionDomainMap = new Dictionary <MemberPath, CellConstantSet>(MemberPath.EqualityComparer); foreach (var cell in extentCells) { var cellQuery = cell.GetLeftQuery(viewTarget); // Get the atoms from cellQuery and only keep the ones that // are condition members foreach (var slot in cellQuery.GetAllQuerySlots()) { var member = slot.MemberPath; if (m_conditionDomainMap.ContainsKey(member) == false && m_nonConditionDomainMap.ContainsKey(member) == false) { var memberSet = Domain.DeriveDomainFromMemberPath( member, m_edmItemCollection, true /* Regardless of validation, leave the domain unbounded because this is not a condition member */); if (member.IsAlwaysDefined(inheritanceGraph) == false) { // nonConditionMember may belong to subclass memberSet.Add(Constant.Undefined); } memberSet = Domain.ExpandNegationsInDomain(memberSet, memberSet); m_nonConditionDomainMap.Add(member, new CellConstantSetInfo(memberSet)); } } } }
private async void ReceiveThread() { while (true) { var url = string.Empty; var line = string.Empty; var statusCode = HttpStatusCode.OK; try { cancel.Token.ThrowIfCancellationRequested(); url = await query.BuildUrl().ConfigureAwait(false); var request = App.Config.HttpStreamFactory.GetStreamHttpRequestMessage(HttpMethod.Get, url); HttpResponseMessage response = null; if (await Task.Run(async delegate { response = await http.SendAsync(request, HttpCompletionOption.ResponseHeadersRead, cancel.Token).ConfigureAwait(false); return(false); }).WithTimeout(App.Config.DatabaseColdStreamTimeout, true).ConfigureAwait(false)) { continue; } var serverEvent = ServerEventType.KeepAlive; statusCode = response.StatusCode; response.EnsureSuccessStatusCode(); using (var stream = await response.Content.ReadAsStreamAsync()) using (var reader = new NonBlockingStreamReader(stream)) { try { reader.Peek(); // ReadlineAsync bug fix (no idea) } catch { } while (true) { cancel.Token.ThrowIfCancellationRequested(); line = string.Empty; if (await Task.Run(async delegate { line = (await reader.ReadLineAsync().ConfigureAwait(false))?.Trim(); return(false); }).WithTimeout(App.Config.DatabaseColdStreamTimeout, true).ConfigureAwait(false)) { break; } if (string.IsNullOrWhiteSpace(line)) { continue; } var tuple = line.Split(new[] { ':' }, 2, StringSplitOptions.RemoveEmptyEntries).Select(s => s.Trim()).ToArray(); switch (tuple[0].ToLower()) { case "event": serverEvent = ParseServerEvent(serverEvent, tuple[1]); break; case "data": ProcessServerData(url, serverEvent, tuple[1]); break; } if (serverEvent == ServerEventType.AuthRevoked) { // auth token no longer valid, reconnect break; } } } } catch (OperationCanceledException) { break; } catch (Exception ex) { var fireEx = new FirebaseException(ExceptionHelpers.GetFailureReason(statusCode), ex); onError?.Invoke(this, fireEx); } await Task.Delay(App.Config.DatabaseRetryDelay).ConfigureAwait(false); } }
private static void TestInstanceOperationFromResumeBookmarkCallback(int operationsId, bool isSync) { var shouldNotExecuteMsg = "Should not see this message"; var value = VariableHelper.Create <int>("value"); var writeLineNotRun = new TestWriteLine("NotExecuted", shouldNotExecuteMsg) { }; var testSequence = new TestSequence() { Variables = { value }, Activities = { new TestWriteLine() { Message = "Workflow Started" }, new TestWaitReadLine <int>("Read", "Read") { BookmarkValue = value }, } }; //Get Expected Trace without TestWriteLine() if (operationsId == 2) { testSequence.ExpectedOutcome = Outcome.Canceled; } var expectedTrace = testSequence.GetExpectedTrace(); if (operationsId == 4) { expectedTrace.Trace.Steps.RemoveAt(expectedTrace.Trace.Steps.Count - 1); } else if (operationsId == 3) { expectedTrace.Trace.Steps.RemoveAt(expectedTrace.Trace.Steps.Count - 1); expectedTrace.Trace.Steps.Add(new ActivityTrace(testSequence.DisplayName, ActivityInstanceState.Faulted)); } //Now Add TestWriteLine to workflow testSequence.Activities.Add(writeLineNotRun); TestWorkflowRuntimeAsyncResult asyncResultResume = null; TestWorkflowRuntimeAsyncResult asyncResultOperation = null; var message = ""; //Execute Workflow var jsonStore = new JsonFileInstanceStore.FileInstanceStore(".\\~"); // using PersistableIdleAction.None here because the idle unload was racing with the // resume bookmark after the wait for the BeforeWait trace. var workflowRuntime = TestRuntime.CreateTestWorkflowRuntime(testSequence, null, jsonStore, PersistableIdleAction.None); workflowRuntime.ExecuteWorkflow(); workflowRuntime.WaitForActivityStatusChange("Read", TestActivityInstanceState.Executing); if (isSync) { //Log.Info("Resuming Bookmark"); if (isSync) { workflowRuntime.ResumeBookMark("Read", 9999); } else { asyncResultResume = workflowRuntime.BeginResumeBookMark("Read", 9999, null, null); } workflowRuntime.WaitForTrace(new UserTrace(WaitReadLine <int> .BeforeWait)); switch (operationsId) { case 2: //Cancel Workflow during OnResumeBookmark is executing //Log.Info("CancelWorkflow during OnResumeBookmark executing"); if (isSync) { workflowRuntime.CancelWorkflow(); } else { asyncResultOperation = workflowRuntime.BeginCancelWorkflow(null, null); workflowRuntime.EndResumeBookMark(asyncResultResume); workflowRuntime.EndCancelWorkflow(asyncResultOperation); } //Trace.WriteLine should not execute break; case 3: //Terminate Workflow during OnResumeBookmark is executing //Log.Info("TerminateWorkflow during OnResumeBookmark executing"); if (isSync) { workflowRuntime.TerminateWorkflow("Terminate Exception"); } else { asyncResultOperation = workflowRuntime.BeginTerminateWorkflow("Terminate Exception", null, null); workflowRuntime.EndResumeBookMark(asyncResultResume); workflowRuntime.EndTerminateWorkflow(asyncResultOperation); } //Trace.WriteLine should not execute. break; case 4: //Unload Workflow during OnResumeBookmark is executing //This should wait till ResumeMark finishes the work //Log.Info("UnloadWorkflow during OnResumeBookmark executing"); if (isSync) { workflowRuntime.UnloadWorkflow(); } else { asyncResultOperation = workflowRuntime.BeginUnloadWorkflow(null, null); workflowRuntime.EndResumeBookMark(asyncResultResume); workflowRuntime.EndUnloadWorkflow(asyncResultOperation); } //message = String.Format(ExceptionStrings.WorkflowInstanceUnloaded, workflowRuntime.CurrentWorkflowInstanceId); ExceptionHelpers.CheckForException(typeof(WorkflowApplicationUnloadedException), message, new ExceptionHelpers.MethodDelegate( delegate { workflowRuntime.ResumeWorkflow(); })); break; } } if (isSync) { switch (operationsId) { case 2: { workflowRuntime.WaitForCanceled(expectedTrace); break; } case 3: { workflowRuntime.WaitForTerminated(1, out var terminationException, expectedTrace); break; } case 4: { // We tried to do a ResumeWorkflow without loading it after an unload, // so we expected to get a WorkflowApplicationUnloadedException. The // workflow will never complete, so don't wait for it to complete. break; } } } else { //Give some time for Workflow to execute Thread.CurrentThread.Join((int)TimeSpan.FromSeconds(1).TotalMilliseconds); } if (isSync) { expectedTrace.AddIgnoreTypes(typeof(WorkflowInstanceTrace)); workflowRuntime.ActualTrace.Validate(expectedTrace); } else { //The traces are vary in the async situations, thus we can not do a full trace valdation //validate the writeline after read activity is not executed is sufficient if (workflowRuntime.ActualTrace.ToString().Contains(shouldNotExecuteMsg)) { throw new Exception("The NotExecuted WriteLine activity has been executed, the expectation is it does not"); } } }