Esempio n. 1
0
        public IActionResult EditComponentType(string button, ComponentType input, IFormFile image, List <long> categoryIds)
        {
            switch (button)
            {
            case "Cancel":
                return(RedirectToAction("Index"));

            case "Update":
                if (image == null)
                {
                    var oldComponent = _componentTypeRepository.GetComponentType(input.ComponentTypeId);
                    input.Image = oldComponent.Image;
                }
                if (image != null)
                {
                    using (var ms = image.OpenReadStream())
                    {
                        var buffer = new byte[ms.Length];
                        ms.Seek(0, SeekOrigin.Begin);
                        ms.ReadAsync(buffer, 0, (int)ms.Length);
                        var esImage = new ESImage {
                            ImageData = buffer
                        };
                        input.Image = esImage;
                    }
                }

                _componentTypeRepository.UpdateComponentType(input);
                var categories = _categoryRepository.GetAllCategories()
                                 .Where(category => categoryIds.Contains(category.CategoryId))
                                 .ToList();

                _componentTypeCategoryRepository.ClearComponentTypeCategoriesForComponentType(input.ComponentTypeId);

                foreach (var category in categories)
                {
                    _componentTypeCategoryRepository.CreateComponentTypeCategory(input, category);
                }
                return(RedirectToAction("Index"));

            default:
                return(RedirectToAction("Index"));
            }
        }
