public DataFile(dbModel model)
            : this()
        {
            Model = model;

            m_mapPort  = MemoryMappedFile.Create(MapProtection.PageReadWrite, 4, Model.Name);
            m_FileName = Model.Name + ".df";
            string m_PathData = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "Data");

            if (!Directory.Exists(m_PathData))
            {
                Directory.CreateDirectory(m_PathData);
            }
            m_FilePath = Path.Combine(m_PathData, m_FileName);

            if (OpenOrCreateFile())
            {
                http_Init();
                Opened = true;

                if (m_listItems == null)
                {
                    m_listItems = (IList)typeof(List <>).MakeGenericType(TypeDynamic).GetConstructor(Type.EmptyTypes).Invoke(null);
                }
            }
            else
            {
                Close();
            }
        }
Exemple #2
0
 /// ------------------------------------------------------------------------------------
 /// <summary>
 /// Initializes a new instance of the <see cref="T:PeFileProcessor"/> class.
 /// </summary>
 /// <param name="fileName">Name of the file.</param>
 /// ------------------------------------------------------------------------------------
 public PeFileProcessor(string fileName)
 {
     m_htDirectories = new Hashtable();
     m_fileName      = fileName;
     m_mappedFile    = MemoryMappedFile.Create(fileName, MapProtection.PageWriteCopy);
     ProcessFile();
 }
Exemple #3
0
        public void TestMMFViewSeeking()
        {
            string           filename = Path.GetTempFileName();
            MemoryMappedFile map      = MemoryMappedFile.Create(filename, MapProtection.PageReadWrite, MAX_BYTES);

            using (Stream view = map.MapView(MapAccess.FileMapWrite, 0, MAX_BYTES))
            {
                view.WriteByte(0x12);
                // seek from start of view
                view.Seek(12, SeekOrigin.Begin);
                Assert.AreEqual(12, (int)view.Position);
                // Seek from current pos
                view.Seek(1, SeekOrigin.Current);
                Assert.AreEqual(13, (int)view.Position);
                // seek from end
                view.Seek(-1, SeekOrigin.End);
                Assert.AreEqual(MAX_BYTES - 1, (int)view.Position);

                try
                {
                    // no seeking past end of stream
                    view.Seek(1, SeekOrigin.End);
                    Assert.Fail("Seeked past end of stream");
                }
                catch (FileMapIOException)
                {
                }
            }
            map.Close();
        }
        public static void LoadMemoryMap()
        {
            if (_memoryMap != null && _mapViewSteam != null)
            {
                return;
            }

            if (string.IsNullOrEmpty(TerrainFilePath))
            {
                SetTerrainDataPath();
            }

            string memoryMapFile = Path.Combine(TerrainFilePath, TERRAIN_FILE_NAME);

            if (!System.IO.File.Exists(memoryMapFile))
            {
                memoryMapFile = "C:\\terrain.bin"; //hack for unit tests!
            }

            try
            {
                GameManager.Instance.Log.LogDebug("TerrainReader->LoadMemoryMap initializing. Reading terrain file: <" + memoryMapFile + "> .");
                _memoryMap    = MemoryMappedFile.Create(memoryMapFile, MapProtection.PageReadOnly);
                _mapViewSteam = _memoryMap.MapAsStream();
            }
            catch (Exception ex)
            {
                GameManager.Instance.Log.LogError("TerrainReader->LoadMemoryMap failed to load terrain from <" + memoryMapFile + "> ." + ex.Message);
                GameManager.Instance.Log.LogError(ex.ToString());
            }
        }
        public void EndUpdate()
        {
            //   Debug.Log("start float late update");
            if (streamFloatValue != null)
            {
                streamFloatValue.Dispose();
                streamFloatValue.Close();
            }


            if (keysToAdd.Count != 0)
            {
                ReadHeaderFile();
                int newKeyCount = (keysFloat.Count + keysToAdd.Count);
                if (fileKeyFloat == null)
                {
                    fileKeyFloat = MemoryMappedFile.Create(MapProtection.PageReadWrite, 100000, "FileKeysFloat3");
                }

                // if (fileKeyFloat1 == null)
                //     fileKeyFloat1 = MemoryMappedFile.Create(MapProtection.PageReadWrite, 100000, "FileKeysFloat3");

                //using (var keyWriter1 = fileKeyFloat1.MapView(MapAccess.FileMapAllAccess, 0, 100000)) { }

                using (var keyWriter = fileKeyFloat.MapView(MapAccess.FileMapAllAccess, 0, 100000))
                {
                    keyWriter.Position = byteCountKeyFloat;

                    foreach (KeyValuePair <string, float> entry in keysToAdd)
                    {
                        var stringBuffer = Encoding.ASCII.GetBytes(entry.Key);
                        // Debug.Log("string byte length " + stringBuffer.Length);
                        keyWriter.Write(BitConverter.GetBytes((float)stringBuffer.Length), 0, 4);
                        //  Debug.Log("write '" + entry.Key + "' at new key at position " + keyWriter.Position);
                        keyWriter.Write(stringBuffer, 0, stringBuffer.Length);
                        Debug.Log("Add server key: " + entry.Key);

                        keysFloat.Add(entry.Key);
                        valueAddressFloat.Add(entry.Key, keysFloat.Count - 1);
                    }
                }
                byteCountKeyFloat   += byteCountKeyFloatNew;
                byteCountKeyFloatNew = 0;
                fileValueFloat       = MemoryMappedFile.Create(MapProtection.PageReadWrite, newKeyCount * 4, "FileValuesFloat3");
                using (var valueStream = fileValueFloat.MapView(MapAccess.FileMapAllAccess, 0, newKeyCount * 4))
                {
                    valueStream.Position = keysFloat.Count * 4 - keysToAdd.Count * 4;

                    foreach (KeyValuePair <string, float> entry in keysToAdd)
                    {
                        // Debug.Log("add value " + entry.Value);
                        valueStream.Write(BitConverter.GetBytes(entry.Value), 0, 4);
                    }
                }

                UpdateHeaderFile();
                keysToAdd = new Dictionary <string, float>();
            }
        }
        public DataHost()
        {
            m_mapPort      = MemoryMappedFile.Create(MapProtection.PageReadWrite, 4, "datafile");
            m_listDataName = new List <string>();
            m_dataFile     = new ConcurrentDictionary <string, DataFile>();

            m_PathData = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().CodeBase), "Data").Replace(@"file:\", string.Empty);
            if (!Directory.Exists(m_PathData))
            {
                Directory.CreateDirectory(m_PathData);
            }
        }
        // Use this for initialization
        public void StartServer(MemoryBridge memoryBridge)
        {
            fileHeader     = MemoryMappedFile.Create(MapProtection.PageReadWrite, 16, "FileHeader");
            fileValueFloat = MemoryMappedFile.Create(MapProtection.PageReadWrite, 16, "FileValuesFloat3");

            this.memoryBridge = memoryBridge;

            keysFloat         = new List <string>();
            valueAddressFloat = new Dictionary <string, int>();
            keysToAdd         = new Dictionary <string, float>();
            UpdateHeaderFile();
        }
 /// <summary>
 ///
 /// </summary>
 public virtual void Open()
 {
     if (m_IsOpen)
     {
         Close();
     }
     //
     m_File   = MemoryMappedFile.Create(null /*m_Address*/, MapProtection.PageReadWrite, m_MaxSize, m_Address);
     m_Stream = m_File.MapView(MapAccess.FileMapAllAccess, 0 /*m_Offset*/, m_MaxSize /*m_Count*/) as MapViewStream;
     //
     m_IsOpen = true;
 }
