public ComponentOperation( ComponentBase component, string operationName, ComponentOperationImplementation <TRequest, TResponse> implementation ) { Assure.ArgumentNotNull(component, nameof(component)); Assure.ArgumentNotNull(operationName, nameof(operationName)); Assure.ArgumentNotNull(implementation, nameof(implementation)); _component = component; OperationName = operationName; _implementation = implementation; }
public ComponentStatePropertyLinkWrapper(ComponentStatePropertyLink propertyLink) { Assure.ArgumentNotNull(propertyLink, nameof(propertyLink)); if (string.IsNullOrEmpty(propertyLink.ContractTypeName)) { throw new ComponentConfigurationException($"Invalid state - {nameof(ComponentStatePropertyLink)}.{nameof(ComponentStatePropertyLink.ContractTypeName)} is not specified."); } if (string.IsNullOrEmpty(propertyLink.PropertyName)) { throw new ComponentConfigurationException($"Invalid state - {nameof(ComponentStatePropertyLink)}.{nameof(ComponentStatePropertyLink.PropertyName)} is not specified."); } _propertyLink = propertyLink; }
public Product(EkProduct ekProduct) { Assure.ArgumentNotNull(ekProduct, nameof(ekProduct)); EkProduct = ekProduct; Key = ekProduct.Key; ThumbnailUrl = ekProduct.GetThumbnailUrl(); Photos = ekProduct.Photos; Name = ekProduct.Name?.GetValue(Languages.RussianCode); Price = ekProduct.Price; PriceString = Price.ToAmountStringWithSpaces(); PriceComment = ekProduct.Source == EkProductSourceEnum.AllegroPl ? "с учетом доставки\nдоставка 1-7 дней" : "доставка 1-3 дня"; switch (ekProduct.State) { case EkProductStateEnum.New: StateString = "новое"; break; case EkProductStateEnum.Used: StateString = "б/у"; break; case EkProductStateEnum.Recovered: StateString = "восстановлено"; break; case EkProductStateEnum.Broken: StateString = "неисправно"; break; default: StateString = "?"; break; } ProductionYear = ekProduct.ProductionYear; PartNumber = ekProduct.PartNumber; IsNotAvailable = Price <= 0; // description _descriptionValue = ekProduct.Description; UpdateDescriptionByValue(); IsDescriptionRequestRequired = !IsNotAvailable && _descriptionValue == null && ekProduct.Source == EkProductSourceEnum.AllegroPl; }
public void SetVSForCache(GeometryCache cache, VertexShader vs) { Assure.NotNull(cache); using (RenderingModule.RenderStateBarrier.AcquirePermit(withLock: InstanceMutationLock)) { if (vs == null) { deferredGeometryVertexShaders.Remove(cache); } else { deferredGeometryVertexShaders[cache] = vs; } } }
/// <summary> /// Gets or sets the data at the requested co-ordinates. /// </summary> /// <remarks> /// For reading/writing single elements, using this member is recommended, but may be slow when attempting /// to copy large sections of the data. In these circumstances, consider using something like /// <see cref="UnsafeUtils.CopyGenericArray{T}(Ophidian.Losgap.ArraySlice{T},System.IntPtr,uint)"/> / /// <see cref="UnsafeUtils.CopyGenericArray{T}(System.IntPtr,Ophidian.Losgap.ArraySlice{T},uint)"/> in combination with the /// <see cref="Data"/> member. /// </remarks> /// <param name="u">The u-coordinate to copy.</param> /// <param name="v">The v-coordinate to copy.</param> /// <param name="w">The w-coordinate to copy.</param> /// <returns>A copy of the data at the requested co-ordinate.</returns> public T this[uint u, uint v, uint w] { get { Assure.LessThan(u, Width, "Index out of bounds: u"); Assure.LessThan(v, Height, "Index out of bounds: v"); Assure.LessThan(w, Depth, "Index out of bounds: w"); return(UnsafeUtils.ReadGenericFromPtr <T>(Data + (int)(u * sizeOfT + v * rowStrideBytes + w * sliceStrideBytes), sizeOfT)); } set { Assure.LessThan(u, Width, "Index out of bounds: u"); Assure.LessThan(v, Height, "Index out of bounds: v"); Assure.LessThan(w, Depth, "Index out of bounds: w"); UnsafeUtils.WriteGenericToPtr(Data + (int)(u * sizeOfT + v * rowStrideBytes + w * sliceStrideBytes), value, sizeOfT); } }
/// <summary> /// Gets or sets the texel at the specified index. /// </summary> /// <param name="u">The x-coordinate of the texel to get.</param> /// <param name="v">The y-coordinate of the texel to get.</param> /// <param name="w">The z-coordinate of the texel to get.</param> /// <returns>The <typeparamref name="TTexel"/> at the requested co-ordinates.</returns> public TTexel this[uint u, uint v, uint w] { get { Assure.LessThan(u, Width, "Index out of bounds: u"); Assure.LessThan(v, Height, "Index out of bounds: v"); Assure.LessThan(w, Depth, "Index out of bounds: w"); return(Data[u + (Width * v) + (texHeightTimesTexWidthTx * w)]); } set { Assure.LessThan(u, Width, "Index out of bounds: u"); Assure.LessThan(v, Height, "Index out of bounds: v"); Assure.LessThan(w, Depth, "Index out of bounds: w"); Data[u + (Width * v) + (texHeightTimesTexWidthTx * w)] = value; } }
public IntPtr GetValue(ConstantBufferBinding binding) { lock (instanceMutationLock) { Assure.NotNull(binding); if (cbBindings.ContainsKey(binding)) { return(cbBindings[binding]); } else { return(binding.CurValuePtr); } } }
internal BaseTextureArrayResource(ResourceHandle resourceHandle, ResourceUsage usage, ByteSize size, GPUBindings permittedBindings, uint length, bool isMipGenTarget, bool allowsDynamicDetail, uint texelSizeBytes, bool isMipmapped, uint numMips, TTexture[] texArray) : base(resourceHandle, usage, size) { Assure.NotNull(texArray); this.permittedBindings = permittedBindings; this.length = length; this.isMipGenTarget = isMipGenTarget; this.allowsDynamicDetail = allowsDynamicDetail; this.texelSizeBytes = texelSizeBytes; this.isMipmapped = isMipmapped; this.numMips = numMips; this.texArray = texArray; }
public KioskApplicationView(KioskApplication model) { Assure.ArgumentNotNull(model, nameof(model)); Model = model; InitializeComponent(); PointerReleased += (sender, args) => { // prevents automatic loss of focus args.Handled = true; }; }
private static unsafe IEnumerable <ModelVertex> TriangulateFace(int numVertices, uint[] pIndices, uint[] tIndices, uint[] nIndices) { Assure.GreaterThan(numVertices, 2); ModelVertex[] result = new ModelVertex[(numVertices - 2) * 3]; for (int i = 2, resultIndex = 0; i < numVertices; i++) { result[resultIndex++] = new ModelVertex(pIndices[0], tIndices[0], nIndices[0]); result[resultIndex++] = new ModelVertex(pIndices[i - 1], tIndices[i - 1], nIndices[i - 1]); result[resultIndex++] = new ModelVertex(pIndices[i], tIndices[i], nIndices[i]); } return(result); }
/// <summary> /// Performs a <see cref="ResourceUsage.StagingReadWrite"/> on this texture, allowing an in-place modification of the data /// through a read/write operation. This can be faster than an individual read and write operation in certain use cases. /// </summary> /// <param name="readWriteAction">An action that takes the supplied <see cref="RawResourceDataView2D{T}"/> and uses it to /// manipulate the data in-place. The supplied resource view is only valid for the duration of the invocation of this /// <see cref="Action"/>.</param> /// <param name="mipIndex">The mip index to read/write.</param> /// <exception cref="ResourceOperationUnavailableException">Thrown if <see cref="BaseResource.CanReadWrite"/> is /// <c>false</c>.</exception> public void ReadWrite(Action <RawResourceDataView2D <TTexel> > readWriteAction, uint mipIndex) { Assure.LessThan( mipIndex, NumMips, "Can not read from mip level " + mipIndex + ": Only " + NumMips + " present in texture." ); ThrowIfCannotReadWrite(); LosgapSystem.InvokeOnMaster(() => { lock (InstanceMutationLock) { if (IsDisposed) { Logger.Warn("Attempted read-write manipulation on disposed resource of type: " + GetType().Name); return; } IntPtr outDataPtr; uint outRowStrideBytes, outSliceStrideBytes; InteropUtils.CallNative( NativeMethods.ResourceFactory_MapSubresource, RenderingModule.DeviceContext, ResourceHandle, GetSubresourceIndex(mipIndex), ResourceMapping.ReadWrite, (IntPtr)(&outDataPtr), (IntPtr)(&outRowStrideBytes), (IntPtr)(&outSliceStrideBytes) ).ThrowOnFailure(); try { readWriteAction(new RawResourceDataView2D <TTexel>( outDataPtr, TexelSizeBytes, MipWidth(mipIndex), MipHeight(mipIndex), outRowStrideBytes )); } finally { InteropUtils.CallNative( NativeMethods.ResourceFactory_UnmapSubresource, RenderingModule.DeviceContext, ResourceHandle, GetSubresourceIndex(mipIndex) ).ThrowOnFailure(); } } }); }
public SerialPortSettings( string serialPortName, uint baudRate, SerialStopBitCount stopBits, SerialParity parity, ushort dataBits = 8) { Assure.ArgumentNotNull(serialPortName, nameof(serialPortName)); SerialPortName = serialPortName; BaudRate = baudRate; StopBits = stopBits; Parity = parity; DataBits = dataBits; }
// 'public' to be used in tests/POCs. public void Initialize(IEnumerable <Type> supportedComponentTypes) { Assure.ArgumentNotNull(supportedComponentTypes, nameof(supportedComponentTypes)); foreach (var supportedComponentType in supportedComponentTypes) { var typeFullName = supportedComponentType.FullName; if (_supportedComponentTypes.ContainsKey(typeFullName)) { throw new ComponentConfigurationException($"Component type with name '{typeFullName}' is presented twice."); } _supportedComponentTypes[typeFullName] = supportedComponentType; } }
public static unsafe RenderCommand ClearRenderTarget(Window renderTarget) { Assure.NotNull(renderTarget); RenderTargetViewHandle outRTV; DepthStencilViewHandle outDSV; bool windowStillOpen = renderTarget.GetWindowRTVAndDSV(out outRTV, out outDSV); if (!windowStillOpen) { return(new RenderCommand(RenderCommandInstruction.NoOperation)); } return(new RenderCommand(RenderCommandInstruction.ClearRenderTarget, (IntPtr)(ResourceViewHandle)outRTV)); }
public static void UnloadTexture(string filename) { Assure.NotNull(filename); lock (staticMutationLock) { if (!textureRefCounts.ContainsKey(filename)) { throw new KeyNotFoundException("Texture is already unloaded (or was never loaded in the first place)."); } if (--textureRefCounts[filename] == 0U) { loadedTextures[filename].Dispose(); loadedTextures.Remove(filename); } } }
public AllegroPlClient( IOptions <AllegroPlClientSettings> settings, YandexTranslateClient yandexTranslateClient, ILogger <AllegroPlClient> logger, ITranslateService translateService) { _settings = settings.Value; Assure.ArgumentNotNull(_settings, nameof(_settings)); _yandexTranslateClient = yandexTranslateClient; _logger = logger; _translateService = translateService; _restClient = new RestClient(_settings.ApiClientId, _settings.ApiClientSecret); _valuesToTranslate = new HashSet <string>(); }
internal Texture3DBuilder(ResourceUsage usage, ArraySlice <TTexel>?initialData, GPUBindings permittedBindings, uint width, uint height, uint depth, bool mipAllocation, bool mipGenerationTarget, bool dynamicDetail) : base(usage, initialData) { Assure.True(typeof(TTexel).IsBlittable()); Assure.GreaterThan(UnsafeUtils.SizeOf <TTexel>(), 0); this.permittedBindings = permittedBindings; this.width = width; this.height = height; this.depth = depth; this.mipAllocation = mipAllocation; this.mipGenerationTarget = mipGenerationTarget; this.dynamicDetail = dynamicDetail; this.numMips = mipAllocation ? TextureUtils.GetNumMips(width, height) : 1U; }
public static Task RunInUiThreadAsync(Action code, CancellationToken?cancellationToken = null) { Assure.ArgumentNotNull(code, nameof(code)); var dispatcher = GetCoreDispatcher(); if (dispatcher.HasThreadAccess) { code(); return(Task.CompletedTask); } return(dispatcher.RunAsync(CoreDispatcherPriority.Normal, () => { code(); }) .AsTask(cancellationToken ?? CancellationToken.None)); }
public TVertex[] GetVerticesWithoutTangents <TVertex>(ConstructorInfo positionNormalTexCoordCtor) where TVertex : struct { Assure.NotNull(positionNormalTexCoordCtor); TVertex[] result = new TVertex[NumVertices]; for (int i = 0; i < NumVertices; ++i) { result[i] = (TVertex)positionNormalTexCoordCtor.Invoke(new object[] { Positions[Vertices[i].PositionIndex], Normals.Length > 0 ? Normals[Vertices[i].NormalIndex] : Vector3.ZERO, TexCoords.Length > 0 ? TexCoords[Vertices[i].TexCoordIndex] : Vector2.ZERO }); } return(result); }
// http://www.beansoftware.com/ASP.NET-Tutorials/Convert-HTML-To-Plain-Text.aspx // https://www.codeproject.com/Articles/11902/Convert-HTML-to-Plain-Text-2 private string ConvertDescriptionHtmlToText(string html) { Assure.ArgumentNotNull(html, nameof(html)); // removal of head/script are not required since they are not presented in Allegro description HTML var htmlStringBuilder = new StringBuilder(html); // remove new lines since they are not visible in HTML htmlStringBuilder.Replace("\n", " "); htmlStringBuilder.Replace("\r", " "); // remove tab spaces htmlStringBuilder.Replace("\t", " "); // replace special characters like &, <, >, " etc. foreach (var(specialSymbol, replacement) in SpecialHtmlSymbolReplacements) { htmlStringBuilder.Replace(specialSymbol, replacement); } // insert line breaks, spaces, etc. (simple replace is used instead of regex since allegro description contains HTML tags without attributes) htmlStringBuilder.Replace("<p>", "\n<p>"); htmlStringBuilder.Replace("<h1>", "\n<h1>"); htmlStringBuilder.Replace("<h2>", "\n<h2>"); htmlStringBuilder.Replace("<h3>", "\n<h3>"); htmlStringBuilder.Replace("<tr>", "\n<tr>"); htmlStringBuilder.Replace("<td>", " <td>"); htmlStringBuilder.Replace("<li>", "\n- <li>"); html = htmlStringBuilder.ToString(); // remove others special symbols html = Regex.Replace(html, @"&(.{2,6});", "", RegexOptions.IgnoreCase); // remove all HTML tags html = Regex.Replace(html, "<[^>]*>", ""); // remove multiple spaces html = Regex.Replace(html, " +", " "); // remove first space in line html = html .Replace("\n ", "\n") .Trim(); return(html); }
/// <summary> /// Performs a <see cref="ResourceUsage.StagingRead"/> on this texture, /// returning a view of the texel data at the given <paramref name="mipIndex"/>. /// </summary> /// <param name="mipIndex">The mip index to read data from. Must be less than <see cref="ITexture.NumMips"/>.</param> /// <returns>A <see cref="TexelArray1D{TTexel}"/> of the data.</returns> /// <exception cref="ResourceOperationUnavailableException">Thrown if <see cref="BaseResource.CanRead"/> is /// <c>false</c>.</exception> public TexelArray1D <TTexel> Read(uint mipIndex) { Assure.LessThan( mipIndex, NumMips, "Can not read from mip level " + mipIndex + ": Only " + NumMips + " present in texture." ); ThrowIfCannotRead(); TTexel[] data = LosgapSystem.InvokeOnMaster(() => { TTexel[] result = new TTexel[MipWidth(mipIndex)]; lock (InstanceMutationLock) { if (IsDisposed) { Logger.Warn("Attempted read manipulation on disposed resource of type: " + GetType().Name); return(result); } IntPtr outDataPtr; uint outRowStrideBytes, outSliceStrideBytes; InteropUtils.CallNative( NativeMethods.ResourceFactory_MapSubresource, RenderingModule.DeviceContext, ResourceHandle, GetSubresourceIndex(mipIndex), ResourceMapping.Read, (IntPtr)(&outDataPtr), (IntPtr)(&outRowStrideBytes), (IntPtr)(&outSliceStrideBytes) ).ThrowOnFailure(); try { UnsafeUtils.CopyGenericArray <TTexel>(outDataPtr, result, TexelSizeBytes); return(result); } finally { InteropUtils.CallNative( NativeMethods.ResourceFactory_UnmapSubresource, RenderingModule.DeviceContext, ResourceHandle, GetSubresourceIndex(mipIndex) ).ThrowOnFailure(); } } }); return(new TexelArray1D <TTexel>(data)); }
public string GetValue(string languageCode) { Assure.ArgumentNotNull(languageCode, nameof(languageCode)); if (Count == 0) { return(null); } if (ContainsKey(languageCode)) { return(this[languageCode]); } return(Values.First()); }
public FontString AddString(SceneLayer sceneLayer, SceneViewport viewport, ViewportAnchoring anchoring, Vector2 anchorOffset, Vector2 scale) { lock (instanceMutationLock) { Assure.NotNull(sceneLayer); Assure.False(sceneLayer.IsDisposed); Assure.NotNull(viewport); Assure.False(viewport.IsDisposed); if (isDisposed) { throw new ObjectDisposedException(Name); } return(new FontString(this, sceneLayer, viewport, anchoring, anchorOffset, scale)); } }
internal ComponentState GetContractState(ComponentStatePropertyLinkWrapper componentStatePropertyLink) { Assure.ArgumentNotNull(componentStatePropertyLink, nameof(componentStatePropertyLink)); var contractTypes = _componentContracts .Keys .Where(x => x.FullName.EndsWith(componentStatePropertyLink.ContractTypeName)) .ToArray(); if (contractTypes.Length == 0) { throw new ComponentConfigurationException($"No contracts were found by contract type name (link '{componentStatePropertyLink}')."); } if (contractTypes.Length > 1) { Log.Warning(LogContextEnum.Configuration, $"More than 1 contract matches contract name (link '{componentStatePropertyLink}'): {string.Join(", ", contractTypes.Select(x => $"'{x.FullName}'"))}. Specify namespace."); } var contractComponents = _componentContracts[contractTypes[0]].ToArray(); if (!string.IsNullOrEmpty(componentStatePropertyLink.ComponentRole)) { // filter by component role contractComponents = contractComponents .Where(x => x.Component.ComponentRole == componentStatePropertyLink.ComponentRole) .ToArray(); } if (contractComponents.Length == 0) { throw new ComponentConfigurationException($"Component was not found for link '{componentStatePropertyLink}'."); } if (contractComponents.Length > 1) { Log.Warning(LogContextEnum.Configuration, $"More than 1 component matches link '{componentStatePropertyLink}': {string.Join(", ", contractComponents.Select(x => $"'{x.Component.FullName}'"))}. Specify component role."); } var componentState = contractComponents[0].ContractState; if (componentState == null) { throw new ComponentConfigurationException($"Contract state was not found or is not implemented (link '{componentStatePropertyLink}')."); } return(componentState); }
public NotificationManager( IOptions <NotificationManagerSettings> settings, KioskBrainsContext dbContext, ViberChannelManager viberChannelManager, AzureStorageClient azureStorageClient, SystemCustomerProvider systemCustomerProvider, ILogger <NotificationManager> logger) { _settings = settings.Value; Assure.ArgumentNotNull(_settings, nameof(_settings)); _dbContext = dbContext; _viberChannelManager = viberChannelManager; _azureStorageClient = azureStorageClient; _systemCustomerProvider = systemCustomerProvider; _logger = logger; }
public void Initialize(UserControl rootControl, IInactivityViewProvider inactivityViewProvider) { Assure.ArgumentNotNull(rootControl, nameof(rootControl)); Assure.ArgumentNotNull(inactivityViewProvider, nameof(inactivityViewProvider)); _rootControl = rootControl; _inactivityViewProvider = inactivityViewProvider; // touch events _rootControl.PointerEntered += OnScreenTouched; _rootControl.PointerExited += OnScreenTouched; // keyboard events _rootControl.KeyDown += OnKeyEntered; RunInactivityProcessing(); }
public static unsafe RenderCommand SetShaderConstantBuffers(Shader shader) { Assure.NotNull(shader); Assure.False(shader.IsDisposed, "Shader was disposed."); IntPtr *resourceHandleArrayPtr = (IntPtr *)AllocAndZeroTemp(shader.NumConstantBufferSlots * (uint)sizeof(IntPtr)); for (int i = 0; i < shader.ConstantBufferBindings.Length; i++) { IConstantBuffer boundResource = shader.ConstantBufferBindings[i].GetBoundResource(); if (boundResource == null) { continue; } resourceHandleArrayPtr[shader.ConstantBufferBindings[i].SlotIndex] = (IntPtr)boundResource.ResourceHandle; } return(new RenderCommand(shader.SetConstantBuffersInstruction, (IntPtr)resourceHandleArrayPtr, shader.NumConstantBufferSlots, 0U)); }
public static async Task SaveFileAsync(string filePath, string fileContent) { Assure.ArgumentNotNull(filePath, nameof(filePath)); Assure.ArgumentNotNull(fileContent, nameof(fileContent)); // .temp in order to prevent reading before write completion var tempFilePath = filePath + ".temp"; var messageBytes = Encoding.UTF8.GetBytes(fileContent); using (var fileStream = new FileStream(tempFilePath, FileMode.CreateNew, FileAccess.Write, FileShare.None, bufferSize: 4096, useAsync: true)) { await fileStream.WriteAsync(messageBytes, 0, messageBytes.Length); } // rename ready file File.Move(tempFilePath, filePath); }
public static Currency GetCurrencyByCode(string code, bool failIfNotFound = true) { Assure.ArgumentNotNull(code, nameof(code)); code = code.ToUpper(); if (!_currenciesByCode.TryGetValue(code, out var currency)) { if (failIfNotFound) { throw new NotSupportedException($"Currency '{code}' is not supported."); } return(null); } return(currency); }
private static MethodInfo GetToArrayMethod(Type valueType) { Assure.ArgumentNotNull(valueType, nameof(valueType)); lock (_toArrayMethodsLocker) { var method = ToArrayMethods.GetValueOrDefault(valueType); if (method == null) { var genericMethod = typeof(BrokenJsonArrayConverter).GetMethod(nameof(ToArray), BindingFlags.Static | BindingFlags.NonPublic); method = genericMethod.MakeGenericMethod(valueType); ToArrayMethods[valueType] = method; } return(method); } }