/// <summary> /// Queue a write operation /// </summary> /// <param name="task">write operation</param> public void Enqueue(WriteOperation operationResult) { lock (this._queue) { this._queue.Add(operationResult); } }
public PlcDataMapper(int pduSize, ReadOperation readEventHandler, WriteOperation writeEventHandler, UpdateMonitoring updateHandler, OptimizerType optimizer = OptimizerType.Block) : this(pduSize, readEventHandler, writeEventHandler, updateHandler, null, optimizer) { }
public Stream OpenWrite(string file) { var ret = new WriteOnlyStream(_backend.Open(file, OpenMode.OpenOrCreate)); WriteOperation?.Invoke(file); // Won't fire if the stream is written to afterwards... FIXME? return(ret); }
public async Task <object> WriteOperation(WriteOperation writeOperation) { Response response = new Response(); try { //string spe = await _unitOfWork.WriteOperation.GetStoreProcedure(writeOperation.IdOperacion); writeOperation.XML = AuxiliarMethods.StandardXML(writeOperation.XMLDatos); List <WriteOutput> list = await _unitOfWork.WriteOperation.WriteOperation(writeOperation); if (list.Count > 0) { response.Status = Constant.Status; response.Message = Constant.Ok; response.Data = list; } else { response.Status = Constant.Error400; response.Message = Constant.Consult; } } catch (Exception e) { response.Status = Constant.Error500; response.Message = e.Message; } return(response); }
public Stream Open(string file, OpenMode mode) { var ret = _backend.Open(file, mode); WriteOperation?.Invoke(file); return(ret); }
/// <summary> /// Begins an asynchronous write operation. /// </summary> public IAsyncResult BeginWriteMessage(BufferCollection buffers, int timeout, AsyncCallback callback, object state) { lock (m_socketLock) { if (m_socket == null) { throw new ServiceResultException(StatusCodes.BadConnectionClosed); } } WriteOperation operation = new WriteOperation(timeout, callback, state); operation.ChunksToSend = buffers; operation.BufferManager = m_bufferManager; lock (m_writeQueue) { for (int ii = 0; ii < buffers.Count; ii++) { m_bufferManager.TransferBuffer(buffers[ii].Array, "BeginWriteMessage"); } m_writeQueue.AddLast(operation); if (m_writeQueue.Count == 1 && !m_writeThreadActive) { ThreadPool.QueueUserWorkItem(WriteQueuedMessages, null); } return(operation); } }
/// <summary> /// Completes an asynchronous write operation. /// </summary> public int EndWriteMessage(IAsyncResult result, int timeout) { // ensure the caller passed in a valid object. WriteOperation operation = result as WriteOperation; if (result == null) { throw new ArgumentException("Not a valid IAsyncResult object.", "result"); } // block until the operation completes. try { return(operation.End(timeout)); } catch (Exception e) { // make sure operation is removed from queue if there was a timeout. lock (m_writeQueue) { for (LinkedListNode <WriteOperation> ii = m_writeQueue.First; ii != null; ii = ii.Next) { if (Object.ReferenceEquals(ii.Value, operation)) { m_writeQueue.Remove(ii); break; } } } throw new ServiceResultException(e, StatusCodes.BadUnexpectedError); } }
private void WriteToFile(string contentToWrite, WriteOperation operationType, string fileName) { string dirPath = string.Empty; string extension = string.Empty; switch (operationType) { case WriteOperation.SchemaDefinition: dirPath = schemaDef_FilePath; extension = ".html"; break; case WriteOperation.DataModelDefinition: dirPath = dataModel_FilePath; extension = ".cs"; break; } string filePath = string.Concat(dirPath, fileName, extension); if (!Directory.Exists(dirPath)) { Directory.CreateDirectory(dirPath); } using (System.IO.StreamWriter file = new System.IO.StreamWriter(filePath)) { file.WriteLine(contentToWrite); file.Close(); } }
/// <summary> /// Responsible for updating/inserting an object to the data source. The Key and the /// object are passed as parameter. /// </summary> /// <param name="key"></param> /// <param name="val"></param> /// <returns>-1 if writer is null, 0 if user operation returned false, 1 if successful</returns> private OperationResult WriteThru(WriteOperation writeOp, OperationContext operationContext) { OperationResult result = null; if (_dsWriter == null) { return(result); } Stopwatch writeThruWatch = new Stopwatch(); writeThruWatch.Start(); if (operationContext.Contains(OperationContextFieldName.MethodOverload)) { writeOp.MethodOverlaod = (int)operationContext.GetValueByField(OperationContextFieldName.MethodOverload); } result = _dsWriter.WriteToDataSource(writeOp); writeThruWatch.Stop(); double elapsedByWriteThru = writeThruWatch.Elapsed.TotalSeconds; if (elapsedByWriteThru > ServiceConfiguration.CommandExecutionThreshold && ServiceConfiguration.EnableCommandThresholdLogging) { if (_context.NCacheLog != null) { _context.NCacheLog.Warn("WriteThruProviderMgr.WriteThru", "WriteThru took " + elapsedByWriteThru + " seconds to complete. Which is longer than expected."); } } return(result); }
/// <summary> /// Cancels all outstanding I/O operations. /// </summary> private void CancelOperations() { // cancel any outstanding write operations. WriteOperation operation = null; do { operation = null; lock (m_writeQueue) { if (m_writeQueue.Count > 0) { operation = m_writeQueue.First.Value; m_writeQueue.RemoveFirst(); } } if (operation != null) { operation.Fault(StatusCodes.BadConnectionClosed); } } while (operation != null); // cancel any outstanding read operations. byte[] buffer = null; do { buffer = null; lock (m_readQueue) { if (m_readQueue.Count > 0) { buffer = m_readQueue.First.Value.Array; m_readQueue.RemoveFirst(); // check for graceful shutdown. if (buffer != null) { BufferManager.UnlockBuffer(buffer); #if TRACK_MEMORY int cookie = BitConverter.ToInt32(buffer, 0); if (cookie < 0) { Utils.Trace("BufferCookieError (CancelOperations): Cookie={0:X8}", cookie); } #endif } } } if (buffer != null) { m_bufferManager.ReturnBuffer(buffer, "CancelOperations"); } } while (buffer != null); }
/// <inheritdoc cref="CreateDirectory(string)"/> public async Task CreateDirectoryAsync(string path) { await Task.Run(() => { _backend.CreateDirectory(path); WriteOperation?.Invoke(path); }); }
/// <inheritdoc cref="WriteAllBytes(string, byte[])"/> public async Task WriteAllBytesAsync(string path, byte[] bytes) { await Task.Run(() => { _backend.WriteAllBytes(path, bytes); WriteOperation?.Invoke(path); }); }
internal void Enqueue(WriteOperation operation) { lock (this) { this._updateQueue.Enqueue(operation); Monitor.PulseAll(this); } }
/// <summary> /// Thread function, keeps running. /// </summary> protected void Run() { while (this._worker != null && !this._isDisposing) { WriteOperation operation = null; try { lock (this) { if (this._updateQueue.Count < 1) { if (_shutdownStatusLatch.IsAnyBitsSet(ShutDownStatus.SHUTDOWN_INPROGRESS)) { _shutdownStatusLatch.SetStatusBit(ShutDownStatus.SHUTDOWN_COMPLETED, ShutDownStatus.SHUTDOWN_INPROGRESS); return; } Monitor.Wait(this); } if (this._updateQueue.Count > 0) { operation = this._updateQueue.Dequeue(); } else if (_updateQueue.Count == 0 && _shutdownStatusLatch.IsAnyBitsSet(ShutDownStatus.SHUTDOWN_INPROGRESS)) { break; } } if (operation == null) { continue; } lock (_processMutex) { if (!_isDisposing) { if (_dsMgr != null) { _dsMgr.DSAsyncUpdateInCache(operation); } } } } catch (ThreadAbortException e) { break; } catch (ThreadInterruptedException e) { break; } catch (Exception e) { } } }
private void ResolveTypeAndInstance(WriteOperation value, out Type type, out object instance) { type = TypeResolver.ResolveType(value); instance = type.Construct(); value.Properties.Each(new { Instance = instance }, (ctx, dp) => { ReflectionExtensions.Property(ctx.Instance, dp.Name, dp.Value); }); }
/// <summary> /// Write binary data to a file /// </summary> /// <param name="path">The path to a file to write to</param> /// <param name="data">The binary data to write</param> public void WriteAllBytes(string path, byte[] data) { if (data == null) { data = new byte[0]; } _backend.WriteAllBytes(path, data); WriteOperation?.Invoke(path); }
/// <summary> /// Delete a file or directory from the VFS /// </summary> /// <param name="path">A path to the file or directory to delete</param> public void Delete(string path) { if (IsOpenInProgram(path)) { throw new IOException("The process cannot access the file because it is currently opened in another process."); } _backend.Delete(path); WriteOperation?.Invoke(path); }
/// <inheritdoc cref="Delete(string)"/> public async Task DeleteAsync(string path) { if (IsOpenInProgram(path)) { throw new IOException("The process cannot access the file because it is currently opened in another process."); } await Task.Run(() => { _backend.Delete(path); WriteOperation?.Invoke(path); }); }
public async Task <List <WriteOutput> > WriteOperation(WriteOperation writeOperation) { var parameters = new DynamicParameters(); parameters.Add("@ACCION", writeOperation.Accion); parameters.Add("@IDDATO", writeOperation.IdDato); parameters.Add("@XMLDatos", writeOperation.XML); using (var connection = new SqlConnection(_connectionString)) { return((await connection.QueryAsync <WriteOutput>("[dbo].[SP_UDP_CLIENTE]", parameters, commandType: System.Data.CommandType.StoredProcedure)).ToList()); } }
/// <summary> /// Dequeue a write operation /// </summary> /// <returns>write operation</returns> public WriteOperation Dequeue() { lock (this._queue) { if (this._queue.Count == 0) { return(null); } WriteOperation value = this._queue[0] as WriteOperation; this._queue.RemoveAt(0); return(value); } }
public void SaveMetadata() { try { string content = JsonUtility.ToJson(_metadata, true); WriteOperation <string> operation = IOFactory.GetWriteTextOperation(_pathToMetadata, content); operation.DoOperationSync(); } catch (Exception e) { Debug.Log("Error at SaveMetadata :" + e.Message); throw; } }
public OperationResult WriteToDataSource(WriteOperation operation) { bool result = false; OperationResult operationResult = new OperationResult(operation, OperationResult.Status.Failure); Customer value = (Customer)operation.ProviderCacheItem.Value; if (value.GetType().Equals(typeof(Customer))) { result = _source.SaveCustomer((Customer)value); } if (result) { operationResult.DSOperationStatus = OperationResult.Status.Success; } return(operationResult); }
private void HandleAddRequest(string indexName, IEnumerable <Dictionary <string, string> > docs) { try { var dir = Path.Combine(ToolBelt.GetDataDirectory(), indexName); using (var write = new WriteOperation(dir, new Analyzer(), docs.ToDocuments())) { write.Execute(); } } catch (Exception ex) { Log.Error(ex); throw; } }
/// <summary> /// Writes the messages in the queue. /// </summary> private void WriteQueuedMessages(object state) { // get first operation on the queue. WriteOperation operation = null; lock (m_writeQueue) { if (m_writeQueue.Count == 0) { return; } operation = m_writeQueue.First.Value; m_writeQueue.RemoveFirst(); m_writeThreadActive = true; } // keep processing messages until the queue is empty. while (operation != null) { // write message. try { WriteMessage(operation); } catch (Exception e) { Utils.Trace(e, "Unexpected error during write."); } // check if more operations are queued. lock (m_writeQueue) { if (m_writeQueue.Count == 0) { m_writeThreadActive = false; break; } operation = m_writeQueue.First.Value; m_writeQueue.RemoveFirst(); } } }
public PlcDataMapper(int pduSize, ReadOperation readEventHandler, WriteOperation writeEventHandler, UpdateMonitoring updateHandler, ReadBlockInfo blockInfoHandler, OptimizerType optimizer = OptimizerType.Block) { PduSize = pduSize; _readEventHandler = readEventHandler; _writeEventHandler = writeEventHandler; _updateHandler = updateHandler; _blockInfoHandler = blockInfoHandler; Optimizer = OptimizerFactory.CreateOptimizer(optimizer); ReadDataBlockSize = pduSize - _readDataHeaderLength; if (ReadDataBlockSize <= 0) { ExceptionThrowHelper.ThrowInvalidPduSizeException(_readDataHeaderLength); } PlcMetaDataTreePath.CreateAbsolutePath(PlcObjectResolver.RootNodeName); }
/// <summary> /// Write a single message. /// </summary> private void WriteMessage(WriteOperation operation) { // get the buffers to write. BufferCollection buffers = operation.ChunksToSend; // get the socket. Socket socket = null; lock (m_socketLock) { socket = m_socket; } // check if the socket has been closed. if (socket == null) { operation.Fault(ServiceResult.Create(StatusCodes.BadConnectionClosed, "Socket is no longer available.")); return; } // begin the write operation (blocks until data is copied into the transport buffer). try { int bytesSent = socket.Send(buffers, SocketFlags.None); // check that all the data was sent. if (bytesSent < buffers.TotalSize) { operation.Fault(ServiceResult.Create(StatusCodes.BadConnectionClosed, "Write operation could not complete.")); return; } // everything ok - yeah!. operation.Complete(bytesSent); } catch (Exception e) { operation.Fault(ServiceResult.Create(e, StatusCodes.BadConnectionClosed, "Write to socket failed.")); } }
public WriteOperation Write(ICollection <DriveBlock> blocks, byte[] buffer, int offset) { var operation = new WriteOperation(drive => { var retv = 0L; var currentOffset = offset; foreach (var block in blocks) { drive.Position = block.Position; drive.Write(buffer, currentOffset, block.Length); currentOffset += block.Length; retv += block.Length; } return(retv); }, blocks.Last().Position); CurrentPosition = blocks.Last().Position + blocks.Last().Length; Synchronizer.EnqueueOperation(operation); return(operation); }
/// <summary> /// write an operation to data source /// </summary> /// <param name="operation"></param> /// <returns></returns> public OperationResult WriteToDataSource(WriteOperation operation) { // initialize variable for confirmation of write operation bool result = false; // initialize operation result with failure OperationResult operationResult = new OperationResult(operation, OperationResult.Status.Failure); // get value of object Customer value = operation.ProviderItem.GetValue <Customer>(); // check if value is the type you need if (value.GetType().Equals(typeof(Customer))) { // send data to cache for writing result = sqlDatasource.SaveCustomer((Customer)value); // if write operatio is success, change status of operation result if (result) { operationResult.OperationStatus = OperationResult.Status.Success; } } // return result to cache return(operationResult); }
public async Task <ActionResult <Response> > WriteOperation([FromBody] WriteOperation writeOperation) { object rpta = new object(); try { writeOperation = (WriteOperation)BusinessLogic.Utilities.AuxiliarMethods.ValidateParameters(writeOperation, writeOperation.GetType()); rpta = await _writeoperationlogic.WriteOperation(writeOperation); if (rpta == null) { return(NotFound()); } } catch (Exception e) { Response response = new Response(); response.Status = Constant.Error500; response.Message = e.Message; return(Ok(response)); } return(Ok(rpta)); }
public async Task <List <WriteOutput> > WriteOperation(WriteOperation writeOperation) { List <WriteOutput> obj = new List <WriteOutput>(); var parameters = new DynamicParameters(); parameters.Add("@ACCION", writeOperation.Accion); parameters.Add("@IDDATO", writeOperation.IdDato); parameters.Add("@XMLDatos", writeOperation.XML); using (var connection = new SqlConnection(_connectionString)) { if ((writeOperation.IdOperacion).Equals(1)) { return((await connection.QueryAsync <WriteOutput>("[dbo].[SP_UDP_CLIENTE]", parameters, commandType: CommandType.StoredProcedure)).ToList()); } else if ((writeOperation.IdOperacion).Equals(2)) { return((await connection.QueryAsync <WriteOutput>("[dbo].[SP_UDP_OPERACION]", parameters, commandType: CommandType.StoredProcedure)).ToList()); } return(obj); } }
/// <summary> /// Sends a request to the server. /// </summary> private void SendRequest(WriteOperation operation, int timeout, IServiceRequest request) { bool success = false; BufferCollection buffers = null; try { // check for valid token. TcpChannelToken token = CurrentToken; if (token == null) { throw new ServiceResultException(StatusCodes.BadSecureChannelClosed); } // must return an error to the client if limits are exceeded. bool limitsExceeded = false; buffers = WriteSymmetricMessage( TcpMessageType.Message, operation.RequestId, token, request, true, out limitsExceeded); BeginWriteMessage(buffers, timeout, operation); buffers = null; success = true; if (limitsExceeded) { throw new ServiceResultException(StatusCodes.BadRequestTooLarge); } } catch (Exception e) { operation.Fault(e, StatusCodes.BadRequestInterrupted, "Could not send request to server."); } finally { if (buffers != null) { buffers.Release(BufferManager, "SendRequest"); } if (!success) { OperationCompleted(operation); } } }
/// <summary> /// Sends a Hello message. /// </summary> private void SendHelloMessage(WriteOperation operation) { // Utils.Trace("Channel {0}: SendHelloMessage()", ChannelId); byte[] buffer = BufferManager.TakeBuffer(SendBufferSize, "SendHelloMessage"); try { MemoryStream ostrm = new MemoryStream(buffer, 0, SendBufferSize); BinaryEncoder encoder = new BinaryEncoder(ostrm, Quotas.MessageContext); encoder.WriteUInt32(null, TcpMessageType.Hello); encoder.WriteUInt32(null, 0); encoder.WriteUInt32(null, 0); // ProtocolVersion encoder.WriteUInt32(null, (uint)ReceiveBufferSize); encoder.WriteUInt32(null, (uint)SendBufferSize); encoder.WriteUInt32(null, (uint)MaxResponseMessageSize); encoder.WriteUInt32(null, (uint)MaxResponseChunkCount); byte[] endpointUrl = new UTF8Encoding().GetBytes(m_url.ToString()); if (endpointUrl.Length > TcpMessageLimits.MaxEndpointUrlLength) { byte[] truncatedUrl = new byte[TcpMessageLimits.MaxEndpointUrlLength]; Array.Copy(endpointUrl, truncatedUrl, TcpMessageLimits.MaxEndpointUrlLength); endpointUrl = truncatedUrl; } encoder.WriteByteString(null, endpointUrl); int size = encoder.Close(); UpdateMessageSize(buffer, 0, size); BeginWriteMessage(new ArraySegment<byte>(buffer, 0, size), Int32.MaxValue, operation); buffer = null; } finally { if (buffer != null) { BufferManager.ReturnBuffer(buffer, "SendHelloMessage"); } } }
/// <summary> /// Sends an CloseSecureChannel request message. /// </summary> private void SendCloseSecureChannelRequest(WriteOperation operation) { // Utils.Trace("Channel {0}: SendCloseSecureChannelRequest()", ChannelId); // supress reconnects if an error occurs. m_waitBetweenReconnects = Timeout.Infinite; // check for valid token. TcpChannelToken currentToken = CurrentToken; if (currentToken == null) { throw new ServiceResultException(StatusCodes.BadSecureChannelClosed); } CloseSecureChannelRequest request = new CloseSecureChannelRequest(); request.RequestHeader.Timestamp = DateTime.UtcNow; // limits should never be exceeded sending a close message. bool limitsExceeded = false; // construct the message. BufferCollection buffers = WriteSymmetricMessage( TcpMessageType.Close, operation.RequestId, currentToken, request, true, out limitsExceeded); // send the message. try { BeginWriteMessage(buffers, 1000, operation); buffers = null; } finally { if (buffers != null) { buffers.Release(BufferManager, "SendCloseSecureChannelRequest"); } } }
public QueuedOperation(WriteOperation operation, int timeout, IServiceRequest request) { Operation = operation; Timeout = timeout; Request = request; }
/// <summary> /// Cleans up after an asychronous operation completes. /// </summary> private void OperationCompleted(WriteOperation operation) { if (operation == null) { return; } lock (DataLock) { if (m_handshakeOperation == operation) { m_handshakeOperation = null; } m_requests.Remove(operation.RequestId); } }
/// <summary> /// Creates a object to manage the state of an asynchronous operation. /// </summary> private WriteOperation BeginOperation(int timeout, AsyncCallback callback, object state) { WriteOperation operation = new WriteOperation(timeout, callback, state); operation.RequestId = Utils.IncrementIdentifier(ref m_lastRequestId); m_requests.Add(operation.RequestId, operation); return operation; }
private static Event WriteBytesInternal(CLMem openCLMem, CommandQueue commandQueue, Array array, Int64 bytesToCopy, Int64 arrayOffset, Int64 arraySize, Int64 bufferOffset, Int64 bufferSize, Events eventWaitList, WriteOperation writeDelegate) { if (bufferSize < bufferOffset + bytesToCopy) throw new ArgumentException(Resources.Buffer_out_of_bounds); if (arraySize < arrayOffset + bytesToCopy) throw new ArgumentException(Resources.Array_out_of_bounds); GCHandle valueHandle = GCHandle.Alloc(array, GCHandleType.Pinned); try { CLEvent e = new CLEvent(); unsafe { IntPtr valuePtr = new IntPtr((Byte*)(valueHandle.AddrOfPinnedObject().ToPointer()) + arrayOffset); OpenCLError.Validate ( writeDelegate ( commandQueue.CLCommandQueue, openCLMem, CLBool.True, new SizeT(bufferOffset), new SizeT(bytesToCopy), valuePtr, eventWaitList == null ? 0 : eventWaitList.Count, eventWaitList == null ? null : eventWaitList.OpenCLEventArray, ref e ) ); } return new Event(e); } finally { valueHandle.Free(); } }
public ParsedChangeFile(string fn, ulong partitionOffset, ulong deviceSize) { _File = new FileStream(fn, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); _FileName = fn; byte[] tmp = new byte[Marshal.SizeOf(typeof(ChangeFileFooter))]; _File.Seek(-tmp.Length, SeekOrigin.End); if (_File.Read(tmp, 0, tmp.Length) != tmp.Length) throw new Exception("Cannot read change file footer"); var footer = (ChangeFileFooter)ConvertByteArrayToStruct(tmp, typeof(ChangeFileFooter), 0); if (Encoding.ASCII.GetString(footer.Signature, 0, footer.Signature.Length) != "XXCHANGEFILEv10\0") throw new Exception("Change file signature mismatch"); ulong smallAreaOffset = (ulong)(_File.Length - tmp.Length - footer.SmallWriteAreaSize); ulong blockAreaOffset = 0; tmp = new byte[footer.LogSize]; _File.Seek(-Marshal.SizeOf(typeof(ChangeFileFooter)) - footer.LogSize - footer.SmallWriteAreaSize, SeekOrigin.End); if (_File.Position != footer.LogOffset) throw new Exception("Mismatching log position"); if (_File.Read(tmp, 0, tmp.Length) != tmp.Length) throw new Exception("Cannot read change log"); if (tmp.Length % 16 != 0) throw new Exception("Invalid log size"); ulong fileSize = (ulong)_File.Length; for (int i = 0; i < tmp.Length; ) { ulong offset = BitConverter.ToUInt64(tmp, i); i += 8; ulong sizeWithFlags = BitConverter.ToUInt64(tmp, i); i += 8; WriteOperation op; if ((sizeWithFlags & (1UL << 63)) != 0) { op = new WriteOperation { OffsetInFile = smallAreaOffset, OffsetInDevice = offset + partitionOffset, SizeInBytes = (int)(sizeWithFlags & 0x3fffffffffffffffL) }; smallAreaOffset += (uint)op.SizeInBytes; } else { if ((sizeWithFlags & (1UL << 62)) != 0) op = new WriteOperation { OffsetInFile = 0, OffsetInDevice = offset + partitionOffset, SizeInBytes = (int)(sizeWithFlags & 0x3fffffffffffffffL), Zero = true }; else { op = new WriteOperation { OffsetInFile = blockAreaOffset, OffsetInDevice = offset + partitionOffset, SizeInBytes = (int)(sizeWithFlags & 0x3fffffffffffffffL) }; blockAreaOffset += (uint)op.SizeInBytes; } } if (op.OffsetInDevice > deviceSize || (op.OffsetInDevice + (uint)op.SizeInBytes) > deviceSize) throw new Exception("Bad write operation at " + op.OffsetInFile); if (!op.Zero) { if (op.OffsetInFile > fileSize || (op.OffsetInFile + (uint)op.SizeInBytes) > fileSize) throw new Exception("Bad write operation at " + op.OffsetInFile); } _WriteOps.Add(op); } }