public void TestDefaultMessage() { // This will get the default message for Result.Ok code var descriptor = ResultDescriptor.Find(Result.Ok); Assert.True(!descriptor.Description.Contains("Unknown")); }
public Task SubscribeToTriggerAsync(SubscribeToTriggerIntent intent, CancellationToken ct) { _dataStore.SubscribeToTrigger( intent.TriggerId, taskResult => { var transitionDescriptor = new TransitionDescriptor { Type = TransitionType.ContinueRoutine, ETag = intent.Continuation.Routine.ETag }; var resultDescriptor = new ResultDescriptor { CorrelationId = intent.TriggerId, Result = taskResult }; var message = new Message { [nameof(TransitionDescriptor)] = _serializer.SerializeToString(transitionDescriptor), [nameof(ServiceId)] = _serializer.SerializeToString(intent.Continuation.ServiceId), [nameof(RoutineDescriptor)] = _serializer.SerializeToString(intent.Continuation.Routine), [nameof(ResultDescriptor)] = _serializer.SerializeToString(resultDescriptor), DeliverAt = intent.Continuation.ContinueAt?.ToUniversalTime() }; _dataStore.ScheduleMessage(message); }); return(Task.FromResult(0)); }
public Task <ResultDescriptor> GetAwaitedResultAsync(CancellationToken ct) { ResultDescriptor result = null; if (EventData.Result != null) { result = _serializer.Deserialize <ResultDescriptor>(EventData.Result); } return(Task.FromResult(result)); }
public void TestDXGI() { // Force to load DXGI assembly var factory = new Factory1(); factory.Dispose(); // Look for DXGI descriptor SharpDX.DXGI.ResultCode.DeviceRemoved var descriptor = ResultDescriptor.Find(0x887A0005); Assert.AreEqual(descriptor.NativeApiCode, "DXGI_ERROR_DEVICE_REMOVED"); }
/// <summary> /// Presents this instance. /// </summary> /// <returns></returns> public override bool Present() { var res = swapChain.Present(VSyncInterval, PresentFlags.None, presentParams); if (res.Success) { return(true); } else { var desc = ResultDescriptor.Find(res); if (desc == global::SharpDX.DXGI.ResultCode.DeviceRemoved || desc == global::SharpDX.DXGI.ResultCode.DeviceReset || desc == global::SharpDX.DXGI.ResultCode.DeviceHung) { RaiseOnDeviceLost(); } else { swapChain.Present(VSyncInterval, PresentFlags.Restart, presentParams); } return(false); } }
/// <summary> /// Updates the and render. /// </summary> public void UpdateAndRender() { if (CanRender()) { IsBusy = true; var t0 = TimeSpan.FromSeconds((double)Stopwatch.GetTimestamp() / Stopwatch.Frequency); RenderStatistics.FPSStatistics.Push((t0 - lastRenderTime).TotalMilliseconds); RenderStatistics.Camera = viewport.CameraCore; lastRenderTime = t0; UpdateRequested = false; ++updateCounter; renderContext.AutoUpdateOctree = RenderConfiguration.AutoUpdateOctree; renderContext.EnableBoundingFrustum = EnableRenderFrustum; if (RenderConfiguration.UpdatePerFrameData) { viewport.Update(t0); renderContext.TimeStamp = t0; renderContext.Camera = viewport.CameraCore; renderContext.WorldMatrix = viewport.WorldMatrix; renderContext.OITWeightPower = RenderConfiguration.OITWeightPower; renderContext.OITWeightDepthSlope = RenderConfiguration.OITWeightDepthSlope; renderContext.OITWeightMode = RenderConfiguration.OITWeightMode; } PreRender(); UpdateSceneGraphRequested = false; try { if (renderBuffer.BeginDraw()) { OnRender(t0); renderBuffer.EndDraw(); } if (RenderConfiguration.RenderD2D && D2DTarget.D2DTarget != null) { OnRender2D(t0); } renderBuffer.Present(); } catch (SharpDXException ex) { var desc = ResultDescriptor.Find(ex.ResultCode); if (desc == global::SharpDX.DXGI.ResultCode.DeviceRemoved || desc == global::SharpDX.DXGI.ResultCode.DeviceReset || desc == global::SharpDX.DXGI.ResultCode.DeviceHung || desc == global::SharpDX.Direct2D1.ResultCode.RecreateTarget || desc == global::SharpDX.DXGI.ResultCode.AccessLost) { Log(LogLevel.Warning, $"Device Lost, code = {desc.Code}"); RenderBuffer_OnDeviceLost(RenderBuffer, EventArgs.Empty); } else { Log(LogLevel.Error, ex); EndD3D(); ExceptionOccurred?.Invoke(this, new RelayExceptionEventArgs(ex)); } } catch (Exception ex) { Log(LogLevel.Error, ex); EndD3D(); ExceptionOccurred?.Invoke(this, new RelayExceptionEventArgs(ex)); } finally { PostRender(); IsBusy = false; } lastRenderingDuration = TimeSpan.FromSeconds((double)Stopwatch.GetTimestamp() / Stopwatch.Frequency) - t0; RenderStatistics.LatencyStatistics.Push(lastRenderingDuration.TotalMilliseconds); OnRendered?.Invoke(this, EventArgs.Empty); } }
internal static void Setup() { // Register automatically Resultcode from DXGI ResultDescriptor.RegisterProvider(typeof(ResultCode)); }
private static string FormatMessage(ResultDescriptor descriptor, string?message, object[]?args) => message != null ? args is { Length : > 0
public SharpGenException(string message, Exception?innerException = null, params object[]?args) : this(ResultDescriptor.Find(innerException?.HResult ?? Result.Fail), message, innerException, args) { }
public SharpGenException(string message, Exception?innerException = null) : this(ResultDescriptor.Find(innerException?.HResult ?? Result.Fail), message, innerException) { }
public SharpGenException(Result result, string?message = null, Exception?innerException = null, params object[]?args) : this(ResultDescriptor.Find(result), message, innerException, args) { }
public SharpGenException(Result result, string?message = null, Exception?innerException = null) : this(ResultDescriptor.Find(result), message, innerException) { }
public SharpGenException(Exception innerException, string?message = null) : this(ResultDescriptor.Find(innerException.HResult), message, innerException) { }
public SharpGenException() : this(ResultDescriptor.Find(Result.Fail), GenericSharpGenExceptionMessage) { }
public static bool ShouldResetD2DForError(ResultDescriptor resultDescriptor) { return(ShouldResetD2DForError(resultDescriptor.Code)); }
internal static void Setup() { // Register automatically Result code for SharpDX ResultDescriptor.RegisterProvider(typeof(Result)); }
/// <summary> /// Prepares the WHERE clause of the SQL query from the <see cref="Filter"/> argument: WHERE ABC /// </summary> private string PrepareWhereSql(QxCompilationContext ctx) { var ps = ctx.Parameters; // WHERE is cached if (_cachedWhere == null) { string whereFilter = null; string whereInIds = null; string whereInParentIds = null; string whereInPropValues = null; if (Filter != null) { whereFilter = Filter.Expression.CompileToBoolean(ctx); } if (Ids != null && Ids.Any()) { if (Ids.Count() == 1) { string paramName = ps.AddParameter(Ids.Single()); whereInIds = $"[P].[Id] = @{paramName}"; } else { var isIntKey = KeyType == KeyType.Int; // (Nullable.GetUnderlyingType(KeyType) ?? KeyType) == typeof(int); var isStringKey = KeyType == KeyType.String; // Prepare the ids table DataTable idsTable = isIntKey ? RepositoryUtilities.DataTable(Ids.Select(id => new IdListItem { Id = (int)id })) : isStringKey?RepositoryUtilities.DataTable(Ids.Select(id => new StringListItem { Id = id.ToString() })) : throw new InvalidOperationException("Only string and Integer Ids are supported"); // var idsTvp = new SqlParameter("@Ids", idsTable) { TypeName = isIntKey ? "[dbo].[IdList]" : isStringKey ? "[dbo].[StringList]" : throw new InvalidOperationException("Only string and Integer Ids are supported"), SqlDbType = SqlDbType.Structured }; ps.AddParameter(idsTvp); whereInIds = $"[P].[Id] IN (SELECT Id FROM @Ids)"; } } if (ParentIds != null) { if (!ParentIds.Any()) { if (IncludeRoots) { whereInParentIds = $"[P].[ParentId] IS NULL"; } } else if (ParentIds.Count() == 1) { string paramName = ps.AddParameter(ParentIds.Single()); whereInParentIds = $"[P].[ParentId] = @{paramName}"; if (IncludeRoots) { whereInParentIds += " OR [P].[ParentId] IS NULL"; } } else { var isIntKey = KeyType == KeyType.Int; // (Nullable.GetUnderlyingType(KeyType) ?? KeyType) == typeof(int); var isStringKey = KeyType == KeyType.String; // Prepare the data table var parentIdsTable = new DataTable(); string idName = "Id"; var idType = KeyType switch { KeyType.String => typeof(string), KeyType.Int => typeof(int), _ => throw new InvalidOperationException("Bug: Only string and Integer ParentIds are supported"), }; var column = new DataColumn(idName, idType); if (isStringKey) { column.MaxLength = 450; // Just for performance } parentIdsTable.Columns.Add(column); foreach (var id in ParentIds.Where(e => e != null)) { DataRow row = parentIdsTable.NewRow(); row[idName] = id; parentIdsTable.Rows.Add(row); } // Prepare the TVP var parentIdsTvp = new SqlParameter("@ParentIds", parentIdsTable) { TypeName = KeyType == KeyType.Int ? "[dbo].[IdList]" : KeyType == KeyType.String ? "[dbo].[StringList]" : throw new InvalidOperationException("Bug: Only string and Integer ParentIds are supported"), SqlDbType = SqlDbType.Structured }; ps.AddParameter(parentIdsTvp); whereInParentIds = $"[P].[ParentId] IN (SELECT Id FROM @ParentIds)"; if (IncludeRoots) { whereInParentIds += " OR [P].[ParentId] IS NULL"; } } } if (!string.IsNullOrWhiteSpace(PropName) && Values != null && Values.Any()) { var propDesc = ResultDescriptor.Property(PropName); var propType = propDesc.Type; var isIntKey = propType == typeof(int?) || propType == typeof(int); var isStringKey = propType == typeof(string); // Prepare the ids table DataTable valuesTable = isStringKey ? RepositoryUtilities.DataTable(Values.Select(id => new StringListItem { Id = id.ToString() })) : isIntKey?RepositoryUtilities.DataTable(Values.Select(id => new IdListItem { Id = (int)id })) : throw new InvalidOperationException("Only string and Integer Ids are supported"); var valuesTvp = new SqlParameter("@Values", valuesTable) { TypeName = isIntKey ? "[dbo].[IdList]" : isStringKey ? "[dbo].[StringList]" : throw new InvalidOperationException("Only string and Integer values are supported"), SqlDbType = SqlDbType.Structured }; ps.AddParameter(valuesTvp); whereInPropValues = $"[P].[{propDesc.Name}] IN (SELECT Id FROM @Values)"; } // The final WHERE clause (if any) string whereSql = ""; var clauses = new List <string> { whereFilter, whereInIds, whereInParentIds, whereInPropValues }.Where(e => !string.IsNullOrWhiteSpace(e)); if (clauses.Any()) { whereSql = clauses.Aggregate((c1, c2) => $"{c1}) AND ({c2}"); whereSql = $"WHERE ({whereSql})"; } _cachedWhere = whereSql; } return(_cachedWhere); }
private SharpGenException(ResultDescriptor descriptor, string?message, Exception?innerException) : base(FormatMessage(descriptor, message, null), innerException) { Descriptor = descriptor; HResult = descriptor.Result.Code; }
private SharpGenException(ResultDescriptor descriptor, string?message, Exception?innerException, params object[]?args) : base(FormatMessage(descriptor, message, args), innerException) { Descriptor = descriptor; HResult = descriptor.Result.Code; }
private static void CaptureMain(Int32 adapterIndex, Int32 displayIndex) { Resource screenResource = null; try { using (Factory1 factory1 = new Factory1()) { using (Adapter1 adapter1 = factory1.GetAdapter1(adapterIndex)) { using (Device device = new Device(adapter1)) { using (Output output = adapter1.GetOutput(displayIndex)) { using (Output1 output1 = output.QueryInterface <Output1>()) { Int32 width = output1.Description.DesktopBounds.Right - output1.Description.DesktopBounds.Left; Int32 height = output1.Description.DesktopBounds.Bottom - output1.Description.DesktopBounds.Top; Rectangle bounds = new Rectangle(Point.Empty, new Size(width, height)); Texture2DDescription texture2DDescription = new Texture2DDescription { CpuAccessFlags = CpuAccessFlags.Read, BindFlags = BindFlags.None, Format = Format.B8G8R8A8_UNorm, Width = width, Height = height, OptionFlags = ResourceOptionFlags.None, MipLevels = 1, ArraySize = 1, SampleDescription = { Count = 1, Quality = 0 }, Usage = ResourceUsage.Staging }; using (Texture2D texture2D = new Texture2D(device, texture2DDescription)) { using (OutputDuplication outputDuplication = output1.DuplicateOutput(device)) { status = Status.Active; Int32 frameNumber = 0; do { try { Result result = outputDuplication.TryAcquireNextFrame(100, out _, out screenResource); if (result.Success) { frameNumber += 1; using (Texture2D screenTexture2D = screenResource.QueryInterface <Texture2D>()) { device.ImmediateContext.CopyResource(screenTexture2D, texture2D); DataBox dataBox = device.ImmediateContext.MapSubresource(texture2D, 0, MapMode.Read, MapFlags.None); Bitmap bitmap = new Bitmap(width, height, PixelFormat.Format32bppRgb); BitmapData bitmapData = bitmap.LockBits(bounds, ImageLockMode.WriteOnly, bitmap.PixelFormat); IntPtr dataBoxPointer = dataBox.DataPointer; IntPtr bitmapDataPointer = bitmapData.Scan0; for (Int32 y = 0; y < height; y++) { Utilities.CopyMemory(bitmapDataPointer, dataBoxPointer, width * 4); dataBoxPointer = IntPtr.Add(dataBoxPointer, dataBox.RowPitch); bitmapDataPointer = IntPtr.Add(bitmapDataPointer, bitmapData.Stride); } bitmap.UnlockBits(bitmapData); device.ImmediateContext.UnmapSubresource(texture2D, 0); while (SkipFrames && bitmapQueue.Count > 1) { bitmapQueue.TryDequeue(out Bitmap dequeuedBitmap); dequeuedBitmap.Dispose(); } if (frameNumber > 1 || SkipFirstFrame == false) { bitmapQueue.Enqueue(bitmap); waitHandle.Set(); } } } else { if (ResultDescriptor.Find(result).ApiCode != Result.WaitTimeout.ApiCode) { result.CheckError(); } } } finally { screenResource?.Dispose(); try { outputDuplication.ReleaseFrame(); } catch { } } } while (status == Status.Active); } } } } } } } } catch (Exception exception) { globalException = exception; status = Status.Stops; } finally { callbackThread.Join(); Exception exception = globalException; while (bitmapQueue.Count > 0) { bitmapQueue.TryDequeue(out Bitmap dequeuedBitmap); dequeuedBitmap.Dispose(); } globalException = null; waitHandle = null; bitmapQueue = null; captureThread = null; callbackThread = null; status = Status.Inactive; if (OnCaptureStop != null) { OnCaptureStop(null, new OnCaptureStopEventArgs(exception != null ? new Exception(exception.Message, exception) : null)); } else { if (exception != null) { ExceptionDispatchInfo.Capture(exception).Throw(); } } } }