Exemple #9
0
        public object Post()
        {
            int port             = 0;
            MemoryMappedFile map = MemoryMappedFile.Create(MapProtection.PageReadWrite, 4, this.Name);

            byte[] buf = new byte[4];
            using (Stream view = map.MapView(MapAccess.FileMapRead, 0, 4))
                view.Read(buf, 0, 4);
            port = BitConverter.ToInt32(buf, 0);

            return(Post("http://127.0.0.1:" + port.ToString()));
        }
 public static void Initialize()
 {
     try
     {
         mappedFile = MemoryMappedFile.Open(MapAccess.FileMapAllAccess, "Local\\BROKENGEKI_SHARED_BUFFER");
         NekoClient.Logging.Log.Info("Brokengeki shared memory exists, opening...");
     }
     catch (FileMapIOException)
     {
         NekoClient.Logging.Log.Info("Brokengeki shared memory does not exist, creating...");
         mappedFile = MemoryMappedFile.Create(MapProtection.PageReadWrite, 256, "Local\\BROKENGEKI_SHARED_BUFFER");
     }
     mapViewStream = (MapViewStream)mappedFile.MapView(MapAccess.FileMapAllAccess, 0, 256);
 }
Exemple #11
0
        public void TestNamedMMF()
        {
            try {
                const string     NAME = "MyMappedFile";
                MemoryMappedFile map  =
                    MemoryMappedFile.Create(MapProtection.PageReadWrite, MAX_BYTES, NAME);

                MemoryMappedFile map2 =
                    MemoryMappedFile.Open(MapAccess.FileMapRead, NAME);
                map2.Close();
                map.Close();
            } catch (FileMapIOException e) {
                Assert.Fail("Failed Named MMF: " + e);
            }
        }