Esempio n. 2
0
        public static void Initializer(EmbeddedStockContext context)
        {
            context.Database.EnsureCreated();


            if (context.Components.Any())
            {
                return;
            }

            var component1 = new Component {
                ComponentNumber = 89,
                SerialNo        = "KL89",
                Status          = ComponentStatus.Available,
                AdminComment    = "Working",
                UserComment     = "A small flaw"
            };
            var component2 = new Component {
                ComponentNumber = 42,
                SerialNo        = "ML42",
                Status          = ComponentStatus.Loaned,
                AdminComment    = "User au593874 has it",
                UserComment     = "I'm keeping it"
            };
            var image = new Byte[0];//System.IO.File.ReadAllBytes("resistor.jpg");

            var esimage = new ESImage {
                ImageData     = image,
                Thumbnail     = image,
                ImageMimeType = "image/jpeg"
            };
            var componenttype = new ComponentType
            {
                ComponentName = "Resistor",
                ComponentInfo = "Just a resistor",
                Location      = "in yer butt",
                Status        = ComponentTypeStatus.Available,
                Datasheet     = "data",
                ImageUrl      = "url",
                Image         = esimage,
                Manufacturer  = "Poul Ejnar A/S",
                WikiLink      = "wikilink",
                AdminComment  = "comment"
            };

            componenttype.Components.Add(component1);
            componenttype.Components.Add(component2);
            var category = new Category
            {
                Name = "Test"
            };

            var categoryComponentType = new CategoryComponentType
            {
                Category      = category,
                ComponentType = componenttype
            };

            context.CategoryComponentTypes.Add(categoryComponentType);
            context.SaveChanges();
        }
        public T Load <T>(string assetName)
        {
            string originalAssetName = assetName;
            object result            = null;

            if (this.graphicsDeviceService == null)
            {
                this.graphicsDeviceService = serviceProvider.GetService(typeof(IGraphicsDeviceService)) as IGraphicsDeviceService;
                if (this.graphicsDeviceService == null)
                {
                    throw new InvalidOperationException("No Graphics Device Service");
                }
            }

            // Check for windows-style directory separator character
            //Lowercase assetName (monodroid specification all assests are lowercase)
            assetName = Path.Combine(_rootDirectory, assetName.Replace('\\', Path.DirectorySeparatorChar)).ToLower();

            // Get the real file name
            if ((typeof(T) == typeof(Texture2D)))
            {
                assetName = Texture2DReader.Normalize(assetName);
            }
            else if ((typeof(T) == typeof(SpriteFont)))
            {
                assetName = SpriteFontReader.Normalize(assetName);
            }
            else if ((typeof(T) == typeof(Effect)))
            {
                assetName = Effect.Normalize(assetName);
            }

            /*else if ((typeof(T) == typeof(Song)))
             * {
             *  assetName = SongReader.Normalize(assetName);
             * }
             * else if ((typeof(T) == typeof(SoundEffect)))
             * {
             *  assetName = SoundEffectReader.Normalize(assetName);
             * }
             * else if ((typeof(T) == typeof(Video)))
             * {
             *  assetName = Video.Normalize(assetName);
             * }*/
            else
            {
                throw new NotSupportedException("Format not supported");
            }

            if (string.IsNullOrEmpty(assetName))
            {
                throw new ContentLoadException("Could not load " + originalAssetName + " asset!");
            }

            if (Path.GetExtension(assetName).ToUpper() != ".XNB")
            {
                if ((typeof(T) == typeof(Texture2D)))
                {
                    //Basically the same as Texture2D.FromFile but loading from the assets instead of a filePath
                    Stream  assetStream = File.Open(assetName, FileMode.Open, FileAccess.Read);
                    Bitmap  image       = (Bitmap)Bitmap.FromStream(assetStream);
                    ESImage theTexture  = new ESImage(image, graphicsDeviceService.GraphicsDevice.PreferedFilter);
                    result = new Texture2D(theTexture)
                    {
                        Name = Path.GetFileNameWithoutExtension(assetName)
                    };
                }
                if ((typeof(T) == typeof(SpriteFont)))
                {
                    //result = new SpriteFont(Texture2D.FromFile(graphicsDeviceService.GraphicsDevice,assetName), null, null, null, 0, 0.0f, null, null);
                    throw new NotImplementedException();
                }

                /*if ((typeof(T) == typeof(Song)))
                 *  result = new Song(assetName);
                 * if ((typeof(T) == typeof(SoundEffect)))
                 *  result = new SoundEffect(assetName);
                 * if ((typeof(T) == typeof(Video)))
                 *  result = new Video(assetName);*/
            }
            else
            {
                // Load a XNB file
                //Loads from Assets directory + /assetName
                Stream assetStream = File.Open(assetName, FileMode.Open, FileAccess.Read);

                ContentReader            reader      = new ContentReader(this, assetStream, this.graphicsDeviceService.GraphicsDevice);
                ContentTypeReaderManager typeManager = new ContentTypeReaderManager(reader);
                reader.TypeReaders = typeManager.LoadAssetReaders(reader);
                foreach (ContentTypeReader r in reader.TypeReaders)
                {
                    r.Initialize(typeManager);
                }
                // we need to read a byte here for things to work out, not sure why
                reader.ReadByte();

                // Get the 1-based index of the typereader we should use to start decoding with
                int index = reader.ReadByte();
                ContentTypeReader contentReader = reader.TypeReaders[index - 1];
                result = reader.ReadObject <T>(contentReader);

                reader.Close();
                assetStream.Close();
            }

            if (result == null)
            {
                throw new ContentLoadException("Could not load " + originalAssetName + " asset!");
            }

            return((T)result);
        }
