Beispiel #1
0
        public byte[] GetFile(string serverKey, string hardwareKey, string filePath, string fileType, long chunkOffset, long chuckSize, string version)
        {


            if (fileType == "layout")
            {

                var bytes = File.ReadAllBytes(AppPath + filePath);

                return bytes;
                //var text = File.ReadAllText(AppPath + filePath);
                //return text.Select(f => (byte)(f)).ToArray();
                //using (var stream = new StreamReader(HttpContext.Current.Server.MapPath("~/Media/" + filePath)))//return actual byte stream

                //{



                //    var allbytes = stream.ReadToEnd().Select(f=> (byte)(f)).ToArray();

                //    return allbytes;

                //}

            }

            else
            {


                try
                {


                    using (var stream = new FileStream((System.Web.Hosting.HostingEnvironment.ApplicationPhysicalPath + ServerPath + filePath), FileMode.OpenOrCreate, FileAccess.Read, FileShare.ReadWrite))//return actual byte stream
                    {

                        stream.Seek(chunkOffset, SeekOrigin.Begin);



                        Byte[] documentcontents = new Byte[chuckSize];

                        int actual = stream.Read(documentcontents, 0, (int)chuckSize);



                        return documentcontents.Take(actual).ToArray();

                    }
                }
                catch (Exception)
                {

                    return new byte[0];
                }

            }

        }
 public static Byte[] KeyDer(Byte[] key)
 {
     if (key.Length == 16)
         return key;
     else
         return key.Take(16).ToArray();
 }
 static void OnRead(List<Byte> queue, Byte[] buffer, int count)
 {
     lock (((ICollection)queue).SyncRoot)
     {
         queue.AddRange(buffer.Take(count));
     }
 }
Beispiel #4
0
 public static Byte[] ReadAll(this Stream stream, Int32 bufferSize)
 {
     IEnumerable<Byte> ret = Enumerable.Empty<Byte>();
     Byte[] buffer = new Byte[bufferSize];
     for (Int32 length; (length = stream.Read(buffer, 0, bufferSize)) != 0; )
     {
         ret = ret.Concat(buffer.Take(length).ToArray());
         if (length < bufferSize)
         {
             break;
         }
     }
     return ret.ToArray();
 }
Beispiel #5
0
        //Метод потока
        protected void FileReceiver()
        {
            //Создаем Listener на порт "по умолчанию"
            TcpListener Listen = new TcpListener(6999);
            //Начинаем прослушку
            Listen.Start();
            //и заведем заранее сокет
            Socket ReceiveSocket;
            while (true)
            {
                try
                {
                    //Пришло сообщение
                    ReceiveSocket = Listen.AcceptSocket();
                    Byte[] Receive = new Byte[256];
                    //Читать сообщение будем в поток
                    using (MemoryStream MessageR = new MemoryStream())
                    {
                        
                        //Количество считанных байт
                        Int32 ReceivedBytes;
                        Int32 Firest256Bytes = 0;
                        String FilePath = "";
                        do
                        {//Собственно читаем
                            ReceivedBytes = ReceiveSocket.Receive(Receive, Receive.Length, 0);
                            //Разбираем первые 256 байт
                            if (Firest256Bytes < 256) 
                            {
                                Firest256Bytes += ReceivedBytes;
                                Byte[] ToStr = Receive;
                                //Учтем, что может возникнуть ситуация, когда они не могу передаться "сразу" все
                                if (Firest256Bytes > 256)
                                {
                                    Int32 Start = Firest256Bytes - ReceivedBytes;
                                    Int32 CountToGet = 256 - Start;
                                    Firest256Bytes = 256;
                                    //В случае если было принято >256 байт (двумя сообщениями к примеру)
                                    //Остаток (до 256) записываем в "путь файла"
                                    ToStr = Receive.Take(CountToGet).ToArray();
                                    //А остальную часть - в будующий файл
                                    Receive = Receive.Skip(CountToGet).ToArray();
                                    MessageR.Write(Receive, 0, ReceivedBytes);
                                }
                                //Накапливаем имя файла
                                FilePath += Encoding.Default.GetString(ToStr);
                            } else

                            //и записываем в поток
                            MessageR.Write(Receive, 0, ReceivedBytes);
                            //Читаем до тех пор, пока в очереди не останется данных
                        } while (ReceivedBytes == Receive.Length);
                        //Убираем лишние байты
                        String resFilePath = FilePath.Substring(0, FilePath.IndexOf('\0'));
                        using (var File = new FileStream(resFilePath, FileMode.Create))
                        {//Записываем в файл
                            File.Write(MessageR.ToArray(), 0, MessageR.ToArray().Length);
                        }//Уведомим пользователя
                        ChatBox.BeginInvoke(AcceptDelegate, new object[] { "Received: " + resFilePath, ChatBox });
                    }
                }
                catch (System.Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }

            }
        }
