public void ReadRow_AutoMappedGuid_Success()
        {
            using var importer = Helpers.GetImporter("Guids.xlsx");

            ExcelSheet sheet = importer.ReadSheet();

            sheet.ReadHeading();

            // Valid cell value.
            GuidClass row1 = sheet.ReadRow <GuidClass>();

            Assert.Equal(new Guid("a8a110d5fc4943c5bf46802db8f843f1"), row1.Value);

            GuidClass row2 = sheet.ReadRow <GuidClass>();

            Assert.Equal(new Guid("a8a110d5fc4943c5bf46802db8f843f2"), row2.Value);

            GuidClass row3 = sheet.ReadRow <GuidClass>();

            Assert.Equal(new Guid("a8a110d5fc4943c5bf46802db8f843f3"), row3.Value);

            GuidClass row4 = sheet.ReadRow <GuidClass>();

            Assert.Equal(new Guid("a8a110d5fc4943c5bf46802db8f843f4"), row4.Value);

            GuidClass row5 = sheet.ReadRow <GuidClass>();

            Assert.Equal(new Guid("a8a110d5fc4943c5bf46802db8f843f5"), row5.Value);

            // Empty cell value.
            Assert.Throws <ExcelMappingException>(() => sheet.ReadRow <GuidClass>());

            // Invalid cell value.
            Assert.Throws <ExcelMappingException>(() => sheet.ReadRow <GuidClass>());
        }
Exemple #2
0
        internal void Send(string text, ReceiveStringDelegate receiveStringDelegate, GuidClass messageGuid,
                           string parentID, string description, Guid plcGuid, bool isIdMessage = false,
                           bool suppressEthernetHeader = false)
        {
            MessageRecord message = new MessageRecord()
            {
                MessageGuid            = messageGuid,
                PlcGuid                = plcGuid,
                ParentID               = parentID,
                UnitId                 = GetUnitIdFromStringMessage(text),
                IsSent                 = false,
                MessageRequest         = text,
                RemainingRetries       = m_retry,
                Description            = description,
                IsIdMessage            = isIdMessage,
                SuppressEthernetHeader = suppressEthernetHeader,
                ReceiveBytesDelegate   = null,
                ReceiveStringDelegate  = new ReceiveStringDelegate(receiveStringDelegate)
            };

            lock (messageQueue)
            {
                abortRetries = false;
                messageQueue.Enqueue(message);
                messageQueue_Changed();
            }
        }
        private void ReceiveString(string responseMessage, CommunicationException communicationException,
                                   GuidClass messageGuid)
        {
            if (this.BreakFlag)
            {
                throw new ComDriveExceptions("Request aborted by user",
                                             ComDriveExceptions.ComDriveException.AbortedByUser);
            }

            Console.WriteLine("Message received in ASCII ReceiveString method : " + responseMessage);
            PlcResponseMessage plcResponseMessage = new PlcResponseMessage
            {
                comException = communicationException,
                response     = responseMessage
            };

            lock (_lockObj)
            {
                m_responseMessageQueue.Add(messageGuid, plcResponseMessage);
            }

            lock (messageGuid)
            {
                Monitor.PulseAll(messageGuid);
            }
        }
Exemple #4
0
        internal void Send(byte[] bytes, ReceiveBytesDelegate receiveBytesDelegate, GuidClass messageGuid,
                           string parentID, string description, Guid plcGuid, byte messageEnumerator)
        {
            MessageRecord message = new MessageRecord()
            {
                MessageGuid           = messageGuid,
                PlcGuid               = plcGuid,
                ParentID              = parentID,
                UnitId                = GetUnitIdFromBinaryMessage(bytes),
                IsSent                = false,
                MessageRequest        = bytes,
                RemainingRetries      = m_retry,
                Description           = description,
                ReceiveBytesDelegate  = new ReceiveBytesDelegate(receiveBytesDelegate),
                ReceiveStringDelegate = null,
                MessageEnumerator     = messageEnumerator
            };

            lock (messageQueue)
            {
                abortRetries = false;
                messageQueue.Enqueue(message);
                messageQueue_Changed();
            }
        }