Exemple #12
0
        public void TestMMFViewSize()
        {
            string           filename = Path.GetTempFileName();
            MemoryMappedFile map      = MemoryMappedFile.Create(filename, MapProtection.PageReadWrite, MAX_BYTES);

            using (Stream view = map.MapView(MapAccess.FileMapWrite, 0, MAX_BYTES))
            {
                view.Seek(MAX_BYTES, SeekOrigin.Begin);
                // no writing past end of view
                view.WriteByte(0x01);
                Assert.AreEqual(MAX_BYTES, (int)view.Position);
                // no reading past end of stream
                Assert.AreEqual(-1, view.ReadByte());
            }
            map.Close();
        }
        public void BuildCameraFeed(MemoryBridge memoryBridge, string fileName)
        {
            //Debug.Log("Build Camera Feed");
            this.memoryBridge = memoryBridge;
            this.fileName     = fileName;

            threadList = new List <int>();
            threadList.Add(0);
            threadList.Add(1);
            //   threadList.Add(2);
            //  threadList.Add(3);

            GameObject camObject = new GameObject();

            DebugVector.DrawVector(camObject.transform);
            camObject.transform.SetParent(FlightGlobals.ActiveVessel.vesselTransform);

            feedCam = camObject.AddComponent <Camera>();

            rendTextHeight = feedCam.pixelHeight;
            rendTextWidth  = feedCam.pixelWidth;
            //Debug.Log("height " + rendTextHeight + " width " + rendTextWidth);
            rendText = new RenderTexture(rendTextWidth, rendTextHeight, 16, RenderTextureFormat.ARGB32);
            rendText.Create();
            feedCam.targetTexture = rendText;

            tex     = new Texture2D(rendTextWidth, rendTextWidth, TextureFormat.RGB24, false);
            texCopy = new Texture2D(rendTextWidth, rendTextHeight, TextureFormat.RGB24, false);

            RenderTexture.active = rendText;
            //Debug.Log("Render width " + rendTextWidth);
            //Debug.Log("render height " + rendTextHeight);
            tex.ReadPixels(new Rect(0, 0, rendTextWidth, rendTextHeight), 0, 0);
            tex.Apply();
            camTexture = tex;
            // var colorBuffer = rendText.colorBuffer;
            var textureByte = camTexture.GetRawTextureData();

            camFeedFile = MemoryMappedFile.Create(MapProtection.PageReadWrite, textureByte.Length, "CamFeedFile" + fileName + memoryBridge.cameraFeeds.Count);

            memoryBridge.SetFloat("rendTextHeight" + fileName + memoryBridge.cameraFeeds.Count, rendTextHeight);
            memoryBridge.SetFloat("rendTextWidth" + fileName + memoryBridge.cameraFeeds.Count, rendTextWidth);
            memoryBridge.SetFloat("feedByteCount" + fileName + memoryBridge.cameraFeeds.Count, textureByte.Length);

            ////Debug.Log("ByteSize " + textureByte.Length);
            //Debug.Log("mem map loaded");
        }
        private bool OpenOrCreateFile()
        {
            try
            {
                if (File.Exists(m_FilePath))
                {
                    /////////////////////////////////////////////////
                    // OPEN m_FilePath

                    FileInfo fi = new FileInfo(m_FilePath);
                    m_FileSize = (int)fi.Length;
                    m_mapFile  = MemoryMappedFile.Create(m_FilePath, MapProtection.PageReadWrite, m_FileSize);
                    if (m_FileSize > m_HeaderSize)
                    {
                        byte[] buf = new byte[m_FileSize];
                        using (Stream view = m_mapFile.MapView(MapAccess.FileMapRead, 0, m_FileSize))
                            view.Read(buf, 0, m_FileSize);

                        bool val = bindHeader(buf);
                        if (val)
                        {
                            m_mapPort  = MemoryMappedFile.Create(MapProtection.PageReadWrite, 4, Model.Name);
                            m_FileName = Model.Name + ".df";
                            return(true);
                        }
                    }
                }
                else
                {
                    /////////////////////////////////////////////////
                    // CREATE NEW m_FilePath

                    m_Capacity = m_BlobGrowSize;
                    m_FileSize = m_HeaderSize + (m_Capacity * m_BlobSizeMax) + 1;
                    m_mapFile  = MemoryMappedFile.Create(m_FilePath, MapProtection.PageReadWrite, m_FileSize);

                    //string fs = _model.Name + ";" + string.Join(",", _model.Fields.Select(x => ((int)x.Type).ToString() + x.Name).ToArray());
                    writeHeaderBlank();

                    return(true);
                }
            }
            catch
            {
            }
            return(false);
        }
Exemple #15
0
        public void TestNonBackedMMF()
        {
            try {
                MemoryMappedFile map =
                    MemoryMappedFile.Create(MapProtection.PageReadWrite, MAX_BYTES);

                using (Stream view = map.MapView(MapAccess.FileMapWrite, 0, MAX_BYTES))
                {
                    WriteBytesToStream(view, MAX_BYTES);
                }
                using (Stream view = map.MapView(MapAccess.FileMapRead, 0, MAX_BYTES / 2))
                {
                    VerifyBytesInStream(view, MAX_BYTES / 2);
                }
                map.Close();
            } catch (FileMapIOException e) {
                Assert.Fail("Write error: " + e);
            }
        }
