System.Collections.Generic.IEnumerable.SequenceEqual(System.Collections.Generic.IEnumerable, System.Collections.Generic.IEqualityComparer)

Here are the examples of the csharp api System.Collections.Generic.IEnumerable.SequenceEqual(System.Collections.Generic.IEnumerable, System.Collections.Generic.IEqualityComparer) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

800 Examples 7

19 View Source File : SemanticComparerTest.cs
License : MIT License
Project Creator : AutoFixture

[Fact]
        public void SutDoesNotEqualAnonymousObjectSequence()
        {
            // Fixture setup
            var sut = new SemanticComparer<ConcreteType, ConcreteType>();

            object anonymousObject = new object();
            object[] anonymousObjects = new object[] { anonymousObject, anonymousObject, anonymousObject };
            
            ConcreteType concreteType = new ConcreteType();
            ConcreteType[] concreteTypes = new ConcreteType[] { concreteType, concreteType, concreteType };
            
            // Exercise system
            var result = concreteTypes.SequenceEqual(anonymousObjects, sut);
            // Verify outcome
            replacedert.False(result);
            // Teardown
        }

19 View Source File : ValueAccessorTests.cs
License : MIT License
Project Creator : azist

[Run]
    public void ByteArray1()
    {
      Aver.IsTrue(new byte[] { 0xFA, 0xCA, 0xDA, 0xBA }.SequenceEqual(root.AttrByName("vBuffer1").ValueAsByteArray()));
    }

19 View Source File : ProtocolTests.cs
License : GNU Lesser General Public License v3.0
Project Creator : Apollo3zehn

[Fact]
        public void FC023Test()
        {
            // Arrange
            var endpoint = EndpointSource.GetNext();

            using var server = new ModbusTcpServer();
            server.Start(endpoint);

            lock (server.Lock)
            {
                var buffer = server.GetHoldingRegisterBuffer<float>();

                buffer[6] = 65.455F;
                buffer[7] = 24;
                buffer[8] = 25;
            }

            var client = new ModbusTcpClient();
            client.Connect(endpoint);

            // Act
            var actual1 = client.ReadWriteMultipleRegisters<float, float>(0, 2, 10, 12, new float[] { 1.211F });

            // replacedert
            var expected = new float[] { 0, 0, 0, 0, 0, 1.211F, 24, 25, 0, 0 };

            replacedert.True(expected.SequenceEqual(actual1.ToArray()));

            lock (server.Lock)
            {
                var actual2 = server.GetHoldingRegisterBuffer<float>().Slice(1, 10);
                replacedert.True(expected.SequenceEqual(actual2.ToArray()));
            }
        }

19 View Source File : BotModule.cs
License : GNU Affero General Public License v3.0
Project Creator : asmejkal

private (CommandInfo registration, CommandInfo.Usage usage)? TryFindRegistration(string invoker, ICollection<string> verbs)
        {
            foreach (var module in _frameworkReflector.Modules.Where(x => !x.Hidden))
            {
                foreach (var handledCommand in module.Commands.Where(x => !x.Flags.HasFlag(CommandFlags.Hidden)))
                {
                    foreach (var usage in handledCommand.EveryUsage)
                    {
                        if (string.Compare(usage.InvokeString, invoker, true) == 0 && verbs.SequenceEqual(usage.Verbs.Select(x => x.ToLowerInvariant())))
                        {
                            return (handledCommand, usage);
                        }
                    }
                }
            }

            return null;
        }

19 View Source File : ProtocolTestsAsync.cs
License : GNU Lesser General Public License v3.0
Project Creator : Apollo3zehn

[Fact]
        public async Task FC01Test()
        {
            // Arrange
            var endpoint = EndpointSource.GetNext();

            using var server = new ModbusTcpServer();
            server.Start(endpoint);

            void AsyncWorkaround()
            {
                var buffer = server.GetCoilBuffer<byte>();

                buffer[1] = 9;
                buffer[2] = 0;
                buffer[3] = 24;
            }

            lock (server.Lock)
            {
                AsyncWorkaround();
            }

            var client = new ModbusTcpClient();
            client.Connect(endpoint);

            // Act
            var actual = await client.ReadCoilsAsync(0, 8, 25);

            // replacedert
            var expected = new byte[] { 9, 0, 24, 0 };

            replacedert.True(expected.SequenceEqual(actual.ToArray()));
        }

19 View Source File : ProtocolTests.cs
License : GNU Lesser General Public License v3.0
Project Creator : Apollo3zehn

[Fact]
        public void FC02Test()
        {
            // Arrange
            var endpoint = EndpointSource.GetNext();

            using var server = new ModbusTcpServer();
            server.Start(endpoint);

            lock (server.Lock)
            {
                var buffer = server.GetDiscreteInputBuffer<byte>();

                buffer[1] = 9;
                buffer[2] = 0;
                buffer[3] = 24;
            }

            var client = new ModbusTcpClient();
            client.Connect(endpoint);

            // Act
            var actual = client.ReadDiscreteInputs(0, 8, 25);

            // replacedert
            var expected = new byte[] { 9, 0, 24, 0 };

            replacedert.True(expected.SequenceEqual(actual.ToArray()));
        }

19 View Source File : BinarySerializerTest.cs
License : Apache License 2.0
Project Creator : awslabs

[Fact]
        public void TestBinarySerializer()
        {
            List<MockClreplaced> list = CreateList();
            MemoryStream stream = new MemoryStream();
            ListBinarySerializer<MockClreplaced> listSerializer = new ListBinarySerializer<MockClreplaced>
                (
                    MockSerializer,
                    MockDeserializer
                );

            BinarySerializer<List<MockClreplaced>> serializer = new BinarySerializer<List<MockClreplaced>>(
                listSerializer.Serialize,
                listSerializer.Deserialize);
            serializer.Serialize(stream, list);
            stream.Position = 0;
            List<MockClreplaced> list2 = serializer.Deserialize(stream);
            replacedert.True(list.SequenceEqual(list2, new MockClreplacedComparer()));
        }

19 View Source File : DnsMessageBase.cs
License : Apache License 2.0
Project Creator : alexreinert