Exemple #5
0
        private void WriteOperations(ref List <ReadWriteRequest> values, string parentID, bool suppressEthernetHeader)
        {
            PComA pcomA = new PComA();

            if (this.BreakFlag)
            {
                throw new ComDriveExceptions("Request aborted by user",
                                             ComDriveExceptions.ComDriveException.AbortedByUser);
            }

            foreach (WriteOperands wo in values)
            {
                pcomA.BuildAsciiCommand(UnitId,
                                        Utils.ASCIIOperandTypes[Enum.GetName(typeof(OperandTypes), wo.OperandType)].CommandCodeForWrite,
                                        (wo as WriteOperands).StartAddress, wo.NumberOfOperands, (wo as WriteOperands).Values,
                                        (wo as WriteOperands).TimerValueFormat);
                string readMessage = pcomA.MessageToPLC as string;

                if (this.BreakFlag)
                {
                    throw new ComDriveExceptions("Request aborted by user",
                                                 ComDriveExceptions.ComDriveException.AbortedByUser);
                }

                GuidClass guid = new GuidClass();

                lock (guid)
                {
                    Channel.Send(readMessage, ReceiveString, guid, parentID, "ASCII Protocol - Write Operands", PlcGuid,
                                 suppressEthernetHeader);
                    Monitor.Wait(guid);
                }

                if (this.BreakFlag)
                {
                    throw new ComDriveExceptions("Request aborted by user",
                                                 ComDriveExceptions.ComDriveException.AbortedByUser);
                }

                PlcResponseMessage plcResponseMessage;

                lock (_lockObj)
                {
                    plcResponseMessage = m_responseMessageQueue[guid];
                    m_responseMessageQueue.Remove(guid);
                }

                if (plcResponseMessage.comException == CommunicationException.Timeout)
                {
                    throw new ComDriveExceptions("Cannot communicate with the PLC with the specified UnitID!",
                                                 ComDriveExceptions.ComDriveException.CommunicationTimeout);
                }

                pcomA.DisAssembleAsciiResult(plcResponseMessage.responseStringMessage, UnitId,
                                             Utils.ASCIIOperandTypes[Enum.GetName(typeof(OperandTypes), wo.OperandType)].CommandCodeForWrite,
                                             wo.StartAddress, wo.NumberOfOperands, null, wo.TimerValueFormat);
            }
        }
 internal static extern int DsGetDcName
 (
     [MarshalAs(UnmanagedType.LPTStr)] string ComputerName,
     [MarshalAs(UnmanagedType.LPTStr)] string DomainName,
     [In] GuidClass DomainGuid,
     [MarshalAs(UnmanagedType.LPTStr)] string SiteName,
     uint Flags,
     out IntPtr pDOMAIN_CONTROLLER_INFO
 );
        public void GetHashCode_should_return_value_for_guid_class()
        {
            var instance = new GuidClass();

            instance.Key = Guid.NewGuid();

            var result = instance.GetHashCode();

            Assert.NotEqual(0, result);
        }
        private void ReadWriteReadOperand(ReadWriteRequest operand, string parentID, bool suppressEthernetHeader)
        {
            ReadOperands readOperands = operand as ReadOperands;
            GuidClass    guid         = new GuidClass();

            pcomA.BuildAsciiCommand(UnitId,
                                    Utils.ASCIIOperandTypes[Enum.GetName(typeof(OperandTypes), readOperands.OperandType)]
                                    .CommandCodeForRead,
                                    (operand as ReadOperands).StartAddress, readOperands.NumberOfOperands, null,
                                    readOperands.TimerValueFormat);

            string readMessage = pcomA.MessageToPLC as string;

            if (this.BreakFlag)
            {
                throw new ComDriveExceptions("Request aborted by user",
                                             ComDriveExceptions.ComDriveException.AbortedByUser);
            }

            lock (guid)
            {
                Channel.Send(readMessage, ReceiveString, guid, parentID, "ASCII Protocol - Read Operands", PlcGuid,
                             suppressEthernetHeader);
                Monitor.Wait(guid);
            }

            if (this.BreakFlag)
            {
                throw new ComDriveExceptions("Request aborted by user",
                                             ComDriveExceptions.ComDriveException.AbortedByUser);
            }

            PlcResponseMessage plcResponseMessage;

            {
                plcResponseMessage = m_responseMessageQueue[guid];
                m_responseMessageQueue.Remove(guid);
            }

            if (plcResponseMessage.comException == CommunicationException.Timeout)
            {
                throw new ComDriveExceptions("Cannot communicate with the PLC with the specified UnitID!",
                                             ComDriveExceptions.ComDriveException.CommunicationTimeout);
            }

            pcomA.DisAssembleAsciiResult(plcResponseMessage.response, UnitId,
                                         Utils.ASCIIOperandTypes[Enum.GetName(typeof(OperandTypes), readOperands.OperandType)]
                                         .CommandCodeForRead,
                                         (operand as ReadOperands).StartAddress, readOperands.NumberOfOperands, null,
                                         readOperands.TimerValueFormat);
            if (pcomA.MessageFromPLC != null)
            {
                operand.ResponseValues = (pcomA.MessageFromPLC as AbstractASCIIMessage).ArrayValues; //Values;
            }
        }
Exemple #9
0
        public void Equality_operator_should_return_true_for_equal_guid_instances()
        {
            var first  = new GuidClass();
            var second = new GuidClass();

            var newGuid = Guid.NewGuid();

            first.Key  = newGuid;
            second.Key = newGuid;

            Assert.True(first == second);
            Assert.False(first != second);
        }
Exemple #10
0
        private void ReceiveBytes(byte[] responseBytes, CommunicationException communicationException,
                                  GuidClass messageGuid)
        {
            PlcResponseMessage plcResponseMessage = new PlcResponseMessage
            {
                comException         = communicationException,
                responseBytesMessage = responseBytes
            };

            lock (_lockObj)
            {
                m_responseMessageQueue.Add(messageGuid, plcResponseMessage);
            }

            lock (messageGuid)
            {
                Monitor.PulseAll(messageGuid);
            }
        }
Exemple #11
0
        private void ReceiveString(string responseMessage, CommunicationException communicationException,
                                   GuidClass messageGuid)
        {
            PlcResponseMessage plcResponseMessage = new PlcResponseMessage
            {
                comException          = communicationException,
                responseStringMessage = responseMessage
            };

            lock (_lockObj)
            {
                m_responseMessageQueue.Add(messageGuid, plcResponseMessage);
            }

            lock (messageGuid)
            {
                Monitor.PulseAll(messageGuid);
            }
        }
        private IMessage ReceiveMessage(PComB pComB, List <List <byte> > readDataTablesDataRequestBytes, string parentID)
        {
            if (this.BreakFlag)
            {
                throw new ComDriveExceptions("Request aborted by user",
                                             ComDriveExceptions.ComDriveException.AbortedByUser);
            }

            GuidClass guid = new GuidClass();

            lock (guid)
            {
                Channel.Send(pComB.MessageToPLC as byte[], ReceiveBytes, guid, parentID,
                             "Binary Protocol - Read/Write Data Tables", PlcGuid);
                Monitor.Wait(guid);
            }

            if (this.BreakFlag)
            {
                throw new ComDriveExceptions("Request aborted by user",
                                             ComDriveExceptions.ComDriveException.AbortedByUser);
            }

            PlcResponseMessage plcResponseMessage;

            lock (_lockObj)
            {
                plcResponseMessage = m_responseMessageQueue[guid];
                m_responseMessageQueue.Remove(guid);
            }

            if (plcResponseMessage.comException == CommunicationException.Timeout)
            {
                throw new ComDriveExceptions("Cannot communicate with the PLC with the specified UnitID!",
                                             ComDriveExceptions.ComDriveException.CommunicationTimeout);
            }

            pComB.DisAssembleBinaryResult(plcResponseMessage.responseBytesMessage, null);

            return(pComB.MessageFromPLC);
        }
        public void ReadRow_CustomMappedGuid_Success()
        {
            using var importer = Helpers.GetImporter("Guids.xlsx");
            importer.Configuration.RegisterClassMap <CustomGuidClassMap>();

            ExcelSheet sheet = importer.ReadSheet();

            sheet.ReadHeading();

            // Valid cell value.
            GuidClass row1 = sheet.ReadRow <GuidClass>();

            Assert.Equal(new Guid("a8a110d5fc4943c5bf46802db8f843f1"), row1.Value);

            GuidClass row2 = sheet.ReadRow <GuidClass>();

            Assert.Equal(new Guid("a8a110d5fc4943c5bf46802db8f843f2"), row2.Value);

            GuidClass row3 = sheet.ReadRow <GuidClass>();

            Assert.Equal(new Guid("a8a110d5fc4943c5bf46802db8f843f3"), row3.Value);

            GuidClass row4 = sheet.ReadRow <GuidClass>();

            Assert.Equal(new Guid("a8a110d5fc4943c5bf46802db8f843f4"), row4.Value);

            GuidClass row5 = sheet.ReadRow <GuidClass>();

            Assert.Equal(new Guid("a8a110d5fc4943c5bf46802db8f843f5"), row5.Value);

            // Empty cell value.
            GuidClass row6 = sheet.ReadRow <GuidClass>();

            Assert.Equal(new Guid("a8a110d5fc4943c5bf46802db8f843f6"), row6.Value);

            // Invalid cell value.
            GuidClass row7 = sheet.ReadRow <GuidClass>();

            Assert.Equal(new Guid("a8a110d5fc4943c5bf46802db8f843f7"), row7.Value);
        }
