Esempio n. 1
0
 public WISEObject(INETWISEDriverSink2 WISE, DatabaseHandle databaseHandle, ObjectHandle objectHandle, TransactionHandle transactionHandle)
 {
     this.WISE = WISE;
     this.Database = databaseHandle;
     this.Object = objectHandle;
     this.Transaction = transactionHandle;
 }
Esempio n. 2
0
 public WISEObject()
 {
     this.WISE = null;
     this.Database = WISEConstants.WISE_TRANSITION_CACHE_DATABASE;
     this.Object = WISEConstants.WISE_INVALID_HANDLE;
     this.Transaction = TransactionHandle.None;            
 }
 public EntityEquipmentSensorCBRNAP2Ce(INETWISEDriverSink2 WISE, DatabaseHandle databaseHandle, ObjectHandle objectHandle, TransactionHandle transactionHandle)
 {
     this.WISE = WISE;
     this.Database = databaseHandle;
     this.Object = objectHandle;
     this.Transaction = transactionHandle;
 }
        public override byte[] GetSlice(int sliceLength)
        {
            ClearStatusVector();

            DatabaseHandle    dbHandle = _db.HandlePtr;
            TransactionHandle trHandle = _transaction.HandlePtr;

            IntPtr arrayDesc = ArrayDescMarshaler.MarshalManagedToNative(Descriptor);

            byte[] buffer = new byte[sliceLength];

            _db.FbClient.isc_array_get_slice(
                _statusVector,
                ref dbHandle,
                ref trHandle,
                ref _handle,
                arrayDesc,
                buffer,
                ref sliceLength);

            ArrayDescMarshaler.CleanUpNativeData(ref arrayDesc);

            _db.ProcessStatusVector(_statusVector);

            return(buffer);
        }
Esempio n. 5
0
 public EntityGroundVehicle(INETWISEDriverSink2 WISE, DatabaseHandle databaseHandle, ObjectHandle objectHandle, TransactionHandle transactionHandle)
 {
     this.WISE = WISE;
     this.Database = databaseHandle;
     this.Object = objectHandle;
     this.Transaction = transactionHandle;
 }
        public override void PutSlice(Array sourceArray, int sliceLength)
        {
            ClearStatusVector();

            DatabaseHandle    dbHandle = _db.HandlePtr;
            TransactionHandle trHandle = _transaction.HandlePtr;

            IntPtr arrayDesc = ArrayDescMarshaler.MarshalManagedToNative(Descriptor);

            Type systemType = GetSystemType();

            byte[] buffer = new byte[sliceLength];
            if (systemType.GetTypeInfo().IsPrimitive)
            {
                Buffer.BlockCopy(sourceArray, 0, buffer, 0, buffer.Length);
            }
            else
            {
                buffer = EncodeSlice(Descriptor, sourceArray, sliceLength);
            }

            _db.FbClient.isc_array_put_slice(
                _statusVector,
                ref dbHandle,
                ref trHandle,
                ref _handle,
                arrayDesc,
                buffer,
                ref sliceLength);

            ArrayDescMarshaler.CleanUpNativeData(ref arrayDesc);

            _db.ProcessStatusVector(_statusVector);
        }
        public void should_commit_transaction()
        {
            var transactionMock = Substitute.For <IDbTransaction>();
            var scope           = new TransactionHandle(transactionMock);

            scope.Dispose();

            transactionMock.Received(1).Commit();
        }
        public void should_commit_transaction()
        {
            var transactionMock = Substitute.For<IDbTransaction>();
            var scope = new TransactionHandle(transactionMock);

            scope.Dispose();

            transactionMock.Received(1).Commit();
        }
Esempio n. 9
0
        public override void Execute()
        {
            if (_state == StatementState.Deallocated)
            {
                throw new InvalidOperationException("Statment is not correctly created.");
            }

            ClearStatusVector();

            IntPtr inSqlda  = IntPtr.Zero;
            IntPtr outSqlda = IntPtr.Zero;

            if (_parameters != null)
            {
                inSqlda = XsqldaMarshaler.MarshalManagedToNative(_db.Charset, _parameters);
            }
            if (_statementType == DbStatementType.StoredProcedure)
            {
                Fields.ResetValues();
                outSqlda = XsqldaMarshaler.MarshalManagedToNative(_db.Charset, _fields);
            }

            TransactionHandle trHandle = _transaction.HandlePtr;

            _db.FbClient.isc_dsql_execute2(
                _statusVector,
                ref trHandle,
                ref _handle,
                IscCodes.SQLDA_VERSION1,
                inSqlda,
                outSqlda);

            if (outSqlda != IntPtr.Zero)
            {
                Descriptor descriptor = XsqldaMarshaler.MarshalNativeToManaged(_db.Charset, outSqlda, true);

                DbValueBase[] values = new DbValueBase[descriptor.Count];

                for (int i = 0; i < values.Length; i++)
                {
                    values[i] = new DbValue(this, descriptor[i]);
                }

                _outputParams.Enqueue(values);
            }

            XsqldaMarshaler.CleanUpNativeData(ref inSqlda);
            XsqldaMarshaler.CleanUpNativeData(ref outSqlda);

            _db.ProcessStatusVector(_statusVector);

            UpdateRecordsAffected();

            _state = StatementState.Executed;
        }
        public void should_trigger_disposed_event()
        {
            var wasDisposedEventHandlerTriggered = false;
            var transaction = Substitute.For<IDbTransaction>();
            var scope = new TransactionHandle(transaction);

            scope.Disposed += (sender, e) => wasDisposedEventHandlerTriggered = true;
            scope.Dispose();

            Assert.True(wasDisposedEventHandlerTriggered);
        } 
        public void should_trigger_disposed_event()
        {
            var wasDisposedEventHandlerTriggered = false;
            var transaction = Substitute.For <IDbTransaction>();
            var scope       = new TransactionHandle(transaction);

            scope.Disposed += (sender, e) => wasDisposedEventHandlerTriggered = true;
            scope.Dispose();

            Assert.True(wasDisposedEventHandlerTriggered);
        }
        public void should_not_use_transaction_if_null()
        {
            var transactionMock = Substitute.For <IDbTransaction>();
            var scope           = new TransactionHandle(transactionMock);

            scope.Dispose();

            //call it again (shouldn't do anything)
            scope.Dispose();

            transactionMock.Received(1).Commit();
        }