private ReturnCode ValidateTSig(byte[] resultData, DnsServer.SelectTsigKey tsigKeySelector, byte[] originalMac)
		{
			byte[] keyData;
			if ((TSigOptions.Algorithm == TSigAlgorithm.Unknown) || (tsigKeySelector == null) || ((keyData = tsigKeySelector(TSigOptions.Algorithm, TSigOptions.Name)) == null))
			{
				return ReturnCode.BadKey;
			}
			else if (((TSigOptions.TimeSigned - TSigOptions.Fudge) > DateTime.Now) || ((TSigOptions.TimeSigned + TSigOptions.Fudge) < DateTime.Now))
			{
				return ReturnCode.BadTime;
			}
			else if ((TSigOptions.Mac == null) || (TSigOptions.Mac.Length == 0))
			{
				return ReturnCode.BadSig;
			}
			else
			{
				TSigOptions.KeyData = keyData;

				// maxLength for the buffer to validate: Original (unsigned) dns message and encoded TSigOptions
				// because of compression of keyname, the size of the signed message can not be used
				int maxLength = TSigOptions.StartPosition + TSigOptions.MaximumLength;
				if (originalMac != null)
				{
					// add length of mac on responses. MacSize not neccessary, this field is allready included in the size of the tsig options
					maxLength += originalMac.Length;
				}

				byte[] validationBuffer = new byte[maxLength];

				int currentPosition = 0;

				// original mac if neccessary
				if ((originalMac != null) && (originalMac.Length > 0))
				{
					EncodeUShort(validationBuffer, ref currentPosition, (ushort) originalMac.Length);
					EncodeByteArray(validationBuffer, ref currentPosition, originalMac);
				}

				// original unsiged buffer
				Buffer.BlockCopy(resultData, 0, validationBuffer, currentPosition, TSigOptions.StartPosition);

				// update original transaction id and ar count in message
				EncodeUShort(validationBuffer, currentPosition, TSigOptions.OriginalID);
				EncodeUShort(validationBuffer, currentPosition + 10, (ushort) _additionalRecords.Count);
				currentPosition += TSigOptions.StartPosition;

				// TSig Variables
				EncodeDomainName(validationBuffer, 0, ref currentPosition, TSigOptions.Name, null, false);
				EncodeUShort(validationBuffer, ref currentPosition, (ushort) TSigOptions.RecordClreplaced);
				EncodeInt(validationBuffer, ref currentPosition, (ushort) TSigOptions.TimeToLive);
				EncodeDomainName(validationBuffer, 0, ref currentPosition, TSigAlgorithmHelper.GetDomainName(TSigOptions.Algorithm), null, false);
				TSigRecord.EncodeDateTime(validationBuffer, ref currentPosition, TSigOptions.TimeSigned);
				EncodeUShort(validationBuffer, ref currentPosition, (ushort) TSigOptions.Fudge.TotalSeconds);
				EncodeUShort(validationBuffer, ref currentPosition, (ushort) TSigOptions.Error);
				EncodeUShort(validationBuffer, ref currentPosition, (ushort) TSigOptions.OtherData.Length);
				EncodeByteArray(validationBuffer, ref currentPosition, TSigOptions.OtherData);

				// Validate MAC
				KeyedHashAlgorithm hashAlgorithm = TSigAlgorithmHelper.GetHashAlgorithm(TSigOptions.Algorithm);
				hashAlgorithm.Key = keyData;
				return (hashAlgorithm.ComputeHash(validationBuffer, 0, currentPosition).SequenceEqual(TSigOptions.Mac)) ? ReturnCode.NoError : ReturnCode.BadSig;
			}
		}

19 View Source File : ValueAccessorTests.cs
License : MIT License
Project Creator : azist

[Run]
    public void LongArray()
    {
      Aver.IsTrue(new long[] { 1, 2, 3, 0b10, 0xFAcaca, 0xbb, -9_666_123_000 }.SequenceEqual(root.AttrByName("vLongArray").ValueAsLongArray()));
    }

19 View Source File : egsTools.cs
License : Apache License 2.0
Project Creator : AntonioDePau