Exemple #14
0
        private void WaitForFlashIdle(byte unitID, string parentID)
        {
            int       idleCount           = 0;
            const int READ_STATUS_COMMAND = 7;
            const int TOTAL_TIME_OUT      = 300;

            byte[]      incomingBuffer;
            FlashStatus flashStatus;
            DateTime    dateTime = DateTime.Now;
            PComB       pComB    = new PComB();

            pComB.BuildBinaryCommand(unitID, 0, READ_STATUS_COMMAND,
                                     0, 0, 106, 0, new byte[0]);

            if (this.BreakFlag)
            {
                throw new ComDriveExceptions("Request aborted by user",
                                             ComDriveExceptions.ComDriveException.AbortedByUser);
            }

            while ((DateTime.Now - dateTime).Seconds <= TOTAL_TIME_OUT)
            {
                GuidClass guid = new GuidClass();

                lock (guid)
                {
                    Channel.Send(pComB.MessageToPLC as byte[], ReceiveBytes, guid, parentID,
                                 "Binary Protocol - Binary Request (" + READ_STATUS_COMMAND + ")", PlcGuid);
                    Monitor.Wait(guid);
                }

                if (this.BreakFlag)
                {
                    throw new ComDriveExceptions("Request aborted by user",
                                                 ComDriveExceptions.ComDriveException.AbortedByUser);
                }

                PlcResponseMessage plcResponseMessage;

                lock (_lockObj)
                {
                    plcResponseMessage = m_responseMessageQueue[guid];
                    m_responseMessageQueue.Remove(guid);
                }

                if (plcResponseMessage.comException == CommunicationException.Timeout)
                {
                    throw new ComDriveExceptions("Cannot communicate with the PLC with the specified UnitID!",
                                                 ComDriveExceptions.ComDriveException.CommunicationTimeout);
                }

                incomingBuffer = new byte[plcResponseMessage.responseBytesMessage.Length -
                                          Utils.Lengths.LENGTH_HEADER_AND_FOOTER];
                if (incomingBuffer.Length > 0)
                {
                    Array.Copy(plcResponseMessage.responseBytesMessage, Utils.Lengths.LENGTH_HEADER, incomingBuffer, 0,
                               incomingBuffer.Length);
                }

                flashStatus = GetFlashStatus(incomingBuffer);

                if ((flashStatus.MemoryStatus != (MemoryStatus)'I') || (flashStatus.eFlashStatus != eFlashStatus.Idle))
                {
                    Thread.Sleep(20);
                }
                else
                {
                    idleCount++;
                    if (idleCount > 1)
                    {
                        return;
                    }
                }
            }
        }
        private void ReadWriteOperandsCommand(ref ReadWriteRequest[] values, string parentID, byte messageEnumerator)
        {
            PComB pComB = new PComB();
            List <List <byte> > dataRequestsBytes = new List <List <byte> >();

            #region Group Requests by type.

            List <ReadOperands>  operandReads  = new List <ReadOperands>();
            List <WriteOperands> operandWrites = new List <WriteOperands>();

            for (int i = 0; i < values.Length; i++)
            {
                if (values[i] is ReadOperands)
                {
                    operandReads.Add(values[i] as ReadOperands);
                }
                if (values[i] is WriteOperands)
                {
                    operandWrites.Add(values[i] as WriteOperands);
                }
            }

            #endregion

            #region Detail Area Header

            int totalNumberOfReads  = 0;
            int totalNumberOfWrites = 0;

            foreach (ReadWriteRequest operand in values)
            {
                if (operand is ReadOperands)
                {
                    totalNumberOfReads += (operand as ReadOperands).NumberOfOperands;
                    dataRequestsBytes.Add(GetDataRequestsBytesForReadOperands(operand as ReadOperands));
                }

                if (operand is WriteOperands)
                {
                    totalNumberOfWrites += (operand as WriteOperands).NumberOfOperands;
                    dataRequestsBytes.Add(GetDataRequestsBytesForWriteOperands(operand as WriteOperands));
                }
            }

            byte[] command_detailes = new byte[4];

            byte[] NoOfReads  = BitConverter.GetBytes(totalNumberOfReads);
            byte[] NoOfWrites = BitConverter.GetBytes(totalNumberOfWrites);

            command_detailes[0] = NoOfReads[0];
            command_detailes[1] = NoOfReads[1];

            command_detailes[2] = NoOfWrites[0];
            command_detailes[3] = NoOfWrites[1];

            #endregion

            if (operandReads.Count > 0 || operandWrites.Count > 0)
            {
                pComB.BuildBinaryCommand((byte)UnitId, BinaryCommand.ReadWrite, command_detailes,
                                         values.ToList(), dataRequestsBytes);

                if (Channel != null)
                {
                    if (this.BreakFlag)
                    {
                        throw new ComDriveExceptions("Request aborted by user",
                                                     ComDriveExceptions.ComDriveException.AbortedByUser);
                    }

                    GuidClass guid = new GuidClass();

                    lock (guid)
                    {
                        Channel.Send(pComB.MessageToPLC as byte[], ReceiveBytes, guid, parentID,
                                     "Binary Protocol - Read/Write Operands (80)", PlcGuid, messageEnumerator);
                        Monitor.Wait(guid);
                    }

                    if (this.BreakFlag)
                    {
                        throw new ComDriveExceptions("Request aborted by user",
                                                     ComDriveExceptions.ComDriveException.AbortedByUser);
                    }

                    PlcResponseMessage plcResponseMessage;

                    lock (_lockObj)
                    {
                        plcResponseMessage = m_responseMessageQueue[guid];
                        m_responseMessageQueue.Remove(guid);
                    }

                    if (plcResponseMessage.comException == CommunicationException.Timeout)
                    {
                        throw new ComDriveExceptions("Cannot communicate with the PLC with the specified UnitID!",
                                                     ComDriveExceptions.ComDriveException.CommunicationTimeout);
                    }

                    // receivedMessage[13] shows if there was occured an error.
                    if (plcResponseMessage.responseBytesMessage[13] == 0)
                    {
                        pComB.DisAssembleBinaryResult(plcResponseMessage.responseBytesMessage, dataRequestsBytes);
                    }
                }
            }
            else
            {
                //System.Diagnostics.Debug.Assert(false);
            }
        }