Esempio n. 4
0
        public async Task <IActionResult> Create(ComponenttypeVM componentType)
        {
            //todo rename kjal
            var kjal = new ESImage();

            if (componentType.Image != null && componentType.Image.Length > 0)
            {
                var fileName = ContentDispositionHeaderValue.Parse(componentType.Image.ContentDisposition).FileName.Trim('"');

                using (var reader = new StreamReader(componentType.Image.OpenReadStream()))
                {
                    string contentAsString = reader.ReadToEnd();
                    byte[] bytes           = new byte[contentAsString.Length * sizeof(char)];
                    System.Buffer.BlockCopy(contentAsString.ToCharArray(), 0, bytes, 0, bytes.Length);

                    kjal.ImageData = bytes;
                }
            }

            kjal.ImageMimeType = "image/png";



            var tmp = new ComponentType();

            tmp.ComponentName = componentType.ComponentName;
            tmp.AdminComment  = componentType.AdminComment;
            tmp.Datasheet     = componentType.Datasheet;
            tmp.ComponentInfo = componentType.ComponentInfo;
            tmp.ImageUrl      = componentType.ImageUrl;
            tmp.Location      = componentType.Location;
            tmp.Status        = componentType.Status;
            tmp.Manufacturer  = componentType.Manufacturer;
            tmp.WikiLink      = componentType.WikiLink;
            tmp.Image         = kjal;

            _context.Add(tmp);
            await _context.SaveChangesAsync();

            //long Id = tmp.ComponentTypeId;

            ICollection <Category> categories = new List <Category>();

            List <Category> cool = new List <Category>();

            if (componentType.Categories != null)
            {
                var catlist = componentType.Categories.Split(",");

                foreach (var item in catlist)
                {
                    cool = _context.Categories.Select(a => a).Where(a => a.Name == item).ToList();

                    if (!cool.Any())
                    {
                        var aCat = new Category
                        {
                            Name = item,
                        };

                        categories.Add(aCat);
                        _context.Add(aCat);
                    }
                    else
                    {
                        //TODO lol :) hacks
                        categories.Add(cool.First());
                    }
                }
            }
            await _context.SaveChangesAsync();

            foreach (var item in categories)
            {
                var free = new CategoryComponenttypebinding()
                {
                    CategoryId      = item.CategoryId,
                    ComponentTypeId = tmp.ComponentTypeId,
                    Category        = item,
                    ComponentType   = tmp
                };

                _context.Add(free);

                tmp.CategoryComponenttypebindings.Add(free);
                item.CategoryComponenttypebindings.Add(free);

                //TODO check if it works without
                _context.Entry(item).State = EntityState.Modified;
                _context.Update(item);
            }

            _context.Entry(tmp).Collection("CategoryComponenttypebindings").IsModified = true;


            await _context.SaveChangesAsync();

            return(RedirectToAction(nameof(Index)));
        }