Esempio n. 13
0
        public FesTransaction(IDatabase db)
        {
            if (!(db is FesDatabase))
            {
                throw new ArgumentException($"Specified argument is not of {nameof(FesDatabase)} type.");
            }

            _db           = (FesDatabase)db;
            _handle       = new TransactionHandle();
            _state        = TransactionState.NoTransaction;
            _statusVector = new IntPtr[IscCodes.ISC_STATUS_LENGTH];
        }
        public void should_not_use_transaction_if_null()
        {
            var transactionMock = Substitute.For<IDbTransaction>();
            var scope = new TransactionHandle(transactionMock);

            scope.Dispose();

            //call it again (shouldn't do anything)
            scope.Dispose();

            transactionMock.Received(1).Commit();
        }
Esempio n. 15
0
        public override void Prepare(string commandText)
        {
            ClearAll();

            ClearStatusVector();

            if (_state == StatementState.Deallocated)
            {
                Allocate();
            }

            _fields = new Descriptor(1);

            IntPtr            sqlda    = XsqldaMarshaler.MarshalManagedToNative(_db.Charset, _fields);
            TransactionHandle trHandle = _transaction.HandlePtr;

            byte[] buffer = _db.Charset.GetBytes(commandText);

            _db.FbClient.isc_dsql_prepare(
                _statusVector,
                ref trHandle,
                ref _handle,
                (short)buffer.Length,
                buffer,
                _db.Dialect,
                sqlda);

            Descriptor descriptor = XsqldaMarshaler.MarshalNativeToManaged(_db.Charset, sqlda);

            XsqldaMarshaler.CleanUpNativeData(ref sqlda);

            _db.ProcessStatusVector(_statusVector);

            _fields = descriptor;

            if (_fields.ActualCount > 0 && _fields.ActualCount != _fields.Count)
            {
                Describe();
            }
            else
            {
                if (_fields.ActualCount == 0)
                {
                    _fields = new Descriptor(0);
                }
            }

            _fields.ResetValues();

            _statementType = GetStatementType();

            _state = StatementState.Prepared;
        }
Esempio n. 16
0
        /// <summary>
        /// Reads the attributes.
        /// </summary>
        protected override void Read(
            RequestContext context,
            TransactionHandle transaction,
            IList <NodeAttributeOperationHandle> operationHandles,
            IList <ReadValueId> settings)
        {
            for (int ii = 0; ii < operationHandles.Count; ii++)
            {
                DataValue dv = null;

                // the data passed to CreateVariable is returned as the UserData in the handle.
                SystemAddress address = operationHandles[ii].NodeHandle.UserData as SystemAddress;

                if (address != null)
                {
                    // read the data from the underlying system.
                    object value = m_system.Read(address.Address, address.Offset);

                    if (value != null)
                    {
                        dv = new DataValue(new Variant(value, null), DateTime.UtcNow);

                        // apply any index range or encoding.
                        if (!String.IsNullOrEmpty(settings[ii].IndexRange) || !QualifiedName.IsNull(settings[ii].DataEncoding))
                        {
                            dv = ApplyIndexRangeAndEncoding(
                                operationHandles[ii].NodeHandle,
                                dv,
                                settings[ii].IndexRange,
                                settings[ii].DataEncoding);
                        }
                    }
                }

                // set an error if not found.
                if (dv == null)
                {
                    dv = new DataValue(new StatusCode(StatusCodes.BadNodeIdUnknown));
                }

                // return the data to the caller.
                ((ReadCompleteEventHandler)transaction.Callback)(
                    operationHandles[ii],
                    transaction.CallbackData,
                    dv,
                    false);
            }
        }
Esempio n. 17
0
        protected override void Open()
        {
            ClearStatusVector();

            DatabaseHandle    dbHandle = _db.HandlePtr;
            TransactionHandle trHandle = ((FesTransaction)_transaction).HandlePtr;

            _db.FbClient.isc_open_blob2(
                _statusVector,
                ref dbHandle,
                ref trHandle,
                ref _blobHandle,
                ref _blobId,
                0,
                new byte[0]);

            _db.ProcessStatusVector(_statusVector);
        }
Esempio n. 18
0
        protected override void Read(
            RequestContext context,
            TransactionHandle transaction,
            IList <NodeAttributeOperationHandle> operationHandles,
            IList <ReadValueId> settings)
        {
            DataValue dv = new DataValue(new Variant(currentData, null), DateTime.UtcNow);

            foreach (var handle in operationHandles)
            {
                SystemAddress address = handle.NodeHandle.UserData as SystemAddress;

                ((ReadCompleteEventHandler)transaction.Callback)(
                    handle,
                    transaction.CallbackData,
                    dv,
                    false);
            }
        }
