public void SetOverIndexThrowsArgumentOutOfRange() { using (var buffer = new NativeBuffer()) { Assert.Throws <ArgumentOutOfRangeException>(() => { buffer[0] = 0; }); } }
internal RenderManager(Engine engine) { this.engine = engine; cameraManager = engine.CameraManager; sceneBuffer = engine.Device.CreateBuffer <SceneBuffer>(BufferTypeEnum.ConstVertex, 1); objectBuffer = engine.Device.CreateBuffer <ObjectBuffer>(BufferTypeEnum.ConstVertex, 1); pixelShaderSceneBuffer = engine.Device.CreateBuffer <PixelShaderSceneBuffer>(BufferTypeEnum.ConstPixel, 1); instancesBuffer = engine.Device.CreateBuffer <Matrix>(BufferTypeEnum.Vertex, 1); instancesArray = new Matrix[1]; renderers = new Dictionary <ShaderHandle, Dictionary <Material, Dictionary <Mesh, List <Transform> > > >(); sceneData = new SceneBuffer(); defaultSampler = engine.Device.CreateSampler(); depthStencilZWrite = engine.Device.CreateDepthStencilState(true); depthStencilNoZWrite = engine.Device.CreateDepthStencilState(false); renderTexture = engine.Device.CreateRenderTexture((int)engine.WindowHost.WindowWidth, (int)engine.WindowHost.WindowHeight); outlineTexture = engine.Device.CreateRenderTexture((int)engine.WindowHost.WindowWidth, (int)engine.WindowHost.WindowHeight); planeMesh = engine.MeshManager.CreateMesh(new ScreenPlane()); blitShader = engine.ShaderManager.LoadShader("../internalShaders/blit.shader"); blitMaterial = engine.MaterialManager.CreateMaterial(blitShader); unlitMaterial = engine.MaterialManager.CreateMaterial(engine.ShaderManager.LoadShader("../internalShaders/unlit.shader")); }
internal NativeBuffer Rent() { if (_disposed) throw new ObjectDisposedException("NativeBufferBucket"); NativeBuffer buffer; // Use a lightweight spinlock for our super-short lock bool taken = false; _lock.Enter(ref taken); Debug.Assert(taken); // Check if all of our buffers have been used if (_index >= _buffers.Length) { // We can safely exit _lock.Exit(false); buffer = new NativeBuffer(Marshal.AllocHGlobal(_elementsInBuffer * Marshal.SizeOf(typeof(byte))).ToPointer(), _elementsInBuffer); } else { buffer = _buffers[_index].Value; _buffers[_index] = null; _index++; _lock.Exit(false); } return buffer; }
/// <summary> /// Populates a list with transformed face vertices. /// </summary> public static unsafe void ComputeFaceClippingPolygon(ref NativeBuffer <ClipVertex> output, int faceIndex, RigidTransform t, NativeHull hull) { Debug.Assert(output.IsCreated); NativeFace * face = hull.GetFacePtr(faceIndex); NativePlane plane = hull.GetPlane(faceIndex); NativeHalfEdge *start = hull.GetEdgePtr(face->Edge); NativeHalfEdge *current = start; do { NativeHalfEdge *twin = hull.GetEdgePtr(current->Twin); float3 vertex = hull.GetVertex(current->Origin); float3 P = math.transform(t, vertex); ClipVertex clipVertex; clipVertex.featurePair.InEdge1 = -1; clipVertex.featurePair.OutEdge1 = -1; clipVertex.featurePair.InEdge2 = (sbyte)current->Next; clipVertex.featurePair.OutEdge2 = (sbyte)twin->Twin; clipVertex.position = P; clipVertex.hull2local = vertex; clipVertex.plane = plane; output.Add(clipVertex); current = hull.GetEdgePtr(current->Next); } while (current != start); }
public static IEnumerable<string> QueryDosDevice(string deviceName) { if (deviceName != null) deviceName = Paths.RemoveTrailingSeparators(deviceName); // Null will return everything defined- this list is quite large so set a higher initial allocation using (NativeBuffer buffer = new NativeBuffer(deviceName == null ? (uint)8192 : 256)) { uint result = 0; // QueryDosDevicePrivate takes the buffer count in TCHARs, which is 2 bytes for Unicode (WCHAR) while ((result = QueryDosDevicePrivate(deviceName, buffer, buffer.Size / 2)) == 0) { int lastError = Marshal.GetLastWin32Error(); switch (lastError) { case WinError.ERROR_INSUFFICIENT_BUFFER: buffer.Resize(buffer.Size * 2); break; default: throw GetIoExceptionForError(lastError, deviceName); } } return Strings.Split(buffer, (int)result - 2, '\0'); } }
unsafe public void GetUnsafePointerTest() { using NativeBuffer buffer = new NativeBuffer(20); buffer.Write(1); buffer.Write(2); buffer.Write(4); buffer.Write(8); byte *ptr = buffer.GetUnsafePointer(); Assert.AreEqual(1, ptr[0]); Assert.AreEqual(0, ptr[1]); Assert.AreEqual(0, ptr[2]); Assert.AreEqual(0, ptr[3]); Assert.AreEqual(2, ptr[4]); Assert.AreEqual(0, ptr[5]); Assert.AreEqual(0, ptr[6]); Assert.AreEqual(0, ptr[7]); Assert.AreEqual(4, ptr[8]); Assert.AreEqual(0, ptr[9]); Assert.AreEqual(0, ptr[10]); Assert.AreEqual(0, ptr[11]); Assert.AreEqual(8, ptr[12]); Assert.AreEqual(0, ptr[13]); Assert.AreEqual(0, ptr[14]); Assert.AreEqual(0, ptr[15]); }
public void GetEnumeratorTest() { using NativeBuffer buffer = new NativeBuffer(20); buffer.Write(1); buffer.Write(2); var enumerator = buffer.GetEnumerator(); Assert.IsTrue(enumerator.MoveNext()); Assert.AreEqual(1, enumerator.Current); Assert.IsTrue(enumerator.MoveNext()); Assert.AreEqual(0, enumerator.Current); Assert.IsTrue(enumerator.MoveNext()); Assert.AreEqual(0, enumerator.Current); Assert.IsTrue(enumerator.MoveNext()); Assert.AreEqual(0, enumerator.Current); Assert.IsTrue(enumerator.MoveNext()); Assert.AreEqual(2, enumerator.Current); Assert.IsTrue(enumerator.MoveNext()); Assert.AreEqual(0, enumerator.Current); Assert.IsTrue(enumerator.MoveNext()); Assert.AreEqual(0, enumerator.Current); Assert.IsTrue(enumerator.MoveNext()); Assert.AreEqual(0, enumerator.Current); Assert.IsFalse(enumerator.MoveNext()); }
public void Update() { collection_mesh_job.FinishUpdateMesh(); NativeBuffer <JobHandle> handles = new NativeBuffer <JobHandle>(batches.Count, Allocator.Temp); bool has_job = false; foreach (var b in batches) { var handle = b.BuildJob(out has_job); if (has_job) { handles.Add(handle); } } //if(handles.Length > 0) { collection_mesh_job.BeginCollectionMeshInfo(); foreach (var g in group_rebuild_mesh) { if (g.mesh == null) { continue; } collection_mesh_job.CollectionMeshfInfo(g); } collection_mesh_job.EndCollectionMeshInfo(JobHandle.CombineDependencies(handles)); group_rebuild_mesh.Clear(); } handles.Dispose(); }
public bool GetDownloadedLeaderboardEntry(LeaderboardEntriesHandle entries, int index, out LeaderboardEntry entry, int[] details) { CheckIfUsable(); int numberOfDetails = details == null ? 0 : details.Length; using (NativeBuffer entryBuffer = new NativeBuffer(Marshal.SizeOf(typeof(LeaderboardEntry)))) { using (NativeBuffer detailsBuffer = new NativeBuffer(numberOfDetails * sizeof(int))) { bool result = NativeMethods.Stats_GetDownloadedLeaderboardEntry(entries.AsUInt64, index, entryBuffer.UnmanagedMemory, detailsBuffer.UnmanagedMemory, numberOfDetails); // Read the entry directly from the unmanaged buffer entry = LeaderboardEntry.Create(entryBuffer.UnmanagedMemory, entryBuffer.UnmanagedSize); for (int i = 0; i < numberOfDetails; i++) { // Read all the detail values from the unmanaged buffer details[i] = Marshal.ReadInt32(detailsBuffer.UnmanagedMemory, sizeof(int) * i); } return(result); } } }
public void EndRequestSpace() { int vertex_count = r_quad_count * 4; if (!build_transform_job_datas.IsCreated) { build_transform_job_datas = new NativeBuffer <BuildTransformJobData>(r_capacity, Allocator.Persistent); build_transform_job_datas.AddLength(r_capacity); build_quad_datas = new NativeBuffer <BuildPerQuadData>(r_quad_count, Allocator.Persistent); build_quad_datas.AddLength(r_quad_count); vertex_datas = new NativeBuffer <Vertex>(vertex_count, Allocator.Persistent); vertex_datas.AddLength(vertex_count); } else { build_transform_job_datas.AddLength(r_capacity); build_quad_datas.AddLength(r_quad_count); vertex_datas.AddLength(vertex_count); } foreach (var info in pending_infos) { buffer_infos.Add(info.offset, info); } pending_infos.Clear(); }
/// <summary> /// Creates a new <see cref="NativeBuffer"/> with the given dimensions. /// </summary> /// <param name="buffer">The storage location for the buffer object.</param> /// <param name="w">The width.</param> /// <param name="h">The height.</param> /// <param name="isDIB">True if the buffer should be DIB backed, false for Marshal.</param> /// <returns>Returns the data buffer.</returns> public static ARGB* CreateBuffer(out NativeBuffer buffer, int w, int h, bool isDIB) { ARGB* pixels; IntPtr handle; DeviceContext context = null; if(isDIB) { context = new DeviceContext(); //create info BITMAPINFO info = new BITMAPINFO(); //init with size info.init(w, h); //create DIB handle = CreateDIBSection(context.Handle, ref info, DIB_RGB_COLORS, out pixels, IntPtr.Zero, 0); WinAPIUtils.Assert(handle != IntPtr.Zero); //select the DIB into the DC context.Push(handle); }else { handle = Marshal.AllocHGlobal(w * h * 4); pixels = (ARGB*)handle; } //create buffer wrapper buffer = new NativeBuffer{isDIB = isDIB, Handle = handle, Context = context}; //return the data return pixels; }
public void NativeBufferTest() { using NativeBuffer buffer = new NativeBuffer(40); Assert.AreEqual(40, buffer.Capacity); Assert.AreEqual(0, buffer.Length); Assert.IsTrue(buffer.IsValid); Assert.IsTrue(buffer.IsEmpty); }
public NativeBufferSlice(NativeBuffer <T> data, int offset, int length, int stride) { this.offset = offset; this.length = length; this.buffer = data; this.used = 0; this.stride = stride; }
public void CanGetSetBytes() { using (var buffer = new NativeBuffer(1)) { buffer[0] = 0xA; buffer[0].Should().Be(0xA); } }
public void SetOverIndexThrowsArgumentOutOfRange() { using (var buffer = new NativeBuffer()) { Action action = () => { buffer[0] = 0; }; action.ShouldThrow<ArgumentOutOfRangeException>(); } }
public string GetQueryAddressString() { using (NativeBuffer buffer = NativeBuffer.CopyToNative(this)) { IntPtr stringPtr = NativeMethods.MatchmakingServerNetworkAddress_GetQueryString(buffer.UnmanagedMemory); return(NativeHelpers.ToStringAnsi(stringPtr)); } }
public static unsafe void *GetUnsafePtr <T>(this NativeBuffer <T> nativeList) where T : struct { #if ENABLE_UNITY_COLLECTIONS_CHECKS AtomicSafetyHandle.CheckWriteAndThrow(nativeList.m_Safety); #endif var data = nativeList.m_ListData; return(data->buffer); }
public void SetOverIndexThrowsArgumentOutOfRange() { using (var buffer = new NativeBuffer()) { Action action = () => { buffer[0] = 0; }; action.ShouldThrow <ArgumentOutOfRangeException>(); } }
public void DisposedBufferIsEmpty() { var buffer = new NativeBuffer(5); buffer.ByteCapacity.Should().Be(5); buffer.Dispose(); buffer.ByteCapacity.Should().Be(0); buffer.DangerousGetHandle().Should().Be(IntPtr.Zero); }
public void CanGetSetBytes() { using (var buffer = new NativeBuffer(1)) { buffer[0] = 0xA; Assert.Equal(buffer[0], 0xA); } }
public void EnsureZeroCapacityDoesNotFreeBuffer() { using (var buffer = new NativeBuffer(10)) { buffer.DangerousGetHandle().Should().NotBe(IntPtr.Zero); buffer.EnsureByteCapacity(0); buffer.DangerousGetHandle().Should().NotBe(IntPtr.Zero); } }
public void NullSafePointerInTest() { using (var buffer = new NativeBuffer(0)) { ((SafeHandle)buffer).IsInvalid.Should().BeTrue(); buffer.ByteCapacity.Should().Be(0); GetCurrentDirectorySafe((uint)buffer.ByteCapacity, buffer); } }
public bool SendDataOnSocket(NetSocketHandle socket, byte[] data, bool reliable) { CheckIfUsable(); using (NativeBuffer bufferKey = new NativeBuffer(data)) { bufferKey.WriteToUnmanagedMemory(); return(NativeMethods.Networking_SendDataOnSocket(socket.AsUInt32, bufferKey.UnmanagedMemory, (uint)bufferKey.UnmanagedSize, reliable)); } }
public OdbcParameter () { _cbLengthInd = new NativeBuffer (); ParameterName = String.Empty; IsNullable = false; SourceColumn = String.Empty; Direction = ParameterDirection.Input; _typeMap = OdbcTypeConverter.GetTypeMap (OdbcType.NVarChar); }
public RenderCommandBuffer(IAllocator allocator, GraphicsDevice device) { _buffer = new NativeBuffer(allocator); _device = device; _defaultEffect = new BasicEffect(_device); _defaultEffect.TextureEnabled = true; _defaultEffect.VertexColorEnabled = true; }
public EntityNativeIterator(NativeBuffer <NT> array) : this() { unsafe { _array = array; _index = (int *)Marshal.AllocHGlobal(sizeof(int)); *_index = -1; } }
public void EnsureZeroCapacityDoesNotFreeBuffer() { using (var buffer = new NativeBuffer(10)) { Assert.NotEqual(buffer.GetHandle().DangerousGetHandle(), IntPtr.Zero); buffer.EnsureByteCapacity(0); Assert.NotEqual(buffer.GetHandle().DangerousGetHandle(), IntPtr.Zero); } }
public void FreedBufferIsEmpty() { using (var buffer = new NativeBuffer(5)) { buffer.ByteCapacity.Should().Be(5); buffer.Free(); buffer.ByteCapacity.Should().Be(0); buffer.DangerousGetHandle().Should().Be(IntPtr.Zero); } }
public bool SendLobbyChatMsg(SteamID steamIDLobby, byte[] msgBody) { CheckIfUsable(); using (NativeBuffer buffer = new NativeBuffer(msgBody)) { buffer.WriteToUnmanagedMemory(); return(NativeMethods.MatchMaking_SendLobbyChatMsg(steamIDLobby.AsUInt64, buffer.UnmanagedMemory, buffer.UnmanagedSize)); } }
public SystemManager(ILoggerFactory logFactory, EntityManager em, IAllocator allocator) { _logFactory = logFactory; _logger = logFactory.CreateLogger <SystemManager>(); _entityManager = em; _allocator = allocator; DefaultStage = "Default"; _variables = new NativeBuffer(allocator); }
public bool HandleIncomingPacket(byte[] data, uint ip, ushort port) { //CheckIfUsable(); using (NativeBuffer packetBuffer = new NativeBuffer(data)) { packetBuffer.WriteToUnmanagedMemory(); return(NativeMethods.GameServer_HandleIncomingPacket(packetBuffer.UnmanagedMemory, packetBuffer.UnmanagedSize, ip, port)); } }
public void Init(HUDBatchData data) { batch_data = data; transform_indices = new NativeBuffer <TransformIndex>(step_capacity, Allocator.Persistent); indeices_offset = new NativeBuffer <CollectionMeshInfoOffset>(step_capacity / 10, Allocator.Persistent); out_poices = new NativeBuffer <Vector3>(step_capacity * 60, Allocator.Persistent); out_uv0 = new NativeBuffer <Vector2>(step_capacity * 60, Allocator.Persistent); out_uv1 = new NativeBuffer <Vector2>(step_capacity * 60, Allocator.Persistent); out_colors = new NativeBuffer <Color32>(step_capacity * 60, Allocator.Persistent); out_indices = new NativeBuffer <int>(step_capacity * 60, Allocator.Persistent); }
public void NullSafePointerInTest() { using (var buffer = new NativeBuffer(0)) { Assert.True(buffer.GetHandle().IsInvalid); Assert.Equal((ulong)0, buffer.ByteCapacity); // This will throw if we don't put a stub SafeHandle in for the empty buffer GetCurrentDirectorySafe((uint)buffer.ByteCapacity, buffer.GetHandle()); } }
public bool GetCurrentBetaName(out string pchName) { CheckIfUsable(); using (NativeBuffer buffer = new NativeBuffer(Constants.Apps.MaxBetaNameLength)) { bool result = NativeMethods.Apps_GetCurrentBetaName(buffer.UnmanagedMemory, buffer.UnmanagedSize); pchName = NativeHelpers.ToStringAnsi(buffer.UnmanagedMemory); return(result); } }
public async Task QuickEnumeration_SmallBuffer_MultiFile_Successful() { //Arrange const string RootPath = @"D:\"; var functions = new Mock <Functions>(); var nsVirtualizationContext = (IntPtr)4; var instanceGuid = Guid.NewGuid(); var tcsStarted = new TaskCompletionSource <IntPtr>(); var enumerationId = Guid.NewGuid(); var callbackData = new PRJ_CALLBACK_DATA { VersionInfo = new PRJ_PLACEHOLDER_VERSION_INFO() }; var dirBuffer1 = (IntPtr)99; var dirBuffer2 = (IntPtr)713; functions.Setup(f => f.PrjStartVirtualizing(RootPath, It.IsAny <IntPtr>(), IntPtr.Zero, It.IsAny <PRJ_STARTVIRTUALIZING_OPTIONS>(), out It.Ref <IntPtr> .IsAny)) .Callback(new StartVirtualizingCallback((String virtualizationRootPath, IntPtr callbacks, IntPtr instanceContext, PRJ_STARTVIRTUALIZING_OPTIONS options, out IntPtr namespaceVirtualizationContext) => { tcsStarted.SetResult(callbacks); namespaceVirtualizationContext = nsVirtualizationContext; }) ).Returns(() => HRESULT.S_OK); functions.Setup(f => f.PrjFileNameMatch(It.IsAny <string>(), null)).Returns(true); functions.SetupSequence(f => f.PrjFillDirEntryBuffer("Boris.txt", It.IsAny <PRJ_FILE_BASIC_INFO>(), dirBuffer1)) .Returns(HRESULT.S_OK) .Returns(HRESULT.ERROR_INSUFFICIENT_BUFFER) .Returns(HRESULT.S_OK); ConfigureVirtualizationInfo(functions, nsVirtualizationContext, instanceGuid); var runnable = new RunnableInstance("Boris", RootPath, instanceGuid, new InstanceOptions(), functions.Object); var fs = TestableFileSystem.MultiFile(); //Act using (var running = runnable.Start(fs)) { var callbacks = NativeBuffer <PRJ_CALLBACKS> .Recover(await tcsStarted.Task); var hr = callbacks.StartDirectoryEnumerationCallback(callbackData, enumerationId); Assert.Equal(HRESULT.S_OK, hr); hr = callbacks.GetDirectoryEnumerationCallback(callbackData, enumerationId, null, dirBuffer1); Assert.Equal(HRESULT.S_OK, hr); hr = callbacks.GetDirectoryEnumerationCallback(callbackData, enumerationId, null, dirBuffer2); Assert.Equal(HRESULT.S_OK, hr); hr = callbacks.EndDirectoryEnumerationCallback(callbackData, enumerationId); Assert.Equal(HRESULT.S_OK, hr); //Assert functions.VerifyAll(); } }
internal NativeBufferBucket(int elementsInBuffer, int numberOfBuffers) { _index = 0; _elementsInBuffer = elementsInBuffer; _lock = new SpinLock(); int bufferLength = numberOfBuffers * _elementsInBuffer; _allocatedMemory = Marshal.AllocHGlobal(bufferLength * Marshal.SizeOf(typeof(byte))); _buffers = new NativeBuffer?[numberOfBuffers]; for (int i = 0; i < bufferLength; i+= _elementsInBuffer) { _buffers[i / _elementsInBuffer] = new NativeBuffer((_allocatedMemory + i).ToPointer(), _elementsInBuffer); } }
internal static IEnumerable<string> GetLogicalDriveStrings() { using (NativeBuffer buffer = new NativeBuffer()) { uint result = 0; // GetLogicalDriveStringsPrivate takes the buffer count in TCHARs, which is 2 bytes for Unicode (WCHAR) while ((result = GetLogicalDriveStringsPrivate((uint)buffer.Size / 2, buffer)) > buffer.Size / 2) { buffer.Resize(result * 2); } if (result == 0) { int lastError = Marshal.GetLastWin32Error(); throw GetIoExceptionForError(lastError); } return Strings.Split(buffer, (int)result - 1, '\0'); } }
internal static IEnumerable<string> GetVolumePathNamesForVolumeName(string volumeName) { using (NativeBuffer buffer = new NativeBuffer()) { uint returnLength = 0; // GetLogicalDriveStringsPrivate takes the buffer count in TCHARs, which is 2 bytes for Unicode (WCHAR) while (!GetVolumePathNamesForVolumeNamePrivate(volumeName, buffer, (uint)buffer.Size / 2, ref returnLength)) { int lastError = Marshal.GetLastWin32Error(); switch (lastError) { case WinError.ERROR_MORE_DATA: buffer.Resize(returnLength * 2); break; default: throw GetIoExceptionForError(lastError, volumeName); } } return Strings.Split(buffer, (int)returnLength - 2, '\0'); } }
internal static int MarshalToNative(object value, int offset, int size, NativeBuffer buffer, int bufferOffset, OCI.DATATYPE ociType, bool bindAsUCS2) { string str; string str2; Encoding encoding = bindAsUCS2 ? Encoding.Unicode : Encoding.UTF8; if (value is OracleString) { str = ((OracleString) value)._value; } else { str = (string) value; } if ((offset == 0) && (size == 0)) { str2 = str; } else if ((size == 0) || ((offset + size) > str.Length)) { str2 = str.Substring(offset); } else { str2 = str.Substring(offset, size); } byte[] bytes = encoding.GetBytes(str2); int length = bytes.Length; int num3 = length; if (length != 0) { int num2 = length; if (bindAsUCS2) { num2 /= 2; } if (OCI.DATATYPE.LONGVARCHAR == ociType) { buffer.WriteInt32(bufferOffset, num2); bufferOffset += 4; num3 += 4; } buffer.WriteBytes(bufferOffset, bytes, 0, length); } return num3; }
internal OracleString(NativeBuffer buffer, int valueOffset, int lengthOffset, MetaType metaType, OracleConnection connection, bool boundAsUCS2, bool outputParameterBinding) { this._value = MarshalToString(buffer, valueOffset, lengthOffset, metaType, connection, boundAsUCS2, outputParameterBinding); }
internal static int GetLength(NativeBuffer buffer, int lengthOffset, MetaType metaType) { int num; if (metaType.IsLong) { num = buffer.ReadInt32(lengthOffset); } else { num = buffer.ReadInt16(lengthOffset); } GC.KeepAlive(buffer); return num; }
internal static string MarshalToString(NativeBuffer buffer, int valueOffset, int lengthOffset, MetaType metaType, OracleConnection connection, bool boundAsUCS2, bool outputParameterBinding) { string str; int length = GetLength(buffer, lengthOffset, metaType); if (boundAsUCS2 && outputParameterBinding) { length /= 2; } bool flag = metaType.IsLong && !outputParameterBinding; if (boundAsUCS2) { if (flag) { byte[] destinationBuffer = new byte[length * System.Data.Common.ADP.CharSize]; NativeBuffer_LongColumnData.CopyOutOfLineBytes(buffer.ReadIntPtr(valueOffset), 0, destinationBuffer, 0, length * System.Data.Common.ADP.CharSize); str = Encoding.Unicode.GetString(destinationBuffer); } else { str = buffer.PtrToStringUni(valueOffset, length); } } else { byte[] buffer2; if (flag) { buffer2 = new byte[length]; NativeBuffer_LongColumnData.CopyOutOfLineBytes(buffer.ReadIntPtr(valueOffset), 0, buffer2, 0, length); } else { buffer2 = buffer.ReadBytes(valueOffset, length); } str = connection.GetString(buffer2, metaType.UsesNationalCharacterSet); } GC.KeepAlive(buffer); return str; }
internal static int OCIServerVersion(OciHandle hndlp, OciHandle errhp, NativeBuffer bufp) { if (Bid.AdvancedOn) { Bid.Trace("<oc.OCIServerVersion|ADV|OCI> hndlp=0x%-07Ix errhp=0x%-07Ix bufp=0x%-07Ix bufsz=%d hndltype=%d{OCI.HTYPE}\n", OciHandle.HandleValueToTrace(hndlp), OciHandle.HandleValueToTrace(errhp), NativeBuffer.HandleValueToTrace(bufp), bufp.Length, (int) hndlp.HandleType); } int num = System.Data.Common.UnsafeNativeMethods.OCIServerVersion(hndlp, errhp, bufp, (uint) bufp.Length, (byte) hndlp.HandleType); if (Bid.AdvancedOn) { Bid.Trace("<oc.OCIServerVersion|ADV|OCI|RET> rc=%d\n%ls\n\n", num, hndlp.PtrToString(bufp)); } return num; }
internal static int GetChars(NativeBuffer buffer, int valueOffset, int lengthOffset, MetaType metaType, OracleConnection connection, bool boundAsUCS2, int sourceOffset, char[] destinationBuffer, int destinationOffset, int charCount) { bool success = false; RuntimeHelpers.PrepareConstrainedRegions(); try { buffer.DangerousAddRef(ref success); if (boundAsUCS2) { if (!metaType.IsLong) { Marshal.Copy(buffer.DangerousGetDataPtrWithBaseOffset(valueOffset + (System.Data.Common.ADP.CharSize * sourceOffset)), destinationBuffer, destinationOffset, charCount); return charCount; } NativeBuffer_LongColumnData.CopyOutOfLineChars(buffer.ReadIntPtr(valueOffset), sourceOffset, destinationBuffer, destinationOffset, charCount); return charCount; } string str = MarshalToString(buffer, valueOffset, lengthOffset, metaType, connection, boundAsUCS2, false); int length = str.Length; int num = ((sourceOffset + charCount) > length) ? (length - sourceOffset) : charCount; Buffer.BlockCopy(str.ToCharArray(sourceOffset, num), 0, destinationBuffer, destinationOffset * System.Data.Common.ADP.CharSize, num * System.Data.Common.ADP.CharSize); charCount = num; } finally { if (success) { buffer.DangerousRelease(); } } return charCount; }
internal object GetOutputValue(NativeBuffer parameterBuffer, OracleConnection connection, bool needCLSType) { object obj2; if (parameterBuffer.ReadInt16(this._indicatorOffset) == -1) { return DBNull.Value; } switch (this._bindingMetaType.OciType) { case OCI.DATATYPE.VARCHAR2: case OCI.DATATYPE.LONG: case OCI.DATATYPE.LONGVARCHAR: case OCI.DATATYPE.CHAR: { obj2 = new OracleString(parameterBuffer, this._valueOffset, this._lengthOffset, this._bindingMetaType, connection, this._bindAsUCS2, true); int size = this._parameter.Size; if (size != 0) { OracleString str4 = (OracleString) obj2; if (size < str4.Length) { OracleString str3 = (OracleString) obj2; string s = str3.Value.Substring(0, size); if (needCLSType) { return s; } return new OracleString(s); } } if (needCLSType) { OracleString str2 = (OracleString) obj2; obj2 = str2.Value; } return obj2; } case OCI.DATATYPE.INTEGER: case OCI.DATATYPE.FLOAT: case OCI.DATATYPE.UNSIGNEDINT: return parameterBuffer.PtrToStructure(this._valueOffset, this._bindingMetaType.BaseType); case OCI.DATATYPE.VARNUM: obj2 = new OracleNumber(parameterBuffer, this._valueOffset); if (needCLSType) { OracleNumber number = (OracleNumber) obj2; obj2 = number.Value; } return obj2; case OCI.DATATYPE.DATE: obj2 = new OracleDateTime(parameterBuffer, this._valueOffset, this._lengthOffset, this._bindingMetaType, connection); if (needCLSType) { OracleDateTime time2 = (OracleDateTime) obj2; obj2 = time2.Value; } return obj2; case OCI.DATATYPE.RAW: case OCI.DATATYPE.LONGRAW: case OCI.DATATYPE.LONGVARRAW: obj2 = new OracleBinary(parameterBuffer, this._valueOffset, this._lengthOffset, this._bindingMetaType); if (needCLSType) { OracleBinary binary = (OracleBinary) obj2; obj2 = binary.Value; } return obj2; case OCI.DATATYPE.CLOB: case OCI.DATATYPE.BLOB: return new OracleLob(this._locator); case OCI.DATATYPE.BFILE: return new OracleBFile(this._locator); case OCI.DATATYPE.RSET: return new OracleDataReader(connection, this._descriptor); case OCI.DATATYPE.INT_TIMESTAMP: case OCI.DATATYPE.INT_TIMESTAMP_TZ: case OCI.DATATYPE.INT_TIMESTAMP_LTZ: obj2 = new OracleDateTime(this._dateTimeDescriptor, this._bindingMetaType, connection); if (needCLSType) { OracleDateTime time = (OracleDateTime) obj2; obj2 = time.Value; } return obj2; case OCI.DATATYPE.INT_INTERVAL_YM: obj2 = new OracleMonthSpan(parameterBuffer, this._valueOffset); if (needCLSType) { OracleMonthSpan span2 = (OracleMonthSpan) obj2; obj2 = span2.Value; } return obj2; case OCI.DATATYPE.INT_INTERVAL_DS: obj2 = new OracleTimeSpan(parameterBuffer, this._valueOffset); if (needCLSType) { OracleTimeSpan span = (OracleTimeSpan) obj2; obj2 = span.Value; } return obj2; } throw System.Data.Common.ADP.TypeNotSupported(this._bindingMetaType.OciType); }
internal static int oermsg(short rcode, NativeBuffer buf) { if (Bid.AdvancedOn) { Bid.Trace("<oc.oermsg|ADV|OCI> rcode=%d\n", rcode); } int num = System.Data.Common.UnsafeNativeMethods.oermsg(rcode, buf); if (Bid.AdvancedOn) { Bid.Trace("<oc.oermsg|ADV|OCI|RET> rc=%d\n", num); } return num; }
internal static int OraMTSOCIErrGet(ref int dwErr, NativeBuffer lpcEMsg, ref int lpdLen) { if (Bid.AdvancedOn) { Bid.Trace("<oc.OraMTSOCIErrGet|ADV|OCI> dwErr=%08X, lpcEMsg=0x%-07Ix lpdLen=%d\n", dwErr, NativeBuffer.HandleValueToTrace(lpcEMsg), lpdLen); } int num = System.Data.Common.UnsafeNativeMethods.OraMTSOCIErrGet(ref dwErr, lpcEMsg, ref lpdLen); if (Bid.AdvancedOn) { if (num == 0) { Bid.Trace("<oc.OraMTSOCIErrGet|ADV|OCI|RET> rc=%d\n", num); return num; } string str = lpcEMsg.PtrToStringAnsi(0, lpdLen); Bid.Trace("<oc.OraMTSOCIErrGet|ADV|OCI|RET> rd=%d message='%ls', lpdLen=%d\n", num, str, lpdLen); } return num; }
internal static int MarshalToNative(object value, NativeBuffer buffer, int offset) { int num2; if (value is OracleMonthSpan) { num2 = ((OracleMonthSpan) value)._value; } else { num2 = (int) value; } byte[] source = new byte[5]; int num = (num2 / 12) + ((int) 0x80000000L); int num3 = num2 % 12; source[0] = (byte) (num >> 0x18); source[1] = (byte) ((num >> 0x10) & 0xff); source[2] = (byte) ((num >> 8) & 0xff); source[3] = (byte) (num & 0xff); source[4] = (byte) (num3 + 60); buffer.WriteBytes(offset, source, 0, 5); return 5; }
internal static int MarshalToInt32(NativeBuffer buffer, int valueOffset) { byte[] buffer2 = buffer.ReadBytes(valueOffset, 5); int num3 = ((((buffer2[0] << 0x18) | (buffer2[1] << 0x10)) | (buffer2[2] << 8)) | buffer2[3]) - ((int) 0x80000000L); int num2 = buffer2[4] - 60; int monthSpan = (num3 * 12) + num2; AssertValid(monthSpan); return monthSpan; }
internal void PostExecute(NativeBuffer parameterBuffer, OracleConnection connection) { OracleParameter parameter = this.Parameter; if (IsDirection(parameter, ParameterDirection.Output) || IsDirection(parameter, ParameterDirection.ReturnValue)) { bool needCLSType = true; if (IsDirection(parameter, ParameterDirection.Input) && (parameter.Value is INullable)) { needCLSType = false; } parameter.Value = this.GetOutputValue(parameterBuffer, connection, needCLSType); } }
internal static int OCIErrorGet(OciHandle hndlp, int recordno, out int errcodep, NativeBuffer bufp) { if (Bid.AdvancedOn) { Bid.Trace("<oc.OCIErrorGet|ADV|OCI> hndlp=0x%-07Ix recordno=%d sqlstate=0x%-07Ix bufp=0x%-07Ix bufsiz=%d type=%d{OCI.HTYPE}\n", OciHandle.HandleValueToTrace(hndlp), recordno, IntPtr.Zero, NativeBuffer.HandleValueToTrace(bufp), bufp.Length, (int) hndlp.HandleType); } int num = System.Data.Common.UnsafeNativeMethods.OCIErrorGet(hndlp, (uint) recordno, IntPtr.Zero, out errcodep, bufp, (uint) bufp.Length, hndlp.HandleType); if (Bid.AdvancedOn) { Bid.Trace("<oc.OCIErrorGet|ADV|OCI|RET> errcodep=%d rc=%d\n\t%ls\n\n", errcodep, num, hndlp.PtrToString(bufp)); } return num; }
internal void Bind(OciStatementHandle statementHandle, NativeBuffer parameterBuffer, OracleConnection connection, ref bool mustRelease, ref SafeHandle handleToBind) { if (IsDirection(this.Parameter, ParameterDirection.Output) || (this.Parameter.Value != null)) { int num2; IntPtr ptr2; string parameterName = this.Parameter.ParameterName; OciErrorHandle errorHandle = connection.ErrorHandle; OciServiceContextHandle serviceContextHandle = connection.ServiceContextHandle; int num = 0; OCI.INDICATOR oK = OCI.INDICATOR.OK; OCI.DATATYPE ociType = this._bindingMetaType.OciType; IntPtr dataPtr = parameterBuffer.DangerousGetDataPtr(this._indicatorOffset); IntPtr alenp = parameterBuffer.DangerousGetDataPtr(this._lengthOffset); IntPtr valuep = parameterBuffer.DangerousGetDataPtr(this._valueOffset); OciHandle.SafeDispose(ref this._dateTimeDescriptor); if (IsDirection(this.Parameter, ParameterDirection.Input)) { if (System.Data.Common.ADP.IsNull(this._coercedValue)) { oK = OCI.INDICATOR.ISNULL; switch (ociType) { case OCI.DATATYPE.INT_TIMESTAMP: case OCI.DATATYPE.INT_TIMESTAMP_TZ: case OCI.DATATYPE.INT_TIMESTAMP_LTZ: this._dateTimeDescriptor = OracleDateTime.CreateEmptyDescriptor(ociType, connection); handleToBind = this._dateTimeDescriptor; break; } } else { num = this.PutOracleValue(this._coercedValue, parameterBuffer, this._valueOffset, this._bindingMetaType, connection, ref handleToBind); } } else { if (this._bindingMetaType.IsVariableLength) { num = 0; } else { num = this._bufferLength; } OciLobLocator.SafeDispose(ref this._locator); OciHandle.SafeDispose(ref this._descriptor); switch (ociType) { case OCI.DATATYPE.CLOB: case OCI.DATATYPE.BLOB: case OCI.DATATYPE.BFILE: this._locator = new OciLobLocator(connection, this._bindingMetaType.OracleType); handleToBind = this._locator.Descriptor; break; case OCI.DATATYPE.RSET: this._descriptor = new OciStatementHandle(serviceContextHandle); handleToBind = this._descriptor; break; case OCI.DATATYPE.INT_TIMESTAMP: case OCI.DATATYPE.INT_TIMESTAMP_TZ: case OCI.DATATYPE.INT_TIMESTAMP_LTZ: this._dateTimeDescriptor = OracleDateTime.CreateEmptyDescriptor(ociType, connection); handleToBind = this._dateTimeDescriptor; break; } } if (handleToBind != null) { handleToBind.DangerousAddRef(ref mustRelease); parameterBuffer.WriteIntPtr(this._valueOffset, handleToBind.DangerousGetHandle()); } parameterBuffer.WriteInt16(this._indicatorOffset, (short) oK); if ((OCI.DATATYPE.LONGVARCHAR == ociType) || (OCI.DATATYPE.LONGVARRAW == ociType)) { alenp = IntPtr.Zero; } else if (this._bindAsUCS2) { parameterBuffer.WriteInt32(this._lengthOffset, num / System.Data.Common.ADP.CharSize); } else { parameterBuffer.WriteInt32(this._lengthOffset, num); } if (IsDirection(this.Parameter, ParameterDirection.Output)) { num2 = this._bufferLength; } else { num2 = num; } OCI.DATATYPE dty = ociType; switch (ociType) { case OCI.DATATYPE.INT_TIMESTAMP: dty = OCI.DATATYPE.TIMESTAMP; break; case OCI.DATATYPE.INT_TIMESTAMP_TZ: dty = OCI.DATATYPE.TIMESTAMP_TZ; break; case OCI.DATATYPE.INT_TIMESTAMP_LTZ: dty = OCI.DATATYPE.TIMESTAMP_LTZ; break; } int rc = TracedNativeMethods.OCIBindByName(statementHandle, out ptr2, errorHandle, parameterName, parameterName.Length, valuep, num2, dty, dataPtr, alenp, OCI.MODE.OCI_DEFAULT); if (rc != 0) { this._command.Connection.CheckError(errorHandle, rc); } this._bindHandle = new OciBindHandle(statementHandle, ptr2); if (this._bindingMetaType.IsCharacterType) { if (OCI.ClientVersionAtLeastOracle9i && IsDirection(this.Parameter, ParameterDirection.Output)) { this._bindHandle.SetAttribute(OCI.ATTR.OCI_ATTR_MAXCHAR_SIZE, this._bindSize, errorHandle); } if ((num2 > (this._bindingMetaType.MaxBindSize / System.Data.Common.ADP.CharSize)) || (!OCI.ClientVersionAtLeastOracle9i && this._bindingMetaType.UsesNationalCharacterSet)) { this._bindHandle.SetAttribute(OCI.ATTR.OCI_ATTR_MAXDATA_SIZE, this._bindingMetaType.MaxBindSize, errorHandle); } if (this._bindingMetaType.UsesNationalCharacterSet) { this._bindHandle.SetAttribute(OCI.ATTR.OCI_ATTR_CHARSET_FORM, 2, errorHandle); } if (this._bindAsUCS2) { this._bindHandle.SetAttribute(OCI.ATTR.OCI_ATTR_CHARSET_ID, 0x3e8, errorHandle); } } GC.KeepAlive(parameterBuffer); } }
internal static int OCIRowidToChar(OciHandle rowidDesc, NativeBuffer outbfp, ref int bufferLength, OciHandle errhp) { ushort outbflp = (ushort) bufferLength; if (Bid.AdvancedOn) { Bid.Trace("<oc.OCIRowidToChar|ADV|OCI> rowidDesc=0x%-07Ix outbfp=0x%-07Ix outbflp=%d, errhp=0x%-07Ix\n", OciHandle.HandleValueToTrace(rowidDesc), NativeBuffer.HandleValueToTrace(outbfp), outbfp.Length, OciHandle.HandleValueToTrace(errhp)); } int num = System.Data.Common.UnsafeNativeMethods.OCIRowidToChar(rowidDesc, outbfp, ref outbflp, errhp); bufferLength = outbflp; if (Bid.AdvancedOn) { Bid.Trace("<oc.OCIRowidToChar|ADV|OCI|RET> outbfp='%ls' rc=%d\n", outbfp.PtrToStringAnsi(0, outbflp), num); } return num; }
internal int PutOracleValue(object value, NativeBuffer buffer, int bufferOffset, MetaType metaType, OracleConnection connection, ref SafeHandle handleToBind) { handleToBind = null; OCI.DATATYPE ociType = metaType.OciType; OracleParameter parameter = this.Parameter; switch (ociType) { case OCI.DATATYPE.VARCHAR2: case OCI.DATATYPE.LONG: case OCI.DATATYPE.LONGVARCHAR: case OCI.DATATYPE.CHAR: return OracleString.MarshalToNative(value, parameter.Offset, parameter.GetActualSize(), buffer, bufferOffset, ociType, this._bindAsUCS2); case OCI.DATATYPE.INTEGER: case OCI.DATATYPE.FLOAT: case OCI.DATATYPE.UNSIGNEDINT: buffer.StructureToPtr(bufferOffset, value); return metaType.BindSize; case OCI.DATATYPE.VARNUM: return OracleNumber.MarshalToNative(value, buffer, bufferOffset, connection); case OCI.DATATYPE.DATE: return OracleDateTime.MarshalDateToNative(value, buffer, bufferOffset, ociType, connection); case OCI.DATATYPE.RAW: case OCI.DATATYPE.LONGRAW: case OCI.DATATYPE.LONGVARRAW: { int num; byte[] buffer2; if (this._coercedValue is OracleBinary) { OracleBinary binary = (OracleBinary) this._coercedValue; buffer2 = binary.Value; } else { buffer2 = (byte[]) this._coercedValue; } int num2 = buffer2.Length - parameter.Offset; int actualSize = parameter.GetActualSize(); if (actualSize != 0) { num2 = Math.Min(num2, actualSize); } if (OCI.DATATYPE.LONGVARRAW == ociType) { buffer.WriteInt32(bufferOffset, num2); bufferOffset += 4; num = num2 + 4; } else { num = num2; } buffer.WriteBytes(bufferOffset, buffer2, parameter.Offset, num2); return num; } case OCI.DATATYPE.CLOB: case OCI.DATATYPE.BLOB: if (!(value is OracleLob)) { throw System.Data.Common.ADP.BadBindValueType(value.GetType(), metaType.OracleType); } handleToBind = ((OracleLob) value).Descriptor; return IntPtr.Size; case OCI.DATATYPE.BFILE: if (!(value is OracleBFile)) { throw System.Data.Common.ADP.BadBindValueType(value.GetType(), metaType.OracleType); } handleToBind = ((OracleBFile) value).Descriptor; return IntPtr.Size; case OCI.DATATYPE.INT_TIMESTAMP: case OCI.DATATYPE.INT_TIMESTAMP_LTZ: if (value is OracleDateTime) { OracleDateTime time = (OracleDateTime) value; if (!time.HasTimeInfo) { throw System.Data.Common.ADP.UnsupportedOracleDateTimeBinding(metaType.OracleType); } } this._dateTimeDescriptor = OracleDateTime.CreateDescriptor(ociType, connection, value); handleToBind = this._dateTimeDescriptor; return IntPtr.Size; case OCI.DATATYPE.INT_TIMESTAMP_TZ: if (value is OracleDateTime) { OracleDateTime time2 = (OracleDateTime) value; if (!time2.HasTimeZoneInfo) { throw System.Data.Common.ADP.UnsupportedOracleDateTimeBinding(OracleType.TimestampWithTZ); } } this._dateTimeDescriptor = OracleDateTime.CreateDescriptor(ociType, connection, value); handleToBind = this._dateTimeDescriptor; return IntPtr.Size; case OCI.DATATYPE.INT_INTERVAL_YM: return OracleMonthSpan.MarshalToNative(value, buffer, bufferOffset); case OCI.DATATYPE.INT_INTERVAL_DS: return OracleTimeSpan.MarshalToNative(value, buffer, bufferOffset); } throw System.Data.Common.ADP.TypeNotSupported(ociType); }
internal OracleMonthSpan(NativeBuffer buffer, int valueOffset) { this._value = MarshalToInt32(buffer, valueOffset); }