Beispiel #6
0
        private Boolean CheckSig(Byte[] sig, PublicKey pubKey, UInt32 txInIndex, Script subScript, Transaction tx)
        {
            HashType hashType = (HashType)sig.Last();
            sig = sig.Take(sig.Length - 1).ToArray();

            Transaction txCopy = tx.CopyForSigning(txInIndex, subScript, hashType);

            Byte[] txHash = txCopy.ToBytes().Concat(new Byte[] { (Byte)hashType, 0x00, 0x00, 0x00 }).ToArray();
            txHash = sha256.ComputeHash(sha256.ComputeHash(txHash));

            return pubKey.VerifySignature(txHash, sig);
        }
Beispiel #7
0
        /// <summary>
        /// Derive Key Bytes using PBKDF2 specification listed in Rfc2898 and HMACSHA512 as the underlying PRF (Psuedo Random Function)
        /// </summary>
        /// <param name="keyLength">Length in Bytes of Derived Key</param>
        /// <returns>Derived Key</returns>
        public Byte[] GetDerivedKeyBytes_PBKDF2_HMACSHA512(Int32 keyLength)
        {
            //no need to throw exception for dkLen too long as per spec because dkLen cannot be larger than Int32.MaxValue so not worth the overhead to check
            dkLen = keyLength;

            Double l = Math.Ceiling((Double)dkLen / hLen);

            Byte[] finalBlock = new Byte[0];

            for (Int32 i = 1; i <= l; i++)
            {
                //Concatenate each block from F into the final block (T_1..T_l)
                finalBlock = pMergeByteArrays(finalBlock, F(P, S, c, i));
            }

            //returning DK note r not used as dkLen bytes of the final concatenated block returned rather than <0...r-1> substring of final intermediate block + prior blocks as per spec
            return finalBlock.Take(dkLen).ToArray();
        }
Beispiel #8
0
        //Метод потока
        protected void FileReceiver()
        {
            //Создаем Listener на порт "по умолчанию"
            TcpListener Listen = new TcpListener(Int32.Parse(PORT.Text));
            //и заведем заранее сокет
            Socket ReceiveSocket;
            try
            {
                //Начинаем прослушку
                Listen.Start();
            }
            catch (System.Exception ex)
            {
                MessageBox.Show(ex.Message);
            }

            while (true)
            {
                try
                {
                    //Пришло сообщение
                    ReceiveSocket = Listen.AcceptSocket();
                    Byte[] Receive = new Byte[QuantityByteInStep];
                    //Читать сообщение будем в поток
                    using (MemoryStream MessageR = new MemoryStream())
                    {

                        //Количество считанных байт
                        Int32 ReceivedBytes;
                        Int32 FirestQuantityByteInStepBytes = 0;
                        String FilePath = "";
                        //Если true, то первые QuantityByteInStep прочитаны
                        bool firstBytes = false;

                        string resFilePath = "";
                        string resFileSize = "";

                        do
                        {//Собственно читаем
                            ReceivedBytes = ReceiveSocket.Receive(Receive, Receive.Length, 0);
                            //Разбираем первые QuantityByteInStep байт
                            if (FirestQuantityByteInStepBytes < QuantityByteInStep)
                            {
                                FirestQuantityByteInStepBytes += ReceivedBytes;
                                Byte[] ToStr = Receive;
                                //Учтем, что может возникнуть ситуация, когда они не могу передаться "сразу" все
                                if (FirestQuantityByteInStepBytes > QuantityByteInStep)
                                {
                                    Int32 Start = FirestQuantityByteInStepBytes - ReceivedBytes;
                                    Int32 CountToGet = QuantityByteInStep - Start;
                                    FirestQuantityByteInStepBytes = QuantityByteInStep;
                                    //В случае если было принято >QuantityByteInStep байт (двумя сообщениями к примеру)
                                    //Остаток (до QuantityByteInStep) записываем в "путь файла"
                                    ToStr = Receive.Take(CountToGet).ToArray();
                                    //А остальную часть - в будующий файл
                                    Receive = Receive.Skip(CountToGet).ToArray();
                                    MessageR.Write(Receive, 0, ReceivedBytes);
                                    firstBytes = true;
                                }
                                //Накапливаем имя файла
                                FilePath += Encoding.Default.GetString(ToStr);

                            }
                            else
                            {
                                if (firstBytes || FirestQuantityByteInStepBytes == QuantityByteInStep)
                                {
                                    //Уже можем прочитать имя и разме рфайла
                                    //Убираем лишние байты
                                    String resFilePathAndFileSize = FilePath.Substring(0, FilePath.IndexOf('\0'));
                                    char[] separators = { '^' };
                                    string[] words = resFilePathAndFileSize.Split(separators);
                                    resFilePath = words[0];
                                    resFileSize = words[1];
                                    firstBytes = false;
                                    FirestQuantityByteInStepBytes = QuantityByteInStep + 1;
                                    ChatBox.BeginInvoke(AcceptDelegate, new object[] { "Началось принятие файла. " + resFilePath, ChatBox });
                                }
                                //и записываем в поток
                                MessageR.Write(Receive, 0, ReceivedBytes);
                            }
                            //Читаем до тех пор, пока в очереди не останется данных
                        } while (ReceivedBytes > 0);

                        string tempFilePath;
                        if (filePath != "")
                        {
                            tempFilePath = filePath + "//" + resFilePath;
                        }
                        else
                        {
                            tempFilePath = resFilePath;
                        }

                        using (var File = new FileStream(tempFilePath, FileMode.Create))
                        {
                            //Записываем в файл
                            File.Write(MessageR.ToArray(), 0, MessageR.ToArray().Length);

                            //Уведомляем об этом
                            ChatBox.BeginInvoke(AcceptDelegate, new object[] { "Файл принят. " + File.Name, ChatBox });
                        }

                    }
                }
                catch (System.Exception ex)
                {
                    MessageBox.Show(ex.Message);
                    break;
                }
            }
        }