Esempio n. 5
0
        protected T ReadAsset <T>(string assetName, Action <IDisposable> recordDisposableObject)
        {
            if (string.IsNullOrEmpty(assetName))
            {
                throw new ArgumentNullException();
            }
            if (disposed)
            {
                throw new ObjectDisposedException("ContentManager");
            }

            string originalAssetName = assetName;
            object result            = null;

            if (this.graphicsDeviceService == null)
            {
                this.graphicsDeviceService = serviceProvider.GetService(typeof(IGraphicsDeviceService)) as IGraphicsDeviceService;
                if (this.graphicsDeviceService == null)
                {
                    throw new InvalidOperationException("No Graphics Device Service");
                }
            }

            // Replace Windows path separators with local path separators
            assetName = Path.Combine(_rootDirectory, assetName.Replace('\\', Path.DirectorySeparatorChar));

            // Get the real file name
            if ((typeof(T) == typeof(Texture2D)))
            {
                assetName = Texture2DReader.Normalize(assetName);
            }
            else if ((typeof(T) == typeof(SpriteFont)))
            {
                assetName = SpriteFontReader.Normalize(assetName);
            }
            else if ((typeof(T) == typeof(Effect)))
            {
                assetName = Effect.Normalize(assetName);
            }
            else if ((typeof(T) == typeof(Song)))
            {
                assetName = SongReader.Normalize(assetName);
            }
            else if ((typeof(T) == typeof(SoundEffect)))
            {
                assetName = SoundEffectReader.Normalize(assetName);
            }
            else if ((typeof(T) == typeof(Video)))
            {
                assetName = Video.Normalize(assetName);
            }
            else
            {
                throw new NotSupportedException("Format not supported");
            }

            if (string.IsNullOrEmpty(assetName))
            {
                throw new ContentLoadException("Could not load " + originalAssetName + " asset!");
            }

            if (!Path.HasExtension(assetName))
            {
                assetName = string.Format("{0}.xnb", assetName);
            }

            if (Path.GetExtension(assetName).ToUpper() == ".XNB")
            {
                // Load a XNB file
                //Loads from Assets directory + /assetName
                Stream       stream    = OpenStream(assetName);
                BinaryReader xnbReader = new BinaryReader(stream);

                // The first 4 bytes should be the "XNB" header. i use that to detect an invalid file
                byte[] headerBuffer = new byte[3];
                xnbReader.Read(headerBuffer, 0, 3);

                string headerString = Encoding.UTF8.GetString(headerBuffer, 0, 3);

                byte platform = xnbReader.ReadByte();

                if (string.Compare(headerString, "XNB") != 0 ||
                    !(platform == 'w' || platform == 'x' || platform == 'm'))
                {
                    throw new ContentLoadException("Asset does not appear to be a valid XNB file. Did you process your content for Windows?");
                }

                ushort version         = xnbReader.ReadUInt16();
                int    graphicsProfile = version & 0x7f00;
                version &= 0x80ff;

                bool compressed = false;
                if (version == 0x8005 || version == 0x8004)
                {
                    compressed = true;
                }
                else if (version != 5 && version != 4)
                {
                    throw new ContentLoadException("Invalid XNB version");
                }

                // The next int32 is the length of the XNB file
                int xnbLength = xnbReader.ReadInt32();

                ContentReader reader;
                if (compressed)
                {
                    //decompress the xnb
                    //thanks to ShinAli (https://bitbucket.org/alisci01/xnbdecompressor)
                    int compressedSize   = xnbLength - 14;
                    int decompressedSize = xnbReader.ReadInt32();
                    int newFileSize      = decompressedSize + 10;

                    MemoryStream decompressedStream = new MemoryStream(decompressedSize);

                    LzxDecoder dec          = new LzxDecoder(16);
                    int        decodedBytes = 0;
                    int        pos          = 0;

                    while (pos < compressedSize)
                    {
                        // let's seek to the correct position
                        stream.Seek(pos + 14, SeekOrigin.Begin);
                        int hi         = stream.ReadByte();
                        int lo         = stream.ReadByte();
                        int block_size = (hi << 8) | lo;
                        int frame_size = 0x8000;
                        if (hi == 0xFF)
                        {
                            hi         = lo;
                            lo         = (byte)stream.ReadByte();
                            frame_size = (hi << 8) | lo;
                            hi         = (byte)stream.ReadByte();
                            lo         = (byte)stream.ReadByte();
                            block_size = (hi << 8) | lo;
                            pos       += 5;
                        }
                        else
                        {
                            pos += 2;
                        }

                        if (block_size == 0 || frame_size == 0)
                        {
                            break;
                        }

                        int lzxRet = dec.Decompress(stream, block_size, decompressedStream, frame_size);
                        pos          += block_size;
                        decodedBytes += frame_size;
                    }

                    if (decompressedStream.Position != decompressedSize)
                    {
                        throw new ContentLoadException("Decompression of " + originalAssetName + "failed. " +
                                                       " Try decompressing with nativeDecompressXnb first.");
                    }

                    decompressedStream.Seek(0, SeekOrigin.Begin);
                    reader = new ContentReader(this, decompressedStream, this.graphicsDeviceService.GraphicsDevice);
                }
                else
                {
                    reader = new ContentReader(this, stream, this.graphicsDeviceService.GraphicsDevice);
                }

                ContentTypeReaderManager typeManager = new ContentTypeReaderManager(reader);
                reader.TypeReaders = typeManager.LoadAssetReaders(reader);
                foreach (ContentTypeReader r in reader.TypeReaders)
                {
                    r.Initialize(typeManager);
                }
                // we need to read a byte here for things to work out, not sure why
                reader.ReadByte();

                // Get the 1-based index of the typereader we should use to start decoding with
                int index = reader.ReadByte();
                ContentTypeReader contentReader = reader.TypeReaders[index - 1];
                result = reader.ReadObject <T>(contentReader);

                reader.Close();
                stream.Close();
            }
            else
            {
                if ((typeof(T) == typeof(Texture2D)))
                {
                    //Basically the same as Texture2D.FromFile but loading from the assets instead of a filePath
                    Stream  assetStream = OpenStream(assetName);
                    Bitmap  image       = BitmapFactory.DecodeStream(assetStream);
                    ESImage theTexture  = new ESImage(image, graphicsDeviceService.GraphicsDevice.PreferedFilter);
                    result = new Texture2D(theTexture)
                    {
                        Name = Path.GetFileNameWithoutExtension(assetName)
                    };
                }
                if ((typeof(T) == typeof(SpriteFont)))
                {
                    //result = new SpriteFont(Texture2D.FromFile(graphicsDeviceService.GraphicsDevice,assetName), null, null, null, 0, 0.0f, null, null);
                    throw new NotImplementedException();
                }

                if ((typeof(T) == typeof(Song)))
                {
                    result = new Song(assetName);
                }
                if ((typeof(T) == typeof(SoundEffect)))
                {
                    result = new SoundEffect(assetName);
                }
                if ((typeof(T) == typeof(Video)))
                {
                    result = new Video(assetName);
                }
            }

            /*else
             * {
             *      // Load a XNB file
             * //Loads from Assets directory + /assetName
             *  Stream assetStream = OpenStream(assetName);
             *
             * ContentReader reader = new ContentReader(this, assetStream, this.graphicsDeviceService.GraphicsDevice);
             *      ContentTypeReaderManager typeManager = new ContentTypeReaderManager(reader);
             *      reader.TypeReaders = typeManager.LoadAssetReaders(reader);
             * foreach (ContentTypeReader r in reader.TypeReaders)
             * {
             * r.Initialize(typeManager);
             * }
             * // we need to read a byte here for things to work out, not sure why
             * reader.ReadByte();
             *
             *      // Get the 1-based index of the typereader we should use to start decoding with
             * int index = reader.ReadByte();
             *      ContentTypeReader contentReader = reader.TypeReaders[index - 1];
             * result = reader.ReadObject<T>(contentReader);
             *
             *      reader.Close();
             *      assetStream.Close();
             * }*/

            if (result == null)
            {
                throw new ContentLoadException("Could not load " + originalAssetName + " asset!");
            }

            // Store references to the asset for later use
            T asset = (T)result;

            if (asset is IDisposable && recordDisposableObject != null)
            {
                recordDisposableObject(asset as IDisposable);
            }
            else
            {
                disposableAssets.Add(asset as IDisposable);
            }
            loadedAssets.Add(originalAssetName, asset);

            return((T)result);
        }