Exemple #16
0
        private void ReadOperations(ref List <ReadWriteRequest> pdataRequestsForRead, string parentID)
        {
            List <ReadWriteRequest> dataRequestsForRead = null;

            dataRequestsForRead = pdataRequestsForRead.OrderBy(dr => GetOperandSize(dr)).ToList();

            List <List <byte> > dataRequestBytes = new List <List <byte> >();

            for (int i = 0; i < dataRequestsForRead.Count; i++)
            {
                if (dataRequestsForRead[i] is ReadOperands)
                {
                    dataRequestBytes.Add(GetDataRequestBytes(dataRequestsForRead[i] as ReadOperands));
                }
            }

            //set number of read requests in position 4 and 5 of command_details which in header will be 18 and 19
            byte[] command_detailes = new byte[6];
            byte[] count            = BitConverter.GetBytes(dataRequestsForRead.Count);
            command_detailes[4] = count[0];
            command_detailes[5] = count[1];

            PComB pComB = new PComB();

            pComB.BuildBinaryCommand((byte)UnitId, BinaryCommand.ReadOperands, command_detailes,
                                     dataRequestsForRead, dataRequestBytes);

            if (this.BreakFlag)
            {
                throw new ComDriveExceptions("Request aborted by user",
                                             ComDriveExceptions.ComDriveException.AbortedByUser);
            }

            GuidClass guid = new GuidClass();

            lock (guid)
            {
                Channel.Send(pComB.MessageToPLC as byte[], ReceiveBytes, guid, parentID,
                             "Binary Protocol - Read Operands (77)", PlcGuid);
                Monitor.Wait(guid);
            }

            if (this.BreakFlag)
            {
                throw new ComDriveExceptions("Request aborted by user",
                                             ComDriveExceptions.ComDriveException.AbortedByUser);
            }

            PlcResponseMessage plcResponseMessage;

            lock (_lockObj)
            {
                plcResponseMessage = m_responseMessageQueue[guid];
                m_responseMessageQueue.Remove(guid);
            }

            if (plcResponseMessage.comException == CommunicationException.Timeout)
            {
                throw new ComDriveExceptions("Cannot communicate with the PLC with the specified UnitID!",
                                             ComDriveExceptions.ComDriveException.CommunicationTimeout);
            }

            pComB.DisAssembleBinaryResult(plcResponseMessage.responseBytesMessage, dataRequestBytes);
        }