private static List<EgsHdreplacedet.RemasteredEntry> ReplaceRemasteredreplacedets(string inputFolder, string originalFile, EgsHdreplacedet replacedet, FileStream pkgStream, byte[] seed, byte[] originalreplacedetData, SDreplacedet sdreplacedet)
        {
            var newRemasteredHeaders = new List<EgsHdreplacedet.RemasteredEntry>();
            var oldRemasteredHeaders = new List<EgsHdreplacedet.RemasteredEntry>();
            var relativePath = Helpers.GetRelativePath(originalFile, Path.Combine(inputFolder, ORIGINAL_FILES_FOLDER_NAME));
            var remasteredreplacedetsFolder = Path.Combine(inputFolder, REMASTERED_FILES_FOLDER_NAME, relativePath);

            var allRemasteredreplacedetsData = new MemoryStream();
            
            foreach (var remasteredreplacedetHeader in replacedet.RemasteredreplacedetHeaders.Values){
            	oldRemasteredHeaders.Add(remasteredreplacedetHeader);
            }

			//At the moment this only applies on fresh PKGs (or ones that haven't been patched with this modded MDLX before, otherwise we'd neet to replacedyse ALL MDLX files)
			if(sdreplacedet != null && !sdreplacedet.Invalid){
				File.AppendAllText("custom_hd_replacedets.txt", "HD replacedets for: " + originalFile + "\n");
				while(oldRemasteredHeaders.Count > sdreplacedet.TextureCount){
					File.AppendAllText("custom_hd_replacedets.txt", "Removing: -" + (oldRemasteredHeaders.Count-1) + ".dds\n");
					oldRemasteredHeaders.RemoveAt(oldRemasteredHeaders.Count-1);
				}
				while(oldRemasteredHeaders.Count < sdreplacedet.TextureCount){
					var newRemasteredreplacedetHeader = new EgsHdreplacedet.RemasteredEntry()
					{
						CompressedLength = 0,
						DecompressedLength = 0,
						Name = "-" + oldRemasteredHeaders.Count + ".dds",
						Offset = 0,
						OriginalreplacedetOffset = 0
					};
					File.AppendAllText("custom_hd_replacedets.txt", "Adding: -" + oldRemasteredHeaders.Count + ".dds\n");
					oldRemasteredHeaders.Add(newRemasteredreplacedetHeader);
				}
				File.AppendAllText("custom_hd_replacedets.txt", "\n");
			}
			
            // 0x30 is the size of this header
            var totalRemasteredreplacedetHeadersSize = oldRemasteredHeaders.Count() * 0x30;
            // This offset is relative to the original replacedet data
            var offset = totalRemasteredreplacedetHeadersSize + 0x10 + replacedet.OriginalreplacedetHeader.DecompressedLength;
			
            for(int i=0;i<oldRemasteredHeaders.Count;i++)
            {
				var remasteredreplacedetHeader = oldRemasteredHeaders[i];
                var filename = remasteredreplacedetHeader.Name;
                var replacedetFilePath = Path.Combine(remasteredreplacedetsFolder, filename);

                // Use base remastered replacedet data
                var replacedetData = replacedet.RemasteredreplacedetsDecompressedData.ContainsKey(filename) ? replacedet.RemasteredreplacedetsDecompressedData[filename] : new byte[]{};
                var decompressedLength = remasteredreplacedetHeader.DecompressedLength;
				var originalreplacedetOffset = remasteredreplacedetHeader.OriginalreplacedetOffset;
                if (File.Exists(replacedetFilePath))
                {
                    Console.WriteLine($"Replacing remastered file: {relativePath}/{filename}");

                    replacedetData = File.ReadAllBytes(replacedetFilePath);
                    decompressedLength = replacedetData.Length;
                    replacedetData = remasteredreplacedetHeader.CompressedLength > -1 ? Helpers.CompressData(replacedetData) : replacedetData;
                    replacedetData = remasteredreplacedetHeader.CompressedLength > -2 ? EgsEncryption.Encrypt(replacedetData, seed) : replacedetData;
					if(sdreplacedet != null && !sdreplacedet.Invalid) originalreplacedetOffset = sdreplacedet.Offsets[i];
                }
                else
                {
                    Console.WriteLine($"Keeping remastered file: {relativePath}/{filename}");
                    // The original file have been replaced, we need to encrypt all remastered replacedet with the new key
                    if (!seed.SequenceEqual(replacedet.Seed))
                    {
                        replacedetData = remasteredreplacedetHeader.CompressedLength > -1 ? Helpers.CompressData(replacedetData) : replacedetData;
                        replacedetData = remasteredreplacedetHeader.CompressedLength > -2 ? EgsEncryption.Encrypt(replacedetData, seed) : replacedetData;
						if(sdreplacedet != null && !sdreplacedet.Invalid && sdreplacedet.TextureCount >= i) originalreplacedetOffset = sdreplacedet.Offsets[i];
                    }else{
						replacedetData = replacedet.RemasteredreplacedetsCompressedData.ContainsKey(filename) ? replacedet.RemasteredreplacedetsCompressedData[filename] : new byte[]{};
					}
                }
                var compressedLength = remasteredreplacedetHeader.CompressedLength > -1 ? replacedetData.Length : remasteredreplacedetHeader.CompressedLength;

                var newRemasteredreplacedetHeader = new EgsHdreplacedet.RemasteredEntry()
                {
                    CompressedLength = compressedLength,
                    DecompressedLength = decompressedLength,
                    Name = filename,
                    Offset = offset,
                    OriginalreplacedetOffset = originalreplacedetOffset
                };

                newRemasteredHeaders.Add(newRemasteredreplacedetHeader);

                // Write replacedet header in the PKG stream
                BinaryMapping.WriteObject<EgsHdreplacedet.RemasteredEntry>(pkgStream, newRemasteredreplacedetHeader);

                // Don't write into the PKG stream yet as we need to write
                // all HD replacedets header juste after original file's data
                allRemasteredreplacedetsData.Write(replacedetData);

                // Make sure to align remastered replacedet data on 16 bytes
                if (replacedetData.Length % 0x10 != 0)
                {
                    allRemasteredreplacedetsData.Write(Enumerable.Repeat((byte)0xCD, 16 - (replacedetData.Length % 0x10)).ToArray());
                }

                offset += decompressedLength;
            }

            pkgStream.Write(originalreplacedetData);
            pkgStream.Write(allRemasteredreplacedetsData.ReadAllBytes());

            return newRemasteredHeaders;
        }

19 View Source File : ApiFlags.cs
License : MIT License
Project Creator : Archomeda

public virtual bool Equals(ApiFlags<T>? other) =>
            !(other is null) && this.List.SequenceEqual(other.List);

19 View Source File : ProtocolTestsAsync.cs
License : GNU Lesser General Public License v3.0
Project Creator : Apollo3zehn

[Fact]
        public async Task FC04Test()
        {
            // Arrange
            var endpoint = EndpointSource.GetNext();

            using var server = new ModbusTcpServer();
            server.Start(endpoint);

            void AsyncWorkaround()
            {
                var buffer = server.GetInputRegisterBuffer<float>();

                buffer[6] = 65.455F;
                buffer[7] = 24;
                buffer[8] = 25;
            }

            lock (server.Lock)
            {
                AsyncWorkaround();
            }

            var client = new ModbusTcpClient();
            client.Connect(endpoint);

            // Act
            var actual = await client.ReadInputRegistersAsync<float>(0, 2, 10);

            // replacedert
            var expected = _array;

            replacedert.True(expected.SequenceEqual(actual.ToArray()));
        }

19 View Source File : ProtocolTests.cs
License : GNU Lesser General Public License v3.0
Project Creator : Apollo3zehn

[Fact]
        public void FC16Test()
        {
            // Arrange
            var endpoint = EndpointSource.GetNext();

            using var server = new ModbusTcpServer();
            server.Start(endpoint);

            var client = new ModbusTcpClient();
            client.Connect(endpoint);

            // Act
            client.WriteMultipleRegisters(0, 2, _array);

            // replacedert
            var expected = _array;

            lock (server.Lock)
            {
                var actual = server.GetHoldingRegisterBuffer<float>().Slice(1, 10);
                replacedert.True(expected.SequenceEqual(actual.ToArray()));
            }
        }