Beispiel #9
0
 /// <summary>
 /// Восстанавливает CAN-сообщение из буфера АППИ
 /// </summary>
 /// <param name="Buff">10 байт буфера</param>
 public static CanFrame FromBufferBytes(Byte[] Buff)
 {
     int id = (int)BitConverter.ToUInt16(Buff.Take(2).Reverse().ToArray(), 0) >> 4;
     int len = Buff[1] & 0x0f;
     if (len > 8) throw new AppiBufferDecodeException("Расшифрована неправильная длина CAN-сообщения ({0} байт)", len);
     return CanFrame.NewWithId(id, Buff, 2, len);
 }
        internal byte[] CreateTextBlock( int Size )
        {
            UInt32 TextLocationRelative = Header.TextLocation - Header.TextOffsetsLocation;

            Byte[] bytes = new Byte[Size];

            TextEntries.Sort();

            UInt16 CurrentTextOffset = 0;
            foreach ( LuxPainEvtText t in TextEntries ) {
                byte[] CurrentTextOffsetBytes = BitConverter.GetBytes( (UInt16)( CurrentTextOffset ) );
                CurrentTextOffsetBytes.CopyTo( bytes, t.OffsetLocation - Header.TextOffsetsLocation );

                byte[] text = LuxPainUtil.BackConvertLuxPainText( t.Text );
                text.CopyTo( bytes, TextLocationRelative );

                TextLocationRelative += (uint)text.Length;
                CurrentTextOffset += (ushort)( text.Length / 2 );
            }

            return bytes.Take( (int)TextLocationRelative ).ToArray();
        }