Exemple #17
0
        private void SplitAndSendBinaryData(ReadWriteRequest binaryRequest, string parentID)
        {
            BinaryRequest binRequest = binaryRequest as BinaryRequest;

            PComB pComB = new PComB();

            int       offsetInBuffer                = 0;
            int       chunkSize                     = 0;
            int       outgoingBufferSize            = 0;
            int       currentAddress                = binRequest.Address;
            int       messageKey                    = binRequest.MessageKey;
            const int MIN_TIME_BETWEEN_CHUNKS_WRITE = 20;

            GuidClass          guid;
            PlcResponseMessage plcResponseMessage;

            byte[] outgoingChunk;

            if (binRequest.OutgoingBuffer != null)
            {
                outgoingBufferSize = binRequest.OutgoingBuffer.Length;
            }

            switch (binRequest.CommandCode)
            {
            case 0x1:
            case 0x41:
            case 75:
            case 5:

                if ((binRequest.OutgoingBuffer == null) || (outgoingBufferSize == 0))
                {
                    binRequest.RaiseProgressEvent(0, binRequest.ElementsCount,
                                                  RequestProgress.en_NotificationType.SetMinMax, 0, "");
                    binRequest.RaiseProgressEvent(0, binRequest.ElementsCount,
                                                  RequestProgress.en_NotificationType.ProgressChanged, 0, "");

                    if (this.BreakFlag)
                    {
                        throw new ComDriveExceptions("Request aborted by user",
                                                     ComDriveExceptions.ComDriveException.AbortedByUser);
                    }

                    if (binRequest.WaitForIdle)
                    {
                        WaitForFlashIdle((byte)UnitId, parentID);
                    }


                    byte[] arrivedData = new byte[binRequest.ElementsCount];
                    while (offsetInBuffer < binRequest.ElementsCount)
                    {
                        int sizeOfDataToCopy;

                        if (this.BreakFlag)
                        {
                            throw new ComDriveExceptions("Request aborted by user",
                                                         ComDriveExceptions.ComDriveException.AbortedByUser);
                        }
                        chunkSize        = binRequest.ElementsCount - offsetInBuffer;
                        sizeOfDataToCopy = chunkSize;

                        if (chunkSize > PLCVersion.PlcBuffer - Utils.Lengths.LENGTH_HEADER_AND_FOOTER)
                        {
                            chunkSize = PLCVersion.PlcBuffer - Utils.Lengths.LENGTH_HEADER_AND_FOOTER;
                        }

                        if (binRequest.ChunkSizeAlignment != 0)
                        {
                            // Chop the end of the chunk to fit into aligment
                            chunkSize -= (chunkSize % binRequest.ChunkSizeAlignment);
                        }

                        if (binRequest.FlashBankSize != 0)
                        {
                            // Chop the end of the chunk so the burned data will not be written on 2 different flash banks
                            if (((currentAddress + chunkSize) / binRequest.FlashBankSize) !=
                                (currentAddress / binRequest.FlashBankSize))
                            {
                                chunkSize -= ((currentAddress + chunkSize) % binRequest.FlashBankSize);
                            }
                        }

                        if (chunkSize == 0)
                        {
                            chunkSize = binRequest.ChunkSizeAlignment;
                        }
                        else
                        {
                            sizeOfDataToCopy = chunkSize;
                        }


                        pComB.BuildBinaryCommand((byte)UnitId, messageKey, binRequest.CommandCode,
                                                 binRequest.SubCommand, currentAddress, chunkSize, 0, new byte[0]);

                        guid = new GuidClass();

                        lock (guid)
                        {
                            Channel.Send(pComB.MessageToPLC as byte[], ReceiveBytes, guid, parentID,
                                         "Binary Protocol - Binary Request (" + binRequest.CommandCode.ToString() + ")",
                                         PlcGuid);
                            Monitor.Wait(guid);
                        }

                        if (this.BreakFlag)
                        {
                            throw new ComDriveExceptions("Request aborted by user",
                                                         ComDriveExceptions.ComDriveException.AbortedByUser);
                        }

                        lock (_lockObj)
                        {
                            plcResponseMessage = m_responseMessageQueue[guid];
                            m_responseMessageQueue.Remove(guid);
                        }

                        if (plcResponseMessage.comException == CommunicationException.Timeout)
                        {
                            throw new ComDriveExceptions(
                                      "Cannot communicate with the PLC with the specified UnitID!",
                                      ComDriveExceptions.ComDriveException.CommunicationTimeout);
                        }

                        binRequest.IncomingBuffer =
                            new byte[plcResponseMessage.responseBytesMessage.Length -
                                     Utils.Lengths.LENGTH_HEADER_AND_FOOTER];

                        if (binRequest.IncomingBuffer.Length > 0)
                        {
                            Array.Copy(plcResponseMessage.responseBytesMessage, Utils.Lengths.LENGTH_HEADER,
                                       binRequest.IncomingBuffer, 0, binRequest.IncomingBuffer.Length);
                        }

                        Array.Copy(binRequest.IncomingBuffer, 0, arrivedData, offsetInBuffer, sizeOfDataToCopy);
                        if (plcResponseMessage.responseBytesMessage[12] == 0xFF)
                        {
                            binRequest.PlcReceiveResult =
                                (BinaryRequest.ePlcReceiveResult)plcResponseMessage.responseBytesMessage[13];
                        }
                        else if (plcResponseMessage.responseBytesMessage[12] == binRequest.CommandCode + 0x80)
                        {
                            binRequest.PlcReceiveResult = BinaryRequest.ePlcReceiveResult.Sucsess;
                        }
                        else
                        {
                            binRequest.PlcReceiveResult = BinaryRequest.ePlcReceiveResult.Unknown;
                        }

                        offsetInBuffer += sizeOfDataToCopy;
                        currentAddress += sizeOfDataToCopy;
                        messageKey++;     // Message Key is % 256. The BuildBinaryCommand takes care of that
                        binRequest.MessageKey = messageKey;
                        binRequest.MessageKey = binRequest.MessageKey % 256;

                        if (binRequest.MessageKey == 0)
                        {
                            messageKey            = binRequest.CycledMessageKey;
                            binRequest.MessageKey = messageKey;
                        }

                        if (binRequest.WaitForIdle)
                        {
                            WaitForFlashIdle((byte)UnitId, parentID);
                        }

                        binRequest.RaiseProgressEvent(0, binRequest.ElementsCount,
                                                      RequestProgress.en_NotificationType.ProgressChanged, offsetInBuffer, "");
                    }

                    binRequest.IncomingBuffer = arrivedData;
                    binRequest.RaiseProgressEvent(0, binRequest.ElementsCount,
                                                  RequestProgress.en_NotificationType.Completed, binRequest.ElementsCount, "");
                }
                else
                {
                    if (this.BreakFlag)
                    {
                        throw new ComDriveExceptions("Request aborted by user",
                                                     ComDriveExceptions.ComDriveException.AbortedByUser);
                    }

                    if (binRequest.WaitForIdle)
                    {
                        WaitForFlashIdle((byte)UnitId, parentID);
                    }

                    binRequest.RaiseProgressEvent(0, outgoingBufferSize,
                                                  RequestProgress.en_NotificationType.SetMinMax, 0, "");
                    binRequest.RaiseProgressEvent(0, outgoingBufferSize,
                                                  RequestProgress.en_NotificationType.ProgressChanged, 0, "");

                    //if (binRequest.SubCommand == (int)MemoryType.InternalFlash && binRequest.CommandCode == 0x41)
                    //{
                    //    if ((binRequest.OutgoingBuffer.Length % 8) != 0)
                    //    {
                    //        byte[] binDataToBurn = new byte[binRequest.OutgoingBuffer.Length + 8 - binRequest.OutgoingBuffer.Length % 8];
                    //        for (int i = binRequest.OutgoingBuffer.Length; i < binDataToBurn.Length; i++)
                    //        {
                    //            binDataToBurn[i] = 0xFF;
                    //        }

                    //        Array.Copy(binRequest.OutgoingBuffer, 0, binDataToBurn, 0, binRequest.OutgoingBuffer.Length);
                    //        binRequest.OutgoingBuffer = binDataToBurn;
                    //        outgoingBufferSize = binRequest.OutgoingBuffer.Length;
                    //    }
                    //}

                    Stopwatch sw = new Stopwatch();
                    sw.Start();
                    long lastTime = 0;
                    while (offsetInBuffer < outgoingBufferSize)
                    {
                        if (this.BreakFlag)
                        {
                            throw new ComDriveExceptions("Request aborted by user",
                                                         ComDriveExceptions.ComDriveException.AbortedByUser);
                        }

                        chunkSize = outgoingBufferSize - offsetInBuffer;
                        if (chunkSize > PLCVersion.PlcBuffer - Utils.Lengths.LENGTH_HEADER_AND_FOOTER)
                        {
                            chunkSize = PLCVersion.PlcBuffer - Utils.Lengths.LENGTH_HEADER_AND_FOOTER;
                        }

                        if (binRequest.ChunkSizeAlignment != 0)
                        {
                            // Chop the end of the chunk to fit into aligment
                            chunkSize -= (chunkSize % binRequest.ChunkSizeAlignment);
                        }

                        if (binRequest.FlashBankSize != 0)
                        {
                            // Chop the end of the chunk so the burned data will not be written on 2 different flash banks
                            if (((currentAddress + chunkSize) / binRequest.FlashBankSize) !=
                                (currentAddress / binRequest.FlashBankSize))
                            {
                                chunkSize -= ((currentAddress + chunkSize) % binRequest.FlashBankSize);
                            }
                        }

                        //if (binRequest.SubCommand == (int)MemoryType.InternalFlash && binRequest.CommandCode == 0x41)
                        //{
                        //    if ((chunkSize % 8) != 0)
                        //        chunkSize -= chunkSize % 8;
                        //}

                        outgoingChunk = new byte[chunkSize];
                        Array.Copy(binRequest.OutgoingBuffer, offsetInBuffer, outgoingChunk, 0, chunkSize);

                        // Programming command (0x41)
                        // We want to put it on PLC even if the chunk is full with 0xff (Because it is not a flash memory)
                        if ((binRequest.CommandCode == 0x41 && binRequest.SubCommand == (int)MemoryType.SRAM) ||
                            IsValidChunkBufferData(outgoingChunk, binRequest.DecodeValue))
                        {
                            if (sw.ElapsedMilliseconds - lastTime < MIN_TIME_BETWEEN_CHUNKS_WRITE)
                            {
                                Thread.Sleep((int)(MIN_TIME_BETWEEN_CHUNKS_WRITE -
                                                   (sw.ElapsedMilliseconds - lastTime)));
                            }

                            pComB.BuildBinaryCommand((byte)UnitId, messageKey, binRequest.CommandCode,
                                                     binRequest.SubCommand, currentAddress, chunkSize, (ushort)chunkSize,
                                                     outgoingChunk);

                            lastTime = sw.ElapsedMilliseconds;
                            messageKey++;     // Message Key is % 256. The BuildBinaryCommand takes care of that
                            binRequest.MessageKey = messageKey;
                            binRequest.MessageKey = binRequest.MessageKey % 256;

                            if (binRequest.MessageKey == 0)
                            {
                                messageKey            = binRequest.CycledMessageKey;
                                binRequest.MessageKey = messageKey;
                            }

                            guid = new GuidClass();

                            lock (guid)
                            {
                                Channel.Send(pComB.MessageToPLC as byte[], ReceiveBytes, guid, parentID,
                                             "Binary Protocol - Binary Request (" + binRequest.CommandCode.ToString() + ")",
                                             PlcGuid);
                                Monitor.Wait(guid);
                            }

                            if (this.BreakFlag)
                            {
                                throw new ComDriveExceptions("Request aborted by user",
                                                             ComDriveExceptions.ComDriveException.AbortedByUser);
                            }

                            lock (_lockObj)
                            {
                                plcResponseMessage = m_responseMessageQueue[guid];
                                m_responseMessageQueue.Remove(guid);
                            }

                            if (plcResponseMessage.comException == CommunicationException.Timeout)
                            {
                                throw new ComDriveExceptions(
                                          "Cannot communicate with the PLC with the specified UnitID!",
                                          ComDriveExceptions.ComDriveException.CommunicationTimeout);
                            }

                            binRequest.IncomingBuffer =
                                new byte[plcResponseMessage.responseBytesMessage.Length -
                                         Utils.Lengths.LENGTH_HEADER_AND_FOOTER];
                            if (binRequest.IncomingBuffer.Length > 0)
                            {
                                Array.Copy(plcResponseMessage.responseBytesMessage, Utils.Lengths.LENGTH_HEADER,
                                           binRequest.IncomingBuffer, 0, binRequest.IncomingBuffer.Length);
                            }

                            if (plcResponseMessage.responseBytesMessage[12] == 0xFF)
                            {
                                binRequest.PlcReceiveResult =
                                    (BinaryRequest.ePlcReceiveResult)plcResponseMessage.responseBytesMessage[13];
                            }
                            else if (plcResponseMessage.responseBytesMessage[12] == binRequest.CommandCode + 0x80)
                            {
                                binRequest.PlcReceiveResult = BinaryRequest.ePlcReceiveResult.Sucsess;
                            }
                            else
                            {
                                binRequest.PlcReceiveResult = BinaryRequest.ePlcReceiveResult.Unknown;
                            }

                            if (binRequest.PlcReceiveResult != BinaryRequest.ePlcReceiveResult.Sucsess)
                            {
                                return;
                            }

                            if (binRequest.WaitForIdle)
                            {
                                WaitForFlashIdle((byte)UnitId, parentID);
                            }
                            else
                            {
                                if (binRequest.CommandCode == 0x41)
                                {
                                    Thread.Sleep(25);
                                }
                            }
                        }
                        else
                        {
                            Debug.Print("Not Valid");
                        }

                        offsetInBuffer += chunkSize;
                        currentAddress += chunkSize;

                        binRequest.RaiseProgressEvent(0, outgoingBufferSize,
                                                      RequestProgress.en_NotificationType.ProgressChanged, offsetInBuffer, "");
                    }

                    binRequest.RaiseProgressEvent(0, outgoingBufferSize,
                                                  RequestProgress.en_NotificationType.Completed, outgoingBufferSize, "");
                }

                break;

            default:

                binRequest.RaiseProgressEvent(0, 100, RequestProgress.en_NotificationType.SetMinMax, 0, "");
                binRequest.RaiseProgressEvent(0, 100, RequestProgress.en_NotificationType.ProgressChanged, 0, "");

                pComB.BuildBinaryCommand((byte)UnitId, messageKey, binRequest.CommandCode,
                                         binRequest.SubCommand, currentAddress, binRequest.ElementsCount, (ushort)outgoingBufferSize,
                                         binRequest.OutgoingBuffer);

                if (this.BreakFlag)
                {
                    throw new ComDriveExceptions("Request aborted by user",
                                                 ComDriveExceptions.ComDriveException.AbortedByUser);
                }

                if (binRequest.WaitForIdle)
                {
                    WaitForFlashIdle((byte)UnitId, parentID);
                }

                guid = new GuidClass();

                lock (guid)
                {
                    Channel.Send(pComB.MessageToPLC as byte[], ReceiveBytes, guid, parentID,
                                 "Binary Protocol - Binary Request (" + binRequest.CommandCode.ToString() + ")", PlcGuid);
                    Monitor.Wait(guid);
                }

                if (this.BreakFlag)
                {
                    throw new ComDriveExceptions("Request aborted by user",
                                                 ComDriveExceptions.ComDriveException.AbortedByUser);
                }

                lock (_lockObj)
                {
                    plcResponseMessage = m_responseMessageQueue[guid];
                    m_responseMessageQueue.Remove(guid);
                }

                if (plcResponseMessage.comException == CommunicationException.Timeout)
                {
                    throw new ComDriveExceptions("Cannot communicate with the PLC with the specified UnitID!",
                                                 ComDriveExceptions.ComDriveException.CommunicationTimeout);
                }

                binRequest.IncomingBuffer = new byte[plcResponseMessage.responseBytesMessage.Length -
                                                     Utils.Lengths.LENGTH_HEADER_AND_FOOTER];
                if (binRequest.IncomingBuffer.Length > 0)
                {
                    Array.Copy(plcResponseMessage.responseBytesMessage, Utils.Lengths.LENGTH_HEADER,
                               binRequest.IncomingBuffer, 0, binRequest.IncomingBuffer.Length);
                }

                if (plcResponseMessage.responseBytesMessage[12] == 0xFF)
                {
                    binRequest.PlcReceiveResult =
                        (BinaryRequest.ePlcReceiveResult)plcResponseMessage.responseBytesMessage[13];
                }
                else if (plcResponseMessage.responseBytesMessage[12] == binRequest.CommandCode + 0x80)
                {
                    binRequest.PlcReceiveResult = BinaryRequest.ePlcReceiveResult.Sucsess;
                }
                else
                {
                    binRequest.PlcReceiveResult = BinaryRequest.ePlcReceiveResult.Unknown;
                }

                if (binRequest.WaitForIdle)
                {
                    WaitForFlashIdle((byte)UnitId, parentID);
                }

                binRequest.RaiseProgressEvent(0, 100, RequestProgress.en_NotificationType.Completed, 100, "");

                break;
            }
        }
        public void ValidateLinqQueries()
        {
            CosmosDatabaseSettings database = this.client.CreateDatabaseAsync(new CosmosDatabaseSettings {
                Id = Guid.NewGuid().ToString("N")
            }).Result.Resource;
            CosmosContainerSettings collection = this.client.CreateDocumentCollectionAsync(
                database.SelfLink, new CosmosContainerSettings {
                Id = Guid.NewGuid().ToString("N")
            }).Result.Resource;

            DataObject doc = new DataObject()
            {
                Id = Guid.NewGuid().ToString("N"), Number = 0, TypeName = "Hello"
            };

            this.client.CreateDocumentAsync(collection, doc).Wait();

            QueryHelper queryHelper           = new QueryHelper(client, collection);
            IEnumerable <BaseDocument> result = queryHelper.Query <BaseDocument>();

            Assert.AreEqual(1, result.Count());

            BaseDocument baseDocument = result.FirstOrDefault <BaseDocument>();

            Assert.AreEqual(doc.Id, baseDocument.Id);

            BaseDocument iDocument           = doc;
            IOrderedQueryable <DataObject> q = this.client.CreateDocumentQuery <DataObject>(collection.DocumentsLink);

            IEnumerable <DataObject> iresult = from f in q
                                               where f.Id == iDocument.Id
                                               select f;
            DataObject id = iresult.FirstOrDefault <DataObject>();

            Assert.AreEqual(doc.Id, id.Id);

            Parent mother = new Parent {
                FamilyName = "Wakefield", GivenName = "Robin"
            };
            Parent father = new Parent {
                FamilyName = "Miller", GivenName = "Ben"
            };
            Pet pet = new Pet {
                GivenName = "Fluffy"
            };
            Child child = new Child
            {
                FamilyName = "Merriam",
                GivenName  = "Jesse",
                Gender     = "female",
                Grade      = 1,
                Pets       = new List <Pet>()
                {
                    pet, new Pet()
                    {
                        GivenName = "koko"
                    }
                },
                Things = new Dictionary <string, string>()
                {
                    { "A", "B" }, { "C", "D" }
                }
            };

            Address address = new Address {
                State = "NY", County = "Manhattan", City = "NY"
            };
            Family family = new Family {
                FamilyId = "WakefieldFamily", Parents = new Parent[] { mother, father }, Children = new Child[] { child }, IsRegistered = false, Int = 3, NullableInt = 5
            };

            List <Family> fList = new List <Family>();

            fList.Add(family);

            this.client.CreateDocumentAsync(collection.SelfLink, family).Wait();

            IOrderedQueryable <Family> query = this.client.CreateDocumentQuery <Family>(collection.DocumentsLink);

            IEnumerable <string> q1 = query.Select(f => f.Parents[0].FamilyName);

            Assert.AreEqual(q1.FirstOrDefault(), family.Parents[0].FamilyName);

            IEnumerable <int> q2 = query.Select(f => f.Children[0].Grade + 13);

            Assert.AreEqual(q2.FirstOrDefault(), family.Children[0].Grade + 13);

            IEnumerable <Family> q3 = query.Where(f => f.Children[0].Pets[0].GivenName == "Fluffy");

            Assert.AreEqual(q3.FirstOrDefault().FamilyId, family.FamilyId);

            IEnumerable <Family> q4 = query.Where(f => f.Children[0].Things["A"] == "B");

            Assert.AreEqual(q4.FirstOrDefault().FamilyId, family.FamilyId);

            for (int index = 0; index < 2; index++)
            {
                IEnumerable <Pet> q5 = query.Where(f => f.Children[0].Gender == "female").Select(f => f.Children[0].Pets[index]);
                Assert.AreEqual(q5.FirstOrDefault().GivenName, family.Children[0].Pets[index].GivenName);
            }

            IEnumerable <dynamic> q6 = query.SelectMany(f => f.Children.Select(c => new { Id = f.FamilyId }));

            Assert.AreEqual(q6.FirstOrDefault().Id, family.FamilyId);

            string nullString       = null;
            IEnumerable <Family> q7 = query.Where(f => nullString == f.FamilyId);

            Assert.IsNull(q7.FirstOrDefault());

            object nullObject = null;

            q7 = query.Where(f => f.NullObject == nullObject);
            Assert.AreEqual(q7.FirstOrDefault().FamilyId, family.FamilyId);

            q7 = query.Where(f => f.FamilyId == nullString);
            Assert.IsNull(q7.FirstOrDefault());

            IEnumerable <Family> q8 = query.Where(f => null == f.FamilyId);

            Assert.IsNull(q8.FirstOrDefault());

            IEnumerable <Family> q9 = query.Where(f => f.IsRegistered == false);

            Assert.AreEqual(q9.FirstOrDefault().FamilyId, family.FamilyId);

            dynamic q10 = System.Linq.Dynamic.Core.DynamicQueryableExtensions.AsEnumerable(query.Where(f => f.FamilyId.Equals("WakefieldFamily"))).FirstOrDefault();

            Assert.AreEqual(q10.FamilyId, family.FamilyId);

            GuidClass guidObject = new GuidClass()
            {
                Id = Guid.NewGuid()
            };

            this.client.CreateDocumentAsync(collection.SelfLink, guidObject).Wait();

            IEnumerable <GuidClass> q11 = this.client.CreateDocumentQuery <GuidClass>(collection.DocumentsLink).Where(g => g.Id == guidObject.Id);

            Assert.AreEqual(q11.FirstOrDefault().Id, guidObject.Id);

            IEnumerable <GuidClass> q12 = this.client.CreateDocumentQuery <GuidClass>(collection.DocumentsLink).Where(g => g.Id.ToString() == guidObject.Id.ToString());

            Assert.AreEqual(q12.FirstOrDefault().Id, guidObject.Id);

            ListArrayClass arrayObject = new ListArrayClass()
            {
                Id = "arrayObject", ArrayField = new int[] { 1, 2, 3 }
            };

            this.client.CreateDocumentAsync(collection.SelfLink, arrayObject).Wait();

            IEnumerable <dynamic> q13 = this.client.CreateDocumentQuery <ListArrayClass>(collection.DocumentsLink).Where(a => a.ArrayField == arrayObject.ArrayField);

            Assert.AreEqual(q13.FirstOrDefault().Id, arrayObject.Id);

            int[] nullArray = null;
            q13 = this.client.CreateDocumentQuery <ListArrayClass>(collection.DocumentsLink).Where(a => a.ArrayField == nullArray);
            Assert.IsNull(q13.FirstOrDefault());

            ListArrayClass listObject = new ListArrayClass()
            {
                Id = "listObject", ListField = new List <int> {
                    1, 2, 3
                }
            };

            this.client.CreateDocumentAsync(collection.SelfLink, listObject).Wait();

            IEnumerable <dynamic> q14 = this.client.CreateDocumentQuery <ListArrayClass>(collection.DocumentsLink).Where(a => a.ListField == listObject.ListField);

            Assert.AreEqual(q14.FirstOrDefault().Id, listObject.Id);

            IEnumerable <dynamic> q15 = query.Where(f => f.NullableInt == null);

            Assert.AreEqual(q15.ToList().Count, 0);

            int?nullInt = null;

            q15 = query.Where(f => f.NullableInt == nullInt);
            Assert.AreEqual(q15.ToList().Count, 0);

            q15 = query.Where(f => f.NullableInt == 5);
            Assert.AreEqual(q15.FirstOrDefault().FamilyId, family.FamilyId);

            nullInt = 5;
            q15     = query.Where(f => f.NullableInt == nullInt);
            Assert.AreEqual(q15.FirstOrDefault().FamilyId, family.FamilyId);

            q15 = query.Where(f => f.NullableInt == nullInt.Value);
            Assert.AreEqual(q15.FirstOrDefault().FamilyId, family.FamilyId);

            nullInt = 3;
            q15     = query.Where(f => f.Int == nullInt);
            Assert.AreEqual(q15.FirstOrDefault().FamilyId, family.FamilyId);

            q15 = query.Where(f => f.Int == nullInt.Value);
            Assert.AreEqual(q15.FirstOrDefault().FamilyId, family.FamilyId);

            nullInt = null;
            q15     = query.Where(f => f.Int == nullInt);
            Assert.AreEqual(q15.ToList().Count, 0);

            var v = fList.Where(f => f.Int > nullInt).ToList();

            q15 = query.Where(f => f.Int < nullInt);

            string   doc1Id = "document1:x:'!@TT){}\"";
            Document doubleQoutesDocument = new Document()
            {
                Id = doc1Id
            };

            this.client.CreateDocumentAsync(collection.DocumentsLink, doubleQoutesDocument).Wait();

            var docQuery = from book in client.CreateDocumentQuery <Document>(collection.DocumentsLink)
                           where book.Id == doc1Id
                           select book;

            Assert.AreEqual(System.Linq.Dynamic.Core.DynamicQueryableExtensions.AsEnumerable(docQuery).Single().Id, doc1Id);

            GreatFamily greatFamily = new GreatFamily()
            {
                Family = family
            };
            GreatGreatFamily greatGreatFamily = new GreatGreatFamily()
            {
                GreatFamilyId = Guid.NewGuid().ToString(), GreatFamily = greatFamily
            };

            this.client.CreateDocumentAsync(collection.DocumentsLink, greatGreatFamily).Wait();

            IOrderedQueryable <GreatGreatFamily> queryable = this.client.CreateDocumentQuery <GreatGreatFamily>(collection.DocumentsLink);

            IEnumerable <GreatGreatFamily> q16 = queryable.SelectMany(gf => gf.GreatFamily.Family.Children.Where(c => c.GivenName == "Jesse").Select(c => gf));

            Assert.AreEqual(q16.FirstOrDefault().GreatFamilyId, greatGreatFamily.GreatFamilyId);

            Sport sport = new Sport()
            {
                SportName = "Tennis", SportType = "Racquet"
            };

            this.client.CreateDocumentAsync(collection.DocumentsLink, sport).Wait();

            IEnumerable <Sport> q17 = this.client.CreateDocumentQuery <Sport>(collection.DocumentsLink)
                                      .Where(s => s.SportName == "Tennis");

            Assert.AreEqual(sport.SportName, q17.FirstOrDefault().SportName);

            q17 = this.client.CreateDocumentQuery <Sport>(collection.DocumentsLink)
                  .Where(s => s.SportType == "Racquet");

            this.VerifyQueryTranslation(q17.ToString(), "SELECT * FROM root WHERE (root[\"json\"] = \"Racquet\") ");

            Sport2 sport2 = new Sport2()
            {
                id = "json"
            };

            this.client.CreateDocumentAsync(collection.DocumentsLink, sport2).Wait();

            IEnumerable <Sport2> q18 = this.client.CreateDocumentQuery <Sport2>(collection.DocumentsLink)
                                       .Where(s => s.id == "json");

            this.VerifyQueryTranslation(q18.ToString(), "SELECT * FROM root WHERE (root[\"id\"] = \"json\") ");
        }