Exemple #16
0
        public void TestMMFFileWrite()
        {
            try {
                string           filename = Path.GetTempFileName();
                MemoryMappedFile map      =
                    MemoryMappedFile.Create(filename, MapProtection.PageReadWrite, MAX_BYTES);

                using (Stream view = map.MapView(MapAccess.FileMapWrite, 0, MAX_BYTES))
                {
                    WriteBytesToStream(view, MAX_BYTES);
                }
                using (Stream view = map.MapView(MapAccess.FileMapRead, 0, MAX_BYTES / 2))
                {
                    VerifyBytesInStream(view, MAX_BYTES / 2);
                }
                map.Close();
            } catch (FileMapIOException e) {
                Assert.Fail("Write error: " + e);
            }
        }
        private void openOrCreateMemoryFileAndWriteData(T data)
        {
            try
            {
                mapFile = MemoryMappedFile.Open(MapAccess.FileMapWrite, fileName);
            }
            catch
            {
                mapFile = MemoryMappedFile.Create(MapProtection.PageReadWrite, 8 * 1024, fileName);
            }


            char[] charArrayOfObject = serializeToXml <T>(data).ToCharArray();
            Stream writer            = mapFile.MapView(MapAccess.FileMapWrite, 0, charArrayOfObject.Length);

            for (int i = 0; i < charArrayOfObject.Length; i++)
            {
                writer.WriteByte((byte)charArrayOfObject[i]);
            }
            writer.Flush();
            writer.Close();
        }
Exemple #18
0
        internal ByteWindow MemoryMappedByteWindow(long pos, int size)
        {
            if (Length < pos + size)
            {
                size = (int)(Length - pos);
            }

            Stream map;

            using (var _fdMap = MemoryMappedFile.Create(File.FullName, MapProtection.PageReadOnly))
            {
                try
                {
                    map = _fdMap.MapView(MapAccess.FileMapRead, pos, size);
                    // was: map = _fd.map(MapMode.READ_ONLY, pos, size);
                }
                catch (IOException)
                {
                    // The most likely reason this failed is the process has run out
                    // of virtual memory. We need to discard quickly, and try to
                    // force the GC to finalize and release any existing mappings.
                    //
                    GC.Collect();
                    GC.WaitForPendingFinalizers();
                    map = _fdMap.MapView(MapAccess.FileMapRead, pos, size);
                }

                byte[] mapArray = map != null?map.toArray() : new byte[0];

                if (mapArray.Length > 0)
                {
                    return(new ByteArrayWindow(this, pos, mapArray));
                }
            }

            return(new ByteBufferWindow(this, pos, map));
        }