19 View Source File : SemanticComparerTest.cs
License : MIT License
Project Creator : AutoFixture

[Fact]
        public void ComparersIsCorrectWhenInitializedWithArray()
        {
            // Fixture setup
            var expected = new[]
            {
                new DelegatingMemberComparer(),
                new DelegatingMemberComparer(),
                new DelegatingMemberComparer()
            };

            var sut = new SemanticComparer<string>(expected);
            // Exercise system
            var result = sut.Comparers;
            // Verify outcome
            replacedert.True(expected.SequenceEqual(result));
            // Teardown
        }

19 View Source File : GGPKContainer.cs
License : GNU Affero General Public License v3.0
Project Creator : aianlinb

public virtual BaseRecord GetRecord(long? offset = null)
        {
            if (offset.HasValue)
                fileStream.Seek(offset.Value, SeekOrigin.Begin);
            var length = Reader.ReadInt32();
            var tag = Reader.ReadBytes(4);
            if (tag.SequenceEqual(FileRecord.Tag))
                return new FileRecord(length, this);
            else if (tag.SequenceEqual(FreeRecord.Tag))
                return new FreeRecord(length, this);
            else if (tag.SequenceEqual(DirectoryRecord.Tag))
                return new DirectoryRecord(length, this);
            else if (tag.SequenceEqual(GGPKRecord.Tag))
                return new GGPKRecord(length, this);
            else
                throw new Exception("Invalid Record Tag: " + Encoding.ASCII.GetString(tag) + " at offset: " + (fileStream.Position - 8).ToString());
        }

19 View Source File : SemanticComparerTest.cs
License : MIT License
Project Creator : AutoFixture

[Fact]
        public void SutEqualsIdenticalWeakTypeSequence()
        {
            // Fixture setup
            var sut = new SemanticComparer<TimeSpan, TimeSpan>();

            var ticks = 8293247;

            var value = TimeSpan.FromTicks(ticks);
            var values = new object[] { value, value, value };

            object other = TimeSpan.FromTicks(ticks);
            object[] others = new object[] { other, other, other };

            // Exercise system
            var result = values.SequenceEqual(others, sut);
            // Verify outcome
            replacedert.True(result);
            // Teardown
        }

19 View Source File : ProtocolTests.cs
License : GNU Lesser General Public License v3.0
Project Creator : Apollo3zehn

[Fact]
        public void FC05Test()
        {
            // Arrange
            var endpoint = EndpointSource.GetNext();

            using var server = new ModbusTcpServer();
            server.Start(endpoint);

            var client = new ModbusTcpClient();
            client.Connect(endpoint);

            // Act
            client.WriteSingleCoil(0, 2, true);
            client.WriteSingleCoil(0, 7, true);
            client.WriteSingleCoil(0, 9, true);
            client.WriteSingleCoil(0, 26, true);

            // replacedert
            var expected = new byte[] { 132, 2, 0, 4 };

            lock (server.Lock)
            {
                var actual = server.GetCoilBuffer<byte>().Slice(0, 4);
                replacedert.True(expected.SequenceEqual(actual.ToArray()));
            }
        }

19 View Source File : MySQLDetailedTests.cs
License : MIT License
Project Creator : azist

[Run]
    public async Task ManyRowsInsertAndReadASYNC()
    {
      using (var ds = makeDataStore())
      {
        var patients = new List<Patient>();
        for (var i = 1; i < 2_000; i++)
        {
          var row = makePatient("Ivanov" + i);
          row.COUNTER = i;
          patients.Add(row);
          await ds.InsertAsync(row);
        }

        var qry = new Query<Patient>("CRUD.Queries.Patient.List") { new Query.Param("LN", "Ivanov%") };
        var result = (await ds.LoadEnumerableAsync(qry)).OrderBy(p => p.COUNTER);
        Aver.IsTrue(patients.Select(p => p.Last_Name).SequenceEqual(result.Select(r => r.Last_Name)));
      }
    }

19 View Source File : LexerTests.cs
License : MIT License
Project Creator : adamant

[Property(MaxTest = 1_000)]
        public Property Token_lexes()
        {
            return Prop.ForAll(Arbitrary.PsuedoToken(), token =>
            {
                var result = Lex(token.Text);
                var outputAsPsuedoTokens = result.ToPsuedoTokens();
                var expectedPsuedoTokens = token.Yield().Append(PsuedoToken.EndOfFile()).ToList();
                return expectedPsuedoTokens.SequenceEqual(outputAsPsuedoTokens)
                    .Label($"Actual:   {outputAsPsuedoTokens.DebugFormat()}")
                    .Label($"Expected: {expectedPsuedoTokens.DebugFormat()}")
                    .Collect(token.TokenType.Name);
            });
        }

19 View Source File : ValueAccessorTests.cs
License : MIT License
Project Creator : azist

[Run]
    public void IntArray()
    {
      Aver.IsTrue(new int[] { 1, 2, 3, 0b10, 0xFAcaca, 0xbb, -1_666_123_000 }.SequenceEqual(root.AttrByName("vIntArray").ValueAsIntArray()));
    }

19 View Source File : ProtocolTestsAsync.cs
License : GNU Lesser General Public License v3.0
Project Creator : Apollo3zehn

[Fact]
        public async Task FC03Test()
        {
            // Arrange
            var endpoint = EndpointSource.GetNext();

            using var server = new ModbusTcpServer();
            server.Start(endpoint);
            
            void AsyncWorkaround()
            {
                var buffer = server.GetHoldingRegisterBuffer<float>();

                buffer[6] = 65.455F;
                buffer[7] = 24;
                buffer[8] = 25;
            }

            lock (server.Lock)
            {
                AsyncWorkaround();
            }

            var client = new ModbusTcpClient();
            client.Connect(endpoint);

            // Act
            var actual = await client.ReadHoldingRegistersAsync<float>(0, 2, 10);

            // replacedert
            var expected = _array;

            replacedert.True(expected.SequenceEqual(actual.ToArray()));
        }