Esempio n. 19
0
        /// <summary>
        /// Reads the attributes.
        /// </summary>
        protected override void Read(
            RequestContext context,
            TransactionHandle transaction,
            IList <NodeAttributeOperationHandle> operationHandles,
            IList <ReadValueId> settings)
        {
            for (int ii = 0; ii < operationHandles.Count; ii++)
            {
                DataValue dv = null;

                // the data passed to CreateVariable is returned as the UserData in the handle.
                if (operationHandles[ii].NodeHandle.UserData is Tuple <Func <object>, Action <object> > accessors)
                {
                    var getter = accessors.Item1;

                    dv = new DataValue(new Variant(getter(), null), DateTime.UtcNow);

                    // apply any index range or encoding.
                    if (!string.IsNullOrEmpty(settings[ii].IndexRange) || !QualifiedName.IsNull(settings[ii].DataEncoding))
                    {
                        dv = ApplyIndexRangeAndEncoding(
                            operationHandles[ii].NodeHandle,
                            dv,
                            settings[ii].IndexRange,
                            settings[ii].DataEncoding);
                    }
                }

                // set an error if not found.
                if (dv == null)
                {
                    dv = new DataValue(new StatusCode(StatusCodes.BadNodeIdUnknown));
                }

                // return the data to the caller.
                ((ReadCompleteEventHandler)transaction.Callback)(
                    operationHandles[ii],
                    transaction.CallbackData,
                    dv,
                    false);
            }
        }
        public override void PutSlice(System.Array sourceArray, int sliceLength)
        {
            // Clear the status vector
            ClearStatusVector();

            DatabaseHandle    dbHandle = _db.HandlePtr;
            TransactionHandle trHandle = _transaction.HandlePtr;

            IntPtr arrayDesc = ArrayDescMarshaler.MarshalManagedToNative(Descriptor);

            // Obtain the System of	type of	Array elements and
            // Fill	buffer
            Type systemType = GetSystemType();

            byte[] buffer = new byte[sliceLength];
#if NET40
            if (systemType.IsPrimitive)
#else
            if (systemType.GetTypeInfo().IsPrimitive)
#endif
            {
                Buffer.BlockCopy(sourceArray, 0, buffer, 0, buffer.Length);
            }
            else
            {
                buffer = EncodeSlice(Descriptor, sourceArray, sliceLength);
            }

            _db.FbClient.isc_array_put_slice(
                _statusVector,
                ref dbHandle,
                ref trHandle,
                ref _handle,
                arrayDesc,
                buffer,
                ref sliceLength);

            // Free	memory
            ArrayDescMarshaler.CleanUpNativeData(ref arrayDesc);

            _db.ProcessStatusVector(_statusVector);
        }
Esempio n. 21
0
        protected override void Create()
        {
            ClearStatusVector();

            DatabaseHandle    dbHandle = _db.HandlePtr;
            TransactionHandle trHandle = ((FesTransaction)_transaction).HandlePtr;

            _db.FbClient.isc_create_blob2(
                _statusVector,
                ref dbHandle,
                ref trHandle,
                ref _blobHandle,
                ref _blobId,
                0,
                new byte[0]);

            _db.ProcessStatusVector(_statusVector);

            RblAddValue(IscCodes.RBL_create);
        }
Esempio n. 22
0
        protected override void Write(
            RequestContext context,
            TransactionHandle transaction,
            IList <NodeAttributeOperationHandle> operationHandles,
            IList <WriteValue> settings)
        {
            StatusCode error = StatusCodes.Good;

            // the data passed to CreateVariable is returned as the UserData in the handle.
            SystemAddress address = operationHandles[0].NodeHandle.UserData as SystemAddress;

            currentData = settings[0].Value.Value.ToString();

            // error = StatusCodes.BadNodeIdUnknown;

            // return the data to the caller.
            ((WriteCompleteEventHandler)transaction.Callback)(
                operationHandles[0],
                transaction.CallbackData,
                error,
                false);
        }
Esempio n. 23
0
        /// <summary>
        /// Write the attributes
        /// </summary>
        protected override void Write(
            RequestContext context,
            TransactionHandle transaction,
            IList <NodeAttributeOperationHandle> operationHandles,
            IList <WriteValue> settings)
        {
            for (int ii = 0; ii < operationHandles.Count; ii++)
            {
                StatusCode error = StatusCodes.Good;

                // the data passed to CreateVariable is returned as the UserData in the handle.
                SystemAddress address = operationHandles[ii].NodeHandle.UserData as SystemAddress;

                if (address != null)
                {
                    if (!String.IsNullOrEmpty(settings[ii].IndexRange))
                    {
                        error = StatusCodes.BadIndexRangeInvalid;
                    }
                    else if (!m_system.Write(address.Address, address.Offset, settings[ii].Value.Value))
                    {
                        error = StatusCodes.BadUserAccessDenied;
                    }
                }
                else
                {
                    error = StatusCodes.BadNodeIdUnknown;
                }

                // return the data to the caller.
                ((WriteCompleteEventHandler)transaction.Callback)(
                    operationHandles[ii],
                    transaction.CallbackData,
                    error,
                    false);
            }
        }
Esempio n. 24
0
        /// <summary>
        /// Write the attributes
        /// </summary>
        protected override void Write(
            RequestContext context,
            TransactionHandle transaction,
            IList <NodeAttributeOperationHandle> operationHandles,
            IList <WriteValue> settings)
        {
            for (int ii = 0; ii < operationHandles.Count; ii++)
            {
                StatusCode error = StatusCodes.Good;

                // the data passed to CreateVariable is returned as the UserData in the handle.

                if (operationHandles[ii].NodeHandle.UserData is Tuple <Func <object>, Action <object> > accessors)
                {
                    if (!string.IsNullOrEmpty(settings[ii].IndexRange))
                    {
                        error = StatusCodes.BadIndexRangeInvalid;
                    }

                    var setter = accessors.Item2;

                    setter(settings[ii].Value.Value);
                }
                else
                {
                    error = StatusCodes.BadNodeIdUnknown;
                }

                // return the data to the caller.
                ((WriteCompleteEventHandler)transaction.Callback)(
                    operationHandles[ii],
                    transaction.CallbackData,
                    error,
                    false);
            }
        }
Esempio n. 25
0
        protected override WISE_RESULT OnUpdateAttribute(DateTime timeStamp, DatabaseHandle hDatabase, ObjectHandle hObject,
            ClassHandle hClass, AttributeHandle hAttribute, object value, AttributeQualityCode quality,
            TransactionHandle hTransaction)
        {
            WISE_RESULT result = WISEError.WISE_OK;

            // Call base class implementation
            result = base.OnUpdateAttribute(timeStamp, hDatabase, hObject, hClass, hAttribute, value, quality, hTransaction);
            WISEError.CheckCallFailedEx(result);

            //string myValue = string.Empty;
            //AttributeHandle myAttributeHandle = AttributeHandle.Invalid;
            //this.WISE.GetAttributeHandle(hDatabase, hObject, "SomeAttribute", ref myAttributeHandle);
            //this.WISE.GetAttributeValue(hDatabase, hObject, myAttributeHandle, ref myValue);

            //global::CBRNSensors.EntityEquipmentSensorCBRNLCD stateObject = new global::CBRNSensors.EntityEquipmentSensorCBRNLCD();
            //stateObject.CreateInstance(this.WISE, hDatabase);
            //stateObject.SensorState =
            //stateObject.AddToDatabase(hDatabase);

            return result;
        }
 public EntityEquipmentSensorCBRNLCD(INETWISEDriverSink2 WISE, DatabaseHandle databaseHandle, ObjectHandle objectHandle, TransactionHandle transactionHandle)
     : base(WISE, databaseHandle, objectHandle, transactionHandle)
 {
 }