Exemple #19
0
        public void CustomStart(List <Part> parts, MemoryBridge memoryBridge)
        {
            Debug.Log("IR Manager custom start");
            limbs = new List <RoboticArm>();

            if (IRWrapper.IRController == null)
            {
                Debug.Log("IR3Controller is not null");
            }
            Debug.Log(IRWrapper.IRController.ServoGroups.Count);
            foreach (IRWrapper.IControlGroup group in IRWrapper.IRController.ServoGroups)
            {
                Debug.Log("Servo Group : " + group.Name);
                if (group.Name.ToLower().Contains("ik"))
                {
                    IRWrapper.IServo basePart  = null;
                    IRWrapper.IServo wristPart = null;
                    foreach (var servo in group.Servos)
                    {
                        if (servo.Name.ToLower().Contains("base"))
                        {
                            basePart = servo;
                        }
                        if (servo.Name.ToLower().Contains("wrist"))
                        {
                            wristPart = servo;
                        }
                    }
                    var newLimb = gameObject.AddComponent(typeof(RoboticArm)) as RoboticArm;
                    newLimb.CustomAwake(group, basePart, wristPart, memoryBridge);
                    limbs.Add(newLimb);

                    byteCount += 4;
                    byteCount += newLimb.limbName.Length;
                }
            }

            byteCount += 16;
            IRFile     = MemoryMappedFile.Create(MapProtection.PageReadWrite, byteCount, "IRFile" + memoryBridge.fileName);

            using (Stream mapStream = IRFile.MapView(MapAccess.FileMapAllAccess, 0, byteCount))
            {
                var bytePackage = BitConverter.GetBytes(byteCount);
                mapStream.Write(bytePackage, 0, 4);
                bytePackage = BitConverter.GetBytes(limbs.Count);
                mapStream.Write(bytePackage, 0, 4);

                mapStream.Position = 16;

                foreach (var limb in limbs)
                {
                    var nameBytePackage = Encoding.ASCII.GetBytes(limb.limbName);
                    bytePackage = BitConverter.GetBytes((float)nameBytePackage.Length);
                    mapStream.Write(bytePackage, 0, 4);
                    mapStream.Write(nameBytePackage, 0, nameBytePackage.Length);
                }
            }

            //legs = new List<MechLeg>();

            //foreach (IRWrapper.IControlGroup group in IRWrapper.IRController.ServoGroups)
            //{
            //    if (group.Name == "Leg One")
            //    {
            //        legOne = new MechLeg(memoryBridge, group, this, "Leg One");
            //        legs.Add(legOne);
            //    }
            //    else if (group.Name == "Leg Two")
            //    {
            //        legTwo = new MechLeg(memoryBridge, group, this, "Leg Two");
            //        legs.Add(legTwo);
            //    }
            //    else if (group.Name == "Leg Three")
            //    {
            //        legThree = new MechLeg(memoryBridge, group, this, "Leg Three");
            //        legs.Add(legThree);
            //    }
            //    else if (group.Name == "Leg Four")
            //    {
            //        legFour = new MechLeg(memoryBridge, group, this, "Leg Four");
            //        legs.Add(legFour);
            //    }
            //    else if (group.Name == "Leg Five")
            //    {
            //        legFive = new MechLeg(memoryBridge, group, this, "Leg Five");
            //        legs.Add(legFive);
            //    }
            //    else if (group.Name == "Leg Six")
            //    {
            //        legSix = new MechLeg(memoryBridge, group, this, "Leg Six");
            //        legs.Add(legSix);
            //    }
            //    else if (group.Name == "Arm")
            //    {
            //        armOne = new MechArm(memoryBridge, group, this);
            //    }
            //}
        }
    public void EndUpdate()
    {
        if (streamFloatValue != null)
        {
            streamFloatValue.Dispose();
            streamFloatValue.Close();
        }

        if (keysToAdd.Count != 0)
        {
            ReadHeaderFile();
            int newKeyCount = (keysFloat.Count + keysToAdd.Count);
            // fileKeyFloat.Dispose();
            //  if (fileKeyFloat != null)
            //     fileKeyFloat.Close();
            var byteCountNew = byteCountKeyFloat + byteCountKeyFloatNew;

            //if(fileKeyFloat1 == null)
            //     fileKeyFloat1 = MemoryMappedFile.Open(MapAccess.FileMapAllAccess, "FileKeysFloat3");
            //   using (var keyWriter = fileKeyFloat1.MapView(MapAccess.FileMapAllAccess, 0, 100000)) {
            //     keyWriter.Position = 3000; }
            //    fileKeyFloat = MemoryMappedFile.Create(MapProtection.PageReadWrite, byteCountNew, "FileKeysFloat");
            using (var keyWriter = fileKeyFloat.MapView(MapAccess.FileMapAllAccess, 0, 100000))
            {
                //Debug.Log("byteCountKeyFloat " + byteCountKeyFloat);

                //Debug.Log("byteCountKey + newKeybytecount " + byteCountNew);
                keyWriter.Position = byteCountKeyFloat;

                foreach (KeyValuePair <string, float> entry in keysToAdd)
                {
                    var stringBuffer = Encoding.ASCII.GetBytes(entry.Key);
                    // //Debug.Log("string byte length " + stringBuffer.Length);
                    keyWriter.Write(BitConverter.GetBytes((float)stringBuffer.Length), 0, 4);
                    // //Debug.Log("write '" + entry.Key + "' at new key at position " + keyWriter.Position);
                    keyWriter.Write(stringBuffer, 0, stringBuffer.Length);
                    // //Debug.Log("add to file " + entry.Key);

                    keysFloat.Add(entry.Key);
                    valueAddressFloat.Add(entry.Key, keysFloat.Count - 1);
                }
            }
            byteCountKeyFloat   += byteCountKeyFloatNew;
            byteCountKeyFloatNew = 0;
            fileValueFloat       = MemoryMappedFile.Create(MapProtection.PageReadWrite, newKeyCount * 4, "FileValuesFloat3");
            using (var valueStream = fileValueFloat.MapView(MapAccess.FileMapAllAccess, 0, newKeyCount * 4))
            {
                valueStream.Position = keysFloat.Count * 4 - keysToAdd.Count * 4;
                foreach (KeyValuePair <string, float> entry in keysToAdd)
                {
                    ////Debug.Log("add value " + entry.Value);
                    valueStream.Write(BitConverter.GetBytes(entry.Value), 0, 4);
                }
            }

            UpdateHeaderFile();
            keysToAdd = new Dictionary <string, float>();

//            if (Input.GetKeyDown(KeyCode.Alpha5))
//            {
//                foreach(KeyValuePair<string,int> pair in valueAddressFloat)
//{
//                    Debug.Log(pair.Key);
//                }
//            }
        }
    }
        public EditStatus[] AddItems(object[] items)
        {
            EditStatus[] rs = new EditStatus[items.Length];
            if (Opened == false || items == null || items.Length == 0)
            {
                return(rs);
            }

            bool ok            = false;
            int  itemConverted = 0;

            /////////////////////////////////////////
            #region [ convert items[] to array dynamic object ]

            //IList lsDynObject = (IList)typeof(List<>).MakeGenericType(TypeDynamic).GetConstructor(Type.EmptyTypes).Invoke(null);
            var lsDynObject = items
                              .Select((x, k) => convertToDynamicObject(x))
                              .ToList();
            if (lsDynObject.Count > 0)
            {
                int[] ids;
                lock (_lockSearch)
                    // performance very bad !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
                    ids = lsDynObject.Select(x => x == null ? -2 : m_listItems.IndexOf(x)).ToArray();

                for (int k = ids.Length - 1; k >= 0; k--)
                {
                    switch (ids[k])
                    {
                    case -2:
                        rs[k] = EditStatus.FAIL_EXCEPTION_CONVERT_TO_DYNAMIC_OBJECT;
                        lsDynObject.RemoveAt(k);
                        break;

                    case -1:
                        itemConverted++;
                        break;

                    default:
                        rs[k] = EditStatus.FAIL_ITEM_EXIST;
                        lsDynObject.RemoveAt(k);
                        break;
                    }
                }
            }

            #endregion

            if (itemConverted == 0)
            {
                return(rs);
            }

            /////////////////////////////////////////
            Dictionary <int, byte[]> dicBytes = new Dictionary <int, byte[]>();
            List <byte> lsByte = new List <byte>()
            {
            };
            List <int> lsIndexItemNew = new List <int>();
            int        itemCount      = 0;

            if (lsDynObject.Count > 0)
            {
                using (m_lockFile.WriteLock())
                {
                    #region [ === CONVERT DYNAMIC OBJECT - SERIALIZE === ]

                    for (int k = 0; k < lsDynObject.Count; k++)
                    {
                        rs[k] = EditStatus.NONE;
                        int index_ = m_Count + itemCount + 1;

                        byte[] buf = serializeDynamicObject(lsDynObject[k], index_);
                        if (buf == null || buf.Length == 0)
                        {
                            rs[k] = EditStatus.FAIL_EXCEPTION_SERIALIZE_DYNAMIC_OBJECT;
                            continue;
                        }
                        else if (buf.Length > m_BlobSizeMax)
                        {
                            rs[k] = EditStatus.FAIL_MAX_LEN_IS_255_BYTE;
                            continue;
                        }
                        else
                        {
                            lsByte.AddRange(buf);
                            dicBytes.Add(index_ - 1, buf);
                            rs[k] = EditStatus.SUCCESS;
                            itemCount++;
                            lsIndexItemNew.Add(k);
                        }
                    } // end for each items

                    #endregion

                    #region [ === TEST === ]

                    ////////////////////var o1 = convertToDynamicObject(items[lsDynamicObject.Count - 1], 0);
                    ////////////////////byte[] b2;
                    ////////////////////using (var ms = new MemoryStream())
                    ////////////////////{
                    ////////////////////    ProtoBuf.Serializer.Serialize(ms, o1);
                    ////////////////////    b2 = ms.ToArray();
                    ////////////////////}
                    ////////////////////byte[] b3 = serializeDynamicObject(o1);
                    ////////////////////string j3 = string.Join(" ", b2.Select(x => x.ToString()).ToArray());
                    ////////////////////string j4 = string.Join(" ", b3.Select(x => x.ToString()).ToArray());
                    ////////////////////if (j3 == j4)
                    ////////////////////    b2 = null;

                    //////////lsDynamicObject.Add(convertToDynamicObject(items[0], 1));
                    //////////lsDynamicObject.Add(convertToDynamicObject(items[1], 2));
                    //////////lsDynamicObject.Add(convertToDynamicObject(items[2], 3));
                    //////////lsDynamicObject.Add(convertToDynamicObject(items[3], 4));

                    //////////byte[] b1;
                    //////////using (var ms = new MemoryStream())
                    //////////{
                    //////////    ProtoBuf.Serializer.Serialize(ms, lsDynamicObject);
                    //////////    b1 = ms.ToArray();
                    //////////}
                    ////////////string j1 = string.Join(" ", b1.Select(x => x.ToString()).ToArray());
                    //////////////string j2 = string.Join(" ", lsByte.Select(x => x.ToString()).ToArray());
                    //////////////if (j1 == j2)
                    //////////////    b1 = null;
                    //////////////byte[] bs = "10 9 8 0 18 5 16 1 82 1 49 10 2 8 1 0 0 0 0 10 2 8 2 10 9 8 3 18 5 16 2 82 1 51".Split(' ').Select(x => byte.Parse(x)).ToArray();
                    //////////////object vs;
                    //////////////Type typeList = typeof(List<>).MakeGenericType(TypeDynamic);
                    //////////////using (var ms = new MemoryStream(bs))
                    //////////////    vs = (IList)ProtoBuf.Serializer.NonGeneric.Deserialize(typeList, ms);

                    //////////return rs;

                    #endregion

                    #region [ === RESIZE GROW === ]

                    int freeStore = m_FileSize - (m_BlobLEN + m_HeaderSize);
                    if (freeStore < lsByte.Count + 1)
                    {
                        m_mapFile.Close();
                        FileStream fs       = new FileStream(m_FilePath, FileMode.OpenOrCreate);
                        long       fileSize = fs.Length + lsByte.Count + (m_BlobGrowSize * m_BlobSizeMax);
                        fs.SetLength(fileSize);
                        fs.Close();
                        m_FileSize = (int)fileSize;
                        m_mapFile  = MemoryMappedFile.Create(m_FilePath, MapProtection.PageReadWrite, m_FileSize);
                    }

                    #endregion

                    #region [ === WRITE FILE === ]

                    bool w = false;
                    w = writeData(lsByte.ToArray(), itemCount);
                    if (w)
                    {
                        //string j1 = string.Join(" ", lsByte.Select(x => x.ToString()).ToArray());
                        lock (_lockSearch)
                        {
                            for (int k = 0; k < itemCount; k++)
                            {
                                Interlocked.Increment(ref m_Count);
                                Interlocked.Increment(ref m_Capacity);
                                m_listItems.Add(lsDynObject[lsIndexItemNew[k]]);
                            }
                        }
                        lock (_lockUpdate)
                        {
                            foreach (KeyValuePair <int, byte[]> kv in dicBytes)
                            {
                                m_bytes.Add(kv.Key, kv.Value);
                            }
                        }
                        ok = true;
                    }
                    if (w == false)
                    {
                        for (int k = 0; k < rs.Length; k++)
                        {
                            if (rs[k] == EditStatus.SUCCESS)
                            {
                                rs[k] = EditStatus.FAIL_EXCEPTION_WRITE_ARRAY_BYTE_TO_FILE;
                            }
                        }
                    }

                    #endregion
                }// end lock
            }

            if (ok)
            {
                SearchExecuteUpdateCache(ItemEditType.ADD_NEW_ITEM);
            }

            return(rs);
        }
        void BuildVessel()
        {
            var kspPartList = vessel.Parts;

            partList = new List <MemoryPart>();
            var byteArrayList = new List <byte[]>();
            int byteCount     = 0;

            foreach (var part in kspPartList)
            {
                //   Debug.Log("Part name to examine " + part.name);
                if (part.name != "strutConnector")
                {
                    var newPart = new MemoryPart(part, vesselControl);
                    partList.Add(newPart);
                    byteCount += newPart.byteCount;
                }
            }

            //for the header
            //+ 8 bytes for header
            //*12 bytes for VesselOffset
            //*12 bytes for PartScale
            //*12 bytes for Rotation
            byteCount += 8;

            Debug.Log("vessel file byte count: " + byteCount);
            Debug.Log("vessel mesh count: " + partList.Count);
            vesselFile = MemoryMappedFile.Create(MapProtection.PageReadWrite, byteCount, "VesselFile" + memoryBridge.fileName);

            using (Stream mapStream = vesselFile.MapView(MapAccess.FileMapAllAccess, 0, byteCount))
            {
                var byteCountPackage = BitConverter.GetBytes(byteCount);
                mapStream.Write(byteCountPackage, 0, 4);
                var partCount = BitConverter.GetBytes(partList.Count);
                mapStream.Write(partCount, 0, 4);

                foreach (var memPart in partList)
                {
                    Debug.Log("start writing part at position " + mapStream.Position);
                    //THESE BYTES ARE ALLOCATED IN THE CLASS
                    mapStream.Write(BitConverter.GetBytes(memPart.uniqueID), 0, 4);
                    mapStream.Write(BitConverter.GetBytes(memPart.parentID), 0, 4);
                    mapStream.Write(BitConverter.GetBytes((float)memPart.meshList.Count), 0, 4);

                    //THESE BYTES ARE ALLOCATED IN THE CLASS
                    mapStream.Write(BitConverter.GetBytes((float)memPart.offset.x), 0, 4);
                    mapStream.Write(BitConverter.GetBytes((float)memPart.offset.y), 0, 4);
                    mapStream.Write(BitConverter.GetBytes((float)memPart.offset.z), 0, 4);

                    //THESE BYTES ARE ALLOCATED IN THE CLASS
                    mapStream.Write(BitConverter.GetBytes((float)memPart.rotOffset.x), 0, 4);
                    mapStream.Write(BitConverter.GetBytes((float)memPart.rotOffset.y), 0, 4);
                    mapStream.Write(BitConverter.GetBytes((float)memPart.rotOffset.z), 0, 4);
                    //for name, allocated in class
                    var bytePackage = BitConverter.GetBytes((float)memPart.nameBytePackage.Length);
                    mapStream.Write(bytePackage, 0, 4);
                    mapStream.Write(memPart.nameBytePackage, 0, memPart.nameBytePackage.Length);

                    foreach (var filter in memPart.meshList)
                    {
                        //Debug.Log("start writing filter at position " + mapStream.Position);
                        //THESE BYTES ARE ALLOCATED IN THE CLASS
                        mapStream.Write(BitConverter.GetBytes((float)filter.vesselPartOffset.x), 0, 4);
                        mapStream.Write(BitConverter.GetBytes((float)filter.vesselPartOffset.y), 0, 4);
                        mapStream.Write(BitConverter.GetBytes((float)filter.vesselPartOffset.z), 0, 4);

                        //THESE BYTES ARE ALLOCATED IN THE CLASS
                        var partEulerAngle = filter.vesselPartLocalEuler;
                        //mapStream.Write(BitConverter.GetBytes((float)partEulerAngle.w), 0, 4);
                        mapStream.Write(BitConverter.GetBytes((float)partEulerAngle.x), 0, 4);
                        mapStream.Write(BitConverter.GetBytes((float)partEulerAngle.y), 0, 4);
                        mapStream.Write(BitConverter.GetBytes((float)partEulerAngle.z), 0, 4);

                        //THESE BYTES ARE ALLOCATED IN THE CLASS
                        var partScale = filter.lossyScale;
                        mapStream.Write(BitConverter.GetBytes((float)partScale.x), 0, 4);
                        mapStream.Write(BitConverter.GetBytes((float)partScale.y), 0, 4);
                        mapStream.Write(BitConverter.GetBytes((float)partScale.z), 0, 4);

                        //THESE BYTES ARE ALLOCATED IN THE CLASS
                        mapStream.Write(BitConverter.GetBytes((float)filter.byteArrMesh.Length), 0, 4);

                        // Debug.Log(memPart.name + " has a mesh byte array count of " + (filter.byteArrMesh.Length));
                        // mapStream.Write(BitConverter.GetBytes((float)filter.byteArrMesh.Length), 0, 4);
                        mapStream.Write(filter.byteArrMesh, 0, filter.byteArrMesh.Length);
                    }
                }
            }
            Debug.Log("Control Awake and Running");
        }
       // List<Part> parts;
        public void CustomAwake(IRWrapper.IControlGroup limbGroup, IRWrapper.IServo servoBase, IRWrapper.IServo servoWrist, MemoryBridge memoryBridge)
        {
            this.memoryBridge = memoryBridge;
            limbName = limbGroup.Name + memoryBridge.fileName;
            limbServos = new List<RoboticServo>();
            //Add wrist servo
            var newServo = servoBase.HostPart.gameObject.AddComponent(typeof(RoboticServo)) as RoboticServo;
            newServo.CustomStart(servoBase, memoryBridge);
            limbServos.Add(newServo);

            //parts = new List<Part>();

            Part tempPart = servoBase.HostPart;

            bool done = false;
            int count = 0;
            do
            {
                count++;
                var armParts = tempPart.children;

                armParts.Remove(tempPart);
                foreach (var part in armParts)
                {
                    Debug.Log(part.name + " is a child of " + tempPart.name);
                    IRWrapper.IServo testServo = null;
                    foreach (var servo in limbGroup.Servos)
                    {
                        if (part == servo.HostPart)
                        {
                            testServo = servo;
                            //break;
                        }
                    }
                    if (testServo != null)
                    {
                        tempPart = part;
                        // if (!testServo.Name.ToLower().Contains("skip"))
                        // {                    
                        Debug.Log("found servo on part");

                        newServo = part.gameObject.AddComponent(typeof(RoboticServo)) as RoboticServo;
                        newServo.CustomStart(testServo, memoryBridge);
                        limbServos.Add(newServo);
                        //  }
                        if (testServo.Name.ToLower().Contains("wrist"))
                        {
                            Debug.Log("wrist servo found");
                            wristServo = newServo;
                            done = true;
                        }
                        //if (servo.Name.ToLower().Contains("wrist"))
                        //{
                        //    wristPart = servo;
                        //}

                    }
                }
            } while (count < 30);

            //newServo = gameObject.AddComponent(typeof(RoboticServo)) as RoboticServo;
            //newServo.CustomStart(servoWrist);
            //limbServos.Add(newServo);

            int byteCount = 0;

            Debug.Log(limbGroup.Name + " servo hierarchy " + limbServos.Count);
            for (int i = 0; i < limbServos.Count; i++)
            {
                Debug.Log(limbServos[i].servo.Name);
                string parentName = "null";
                if (i != 0)
                {
                    parentName = limbServos[i - 1].servoName;
                    limbServos[i].parentID = limbServos[i - 1].servo.HostPart.gameObject.GetInstanceID();
                    limbServos[i].ParentSet(limbServos[i - 1].servo.HostPart.transform);
                }

                limbServos[i].parentServoName = parentName;

                byteCount += 8;
                //parent id
                byteCount += 4;
                byteCount += limbServos[i].servoName.Length;
                // byteCount += limbServos[i].parentServoName.Length;
            }
            byteCount += 16;
            LimbFile = MemoryMappedFile.Create(MapProtection.PageReadWrite, byteCount, limbName);

            using (Stream mapStream = LimbFile.MapView(MapAccess.FileMapAllAccess, 0, byteCount))
            {
                var bytePackage = BitConverter.GetBytes((float)byteCount);
                mapStream.Write(bytePackage, 0, 4);
                bytePackage = BitConverter.GetBytes((float)limbServos.Count);
                mapStream.Write(bytePackage, 0, 4);

                mapStream.Position = 16;

                for (int i = 0; i < limbServos.Count; i++)
                {
                    var nameBytePackage = Encoding.ASCII.GetBytes(limbServos[i].servoName);
                    bytePackage = BitConverter.GetBytes((float)nameBytePackage.Length);
                    mapStream.Write(bytePackage, 0, 4);
                    mapStream.Write(nameBytePackage, 0, nameBytePackage.Length);

                    // nameBytePackage = Encoding.ASCII.GetBytes(limbServos[i].parentServoName);
                    bytePackage = BitConverter.GetBytes((float)limbServos[i].servo.HostPart.gameObject.GetInstanceID());
                    mapStream.Write(bytePackage, 0, 4);
                    //  mapStream.Write(nameBytePackage, 0, nameBytePackage.Length);     
                    bytePackage = BitConverter.GetBytes((float)limbServos[i].parentID);
                    mapStream.Write(bytePackage, 0, 4);
                }
            }


            //var contactPoint = memoryBridge.GetVector3(wristServo.servoName + "contactPoint");

            //if (contactPoint != Vector3.zero)
           // {
               // Debug.Log("Set ground point to " + contactPoint);
                //wristServo.contactPoint = contactPoint;
                wristServo.CreateContactPoint();
              //  contactPointSet = true;
            //}
        }