19 View Source File : ProtocolTestsAsync.cs
License : GNU Lesser General Public License v3.0
Project Creator : Apollo3zehn

[Fact]
        public async Task FC16Test()
        {
            // Arrange
            var endpoint = EndpointSource.GetNext();

            using var server = new ModbusTcpServer();
            server.Start(endpoint);

            var client = new ModbusTcpClient();
            client.Connect(endpoint);

            // Act
            await client.WriteMultipleRegistersAsync(0, 2, _array);

            // replacedert
            var expected = _array;

            lock (server.Lock)
            {
                var actual = server.GetHoldingRegisterBuffer<float>().Slice(1, 10).ToArray();
                replacedert.True(expected.SequenceEqual(actual));
            }
        }

19 View Source File : SearchAutomation.cs
License : MIT License
Project Creator : ADeltaX

private static async Task Download(string name, string version, EdgeFile fileElement, int numTries = 0)
        {
            if (numTries >= _numMaxDLAttempts)
                return;

            try
            {
                string filename = Path.Combine(DownloadFolder, fileElement.FileName);

                if (File.Exists(filename))
                {
                    byte[] fileHash = GetSHA1HashFile(filename);

                    //We already have this update, no need to download it again
                    if (fileHash.SequenceEqual(fileElement.Sha1))
                    {
                        Console.WriteLine($"[{DateTime.Now.ToString("MM/dd/yyyy HH:mm:ss")}] --- The file is already downloaded and valid, using this...");
                        return;
                    }
                    else
                    {
                        File.Delete(filename);
                    }
                }

                using (WebClient wb = new WebClient())
                {
                    await wb.DownloadFileTaskAsync(fileElement.Url, filename);
                    byte[] fileHash = GetSHA1HashFile(filename);

                    if (!fileHash.SequenceEqual(fileElement.Sha1))
                    {
                        if (File.Exists(filename))
                            File.Delete(filename);

                        throw new DataMisalignedException("Rip SHA1 hash");
                    }
                }
            }
            catch (Exception ex)
            {
                var errorMessageIter = ex.Message;

                var currException = ex;

                while ((currException = currException.InnerException) != null)
                    errorMessageIter += "\n\nINNER EXCEPTION: " + currException.Message;

                SharedDBcmd.TraceError($"Internal error: {errorMessageIter}");

                Console.WriteLine("[ERROR] Failed downloading... retrying...");

                //Generate a new link.... just in case
                var res = await _edgeUpdate.GetFiles(name, version);

                if (res.Success)
                {
                    var edgeFileFull = res.Value.EdgeFile.Where(file => file.EdgeFileUpdateType == EdgeFileUpdateType.Full).First();
                    await Download(name, version, edgeFileFull, ++numTries);
                }
                else
                {
                    await Download(name, version, fileElement, ++numTries);
                }
            }
        }

19 View Source File : ProtocolTestsAsync.cs
License : GNU Lesser General Public License v3.0
Project Creator : Apollo3zehn

[Fact]
        public async Task FC02Test()
        {
            // Arrange
            var endpoint = EndpointSource.GetNext();

            using var server = new ModbusTcpServer();
            server.Start(endpoint);

            void AsyncWorkaround()
            {
                var buffer = server.GetDiscreteInputBuffer<byte>();

                buffer[1] = 9;
                buffer[2] = 0;
                buffer[3] = 24;
            }

            lock (server.Lock)
            {
                AsyncWorkaround();
            }

            var client = new ModbusTcpClient();
            client.Connect(endpoint);

            // Act
            var actual = await client.ReadDiscreteInputsAsync(0, 8, 25);

            // replacedert
            var expected = new byte[] { 9, 0, 24, 0 };

            replacedert.True(expected.SequenceEqual(actual.ToArray()));
        }

19 View Source File : LineFormatterTest.cs
License : MIT License
Project Creator : ap0llo

[Theory]
        [InlineData(5, "abcde", new[] { "abcde" })]
        [InlineData(5, "abcde fgh", new[] { "abcde", "fgh" })]
        [InlineData(5, "ab de fgh", new[] { "ab de", "fgh" })]
        [InlineData(5, "abcdefgh", new[] { "abcdefgh" })]
        [InlineData(5, "abcdefgh ijk", new[] { "abcdefgh", "ijk" })]
        [InlineData(5, "abc defgh ijk", new[] { "abc", "defgh", "ijk" })]
        [InlineData(5, "abc def  ijk", new[] { "abc", "def", "ijk" })]
        [InlineData(80, "abc def ijk", new[] { "abc def ijk" })]
        public void Line_is_split_as_expected(int lineLength, string input, string[] expectedResult)
        {
            var actualResult = LineFormatter.GetLines(input, lineLength);

            if (!expectedResult.SequenceEqual(actualResult))
            {
                throw new XunitException("SequenceEqual failure:\r\n" +
                    $"Expected: {expectedResult.Select(x => $"\"{x}\"").JoinToString(", ")}\r\n" +
                    $"Actual:   {actualResult.Select(x => $"\"{x}\"").JoinToString(", ")}");
            }
        }

19 View Source File : ProtocolTestsAsync.cs
License : GNU Lesser General Public License v3.0
Project Creator : Apollo3zehn

[Fact]
        public async Task FC023Test()
        {
            // Arrange
            var endpoint = EndpointSource.GetNext();

            using var server = new ModbusTcpServer();
            server.Start(endpoint);

            void AsyncWorkaround()
            {
                var buffer = server.GetHoldingRegisterBuffer<float>();

                buffer[6] = 65.455F;
                buffer[7] = 24;
                buffer[8] = 25;
            }

            lock (server.Lock)
            {
                AsyncWorkaround();
            }

            var client = new ModbusTcpClient();
            client.Connect(endpoint);

            // Act
            var actual1 = await client.ReadWriteMultipleRegistersAsync<float, float>(0, 2, 10, 12, new float[] { 1.211F });

            // replacedert
            var expected = new float[] { 0, 0, 0, 0, 0, 1.211F, 24, 25, 0, 0 };

            replacedert.True(expected.SequenceEqual(actual1.ToArray()));

            lock (server.Lock)
            {
                var actual2 = server.GetHoldingRegisterBuffer<float>().Slice(1, 10).ToArray();
                replacedert.True(expected.SequenceEqual(actual2));
            }
        }