Beispiel #11
0
        public unsafe String Decode(Byte* start, Byte* end)
        {
            var current = start;
            var buffer = new Byte[end - current];
            Int32 index = 0;
            Byte* rfc2047Start = null;
            Byte* rfc2047Current = null;
            Rfc2047ParsingState state = Rfc2047ParsingState.NotPasing;
            Encoding charset = null;
            Rfc2047Encoding? encoding = null;
            Int32 whiteSpaceCount = 0;
            StringBuilder sb = new StringBuilder(buffer.Length);

            while (current < end)
            {
                switch (state)
                {
                    case Rfc2047ParsingState.NotPasing:
                        #region
                        if (*current == '=')
                        {
                            state = Rfc2047ParsingState.Start;
                            rfc2047Start = current;
                        }
                        break;
                        #endregion
                    case Rfc2047ParsingState.Start:
                        #region
                        if (*current == '?')
                        {
                            state = Rfc2047ParsingState.Charset;
                            rfc2047Current = current + 1;
                        }
                        else
                        {
                            state = Rfc2047ParsingState.NotPasing;
                        }
                        break;
                        #endregion
                    case Rfc2047ParsingState.Charset:
                        #region
                        if (*current == '?')
                        {
                            var bb = CreateNewBytes(new IntPtr(rfc2047Current), current - rfc2047Current);
                            charset = EncodingDictionary.Current.GetEncoding(this.Encoding.GetString(bb));
                            if (charset == null)
                            {
                                state = Rfc2047ParsingState.NotPasing;
                                rfc2047Current = null;
                            }
                            else
                            {
                                state = Rfc2047ParsingState.BorQ;
                                rfc2047Current = current + 1;
                            }
                        }
                        break;
                        #endregion
                    case Rfc2047ParsingState.BorQ:
                        #region
                        if (*current == '?')
                        {
                            var bb = CreateNewBytes(new IntPtr(rfc2047Current), current - rfc2047Current);
                            var BorQ = this.Encoding.GetString(bb).ToUpper();
                            if (BorQ == "B" || BorQ == "Q")
                            {
                                switch (BorQ)
                                {
                                    case "B": encoding = Rfc2047Encoding.Base64; break;
                                    case "Q": encoding = Rfc2047Encoding.QuotedPrintable; break;
                                    default: throw new InvalidOperationException();
                                }
                                state = Rfc2047ParsingState.Value;
                                rfc2047Current = current + 1;
                            }
                            else
                            {
                                state = Rfc2047ParsingState.NotPasing;
                                rfc2047Current = null;
                            }
                        }
                        break;
                        #endregion
                    case Rfc2047ParsingState.Value:
                        #region
                        if (*current == '?')
                        {
                            state = Rfc2047ParsingState.ValueEnd;
                        }
                        break;
                        #endregion
                    case Rfc2047ParsingState.ValueEnd:
                        #region
                        if (*current == '=')
                        {
                            sb.Append(this.Encoding.GetString(buffer.Take(index).ToArray()));
                            index = 0;

                            var bb = CreateNewBytes(new IntPtr(rfc2047Current), current - rfc2047Current - 1);
                            switch (encoding)
                            {
                                case Rfc2047Encoding.Base64: sb.Append(charset.GetString(_Base64Converter.Decode(bb))); break;
                                case Rfc2047Encoding.QuotedPrintable: sb.Append(charset.GetString(_QuotedPrintableHeaderConverter.Decode(bb))); break;
                                default: throw new InvalidOperationException();
                            }
                            rfc2047Start = null;
                            rfc2047Current = null;
                            whiteSpaceCount = 0;
                            state = Rfc2047ParsingState.End;
                        }
                        else
                        {
                            state = Rfc2047ParsingState.NotPasing;
                        }
                        break;
                        #endregion
                    case Rfc2047ParsingState.End: state = Rfc2047ParsingState.NotPasing; break;
                    default: break;
                }

                if (state == Rfc2047ParsingState.NotPasing)
                {
                    #region Add text that is invalid format like "=?Charset?S"
                    if (rfc2047Start != null)
                    {
                        this.AddChar(buffer, (Byte)' ', ref index, whiteSpaceCount);
                        whiteSpaceCount = -1;

                        var length = current - rfc2047Start;
                        for (int i = 0; i < length; i++)
                        {
                            buffer[index++] = *rfc2047Start;
                            rfc2047Start++;
                        }
                        rfc2047Start = null;
                    }
                    #endregion

                    #region
                    if (*current == (Byte)' ')
                    {
                        if (whiteSpaceCount > -1)
                        {
                            whiteSpaceCount++;
                        }
                        else
                        {
                            buffer[index++] = (Byte)' ';
                        }
                    }
                    else if (*current != (Byte)'\r' &&
                        *current != (Byte)'\n' &&
                        *current != (Byte)'\t')
                    {
                        this.AddChar(buffer, (Byte)' ', ref index, whiteSpaceCount);
                        whiteSpaceCount = -1;

                        buffer[index++] = *current;
                    }
                    #endregion
                }
                current++;
            }
            sb.Append(this.Encoding.GetString(buffer.Take(index).ToArray()));
            return sb.ToString();
        }
 private Boolean AreEqual(Stream stream1, Stream stream2)
 {
     stream1.Position = stream2.Position = 0;
      var buffer1 = new Byte[8192];
      var buffer2 = new Byte[8192];
      for (; ; )
      {
     var read1 = stream1.Read(buffer1, 0, buffer1.Length);
     var read2 = stream2.Read(buffer2, 0, buffer2.Length);
     if (read1 != read2)
        return false;
     if (read1 == 0)
        break;
     if (!Enumerable.SequenceEqual(buffer1.Take(read1), buffer2.Take(read2)))
        return false;
      }
      return true;
 }