Esempio n. 6
0
        public static void Initializer(ApplicationDbContext
                                       context)
        {
            context.Database.EnsureCreated();


            if (context.Components.Any())
            {
                return;
            }

            var component1 = new Component {
                ComponentNumber = 89,
                SerialNo        = "KL89",
                Status          = ComponentStatus.Available,
                AdminComment    = "Working",
                UserComment     = "A small flaw"
            };
            var component2 = new Component {
                ComponentNumber = 42,
                SerialNo        = "ML42",
                Status          = ComponentStatus.Loaned,
                AdminComment    = "User au593874 has it",
                UserComment     = "I'm keeping it"
            };
            var component3 = new Component
            {
                ComponentNumber = 3,
                SerialNo        = "JK69",
                Status          = ComponentStatus.Loaned,
                AdminComment    = "Lots of fun",
                UserComment     = "Sure is"
            };

            context.Components.Add(component1);
            context.Components.Add(component2);
            context.Components.Add(component3);
            context.SaveChanges();

            var image = new Byte[0];//System.IO.File.ReadAllBytes("resistor.jpg");

            var esimage = new ESImage {
                ImageData     = image,
                Thumbnail     = image,
                ImageMimeType = "image/jpeg"
            };

            var componentType1 = new ComponentType
            {
                ComponentName = "Resistor",
                ComponentInfo = "Just a resistor",
                Location      = "Shelf",
                Status        = ComponentTypeStatus.Available,
                Datasheet     = "data",
                ImageUrl      = "url",
                Image         = esimage,
                Manufacturer  = "Hest og Co A/S",
                WikiLink      = "wikilink",
                AdminComment  = "comment",
            };

            var componentType2 = new ComponentType
            {
                ComponentName = "Pump",
                ComponentInfo = "Just a pump",
                Location      = "Drawer 5",
                Status        = ComponentTypeStatus.Available,
                Datasheet     = "Push up 4 times",
                ImageUrl      = "url",
                Image         = esimage,
                Manufacturer  = "Fitness World",
                WikiLink      = "wikilink",
                AdminComment  = "Be careful if you don't want to be big",
            };

            componentType1.Components.Add(component1);
            componentType1.Components.Add(component2);
            context.ComponentTypes.Add(componentType1);

            componentType2.Components.Add(component3);
            context.ComponentTypes.Add(componentType2);
            context.SaveChanges();

            var category = new Category
            {
                Name = "Test"
            };

            var categoryComponentType1 = new ComponentTypeCategory
            {
                Category      = category,
                ComponentType = componentType1
            };

            var categoryComponentType2 = new ComponentTypeCategory
            {
                Category      = category,
                ComponentType = componentType2
            };

            category.ComponentTypeCategories.Add(categoryComponentType1);
            category.ComponentTypeCategories.Add(categoryComponentType2);
            context.Categories.Add(category);
            //context.CategoryComponentTypes.Add(categoryComponentType);
            context.SaveChanges();
        }