19 View Source File : ProtocolTestsAsync.cs
License : GNU Lesser General Public License v3.0
Project Creator : Apollo3zehn

[Fact]
        public async Task FC05Test()
        {
            // Arrange
            var endpoint = EndpointSource.GetNext();

            using var server = new ModbusTcpServer();
            server.Start(endpoint);

            var client = new ModbusTcpClient();
            client.Connect(endpoint);

            // Act
            await client.WriteSingleCoilAsync(0, 2, true);
            await client.WriteSingleCoilAsync(0, 7, true);
            await client.WriteSingleCoilAsync(0, 9, true);
            await client.WriteSingleCoilAsync(0, 26, true);

            // replacedert
            var expected = new byte[] { 132, 2, 0, 4 };

            lock (server.Lock)
            {
                var actual = server.GetCoilBuffer<byte>().Slice(0, 4).ToArray();
                replacedert.True(expected.SequenceEqual(actual));
            }
        }

19 View Source File : ProtocolTests.cs
License : GNU Lesser General Public License v3.0
Project Creator : Apollo3zehn

[Fact]
        public void FC03Test()
        {
            // Arrange
            var endpoint = EndpointSource.GetNext();

            using var server = new ModbusTcpServer();
            server.Start(endpoint);
            
            lock (server.Lock)
            {
                var buffer = server.GetHoldingRegisterBuffer<float>();

                buffer[6] = 65.455F;
                buffer[7] = 24;
                buffer[8] = 25;
            }

            var client = new ModbusTcpClient();
            client.Connect(endpoint);

            // Act
            var actual = client.ReadHoldingRegisters<float>(0, 2, 10);

            // replacedert
            var expected = _array;

            replacedert.True(expected.SequenceEqual(actual.ToArray()));
        }

19 View Source File : DictionaryTableDefinitionNode.cs
License : MIT License
Project Creator : areller

public override bool Equals(ExpressionNode other)
        {
            if (!(other is DictionaryTableDefinitionNode)) return false;
            var dict = (DictionaryTableDefinitionNode) other;
            if (Elements is null && dict.Elements is null)
                return true;
            else if ((Elements is null && !(dict.Elements is null)) || (!(Elements is null) && dict.Elements is null))
                return false;
            else
                return Elements.SequenceEqual(dict.Elements,
                    new KeyValuePairEqualityComparer<ExpressionNode, ExpressionNode>());
        }

19 View Source File : GGPKContainer.cs
License : GNU Affero General Public License v3.0
Project Creator : aianlinb

public virtual BaseRecord GetRecord(long? offset = null) {
            if (offset.HasValue)
                FileStream.Seek(offset.Value, SeekOrigin.Begin);
            var length = Reader.ReadInt32();
            var tag = Reader.ReadBytes(4);
            if (tag.SequenceEqual(FileRecord.Tag))
                return new FileRecord(length, this);
            else if (tag.SequenceEqual(DirectoryRecord.Tag))
                return new DirectoryRecord(length, this);
            else if (tag.SequenceEqual(FreeRecord.Tag))
                return new FreeRecord(length, this);
            else if (tag.SequenceEqual(GGPKRecord.Tag))
                return new GGPKRecord(length, this);
            else
                throw new Exception("Invalid Record Tag: " + Encoding.UTF8.GetString(tag) + " at offset: " + (FileStream.Position - 8).ToString());
        }

19 View Source File : SemanticComparerTest.cs
License : MIT License
Project Creator : AutoFixture

[Fact]
        public void ComparersIsCorrectWhenInitializedWithDefaultConstructor()
        {
            // Fixture setup
            var expected = new[]
            {
                new MemberComparer(new SemanticComparer<TimeSpan, TimeSpan>())
            };
            var sut = new SemanticComparer<TimeSpan>();
            // Exercise system
            var result = sut.Comparers.Cast<MemberComparer>();
            // Verify outcome
            replacedert.True(expected.SequenceEqual(result, new MemberComparerComparer()));
            // Teardown
        }

19 View Source File : ProtocolTests.cs
License : GNU Lesser General Public License v3.0
Project Creator : Apollo3zehn

[Fact]
        public void FC01Test()
        {
            // Arrange
            var endpoint = EndpointSource.GetNext();

            using var server = new ModbusTcpServer();
            server.Start(endpoint);

            lock (server.Lock)
            {
                var buffer = server.GetCoilBuffer<byte>();

                buffer[1] = 9;
                buffer[2] = 0;
                buffer[3] = 24;
            }

            var client = new ModbusTcpClient();
            client.Connect(endpoint);

            // Act
            var actual = client.ReadCoils(0, 8, 25);

            // replacedert
            var expected = new byte[] { 9, 0, 24, 0 };

            replacedert.True(expected.SequenceEqual(actual.ToArray()));
        }

19 View Source File : SemanticComparerTest.cs
License : MIT License
Project Creator : AutoFixture

[Fact]
        public void ComparersIsCorrectWhenInitializedWithEnumerable()
        {
            // Fixture setup
            var expected = new[]
            {
                new DelegatingMemberComparer(),
                new DelegatingMemberComparer(),
                new DelegatingMemberComparer()
            }.ToList();

            var sut = new SemanticComparer<string>(expected);
            // Exercise system
            var result = sut.Comparers;
            // Verify outcome
            replacedert.True(expected.SequenceEqual(result));
            // Teardown
        }

19 View Source File : FixedList.cs
License : MIT License
Project Creator : adamant

public bool Equals(FixedList<T>? other)
        {
            return other != null && Count == other.Count && items.SequenceEqual(other.items);
        }

19 View Source File : SemanticComparerTest.cs
License : MIT License
Project Creator : AutoFixture