Beispiel #13
0
        public int GetMessage(byte[] prvkey, byte[] pubkey, Action<Message>store)
        {
            int count = 0;
            sw.WriteByte((byte)ClientServerCmd.GetMessage);
            SendPublicKey(pubkey);

            RSAParameters rsap;
            Shared.LoadKey2(Shared.prvToPem(prvkey), null, out rsap);
            Shared.AnswerRemotePubkeyTest(sr, sw, rsap);

            while (true)
            {
                var resp = sr.ReadByte();
                if (resp == (byte)ClientServerCmd.NoMessage)
                    return count;
                else if (resp != (byte)ClientServerCmd.HasMessage)
                    throw new Exception();
                var len = sr.ReadShort();
                if (len > 1024)
                    throw new Exception();
                var buf = new Byte[len];
                //sr.Read(buf, 0, 8);
                //var ts = BitConverter.ToInt64(buf, 0);
                //DateTime.FromFileTimeUtc(ts);
                if (sr.Read(buf, 0, len) != len)
                    throw new Exception();

                byte[] aeskey,aesIV,aesbuf;
                using (var rsa = new RSACryptoServiceProvider())
                {
                    rsa.ImportParameters(rsap);
                    var rsalen = 128;
                    var rsabuf = buf.Take(rsalen).ToArray();
                    aesbuf = buf.Skip(rsalen).ToArray();
                    var aes_keyivdata = rsa.Decrypt(rsabuf, false);
                    aeskey = aes_keyivdata.Take(32).ToArray();
                    aesIV = aes_keyivdata.Skip(32).Take(16).ToArray();
                }
                var msg=DecodeMessage(aesbuf,aeskey, aesIV, rsap, pubkey);
                store(msg);
                count++;
                sw.WriteByte((Byte)ClientServerCmd.Success);
            }
        }