Esempio n. 7
0
        public T Load <T>(string assetName)
        {
            string originalAssetName = assetName;
            object result            = null;

            if (this.graphicsDeviceService == null)
            {
                this.graphicsDeviceService = serviceProvider.GetService(typeof(IGraphicsDeviceService)) as IGraphicsDeviceService;
                if (this.graphicsDeviceService == null)
                {
                    throw new InvalidOperationException("No Graphics Device Service");
                }
            }

            assetName = Path.Combine(_rootDirectory, assetName.Replace('\\', Path.DirectorySeparatorChar));

            // Get the real file name
            if ((typeof(T) == typeof(Texture2D)))
            {
                assetName = Texture2DReader.Normalize(assetName);
            }
            else if ((typeof(T) == typeof(SpriteFont)))
            {
                assetName = SpriteFontReader.Normalize(assetName);
            }
            else if ((typeof(T) == typeof(Effect)))
            {
                assetName = Effect.Normalize(assetName);
            }
            else if ((typeof(T) == typeof(Song)))
            {
                assetName = SongReader.Normalize(assetName);
            }
            else if ((typeof(T) == typeof(SoundEffect)))
            {
                assetName = SoundEffectReader.Normalize(assetName);
            }
            else if ((typeof(T) == typeof(Video)))
            {
                assetName = Video.Normalize(assetName);
            }
            else
            {
                throw new NotSupportedException("Format not supported");
            }

            if (string.IsNullOrEmpty(assetName))
            {
                throw new ContentLoadException("Could not load " + originalAssetName + " asset!");
            }

            if (Path.GetExtension(assetName).ToUpper() != ".XNB")
            {
                if ((typeof(T) == typeof(Texture2D)))
                {
                    //Basically the same as Texture2D.FromFile but loading from the assets instead of a filePath
                    Stream assetStream = Game.contextInstance.Assets.Open(assetName);
                    Bitmap image       = BitmapFactory.DecodeStream(assetStream);
                    //Bitmap image = BitmapFactory.DecodeFileDescriptor(Game.contextInstance.Assets.OpenFd(assetName).FileDescriptor);
                    ESImage theTexture;

                    if (GraphicsDevice.openGLESVersion == OpenTK.Graphics.GLContextVersion.Gles2_0)
                    {
                        theTexture = new ESImage(image, graphicsDeviceService.GraphicsDevice.PreferedFilterGL20);
                    }
                    else
                    {
                        theTexture = new ESImage(image, graphicsDeviceService.GraphicsDevice.PreferedFilterGL11);
                    }

                    result = new Texture2D(theTexture)
                    {
                        Name = Path.GetFileNameWithoutExtension(assetName)
                    };
                }
                if ((typeof(T) == typeof(SpriteFont)))
                {
                    //result = new SpriteFont(Texture2D.FromFile(graphicsDeviceService.GraphicsDevice,assetName), null, null, null, 0, 0.0f, null, null);
                    throw new NotImplementedException();
                }

                if ((typeof(T) == typeof(Song)))
                {
                    result = new Song(assetName);
                }
                if ((typeof(T) == typeof(SoundEffect)))
                {
                    result = new SoundEffect(assetName);
                }
                if ((typeof(T) == typeof(Video)))
                {
                    result = new Video(assetName);
                }
            }
            else
            {
                // Load a XNB file
                //Loads from Assets directory + /assetName
                Stream assetStream = Game.contextInstance.Assets.Open(assetName);

                ContentReader            reader      = new ContentReader(this, assetStream, this.graphicsDeviceService.GraphicsDevice);
                ContentTypeReaderManager typeManager = new ContentTypeReaderManager(reader);
                reader.TypeReaders = typeManager.LoadAssetReaders(reader);
                foreach (ContentTypeReader r in reader.TypeReaders)
                {
                    r.Initialize(typeManager);
                }
                // we need to read a byte here for things to work out, not sure why
                reader.ReadByte();

                // Get the 1-based index of the typereader we should use to start decoding with
                int index = reader.ReadByte();
                ContentTypeReader contentReader = reader.TypeReaders[index - 1];
                result = reader.ReadObject <T>(contentReader);

                reader.Close();
                assetStream.Close();
            }

            if (result == null)
            {
                throw new ContentLoadException("Could not load " + originalAssetName + " asset!");
            }

            return((T)result);
        }
        public async Task <IActionResult> Edit(ComTypeViewModel componentTypeViewModel)
        {
            if (!ModelState.IsValid)
            {
                return(RedirectToAction(nameof(Edit), componentTypeViewModel.ComponentType.ComponentTypeId));
            }
            try
            {
                _context.ComponentCategoryTypes.RemoveRange(_context.ComponentCategoryTypes.Where(x => x.ComponentTypeId == componentTypeViewModel.ComponentType.ComponentTypeId));

                if (componentTypeViewModel.ChoosenCategories != null)
                {
                    var choosenCategories = _context.Category.Where(x =>
                                                                    componentTypeViewModel.ChoosenCategories.Contains(x.CategoryId.ToString()));

                    var componentCategoryTypes = new List <ComponentCategoryType>();
                    foreach (var choosenCategory in choosenCategories)
                    {
                        componentCategoryTypes.Add(new ComponentCategoryType()
                        {
                            CategoryId    = choosenCategory.CategoryId,
                            ComponentType = componentTypeViewModel.ComponentType
                        });
                    }
                    componentTypeViewModel.ComponentType.ComponentCategoryTypes = componentCategoryTypes;
                }

                var    image  = new ESImage();
                Bitmap target = new Bitmap(64, 64);
                Bitmap imageFullSize;
                if (componentTypeViewModel.Image != null)
                {
                    var filename = Path.GetExtension(componentTypeViewModel.Image.FileName.ToLower());
                    if (!filename.Contains(".jpg") && !filename.Contains(".jpeg") && !filename.Contains(".png") && !filename.Contains(".bmp") && !filename.Contains(".gif"))
                    {
                        return(RedirectToAction(nameof(Edit), componentTypeViewModel.ComponentType.ComponentTypeId));
                    }
                    using (var memoryStream = new MemoryStream())
                    {
                        await componentTypeViewModel.Image.CopyToAsync(memoryStream);

                        image.ImageData = memoryStream.ToArray();
                        imageFullSize   = new Bitmap(memoryStream);
                    }

                    using (var graphics = Graphics.FromImage(target))
                    {
                        graphics.CompositingQuality = CompositingQuality.HighSpeed;
                        graphics.InterpolationMode  = InterpolationMode.HighQualityBicubic;
                        graphics.CompositingMode    = CompositingMode.SourceCopy;
                        graphics.DrawImage(imageFullSize, 0, 0, 64, 64);
                        using (var memoryStream = new MemoryStream())
                        {
                            target.Save(memoryStream, getImageFormat(filename));
                            image.Thumbnail = memoryStream.ToArray();
                        }
                    }

                    image.ImageMimeType = "image/" + filename.Remove(0, 1);
                    componentTypeViewModel.ComponentType.Image = image;
                    _context.EsImages.Add(image);
                }

                _context.Update(componentTypeViewModel.ComponentType);
                await _context.SaveChangesAsync();
            }
            catch (DbUpdateConcurrencyException)
            {
                if (!ComponentTypeExists(componentTypeViewModel.ComponentType.ComponentTypeId))
                {
                    return(NotFound());
                }
                else
                {
                    throw;
                }
            }
            return(RedirectToAction(nameof(Index)));
        }