Esempio n. 27
0
        protected override WISE_RESULT OnSendEvent(DateTime timeStamp, DatabaseHandle hDatabase, EventHandle hEvent,
            ClassHandle hClass, TransactionHandle hTransaction)
        {
            WISE_RESULT result = WISEError.WISE_OK;

            // Call base class implementation
            result = base.OnSendEvent(timeStamp, hDatabase, hEvent, hClass, hTransaction);
            WISEError.CheckCallFailedEx(result);

            try
            {
                //
                // TODO: Send event on driver communication interface.
                //
                // This method typically needs to perform the following steps;
                //   1. Identify the type of event.
                //   2. Based on the event type, extract event attributes.
                //   3. Fill event attribute values into the protocol container associated with the event.
                //   4. Send the event on the underlying protocol.
                //

                #region Sample code: Check event type
                //ClassHandle hTestEventClass = ClassHandle.Invalid;

                //// Get handle corresponding to class "TEST_EVENT" (this can be done once and then cached)
                //result = this.WISETypeInfo.GetWISEClassHandle(hDatabase, "TEST_EVENT", ref hTestEventClass);
                //WISEError.CheckCallFailedEx(result);

                //if (hClass == hTestEventClass)
                //{
                //    #region Sample code: Access TEST_EVENT attributes
                //    string stringAttributeValue = "";
                //    AttributeHandle hAttr = AttributeHandle.Invalid;

                //    result = this.Sink.GetEventAttributeHandle(hDatabase, hEvent, "TEST_STRING", ref hAttr);
                //    WISEError.CheckCallFailedEx(result);

                //    result = this.Sink.GetEventAttributeValue(hDatabase, hEvent, hAttr, ref stringAttributeValue);
                //    WISEError.CheckCallFailedEx(result);
                //    #endregion
                //}
                #endregion
            }
            catch (WISEException ex)
            {
                result = ex.Error.ErrorCode;
            }
            return result;
        }
Esempio n. 28
0
        protected override WISE_RESULT OnAddObject(DateTime timeStamp, DatabaseHandle hDatabase, ObjectHandle hObject,
                ClassHandle hClass, string strObjectName, TransactionHandle hTransaction)
        {
            WISE_RESULT result = WISEError.WISE_OK;

            // Call base class implementation
            result = base.OnAddObject(timeStamp, hDatabase, hObject, hClass, strObjectName, hTransaction);
            WISEError.CheckCallFailedEx(result);

            try
            {
                DatabaseType dbtype = DatabaseType.Unknown;
                result = this.Sink.GetDatabaseType(hDatabase, ref dbtype);
                WISEError.CheckCallFailedEx(result);

                if (dbtype == DatabaseType.Application)
                {
                    // Only process application database objects by default

                    //if (global::CBRNSensors.EntityEquipment.IsTypeOf(this.WISE, hDatabase, hObject))
                    //{
                    //    global::CBRNSensors.EntityEquipment myObject = new global::CBRNSensors.EntityEquipment();
                    //}

                    //
                    // TODO: Add object on driver communication interface.
                    //
                    // This method typically works in either of two ways.
                    // If the underlying protocol requires us to send all object attributes
                    // as a part of the object creation message;
                    //   1. Identify the type of object.
                    //   2. Based on the object type, extract its attributes.
                    //   3. Fill object attribute values into the protocol container associated with object creation.
                    //   4. the creation message on the underlying protocol.
                    //
                    // If the underlying protocol separates the create message from the initial attribute
                    // update message;
                    //   1. Fill object information into the protocol container associated with object creation.
                    //   2. Send the creation message on the underlying protocol.
                    //

                    #region Sample code: Check object type
                    //ClassHandle hTestObjectClass = ClassHandle.Invalid;

                    //// Get handle corresponding to class "TEST_OBJECT" (this can be done once and then cached)
                    //result = this.WISETypeInfo.GetWISEClassHandle(hDatabase, "TEST_OBJECT", ref hTestObjectClass);
                    //WISEError.CheckCallFailedEx(result);

                    //if (hClass == hTestObjectClass)
                    //{
                    //    #region Sample code: Access TEST_OBJECT attributes
                    //    string stringAttributeValue = "";
                    //    AttributeHandle hAttr = AttributeHandle.Invalid;

                    //    result = this.Sink.GetAttributeHandle(hDatabase, hObject, "TEST_STRING", ref hAttr);
                    //    WISEError.CheckCallFailedEx(result);

                    //    result = this.Sink.GetAttributeValue(hDatabase, hObject, hAttr, ref stringAttributeValue);
                    //    WISEError.CheckCallFailedEx(result);
                    //    #endregion
                    //}
                    #endregion
                }
            }
            catch (WISEException ex)
            {
                result = ex.Error.ErrorCode;
            }
            return result;
        }
Esempio n. 29
0
        protected override WISE_RESULT OnCommitTransaction(System.DateTime timeStamp, DatabaseHandle hDatabase, TransactionHandle hTransaction,
                ObjectHandleList newObjects, ObjectHandleList removedObjects, Dictionary<ObjectHandle, List<AttributeHandle>> dictNewAttributes,
                Dictionary<ObjectHandle, List<AttributeHandle>> dictRemovedAttributes,
                Dictionary<ObjectHandle, List<AttributeHandle>> dictUpdatedAttributes, List<EventHandle> newEvents)
        {
            //
            // TODO:
            //      If your protocol handles transactions, process the transaction data here.
            //      Returning WISE_E_NOT_IMPL from this method will trigger the driver base class to use the
            //      fallback behaviour where each change in the transaction is processed individually
            //      through calls to OnAddObject, OnRemoveObject, OnNewAttribute, OnRemoveAttribute,
            //      OnUpdateAttribute and OnSendEvent respectively.
            //

            return WISEError.WISE_E_NOT_IMPL;
        }