[Fact]
        public void SutEqualsIdenticalStrongTypeSequence()
        {
            // Fixture setup
            var sut = new SemanticComparer<TimeSpan, TimeSpan>();
            
            var ticks = 8293247;

            var value = TimeSpan.FromTicks(ticks);
            var values = new object[] { value, value, value };
            
            var other = TimeSpan.FromTicks(ticks);
            var others = new object[] { other, other, other };
            
            // Exercise system
            var result = values.SequenceEqual(others, sut);
            // Verify outcome
            replacedert.True(result);
            // Teardown
        }

19 View Source File : ProtocolTests.cs
License : GNU Lesser General Public License v3.0
Project Creator : Apollo3zehn

[Fact]
        public void FC04Test()
        {
            // Arrange
            var endpoint = EndpointSource.GetNext();

            using var server = new ModbusTcpServer();
            server.Start(endpoint);

            lock (server.Lock)
            {
                var buffer = server.GetInputRegisterBuffer<float>();

                buffer[6] = 65.455F;
                buffer[7] = 24;
                buffer[8] = 25;
            }

            var client = new ModbusTcpClient();
            client.Connect(endpoint);

            // Act
            var actual = client.ReadInputRegisters<float>(0, 2, 10);

            // replacedert
            var expected = _array;

            replacedert.True(expected.SequenceEqual(actual.ToArray()));
        }

19 View Source File : BigIntegerExtensionsTests.cs
License : Apache License 2.0
Project Creator : aws

private void TestFromBigEndianPositive(int number, byte[] expectedBigEndianByteArray, int expectedFromBigEndianPositvie)
        {
            var biNumber = new BigInteger(number);
            var bigEndianByteArray = biNumber.ToBigEndianByteArray();
            var biFromBigEndianPositive = BigIntegerExtensions.FromUnsignedBigEndian(bigEndianByteArray);

            replacedert.True(expectedBigEndianByteArray.SequenceEqual(bigEndianByteArray));
            replacedert.Equal(expectedFromBigEndianPositvie, biFromBigEndianPositive);
        }

19 View Source File : Wallet.cs
License : Apache License 2.0
Project Creator : ajuna-network

public async Task<bool> UnlockAsync(string preplacedword, bool noCheck = false)
        {
            if (IsUnlocked || !IsCreated)
            {
                Logger.Warn("Wallet is already unlocked or doesn't exist.");
                return IsUnlocked && IsCreated;
            }

            Logger.Info("Unlock new wallet.");

            try
            {
                var pswBytes = Encoding.UTF8.GetBytes(preplacedword);

                pswBytes = SHA256.Create().ComputeHash(pswBytes);

                var seed = ManagedAes.DecryptStringFromBytes_Aes(_walletFile.EncryptedSeed, pswBytes, _walletFile.Salt);

                byte[] publicKey = null;
                byte[] privateKey = null;
                switch (_walletFile.KeyType)
                {
                    case KeyType.Ed25519:
                        Ed25519.KeyPairFromSeed(out publicKey, out privateKey, Utils.HexToByteArray(seed));
                        break;
                    case KeyType.Sr25519:
                        var miniSecret = new MiniSecret(Utils.HexToByteArray(seed), ExpandMode.Ed25519);
                        var getPair = miniSecret.GetPair();
                        privateKey = getPair.Secret.ToBytes();
                        publicKey = getPair.Public.Key;
                        break;
                }

                if (noCheck || !publicKey.SequenceEqual(_walletFile.PublicKey))
                    throw new Exception("Public key check failed!");

                Account = Account.Build(_walletFile.KeyType, privateKey, publicKey);
            }
            catch (Exception exception)
            {
                Logger.Warn($"Couldn't unlock the wallet with this preplacedword. {exception}");
                return false;
            }


            if (IsOnline) _subscriptionAccountInfo = await SubscribeAccountInfoAsync();

            return true;
        }

19 View Source File : Aver.cs
License : MIT License
Project Creator : azist

public static bool AreArraysEquivalentTest(Array expect, Array got, IEqualityComparer<object> comparer = null)
    {
      if (expect==null && got==null) return true;
      if (expect==null || got==null) return false;

      if (expect.Length!=got.Length) return false;

      if (comparer==null)
        return expect.Cast<object>().SequenceEqual(got.Cast<object>());

      return expect.Cast<object>().SequenceEqual(got.Cast<object>(), comparer);
    }

19 View Source File : ProtocolTests.cs
License : GNU Lesser General Public License v3.0
Project Creator : Apollo3zehn

[Fact]
        public void FC06Test()
        {
            // Arrange
            var endpoint = EndpointSource.GetNext();

            using var server = new ModbusTcpServer();
            server.Start(endpoint);

            var client = new ModbusTcpClient();
            client.Connect(endpoint);

            // Act
            client.WriteSingleRegister(0, 02, 259);
            client.WriteSingleRegister(0, 10, 125);
            client.WriteSingleRegister(0, 11, 16544);
            client.WriteSingleRegister(0, 12, 4848);

            // replacedert
            var expected = new short[] { 0, 0, 259, 0, 0, 0, 0, 0, 0, 0, 125, 16544, 4848 };

            lock (server.Lock)
            {
                var actual = server.GetHoldingRegisterBuffer<short>().Slice(0, 13);
                replacedert.True(expected.SequenceEqual(actual.ToArray()));
            }
        }

19 View Source File : MySQLDetailedTests.cs
License : MIT License
Project Creator : azist

[Run]
    public async Task ManyRowsInsertAndReadASYNC2()
    {
      using (var ds = makeDataStore())
      {
        var patients = new List<Patient>();
        var pending = new List<Task>();
        for (var i = 1; i < 2_000; i++)
        {
          var row = makePatient("Ivanov" + i);
          row.COUNTER = i;
          patients.Add(row);
          pending.Add(ds.InsertAsync(row));//note: No await here
        }

        await Task.WhenAll(pending);

        var qry = new Query<Patient>("CRUD.Queries.Patient.List") { new Query.Param("LN", "Ivanov%") };
        var result = (await ds.LoadEnumerableAsync(qry)).OrderBy(p => p.COUNTER);
        Aver.IsTrue(patients.Select(p => p.Last_Name).SequenceEqual(result.Select(r => r.Last_Name)));
      }
    }