Beispiel #14
0
        MatrixValue ImageLoad(String filename, out Boolean error, Double coarsening = Double.NaN)
        {
            error = false;
            var imageType = String.Empty;

            using (var fs = File.Open(filename, FileMode.Open))
            {
                var file_bytes = new Byte[fs.Length];
                fs.Read(file_bytes, 0, 8);

                var png_magic_number = new Byte[] { 0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a };

                if (!file_bytes.Take(8).Select((b, i) => b == png_magic_number[i]).Contains(false))
                    imageType = "png";

                var tiff_magic_number_0 = new Byte[] { 0x49, 0x49, 0x2a, 0x00 };

                if (!file_bytes.Take(4).Select((b, i) => b == tiff_magic_number_0[i]).Contains(false))
                    imageType = "tiff";

                var tiff_magic_number_1 = new Byte[] { 0x4d, 0x4d, 0x2a, 0x00 };

                if (!file_bytes.Take(4).Select((b, i) => b == tiff_magic_number_1[i]).Contains(false))
                    imageType = "tiff";

                var bmp_magic_number = new Byte[] { 0x42, 0x4D };

                if (!file_bytes.Take(2).Select((b, i) => b == bmp_magic_number[i]).Contains(false))
                    imageType = "bmp";

                var gif_magic_number_0 = new Byte[] { 0x47, 0x49, 0x46, 0x38, 0x37, 0x61 };

                if (!file_bytes.Take(6).Select((b, i) => b == gif_magic_number_0[i]).Contains(false))
                    imageType = "gif";

                var gif_magic_number_1 = new Byte[] { 0x47, 0x49, 0x46, 0x38, 0x39, 0x61 };

                if (!file_bytes.Take(6).Select((b, i) => b == gif_magic_number_1[i]).Contains(false))
                    imageType = "gif";

                var jpg_magic_number = new Byte[] { 0xff, 0xd8 };

                if (!file_bytes.Take(2).Select((b, i) => b == jpg_magic_number[i]).Contains(false))
                    imageType = "jpg";
            }

            if (imageType == String.Empty)
            {
                error = true;
                return new MatrixValue();
            }

            using (var bmp = new Bitmap(filename))
            {
                var result = default(MatrixValue);

                if (bmp == null)
                {
                    error = true;
                    result = new MatrixValue();
                }
                else
                {
                    var height = bmp.Height;
                    var width = bmp.Width;

                    var rect = new Rectangle(0, 0, bmp.Width, bmp.Height);
                    var bmpData = bmp.LockBits(rect, System.Drawing.Imaging.ImageLockMode.ReadOnly, bmp.PixelFormat);
                    var ptr = bmpData.Scan0;
                    var bytes = Math.Abs(bmpData.Stride) * bmp.Height;
                    var rgbValues = new Byte[bytes];
                    System.Runtime.InteropServices.Marshal.Copy(ptr, rgbValues, 0, bytes);
                    bmp.UnlockBits(bmpData);
                    var bytesPerPixel = 0;

                    if (bmp.PixelFormat == System.Drawing.Imaging.PixelFormat.Canonical ||
                        bmp.PixelFormat == System.Drawing.Imaging.PixelFormat.Format32bppArgb ||
                        bmp.PixelFormat == System.Drawing.Imaging.PixelFormat.Format32bppPArgb ||
                        bmp.PixelFormat == System.Drawing.Imaging.PixelFormat.Format32bppRgb)
                    {
                        bytesPerPixel = 4;
                    }
                    else if (bmp.PixelFormat == System.Drawing.Imaging.PixelFormat.Format24bppRgb)
                    {
                        bytesPerPixel = 3;
                    }
                    else
                    {
                        throw new YAMPPixelFormatNotSupportedException(filename);
                    }

                    if (Double.IsNaN(coarsening))
                    {
                        const Double maxPixelPerDirection = 100.0;

                        if (width > maxPixelPerDirection || height > maxPixelPerDirection)
                        {
                            coarsening = Math.Max(width / maxPixelPerDirection, height / maxPixelPerDirection);
                        }
                        else
                        {
                            coarsening = 1.0;
                        }
                    }

                    if (coarsening < 1.0)
                    {
                        throw new YAMPArgumentInvalidException("Load", "ImageCoarsening");
                    }

                    var cI = 1.0 / coarsening;
                    var finalWidth = (Int32)(width * cI);
                    var finalHeight = (Int32)(height * cI);

                    var count = new Byte[finalHeight, finalWidth];
                    var rvalues = new Double[finalHeight, finalWidth];
                    var gvalues = new Double[finalHeight, finalWidth];
                    var bvalues = new Double[finalHeight, finalWidth];

                    for (var i = 0; i < width; i++)
                    {
                        var idx = (Int32)(i * cI);

                        if (idx >= finalWidth)
                        {
                            idx = finalWidth - 1;
                        }

                        for (var j = 0; j < height; j++)
                        {
                            var jdx = (Int32)(j * cI);

                            if (jdx >= finalHeight)
                            {
                                jdx = finalHeight - 1;
                            }

                            rvalues[jdx, idx] += rgbValues[(j * width + i) * bytesPerPixel + 2];
                            gvalues[jdx, idx] += rgbValues[(j * width + i) * bytesPerPixel + 1];
                            bvalues[jdx, idx] += rgbValues[(j * width + i) * bytesPerPixel + 0];
                            count[jdx, idx]++;
                        }
                    }

                    for (var i = 0; i < finalHeight; i++)
                    {
                        for (var j = 0; j < finalWidth; j++)
                        {
                            var cinv = 1.0 / count[i, j];
                            rvalues[i, j] *= cinv;
                            gvalues[i, j] *= cinv;
                            bvalues[i, j] *= cinv;
                        }
                    }

                    for (var i = 0; i < finalHeight; i++)
                    {
                        for (var j = 0; j < finalWidth; j++)
                        {
                            rvalues[i, j] = (Int32)rvalues[i, j];
                            gvalues[i, j] = (Int32)gvalues[i, j];
                            bvalues[i, j] = (Int32)bvalues[i, j];

                            rvalues[i, j] *= rfactor;
                            gvalues[i, j] *= gfactor;
                            bvalues[i, j] *= bfactor;

                            rvalues[i, j] += gvalues[i, j] + bvalues[i, j];
                        }
                    }

                    return new MatrixValue(rvalues);
                }

                return result;
            }
        }