Esempio n. 30
0
        protected override WISE_RESULT OnRemoveObject(DateTime timeStamp, DatabaseHandle hDatabase, ObjectHandle hObject,
            ClassHandle hClass, TransactionHandle hTransaction)
        {
            WISE_RESULT result = WISEError.WISE_OK;

            // Call base class implementation
            result = base.OnRemoveObject(timeStamp, hDatabase, hObject, hClass, hTransaction);
            WISEError.CheckCallFailedEx(result);

            try
            {
                DatabaseType dbtype = DatabaseType.Unknown;
                result = this.Sink.GetDatabaseType(hDatabase, ref dbtype);

                if (dbtype == DatabaseType.Application)
                {
                    //
                    // TODO: Remove object on driver communication interface.
                    //
                }
            }
            catch (WISEException ex)
            {
                result = ex.Error.ErrorCode;
            }
            return result;
        }
Esempio n. 31
0
 protected override void Write(RequestContext context, TransactionHandle transaction, IList <NodeAttributeOperationHandle> operationHandles, IList <WriteValue> settings)
 {
     base.Write(context, transaction, operationHandles, settings);
 }
Esempio n. 32
0
        public static ObjectInformation GetHandleInfo(this SystemHandleEntry thisHandle, ProcessHandle process, bool getName)
        {
            IntPtr        handle = new IntPtr(thisHandle.Handle);
            IntPtr        objectHandleI;
            int           retLength    = 0;
            GenericHandle objectHandle = null;

            if (thisHandle.Handle == 0 || thisHandle.Handle == -1 || thisHandle.Handle == -2)
            {
                throw new WindowsException(NtStatus.InvalidHandle);
            }

            // Duplicate the handle if we're not using KPH
            if (KProcessHacker.Instance == null)
            {
                NtStatus status;

                if ((status = Win32.NtDuplicateObject(
                         process, handle, ProcessHandle.Current, out objectHandleI, 0, 0, 0)) >= NtStatus.Error)
                {
                    Win32.ThrowLastError(status);
                }

                objectHandle = new GenericHandle(objectHandleI);
            }

            ObjectInformation info = new ObjectInformation();

            // If the cache contains the object type's name, use it. Otherwise, query the type
            // for its name.
            lock (Windows.ObjectTypes)
            {
                if (Windows.ObjectTypes.ContainsKey(thisHandle.ObjectTypeNumber))
                {
                    info.TypeName = Windows.ObjectTypes[thisHandle.ObjectTypeNumber];
                }
                else
                {
                    int baseAddress = 0;

                    if (KProcessHacker.Instance != null)
                    {
                        KProcessHacker.Instance.ZwQueryObject(process, handle, ObjectInformationClass.ObjectTypeInformation,
                                                              IntPtr.Zero, 0, out retLength, out baseAddress);
                    }
                    else
                    {
                        Win32.NtQueryObject(objectHandle, ObjectInformationClass.ObjectTypeInformation,
                                            IntPtr.Zero, 0, out retLength);
                    }

                    if (retLength > 0)
                    {
                        using (MemoryAlloc otiMem = new MemoryAlloc(retLength))
                        {
                            if (KProcessHacker.Instance != null)
                            {
                                if (KProcessHacker.Instance.ZwQueryObject(process, handle, ObjectInformationClass.ObjectTypeInformation,
                                                                          otiMem, otiMem.Size, out retLength, out baseAddress) >= NtStatus.Error)
                                {
                                    throw new Exception("ZwQueryObject failed.");
                                }
                            }
                            else
                            {
                                if (Win32.NtQueryObject(objectHandle, ObjectInformationClass.ObjectTypeInformation,
                                                        otiMem, otiMem.Size, out retLength) >= NtStatus.Error)
                                {
                                    throw new Exception("NtQueryObject failed.");
                                }
                            }

                            var oti = otiMem.ReadStruct <ObjectTypeInformation>();
                            var str = oti.Name;

                            if (KProcessHacker.Instance != null)
                            {
                                str.Buffer = str.Buffer.Increment(otiMem.Memory.Decrement(baseAddress));
                            }

                            info.TypeName = str.Read();
                            Windows.ObjectTypes.Add(thisHandle.ObjectTypeNumber, info.TypeName);
                        }
                    }
                }
            }

            if (!getName)
            {
                return(info);
            }

            // Get the object's name. If the object is a file we must take special
            // precautions so that we don't hang.
            if (info.TypeName == "File")
            {
                if (KProcessHacker.Instance != null)
                {
                    // Use KProcessHacker for files to avoid hangs.
                    info.OrigName = KProcessHacker.Instance.GetHandleObjectName(process, handle);
                }
                else
                {
                    // 0: No hack, query the thing normally.
                    // 1: No hack, use NProcessHacker.
                    // 2: Hack.
                    int hackLevel = 1;

                    // Can't use NPH because XP had a bug where a thread hanging
                    // on NtQueryObject couldn't be terminated.
                    if (OSVersion.IsBelowOrEqual(WindowsVersion.XP))
                    {
                        hackLevel = 2;
                    }

                    // On Windows 7 and above the hanging bug appears to have
                    // been fixed. Query the object normally.
                    // UPDATE: Not so. It still happens.
                    //if (OSVersion.IsAboveOrEqual(WindowsVersion.Seven))
                    //    hackLevel = 0;

                    if (hackLevel == 1)
                    {
                        try
                        {
                            // Use NProcessHacker.
                            using (MemoryAlloc oniMem = new MemoryAlloc(0x4000))
                            {
                                if (NProcessHacker.PhQueryNameFileObject(
                                        objectHandle, oniMem, oniMem.Size, out retLength) >= NtStatus.Error)
                                {
                                    throw new Exception("PhQueryNameFileObject failed.");
                                }

                                var oni = oniMem.ReadStruct <ObjectNameInformation>();

                                info.OrigName = oni.Name.Read();
                            }
                        }
                        catch (DllNotFoundException)
                        {
                            hackLevel = 2;
                        }
                    }

                    if (hackLevel == 0)
                    {
                        info.OrigName = GetObjectNameNt(process, handle, objectHandle);
                    }
                    else if (hackLevel == 2)
                    {
                        // KProcessHacker and NProcessHacker not available. Fall back to using hack
                        // (i.e. not querying the name at all if the access is 0x0012019f).
                        if ((int)thisHandle.GrantedAccess != 0x0012019f)
                        {
                            info.OrigName = GetObjectNameNt(process, handle, objectHandle);
                        }
                    }
                }
            }
            else
            {
                // Not a file. Query the object normally.
                info.OrigName = GetObjectNameNt(process, handle, objectHandle);
            }

            // Get a better name for the handle.
            try
            {
                switch (info.TypeName)
                {
                case "File":
                    // Resolves \Device\Harddisk1 into C:, for example.
                    if (!string.IsNullOrEmpty(info.OrigName))
                    {
                        info.BestName = FileUtils.GetFileName(info.OrigName);
                    }

                    break;

                case "Key":
                    info.BestName = NativeUtils.FormatNativeKeyName(info.OrigName);

                    break;

                case "Process":
                {
                    int processId;

                    if (KProcessHacker.Instance != null)
                    {
                        processId = KProcessHacker.Instance.KphGetProcessId(process, handle);

                        if (processId == 0)
                        {
                            throw new Exception("Invalid PID");
                        }
                    }
                    else
                    {
                        using (var processHandle =
                                   new NativeHandle <ProcessAccess>(process, handle, OSVersion.MinProcessQueryInfoAccess))
                        {
                            if ((processId = Win32.GetProcessId(processHandle)) == 0)
                            {
                                Win32.ThrowLastError();
                            }
                        }
                    }

                    info.BestName = (new ClientId(processId, 0)).GetName(false);
                }

                break;

                case "Thread":
                {
                    int processId;
                    int threadId;

                    if (KProcessHacker.Instance != null)
                    {
                        threadId = KProcessHacker.Instance.KphGetThreadId(process, handle, out processId);

                        if (threadId == 0 || processId == 0)
                        {
                            throw new Exception("Invalid TID or PID");
                        }
                    }
                    else
                    {
                        using (var threadHandle =
                                   new NativeHandle <ThreadAccess>(process, handle, OSVersion.MinThreadQueryInfoAccess))
                        {
                            var basicInfo = ThreadHandle.FromHandle(threadHandle).GetBasicInformation();

                            threadId  = basicInfo.ClientId.ThreadId;
                            processId = basicInfo.ClientId.ProcessId;
                        }
                    }

                    info.BestName = (new ClientId(processId, threadId)).GetName(true);
                }

                break;

                case "TmEn":
                {
                    using (var enHandleDup =
                               new NativeHandle <EnlistmentAccess>(process, handle, EnlistmentAccess.QueryInformation))
                    {
                        var enHandle = EnlistmentHandle.FromHandle(enHandleDup);

                        info.BestName = enHandle.GetBasicInformation().EnlistmentId.ToString("B");
                    }
                }
                break;

                case "TmRm":
                {
                    using (var rmHandleDup =
                               new NativeHandle <ResourceManagerAccess>(process, handle, ResourceManagerAccess.QueryInformation))
                    {
                        var rmHandle = ResourceManagerHandle.FromHandle(rmHandleDup);

                        info.BestName = rmHandle.GetDescription();

                        if (string.IsNullOrEmpty(info.BestName))
                        {
                            info.BestName = rmHandle.GetGuid().ToString("B");
                        }
                    }
                }
                break;

                case "TmTm":
                {
                    using (var tmHandleDup =
                               new NativeHandle <TmAccess>(process, handle, TmAccess.QueryInformation))
                    {
                        var tmHandle = TmHandle.FromHandle(tmHandleDup);

                        info.BestName = FileUtils.GetFileName(FileUtils.GetFileName(tmHandle.GetLogFileName()));

                        if (string.IsNullOrEmpty(info.BestName))
                        {
                            info.BestName = tmHandle.GetBasicInformation().TmIdentity.ToString("B");
                        }
                    }
                }
                break;

                case "TmTx":
                {
                    using (var transactionHandleDup =
                               new NativeHandle <TransactionAccess>(process, handle, TransactionAccess.QueryInformation))
                    {
                        var transactionHandle = TransactionHandle.FromHandle(transactionHandleDup);

                        info.BestName = transactionHandle.GetDescription();

                        if (string.IsNullOrEmpty(info.BestName))
                        {
                            info.BestName = transactionHandle.GetBasicInformation().TransactionId.ToString("B");
                        }
                    }
                }
                break;

                case "Token":
                {
                    using (var tokenHandleDup =
                               new NativeHandle <TokenAccess>(process, handle, TokenAccess.Query))
                    {
                        var tokenHandle = TokenHandle.FromHandle(tokenHandleDup);
                        var sid         = tokenHandle.GetUser();

                        using (sid)
                            info.BestName = sid.GetFullName(true) + ": 0x" +
                                            tokenHandle.GetStatistics().AuthenticationId.ToString();
                    }
                }

                break;

                default:
                    if (info.OrigName != null &&
                        info.OrigName != "")
                    {
                        info.BestName = info.OrigName;
                    }
                    else
                    {
                        info.BestName = null;
                    }

                    break;
                }
            }
            catch
            {
                if (info.OrigName != null && info.OrigName != "")
                {
                    info.BestName = info.OrigName;
                }
                else
                {
                    info.BestName = null;
                }
            }

            if (objectHandle != null)
            {
                objectHandle.Dispose();
            }

            return(info);
        }
        public override void Prepare(string commandText)
        {
            // Clear data
            ClearAll();

            lock (_db)
            {
                // Clear the status vector
                ClearStatusVector();

                // Allocate the statement if needed
                if (_state == StatementState.Deallocated)
                {
                    Allocate();
                }

                // Marshal structures to pointer


                // Setup fields	structure
                _fields = new Descriptor(1);

                IntPtr            sqlda    = XsqldaMarshaler.MarshalManagedToNative(_db.Charset, _fields);
                TransactionHandle trHandle = _transaction.HandlePtr;

                byte[] buffer = _db.Charset.GetBytes(commandText);

                _db.FbClient.isc_dsql_prepare(
                    _statusVector,
                    ref trHandle,
                    ref _handle,
                    (short)buffer.Length,
                    buffer,
                    _db.Dialect,
                    sqlda);

                // Marshal Pointer
                Descriptor descriptor = XsqldaMarshaler.MarshalNativeToManaged(_db.Charset, sqlda);

                // Free	memory
                XsqldaMarshaler.CleanUpNativeData(ref sqlda);

                // Parse status	vector
                _db.ProcessStatusVector(_statusVector);

                // Describe	fields
                _fields = descriptor;

                if (_fields.ActualCount > 0 && _fields.ActualCount != _fields.Count)
                {
                    Describe();
                }
                else
                {
                    if (_fields.ActualCount == 0)
                    {
                        _fields = new Descriptor(0);
                    }
                }

                // Reset actual	field values
                _fields.ResetValues();

                // Get Statement type
                _statementType = GetStatementType();

                // Update state
                _state = StatementState.Prepared;
            }
        }