19 View Source File : TestAmf0Reader.cs
License : MIT License
Project Creator : a1q123456

[TestMethod]
        public void TestReadArray()
        {
            var reader = new Amf0Reader();


            using (var f = new FileStream("../../../../samples/amf0/misc/array.amf0", FileMode.Open))
            {
                var data = new byte[f.Length];
                f.Read(data);
                var arrayData = new List<object> { 1.0d, 2.0d, 3.0d, 4.0d, "a", "asdf", "eee" };
                replacedert.IsTrue(reader.TryGetStrictArray(data, out var dataRead, out var consumed));
                replacedert.IsTrue(arrayData.SequenceEqual(dataRead));
                replacedert.AreEqual(consumed, data.Length);
            }
        }

19 View Source File : ValueAccessorTests.cs
License : MIT License
Project Creator : azist

[Run]
    public void ByteArray2()
    {
      Aver.IsTrue(new byte[] { 0xFA, 0x12, 0b1010 }.SequenceEqual(root.AttrByName("vBuffer2").ValueAsByteArray()));
    }

19 View Source File : ProtocolTests.cs
License : GNU Lesser General Public License v3.0
Project Creator : Apollo3zehn

[Fact] 
        public void HandlesBigEndian()
        {
            // Arrange
            var endpoint = EndpointSource.GetNext();

            using var server = new ModbusTcpServer();
            server.Start(endpoint);

            var client = new ModbusTcpClient();
            client.Connect(endpoint, ModbusEndianness.BigEndian);

            // Act
            client.WriteMultipleRegisters(0, 0, new int[] { 0x20302020, 0x40101010, 0x11220000 });

            // replacedert
            var expected = new int[] { 0x20203020, 0x10101040, 0x00002211 };

            lock (server.Lock)
            {
                var actual = server.GetHoldingRegisterBuffer<int>().Slice(0, 3);
                replacedert.True(expected.SequenceEqual(actual.ToArray()));
            }
        }

19 View Source File : UpdateScenesUseCase.cs
License : Apache License 2.0
Project Creator : Anapher

private static bool VerifySceneState(SceneState state, IReadOnlyList<IScene> availableScenes)
        {
            var (stack, savedAvailableScenes) = state;
            return stack.All(availableScenes.Contains) && availableScenes.SequenceEqual(savedAvailableScenes);
        }

19 View Source File : ExpressionTree.cs
License : MIT License
Project Creator : 71

public static bool Match(this IEnumerable<Expression> expressions, IEnumerable<Expression> second)
        {
            return expressions.SequenceEqual(second, new Comparer());
        }

19 View Source File : TestAmf3Writer.cs
License : MIT License
Project Creator : a1q123456

[TestMethod]
        public void TestByteArray()
        {
            var reader = new Amf3Reader();
            var writer = new Amf3Writer();

            using (var sc = new SerializationContext())
            {
                var arr = new byte[] { 1, 2, 3 };
                writer.WriteBytes(arr, sc);

                var buffer = new byte[sc.MessageLength];
                sc.GetMessage(buffer);

                replacedert.IsTrue(reader.TryGetByteArray(buffer, out var readVal, out var consumed));
                replacedert.IsTrue(arr.SequenceEqual(readVal));
                replacedert.AreEqual(buffer.Length, consumed);
            }

        }

19 View Source File : MapItem.cs
License : GNU General Public License v3.0
Project Creator : AHeroicLlama

public bool GetLockRelevant()
		{
			return
				type == Type.Standard &&
				lockableTypes.Contains(signature) &&
				!filteredLockTypes.OrderBy(e => e).SequenceEqual(DataHelper.GetPermittedLockTypes());
		}

19 View Source File : LineFormatterTest.cs
License : MIT License
Project Creator : ap0llo

[Theory]
        [InlineData("abcde", new[] { "abcde" })]
        [InlineData("abcde fgh", new[] { "abcde", " ", "fgh" })]
        [InlineData("ab  de fgh", new[] { "ab", "  ", "de", " ", "fgh" })]
        [InlineData("  abc", new[] { "  ", "abc" })]
        [InlineData("abc  ", new[] { "abc", "  " })]
        [InlineData("  abc  ", new[] { "  ", "abc", "  " })]
        [InlineData("", new string[0])]
        public void GetStringSegments_returns_the_expected_segments(string input, string[] expectedSegments)
        {
            var actualSegments = LineFormatter.GetStringSegments(input).Select(x => x.value).ToArray();
            if (!expectedSegments.SequenceEqual(actualSegments))
            {
                throw new XunitException("SequenceEqual failure:\r\n" +
                    $"Expected: {expectedSegments.Select(x => $"\"{x}\"").JoinToString(", ")}\r\n" +
                    $"Actual:   {actualSegments.Select(x => $"\"{x}\"").JoinToString(", ")}");
            }
        }

19 View Source File : ProtocolTestsAsync.cs
License : GNU Lesser General Public License v3.0
Project Creator : Apollo3zehn

[Fact]
        public async Task FC06Test()
        {
            // Arrange
            var endpoint = EndpointSource.GetNext();

            using var server = new ModbusTcpServer();
            server.Start(endpoint);

            var client = new ModbusTcpClient();
            client.Connect(endpoint);

            // Act
            await client.WriteSingleRegisterAsync(0, 02, 259);
            await client.WriteSingleRegisterAsync(0, 10, 125);
            await client.WriteSingleRegisterAsync(0, 11, 16544);
            await client.WriteSingleRegisterAsync(0, 12, 4848);

            // replacedert
            var expected = new short[] { 0, 0, 259, 0, 0, 0, 0, 0, 0, 0, 125, 16544, 4848 };

            lock (server.Lock)
            {
                var actual = server.GetHoldingRegisterBuffer<short>().Slice(0, 13).ToArray();
                replacedert.True(expected.SequenceEqual(actual));
            }
        }

See More Examples