Esempio n. 34
0
 protected override void Read(RequestContext context, TransactionHandle transaction, IList <NodeAttributeOperationHandle> operationHandles, IList <ReadValueId> settings)
 {
     base.Read(context, transaction, operationHandles, settings);
 }
Esempio n. 35
0
 public override long Release(long id, TransactionHandle transactionHandle)
 {
     throw new System.NotSupportedException();
 }
Esempio n. 36
0
 public EntityGroundVehicle(INETWISEDriverSink2 WISE, DatabaseHandle databaseHandle, ObjectHandle objectHandle, TransactionHandle transactionHandle)
     : base(WISE, databaseHandle, objectHandle, transactionHandle)
 {
 }
Esempio n. 37
0
 public override long Begin(TransactionHandle handle)
 {
     throw new System.NotSupportedException();
 }
Esempio n. 38
0
        public static ObjectInformation GetHandleInfo(this SystemHandleEntry thisHandle, ProcessHandle process, bool getName)
        {
            IntPtr        handle = new IntPtr(thisHandle.Handle);
            IntPtr        objectHandleI;
            int           retLength;
            GenericHandle objectHandle = null;

            if (thisHandle.Handle == 0 || thisHandle.Handle == -1 || thisHandle.Handle == -2)
            {
                throw new WindowsException(NtStatus.InvalidHandle);
            }

            // Duplicate the handle if we're not using KPH
            //if (KProcessHacker.Instance == null)
            {
                Win32.NtDuplicateObject(
                    process,
                    handle,
                    ProcessHandle.Current,
                    out objectHandleI,
                    0,
                    0,
                    0
                    ).ThrowIf();

                objectHandle = new GenericHandle(objectHandleI);
            }

            ObjectInformation info = new ObjectInformation();

            // If the cache contains the object type's name, use it. Otherwise, query the type
            // for its name.
            Windows.ObjectTypesLock.AcquireShared();

            try
            {
                if (Windows.ObjectTypes.ContainsKey(thisHandle.ObjectTypeNumber))
                {
                    info.TypeName = Windows.ObjectTypes[thisHandle.ObjectTypeNumber];
                }
            }
            finally
            {
                Windows.ObjectTypesLock.ReleaseShared();
            }

            if (string.IsNullOrEmpty(info.TypeName))
            {
                Win32.NtQueryObject(
                    objectHandle,
                    ObjectInformationClass.ObjectTypeInformation,
                    IntPtr.Zero,
                    0,
                    out retLength
                    );

                if (retLength > 0)
                {
                    using (MemoryAlloc otiMem = new MemoryAlloc(retLength))
                    {
                        Win32.NtQueryObject(
                            objectHandle,
                            ObjectInformationClass.ObjectTypeInformation,
                            otiMem,
                            otiMem.Size,
                            out retLength
                            ).ThrowIf();

                        ObjectTypeInformation oti = otiMem.ReadStruct <ObjectTypeInformation>();
                        UnicodeString         str = oti.Name;

                        //if (KProcessHacker.Instance != null)
                        //str.Buffer = str.Buffer.Increment(otiMem.Memory.Decrement(baseAddress));

                        info.TypeName = str.Text;

                        Windows.ObjectTypesLock.AcquireExclusive();

                        try
                        {
                            if (!Windows.ObjectTypes.ContainsKey(thisHandle.ObjectTypeNumber))
                            {
                                Windows.ObjectTypes.Add(thisHandle.ObjectTypeNumber, info.TypeName);
                            }
                        }
                        finally
                        {
                            Windows.ObjectTypesLock.ReleaseExclusive();
                        }
                    }
                }
            }

            if (!getName)
            {
                return(info);
            }

            // Get the object's name. If the object is a file we must take special
            // precautions so that we don't hang.
            if (string.Equals(info.TypeName, "File", StringComparison.OrdinalIgnoreCase))
            {
                //if (KProcessHacker.Instance != null)
                //{
                //    // Use KProcessHacker for files to avoid hangs.
                //    info.OrigName = KProcessHacker.Instance.GetHandleObjectName(process, handle);
                //}
                //else
                {
                    // 0: No hack, query the thing normally.
                    // 1: No hack, use NProcessHacker.
                    // 2: Hack.
                    int hackLevel = 1;

                    // If we already tried to use NPH but it wasn't present,
                    // skip to level 2.
                    if (NphNotAvailable)
                    {
                        hackLevel = 2;
                    }

                    // Can't use NPH because XP had a bug where a thread hanging
                    // on NtQueryObject couldn't be terminated.
                    if (OSVersion.IsBelowOrEqual(WindowsVersion.XP))
                    {
                        hackLevel = 2;
                    }

                    // On Windows 7 and above the hanging bug appears to have
                    // been fixed. Query the object normally.
                    // UPDATE: Not so. It still happens.
                    //if (OSVersion.IsAboveOrEqual(WindowsVersion.Seven))
                    //    hackLevel = 0;

                    if (hackLevel == 1)
                    {
                        try
                        {
                            // Use NProcessHacker.
                            using (MemoryAlloc oniMem = new MemoryAlloc(0x4000))
                            {
                                NProcessHacker.PhQueryNameFileObject(
                                    objectHandle,
                                    oniMem,
                                    oniMem.Size,
                                    out retLength
                                    ).ThrowIf();

                                var oni = oniMem.ReadStruct <ObjectNameInformation>();

                                info.OrigName = oni.Name.Text;
                            }
                        }
                        catch (DllNotFoundException)
                        {
                            hackLevel       = 2;
                            NphNotAvailable = true;
                        }
                    }

                    if (hackLevel == 0)
                    {
                        info.OrigName = GetObjectNameNt(process, handle, objectHandle);
                    }
                    else if (hackLevel == 2)
                    {
                        // KProcessHacker and NProcessHacker not available. Fall back to using hack
                        // (i.e. not querying the name at all if the access is 0x0012019f).
                        if (thisHandle.GrantedAccess != 0x0012019f)
                        {
                            info.OrigName = GetObjectNameNt(process, handle, objectHandle);
                        }
                    }
                }
            }
            else
            {
                // Not a file. Query the object normally.
                info.OrigName = GetObjectNameNt(process, handle, objectHandle);
            }

            // Get a better name for the handle.
            try
            {
                switch (info.TypeName)
                {
                case "File":
                    // Resolves \Device\HarddiskVolume1 into C:, for example.
                    if (!string.IsNullOrEmpty(info.OrigName))
                    {
                        info.BestName = FileUtils.GetFileName(info.OrigName);
                    }

                    break;

                case "Key":
                    info.BestName = NativeUtils.FormatNativeKeyName(info.OrigName);
                    break;

                case "Process":
                {
                    int processId;

                    using (NativeHandle <ProcessAccess> processHandle = new NativeHandle <ProcessAccess>(process, handle, OSVersion.MinProcessQueryInfoAccess))
                    {
                        if ((processId = Win32.GetProcessId(processHandle)) == 0)
                        {
                            Win32.Throw();
                        }
                    }

                    info.BestName = (new ClientId(processId, 0)).GetName(false);
                }
                break;

                case "Thread":
                {
                    int processId;
                    int threadId;

                    using (var threadHandle = new NativeHandle <ThreadAccess>(process, handle, OSVersion.MinThreadQueryInfoAccess))
                    {
                        var basicInfo = ThreadHandle.FromHandle(threadHandle).GetBasicInformation();

                        threadId  = basicInfo.ClientId.ThreadId;
                        processId = basicInfo.ClientId.ProcessId;
                    }

                    info.BestName = (new ClientId(processId, threadId)).GetName(true);
                }
                break;

                case "TmEn":
                {
                    using (NativeHandle <EnlistmentAccess> enHandleDup = new NativeHandle <EnlistmentAccess>(process, handle, EnlistmentAccess.QueryInformation))
                        using (EnlistmentHandle enHandle = EnlistmentHandle.FromHandle(enHandleDup))
                        {
                            info.BestName = enHandle.BasicInformation.EnlistmentId.ToString("B");
                        }
                }
                break;

                case "TmRm":
                {
                    using (var rmHandleDup = new NativeHandle <ResourceManagerAccess>(process, handle, ResourceManagerAccess.QueryInformation))
                    {
                        var rmHandle = ResourceManagerHandle.FromHandle(rmHandleDup);

                        info.BestName = rmHandle.Description;

                        if (string.IsNullOrEmpty(info.BestName))
                        {
                            info.BestName = rmHandle.Guid.ToString("B");
                        }
                    }
                }
                break;

                case "TmTm":
                {
                    using (NativeHandle <TmAccess> tmHandleDup = new NativeHandle <TmAccess>(process, handle, TmAccess.QueryInformation))
                        using (TmHandle tmHandle = TmHandle.FromHandle(tmHandleDup))
                        {
                            info.BestName = FileUtils.GetFileName(FileUtils.GetFileName(tmHandle.LogFileName));

                            if (string.IsNullOrEmpty(info.BestName))
                            {
                                info.BestName = tmHandle.BasicInformation.TmIdentity.ToString("B");
                            }
                        }
                }
                break;

                case "TmTx":
                {
                    using (var transactionHandleDup = new NativeHandle <TransactionAccess>(process, handle, TransactionAccess.QueryInformation))
                    {
                        TransactionHandle transactionHandle = TransactionHandle.FromHandle(transactionHandleDup);

                        info.BestName = transactionHandle.Description;

                        if (string.IsNullOrEmpty(info.BestName))
                        {
                            info.BestName = transactionHandle.BasicInformation.TransactionId.ToString("B");
                        }
                    }
                }
                break;

                case "Token":
                {
                    using (var tokenHandleDup = new NativeHandle <TokenAccess>(process, handle, TokenAccess.Query))
                        using (TokenHandle tokenHandle = TokenHandle.FromHandle(tokenHandleDup))
                            using (tokenHandle.User)
                            {
                                info.BestName = tokenHandle.User.GetFullName(true) + ": 0x" + tokenHandle.Statistics.AuthenticationId;
                            }
                }
                break;

                default:
                    if (!string.IsNullOrEmpty(info.OrigName))
                    {
                        info.BestName = info.OrigName;
                    }
                    else
                    {
                        info.BestName = null;
                    }

                    break;
                }
            }
            catch
            {
                if (!string.IsNullOrEmpty(info.OrigName))
                {
                    info.BestName = info.OrigName;
                }
                else
                {
                    info.BestName = null;
                }
            }

            if (objectHandle != null)
            {
                objectHandle.Dispose();
            }

            return(info);
        }
Esempio n. 39
0
 public FieldCardTransaction(FieldCardProcedure procedure)
 {
     Procedure = procedure;
     Handle    = new TransactionHandle(this);
 }