Exemplo n.º 1
0
 public void ShowPicture(Picture picture)
 {
     lock (this)
     {
         m_Picture = picture;
         if (m_Picture != null)
         {
             m_TextBlockDQId.Text = m_Picture.LayerId.ToString();
             m_TextBlockPictureNumber.Text = m_Picture.Index.ToString();
             m_TextBlockSize.Text = String.Format("{0}x{1}", m_Picture.Width, m_Picture.Height);
             m_TextBlockNumberOfSlices.Text = m_Picture.NumberOfSlices.ToString();
             m_EntropyCodingType.Text = m_Picture.EntropyCodingType;
             m_TextBlockMbBitsCount.Text = (m_Picture as H264Picture).MbBitsCount.ToString();
             m_TextBlockMD5.Text = String.Format("Y\t= {0}\nU\t= {1}\nV\t= {2}\nYUV\t= {3}",
                 m_Picture.GetMd5(Utils.MD5_ELTMB_TYPE, 0),
                 m_Picture.GetMd5(Utils.MD5_ELTMB_TYPE, 1),
                 m_Picture.GetMd5(Utils.MD5_ELTMB_TYPE, 2),
                 m_Picture.GetMd5(Utils.MD5_ELTMB_TYPE, 3)).ToUpper();
         }
         else
         {
             // FIXME: show error image
             Debug.Assert(false);
         }
     }
 }
Exemplo n.º 2
0
        public int BufferCB(double sampleTime, IntPtr buffer, int len)
        {
            using (var rgba = new Picture<Rgba, byte>(Width, Height))
            using (var gray = new Picture<Gray, byte>(Width, Height))
            {
                if ((len / 3) == (Width * Height))
                {
                    using (var bgr = new Image<Bgr, byte>(Width, Height, Width * 3, buffer))
                    {
                        bgr._Flip(FLIP.VERTICAL);
                        CvInvoke.cvCvtColor(bgr.Ptr, rgba.Emgu.Ptr, COLOR_CONVERSION.CV_BGR2RGBA);
                        CvInvoke.cvCvtColor(bgr.Ptr, gray.Emgu.Ptr, COLOR_CONVERSION.CV_BGR2GRAY);
                    }
                }
                else
                {
                    gray.Errorize();
                    rgba.Errorize();
                }

                OnNext(gray.AddRef(), rgba.AddRef());
            }

            return 0;
        }
Exemplo n.º 3
0
        /*
         * Responder stuff 
         */

        /// <summary>
        /// Updates the data with which the web event responds and sets the correct MIME type. 
        /// </summary>
        /// <param name="picture">Picture to be published. </param>
        public void Respond(Picture picture)
        {
            if (CheckResponded()) return;
            if (picture != null)
            {
                string tempMimeType = "application/binary";

                if (picture.Encoding == Picture.PictureEncoding.BMP)
                {
                    tempMimeType = "image/bmp";
                }
                else if (picture.Encoding == Picture.PictureEncoding.GIF)
                {
                    tempMimeType = "image/gif";
                }
                else if (picture.Encoding == Picture.PictureEncoding.JPEG)
                {
                    tempMimeType = "image/jpeg";
                }

                webEvent.ContentType = tempMimeType;
                webEvent.ResponseData = picture.PictureData;
            }
            SendResponse();
        }
Exemplo n.º 4
0
        public void AddPicture(AddPictureInput input)
        {
            if (input != null)
            {
                var picture = new Picture
                {
                    PictureName = input.PictureName,
                    Tags = input.Tags,
                    Description = input.Description,
                    DateAdded = DateTime.Now,
                    PictureMimeType = input.PictureMimeType,
                    PictureData = input.PictureData
                };

                if (input.UserId.HasValue)
                {
                    var user = new User { 
                        Id = input.UserId.Value
                    };

                    picture.AssignedUser = user;
                }
               
                _pictureRepository.Insert(picture);
            }
        } 
Exemplo n.º 5
0
    public override DBlog.Tools.Web.PicturePage.Picture GetPictureWithBitmap(int id)
    {
        Picture pic = new Picture();

        TransitImage img = SessionManager.GetCachedObject<TransitImage>(
            "GetImageWithBitmapById", SessionManager.PostTicket, id);

        if (img == null)
            return null;

        if (img.Data == null && !string.IsNullOrEmpty(img.Path))
        {
            img.Data = new ThumbnailBitmap(Path.Combine(Path.Combine(
                SessionManager.GetSetting("Images", string.Empty),
                img.Path), img.Name)).Bitmap;
        }

        pic.Bitmap = img.Data;
        pic.Created = pic.Modified = img.Modified;
        pic.Name = img.Name;
        pic.Id = img.Id;

        if (SessionManager.CountersEnabled)
        {
            IncrementCounter();
        }

        return pic;
    }
Exemplo n.º 6
0
        public void AddComment(AddCommentInput input)
        {
            if (input != null)
            {
                var comment = new Comment
                {
                    Text = input.Text
                };

                if (input.UserId.HasValue)
                {
                    var user = new User
                    {
                        Id = input.UserId.Value
                    };

                    comment.AssignedUser = user;
                } 

                if (input.PictureId.HasValue)
                {
                    var picture = new Picture
                    {
                        Id = input.PictureId.Value
                    };

                    comment.AssignedPicture = picture;
                }

                _commentRepository.Insert(comment);
            }
        }
Exemplo n.º 7
0
        private PointF[] FindChessBoardCorners(Picture picture, string uniqueSourceId)
        {
            using (var gray = picture.Bgra.Convert<Gray, byte>())
            {
                PointF[] corners;
                var ok = CameraCalibration.FindChessboardCorners(gray, this.Dim, CALIB_CB_TYPE.ADAPTIVE_THRESH | CALIB_CB_TYPE.FILTER_QUADS | CALIB_CB_TYPE.NORMALIZE_IMAGE, out corners);
                foreach (var c in corners)
                    if (float.IsNaN(c.X) || float.IsNaN(c.Y))
                        ok = false;

                if (ok)
                {
                    var window = new Size(15, 15);
                    var zeroZone = new Size(-1, -1);
                    var criteria = new MCvTermCriteria(16, 0.001);
                    gray.FindCornerSubPix(new PointF[][] { corners }, window, zeroZone, criteria);

                    picture.Bgra.ConvertFrom(gray);

                    return corners;
                }
            }

            return null;
        }
Exemplo n.º 8
0
 public void SetTextMesh(Picture script)
 {
     textToChange = script.text;
     simpleText = script.simpleText;
     picture = script;
     rowLimit = 2;
 }
    public void ListView1_InsertItem([QueryString("PhotoAlbumId")] int photoAlbumId)
    {
        Picture picture = new Picture();
        TryUpdateModel(picture);
        FileUpload FileUpload1 = (FileUpload)ListView1.InsertItem.FindControl("FileUpload1");
        if (!FileUpload1.HasFile || !FileUpload1.FileName.ToLower().EndsWith(".jpg"))
        {
          CustomValidator cusValImage = (CustomValidator)ListView1.InsertItem.FindControl("cusValImage");
          cusValImage.IsValid = false;
          ModelState.AddModelError("Invalid", cusValImage.ErrorMessage);
        }
        if (ModelState.IsValid && Page.IsValid)
        {
          using (var myEntities = new PlanetWroxEntities())
          {
        picture.PhotoAlbumId = photoAlbumId;

        string virtualFolder = "~/GigPics/";
        string physicalFolder = Server.MapPath(virtualFolder);
        string fileName = Guid.NewGuid().ToString();
        string extension = System.IO.Path.GetExtension(FileUpload1.FileName);
        FileUpload1.SaveAs(System.IO.Path.Combine(physicalFolder, fileName + extension));
        picture.ImageUrl = virtualFolder + fileName + extension;

        myEntities.Pictures.Add(picture);
        myEntities.SaveChanges();
          }
        }
    }
Exemplo n.º 10
0
        public PreviewGrid(Picture picture)
            : base()
        {
            _displayPicture = picture;
            _viewPort = new ViewportControl();
            this.Children.Add(_viewPort);

            _viewPort.ManipulationStarted += OnViewportManipulationStarted;
            _viewPort.ManipulationDelta += OnViewportManipulationDelta;
            _viewPort.ManipulationCompleted += OnViewportManipulationCompleted;
            _viewPort.ViewportChanged += OnViewportChanged;

            ImageLoaded = false;

            _imageView = new Image();
            _bitmap = new BitmapImage();
            //_bitmap.SetSource(picture.GetImage());
            _imageView.Source = _bitmap;
            _imageView.Stretch = Stretch.Uniform;
            _imageView.RenderTransformOrigin = new Point(0, 0);

            _scaleTransform = new ScaleTransform();
            _imageView.RenderTransform = _scaleTransform;

            _imageHolderCanvas = new Canvas();
            _imageHolderCanvas.Children.Add(_imageView);

            _viewPort.Content = _imageHolderCanvas;

            //LoadImage();
        }
Exemplo n.º 11
0
 public static decimal? ReadAsDecimal(this Queue<EdiEntry> queue, string path, Picture? picture, char? decimalMark) {
     var text = ReadAsString(queue, path);
     if (string.IsNullOrEmpty(text))
         return null;
     
     return text.Parse(picture, decimalMark);
 }
Exemplo n.º 12
0
    public Sprite (float dx, float dy, int color, int width, int height,
      Picture.Format pf) {
      
      x = window.width/2;
      y = window.height/2;
      this.dx = dx;
      this.dy = dy;
      this.color = color;
      this.width = width;
      this.height = height;

      pixmap = new Pixmap (display.default_root, width, height, 
        pf.depth ());
      picture = render.create_picture (pixmap, pf,
        Picture.Attributes.EMPTY); 

      if (sprite_gc == null)
        sprite_gc = new GC (pixmap);      
    
      sprite_gc.set_foreground (0);
      pixmap.rectangle (sprite_gc, 0, 0, width, height, true);
      sprite_gc.set_foreground (color);
      pixmap.arc (sprite_gc, 0, 0, width, height, 0, 360*64, true);


      for (int i=0; i<8; i++) {
        sprite_gc.set_foreground (divide_color (color, 1<<(7-i)));
        pixmap.arc (sprite_gc, i, i, width-2*i, height-2*i, 
          0, 360*64, true);
      }
    }
Exemplo n.º 13
0
 private void NewCommand(object sender, ExecutedRoutedEventArgs e)
 {
     var dlog = new NewDocument
     {
         Owner = this
     };
     var result = dlog.ShowDialog();
     if (!result.HasValue || !result.Value)
     {
         return;
     }
     var bmp = new WriteableBitmap(
         dlog.ViewModel.Width,
         dlog.ViewModel.Height,
         96,
         96,
         PixelFormats.Bgr32,
         null);
     _picture = new Picture(dlog.ViewModel.Name, bmp);
     Title = _picture.Name;
     ViewModel.Document = new ReversibleDocument<IPicture>(_picture);
     ViewModel.AccessPolicy = new PictureAccessPolicy(_picture);
     _image.Source = bmp;
     _image.Stretch = Stretch.None;
     RenderOptions.SetBitmapScalingMode(_image, BitmapScalingMode.NearestNeighbor);
     RenderOptions.SetEdgeMode(_image, EdgeMode.Aliased);
 }
Exemplo n.º 14
0
        public static List<Picture> GetPhotos(string inputFrom, bool R)
        {
            SearchOption option = R ? SearchOption.AllDirectories : SearchOption.TopDirectoryOnly;
            string[] files = Directory.GetFiles(inputFrom, "*.jpg", option);

            if (files.Length == 0)
                return null;

            Debug("Found {0} files ", files.Length);
            Debug("Building list of photos to process");
            List<Picture> pics = new List<Picture>();
            int count = 1;
            foreach (var file in files)
            {
                Picture pic = new Picture(file);
                pics.Add(new Picture(file));
                if (verbosity > 0)
                {
                    drawTextProgressBar(count, files.Length);
                }
                ++count;
            }

            return pics;
        }
Exemplo n.º 15
0
        //Load pictures to the canvas
        private void LoadPictures()
        {
            string[] pictureLocations = GetPictureLocations();
            double angle = 0;
            double angleStep = 360 / pictureLocations.Length;

            foreach (string filePath in pictureLocations)
            {
                try
                {
                    Picture p = new Picture();
                    p.ImagePath = filePath;
                    p.Width = 300;
                    p.Angle = 180 - angle;
                    double angleRad = angle * Math.PI / 180.0;
                    p.X = Math.Sin(angleRad) * 300 + (_canvas.ActualWidth - 300) / 2.0;
                    p.Y = Math.Cos(angleRad) * 300 + (_canvas.ActualHeight - 300) / 2.0;
                    _canvas.Children.Add(p);

                    angle += angleStep;
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Trace.WriteLine("Error:" + ex.Message);
                }
            }
        }
 private BitmapImage GetImage(Picture picture)
 {
     var type = picture.MimeType;
     var data = picture.PictureBinary;
     var bmp = new BitmapImage();
     bmp.StreamSource = new System.IO.MemoryStream(data);
     return bmp;
 }
        private void InitLayout()
        {
            this.pic = new Picture();
            this.Children.Add(this.pic);

            this.button = new Button();
            this.pic.Children.Add(this.button);
        }
Exemplo n.º 18
0
 /// <summary>
 /// 修改Books表信息时 添加修改索引(实质上是先删除原有索引 再新增修改后索引)请求至队列
 /// </summary>
 /// <param name="picture"></param>
 public void Mod(Picture.Model.TagModel tag)
 {
     TagViewMode bvm = new TagViewMode();
     bvm.Id = tag.TId;
     bvm.Tag = tag.TagName;
     bvm.IT = IndexType.Modify;
     tagQueue.Enqueue(bvm);
 }
 public void StorePicture(User user, Picture picture, Stream pictureStream)
 {
     var storagePath = GetStoragePath(user, picture);
     using (var writer = File.OpenWrite(storagePath))
     {
         pictureStream.CopyTo(writer);
     }
 }
Exemplo n.º 20
0
 /// <summary>
 /// New employee photo without any link to database
 /// </summary>
 /// <returns>Employee photo instance</returns>
 public EmployeePhoto NewEmployeePhoto(Employee employee, Picture picture)
 {
     return New<EmployeePhoto>((e) =>
     {
         e.Employee = employee;
         e.Picture = picture;
         employee.Photos.Add(e);
     });
 }
Exemplo n.º 21
0
        private bool CanUpload(Picture x)
        {
            if (UploadAll)
            {
                return true;
            }

            return x.Date.Date >= AfterDateTime.Date;
        }
Exemplo n.º 22
0
 private async void UpdateTexture2D(Picture<Gray, byte> gray, Picture<Rgba, byte> rgba)
 {
     await Program.SwitchToRender();
         
     using (rgba)
     using (gray)
     {
         GrayTexture2D.SetData(gray.Bytes);
         RgbaTexture2D.SetData(rgba.Bytes);
     }
 }
Exemplo n.º 23
0
        public ActionResult Add(IList<PictureViewModel> imageFile)
        {
            if (!ModelState.IsValid)
            {
                ModelState.AddModelError("ImageUpload","");
                return View(imageFile);
            }
            if (imageFile != null || imageFile.Count > 0)
            {
                string fileNameStr = "";
                foreach (var file in imageFile)
                {
                    if (file.ImageUpload != null)
                    {
                        fileNameStr = file.ImageUpload.FileName;
                        var imageLocation = Path.Combine(Server.MapPath("~/Content/Gallery"), fileNameStr);
                        if (System.IO.File.Exists(imageLocation))
                        {
                            string extension = Path.GetExtension(file.ImageUpload.FileName);
                            fileNameStr = Guid.NewGuid() + extension;
                            imageLocation = Path.Combine(
                                           Server.MapPath("~/Content/Gallery"), fileNameStr);
                        }
                        var picture = new Picture();
                        picture.Description = file.Description;
                        picture.FilePath ="/Content/Gallery/"+ fileNameStr;
                        picture.IsFront = file.IsFront;
                        if (Enum.IsDefined(typeof(RoomType), file.RoomType))
                        {
                            picture.RoomType = file.RoomType;
                        }
                        else
                        {
                            picture.RoomType = null;
                        }
                 
                        this.pictures.Add(picture);
                        try
                        {                    
                            this.pictures.SaveChanges();
                            picture.FilePath = "/Content/Gallery/" + file.ImageUpload.FileName;
                        }
                        catch (Exception)
                        {
                            throw new ArgumentException("Problem when trying to save in database!");
                        }

                        file.ImageUpload.SaveAs(imageLocation);
                    }
                }
            }

            return RedirectToAction("Index");
        }
Exemplo n.º 24
0
 public void MaybeUndistort(Picture picture)
 {
     if (intrinsics != null && this.mapx != null && this.mapy != null)
     {
         using (var other = new Picture(picture.Width, picture.Height))
         {
             picture.Bgra.CopyTo(other.Bgra);
             CvInvoke.cvRemap(other.Bgra.Ptr, picture.Bgra.Ptr, mapx, mapy, (int)INTER.CV_INTER_LINEAR | (int)Emgu.CV.CvEnum.WARP.CV_WARP_FILL_OUTLIERS, new MCvScalar(255.0f, 0.0f, 255.0f, 255.0f));
         }
     }
 }
Exemplo n.º 25
0
        public ImageListItem(Picture picture, SelectiveSyncViewModel parent)
        {
            Picture = picture;
            Parent = parent;
            Thumb = new BitmapImage();
            BackgroundWorker imageLoader = new BackgroundWorker();
            imageLoader.DoWork += new DoWorkEventHandler(imageLoader_DoWork);
            imageLoader.RunWorkerAsync();

            SelectCommand = new DelegateCommand(SelectImage);
        }
        private PictureRef CreatePicRef(Picture picture)
        {
            var bitmap = new BitmapImage();
            bitmap.SetSource(picture.GetThumbnail());
            var result = new PictureRef()
                {
                    Id = picture,
                    Src = bitmap
                };

            return result;
        }
Exemplo n.º 27
0
        /// <summary>
        /// Constructs a new hit circle.
        /// </summary>
        public HitCircle()
        {
            circlePicture = new Picture(new Texture("Assets/Gameplay/circle.png"));
            circlePicture.Center();
            addChild(circlePicture);

            approachCirclePicture = new Picture(new Texture("Assets/Gameplay/approachcircle.png"));
            approachCirclePicture.Center();
            addChild(approachCirclePicture);

            MouseButton += HitCircle_MouseButton;
            MouseEvents = true;
        }
Exemplo n.º 28
0
        /// <summary>
        /// Constructor
        /// </summary>
        public PicturePreviewModel(Picture picture)
        {
            Title = picture.Name;

            Created = picture.Date.ToString();

            Resolution = picture.Height.ToString() + "x" + picture.Width.ToString();

            // load source of the image
            ImageSource = new BitmapImage();
            System.IO.Stream stream = picture.GetImage();

            ImageSource.SetSource(stream);
        }
        //private VacationMTEAdapter vacationAdapter = new VacationMTEAdapter();
        public Picture MapData(PictureModel pictureModel)
        {
            Picture pic = new Picture();

            if (pictureModel != null)
            {
                pic.Id = pictureModel.Id;
                pic.Titel = pictureModel.Titel;
                pic.Url = pictureModel.Url;
                pic.Description = pictureModel.Description;
                pic.VacationId = pictureModel.VacId;
            }
            return pic;
        }
Exemplo n.º 30
0
        public static void ProcessUploadedPicture(Guid uploadId)
        {
            var fileUpload = _db.FirstOrDefault<FileUpload>("select * from [FileUploads] where [Id] = @0", uploadId);
            if(fileUpload == null)
                throw new Exception(String.Format("FileUpload with Id {0} does not exist", uploadId));

            var storageContainer = StorageContext.GetContainer(String.Format("user-{0}", fileUpload.UserId));
            var directory = storageContainer.GetDirectoryReference("uploads");
            var blob = directory.GetBlobReference(fileUpload.Id.ToString());
            var localFileName = Path.GetTempFileName();
            blob.DownloadToFile(localFileName, FileMode.Create);

            var md5 = GetMd5(localFileName);

            var localFileInfo = new FileInfo(localFileName);
            int height;
            int width;
            using(var image = Image.FromFile(localFileName))
            {
                height = image.Height;
                width = image.Width;
            }

            var metadata = GetMetadata(localFileName).ToList();
            var taken = GetPictureTakenDateTime(metadata);

            var picture = new Picture()
            {
                GpsLatitude = null,//TODO
                GpsLongitude = null,//TODO
                LastModifiedUtc = DateTime.UtcNow,
                Height = height,
                Width = width,
                OriginalFileName = fileUpload.FileName,
                Name = fileUpload.FileName,
                DateTimeTaken = taken,
                FileMd5 = md5,
                Size = localFileInfo.Length,
                UploadedUtc = fileUpload.UploadStartDateTimeUtc,
                UserId = fileUpload.UserId.Value,
            };

            //Console.WriteLine("    {0,-20} {1}", tag.TagName, tag.Description);
            ////"yyyy:MM:dd HH:mm:ss"
            //if(tag.TagName == "Date/Time Original")
            //{
            //    var pictureDateTime = DateTime.ParseExact(tag.Description, "yyyy:MM:dd HH:mm:ss", CultureInfo.InvariantCulture);
            //    Console.WriteLine(pictureDateTime.ToString(CultureInfo.InvariantCulture));
            //}
        }
Exemplo n.º 31
0
        /// <summary>
        ///    Renders the values in the current instance into field
        ///    data for a specified version.
        /// </summary>
        /// <param name="version">
        ///    A <see cref="byte" /> indicating the ID3v2 version the
        ///    field data is to be encoded in.
        /// </param>
        /// <returns>
        ///    A <see cref="ByteVector" /> object containing the
        ///    rendered field data.
        /// </returns>
        protected override ByteVector RenderFields(byte version)
        {
            if (file != null)
            {
                Load();
            }

            if (raw_data != null && raw_version == version)
            {
                return(raw_data);
            }

            StringType encoding = CorrectEncoding(TextEncoding, version);
            ByteVector data     = new ByteVector();

            if (header.FrameId == FrameType.APIC)
            {
                // Make an ID3v2 Attached Picture (APIC)

                data.Add((byte)encoding);

                if (version == 2)
                {
                    string ext = Picture.GetExtensionFromMime(MimeType);
                    data.Add(ext != null && ext.Length == 3 ?
                             ext.ToUpper() : "XXX");
                }
                else
                {
                    data.Add(ByteVector.FromString(MimeType, StringType.Latin1));
                    data.Add(ByteVector.TextDelimiter(StringType.Latin1));
                }

                data.Add((byte)type);
                data.Add(ByteVector.FromString(Description, encoding));
                data.Add(ByteVector.TextDelimiter(encoding));
            }
            else if (header.FrameId == FrameType.GEOB)
            {
                // Make an ID3v2 General Encapsulated Object (GEOB)

                data.Add((byte)encoding);

                if (MimeType != null)
                {
                    data.Add(ByteVector.FromString(MimeType, StringType.Latin1));
                }
                data.Add(ByteVector.TextDelimiter(StringType.Latin1));

                if (filename != null)
                {
                    data.Add(ByteVector.FromString(filename, encoding));
                }
                data.Add(ByteVector.TextDelimiter(encoding));

                if (Description != null)
                {
                    data.Add(ByteVector.FromString(Description, encoding));
                }
                data.Add(ByteVector.TextDelimiter(encoding));
            }
            else
            {
                throw new InvalidOperationException("Bad Frame type");
            }

            data.Add(this.data);
            return(data);
        }
Exemplo n.º 32
0
 public Picture Add(Picture picture) => Pictures.Add(picture);
Exemplo n.º 33
0
 /// <summary>
 /// Constructs the attribute given the <see cref="Picture"/>
 /// </summary>
 /// <param name="picture"></param>
 public EdiValueAttribute(Picture picture)
 {
     _picture = picture;
 }
Exemplo n.º 34
0
        private void DrawBuilding <T>(Picture picture = null, int x = -1, int y = -1) where T : IBuilding
        {
            if (_buildingFile == null)
            {
                _buildingFile = Game.GetPlayer(_city.Owner).HasAdvance <Invention>() ? "CITYPIX3" : "CITYPIX2";
            }

            if (picture == null)
            {
                picture = _background;
            }
            if (typeof(T) == typeof(Aqueduct))
            {
                picture.AddLayer(Resources[_buildingFile][51, 151, 49, 49], 0, 72);
            }

            if (typeof(T) == typeof(CityWalls))
            {
                Picture wall = Resources[_buildingFile][251, 101, 43, 49];
                Picture door = Resources[_buildingFile][51, 101, 49, 49];

                for (int xx = 0; xx < 142; xx += 43)
                {
                    picture.AddLayer(wall, xx, 108);
                }
                picture.AddLayer(door, 142, 108);
                for (int xx = 191; xx < 320; xx += 43)
                {
                    picture.AddLayer(wall, xx, 108);
                }
            }

            if (typeof(T) == typeof(Barracks))
            {
                picture.AddLayer(Resources[_buildingFile][1, 1, 49, 49], x, y);
            }
            if (typeof(T) == typeof(Granary))
            {
                picture.AddLayer(Resources[_buildingFile][1, 51, 49, 49], x, y);
            }
            if (typeof(T) == typeof(Temple))
            {
                picture.AddLayer(Resources[_buildingFile][1, 101, 49, 49], x, y);
            }
            if (typeof(T) == typeof(MarketPlace))
            {
                picture.AddLayer(Resources[_buildingFile][1, 151, 49, 49], x, y);
            }
            if (typeof(T) == typeof(Library))
            {
                picture.AddLayer(Resources[_buildingFile][51, 1, 49, 49], x, y);
            }
            if (typeof(T) == typeof(Courthouse))
            {
                picture.AddLayer(Resources[_buildingFile][51, 51, 49, 49], x, y);
            }
            if (typeof(T) == typeof(Bank))
            {
                picture.AddLayer(Resources[_buildingFile][101, 1, 49, 49], x, y);
            }
            if (typeof(T) == typeof(Cathedral))
            {
                picture.AddLayer(Resources[_buildingFile][101, 51, 49, 49], x, y);
            }
            if (typeof(T) == typeof(UniversityBuilding))
            {
                picture.AddLayer(Resources[_buildingFile][101, 101, 49, 49], x, y);
            }
            if (typeof(T) == typeof(Colosseum))
            {
                picture.AddLayer(Resources[_buildingFile][151, 1, 49, 49], x, y);
            }
            if (typeof(T) == typeof(Factory))
            {
                picture.AddLayer(Resources[_buildingFile][151, 51, 49, 49], x, y);
            }
            if (typeof(T) == typeof(MfgPlant))
            {
                picture.AddLayer(Resources[_buildingFile][151, 101, 49, 49], x, y);
            }
            if (typeof(T) == typeof(SdiDefense))
            {
                picture.AddLayer(Resources[_buildingFile][151, 151, 49, 49], x, y);
            }
            if (typeof(T) == typeof(RecyclingCenter))
            {
                picture.AddLayer(Resources[_buildingFile][201, 1, 49, 49], x, y);
            }
            if (typeof(T) == typeof(NuclearPlant))
            {
                picture.AddLayer(Resources[_buildingFile][201, 151, 49, 49], x, y);
            }
        }
Exemplo n.º 35
0
        private static Texture LoadGraphic(string fileName, long lColorKey, int iMaxWidth, int iMaxHeight, int iRotation,
                                           out int width, out int height)
        {
            width  = 0;
            height = 0;
            if (string.IsNullOrEmpty(fileName))
            {
                return(null);
            }

            Texture texture = null;

            try
            {
                using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read))
                {
                    using (Image theImage = Image.FromStream(fs, true, false))
                    {
                        if (theImage == null)
                        {
                            return(null);
                        }
                        Log.Debug("TextureManager: Fast loaded texture {0}|{1}", iRotation, fileName);

                        if (iRotation > 0)
                        {
                            RotateFlipType fliptype;
                            switch (iRotation)
                            {
                            case 1:
                                fliptype = RotateFlipType.Rotate90FlipNone;
                                theImage.RotateFlip(fliptype);
                                break;

                            case 2:
                                fliptype = RotateFlipType.Rotate180FlipNone;
                                theImage.RotateFlip(fliptype);
                                break;

                            case 3:
                                fliptype = RotateFlipType.Rotate270FlipNone;
                                theImage.RotateFlip(fliptype);
                                break;

                            default:
                                fliptype = RotateFlipType.RotateNoneFlipNone;
                                break;
                            }
                        }
                        width  = theImage.Size.Width;
                        height = theImage.Size.Height;

                        texture = Picture.ConvertImageToTexture((Bitmap)theImage, lColorKey, Format.A8R8G8B8, out width, out height);
                    }
                }
            }
            catch (Exception ex)
            {
                Log.Error("TextureManager: LoadGraphic: exception loading {0} {1}", fileName, ex.Message);
            }
            return(texture);
        }
Exemplo n.º 36
0
        public ActionResult Create(CommentModels commentModels,
                                   IEnumerable <HttpPostedFileBase> fileData)
        {
            try
            {
                List <Picture> pictures = new List <Picture>();
                if (ModelState.IsValid)
                {
                    if (fileData != null)
                    {
                        fileData = fileData.Where(f => f != null);
                        foreach (var someFile in fileData)
                        {
                            System.IO.FileInfo file = new System.IO.FileInfo(someFile.FileName);
                            if (file.Extension == ".jpeg" || file.Extension == ".jpg" || file.Extension == ".png" ||
                                file.Extension == ".gif" || file.Extension == ".bmp")
                            {
                                string fname = file.Name.Remove((file.Name.Length - file.Extension.Length));
                                fname = fname + System.DateTime.Now.ToString("_ddMMyyhhmmssms") + file.Extension;
                                someFile.SaveAs(Server.MapPath("../Content/Images/" + fname));
                                Picture pic = new Picture
                                {
                                    Name = fname,
                                    Path = Server.MapPath("../Content/Images/" + fname),
                                };
                                pictures.Add(pic);
                            }
                            else
                            {
                                ModelState.AddModelError("WrongFormatImages",
                                                         "Разрешенные только следующие форматы изображений : jpeg, jpg, png, gif, bmp");
                                return(PartialView(commentModels));
                            }
                        }
                    }
                    else
                    {
                        ModelState.AddModelError("NoImage", "Не выбрано не одного фото");
                        return(PartialView(commentModels));
                    }

                    if (commentModels.TypeComment == "Place")
                    {
                        CommentPlace commetPlace = new CommentPlace();
                        commetPlace.PlaceId      = commentModels.TargetId;
                        commetPlace.Assessment   = commentModels.Assessment;
                        commetPlace.Pictures     = pictures;
                        commetPlace.PlaceComment = _placeService.GetItem(commentModels.TargetId);
                        commetPlace.Author       = _userService.GetItemList().First(user => user.Email == User.Identity.Name);
                        commetPlace.AuthorId     = _userService.GetItemList().First(user => user.Email == User.Identity.Name).Id;
                        commetPlace.Text         = commentModels.Text;
                        _commentPlaceService.Create(commetPlace);
                        _commentPlaceService.Save();
                        var summ  = 0;
                        var count = 0;
                        foreach (var comment in _commentPlaceService.GetItemList().Where(place => place.PlaceId == commentModels.TargetId))
                        {
                            summ += comment.Assessment;
                            count++;
                        }
                        var someplace = _placeService.GetItem(commentModels.TargetId);
                        someplace.Rating = summ / count;
                        _placeService.Update(someplace);
                        _placeService.Save();
                        return(Json(1));
                    }

                    if (commentModels.TypeComment == "Track")
                    {
                        CommentTrack commentTrack = new CommentTrack();
                        commentTrack.TrackId      = commentModels.TargetId;
                        commentTrack.Assessment   = commentModels.Assessment;
                        commentTrack.Pictures     = pictures;
                        commentTrack.TrackComment = _trackService.GetItem(commentModels.TargetId);
                        commentTrack.Author       = _userService.GetItemList().First(user => user.Email == User.Identity.Name);
                        commentTrack.AuthorId     = _userService.GetItemList().First(user => user.Email == User.Identity.Name).Id;
                        commentTrack.Text         = commentModels.Text;
                        _commentTrackService.Create(commentTrack);
                        _commentTrackService.Save();
                        var summ  = 0;
                        var count = 0;
                        foreach (var comment in _commentTrackService.GetItemList()
                                 .Where(place => place.TrackId == commentModels.TargetId))
                        {
                            summ += comment.Assessment;
                            count++;
                        }
                        var someTrack = _trackService.GetItem(commentModels.TargetId);
                        someTrack.Rating = summ / count;
                        _trackService.Update(someTrack);
                        _trackService.Save();
                        return(Json(1));
                    }
                }
            }
            catch (Exception e)
            {
                return(PartialView(commentModels));
            }
            return(PartialView(commentModels));

            return(PartialView());
        }
Exemplo n.º 37
0
 public TryResult TryCopy(Picture picture, string fullFolderPath) =>
 _fileService.CopyTo(picture.FullFileName, fullFolderPath);
Exemplo n.º 38
0
        public Picture GetCroppedImage(Picture picture, Int32Rect rect)
        {
            var bitmap = _bitmapService.Crop(picture.BitmapImage, rect, picture.FileExtension.ToEncoderType());

            return(new Picture(bitmap, picture.FullFileName));
        }
Exemplo n.º 39
0
        public override bool HasUpdate(uint gameTick)
        {
            if (_update || _centerChanged)
            {
                RenderTile[] renderTiles = RenderTiles.ToArray();
                if (Game.MovingUnit != null && !_centerChanged)
                {
                    IUnit   unit  = Game.MovingUnit;
                    ITile[] tiles = Map.QueryMapPart(unit.X - 1, unit.Y - 1, 3, 3).ToArray();
                    renderTiles = renderTiles.Where(t => tiles.Any(x => x != null && x.X == t.Tile.X && x.Y == t.Tile.Y)).ToArray();
                }
                else
                {
                    _centerChanged = false;
                    _canvas        = new Picture(_canvas.Width, _canvas.Height, _palette);
                }

                foreach (RenderTile t in renderTiles)
                {
                    if (!Settings.RevealWorld && !t.Visible)
                    {
                        _canvas.FillRectangle(5, t.X * 16, t.Y * 16, 16, 16);
                        continue;
                    }
                    AddLayer(t.Image, t.Position);
                    if (Settings.RevealWorld)
                    {
                        continue;
                    }

                    if (!Human.Visible(t.Tile, Direction.West))
                    {
                        AddLayer(Resources.Instance.GetFog(Direction.West), t.Position);
                    }
                    if (!Human.Visible(t.Tile, Direction.North))
                    {
                        AddLayer(Resources.Instance.GetFog(Direction.North), t.Position);
                    }
                    if (!Human.Visible(t.Tile, Direction.East))
                    {
                        AddLayer(Resources.Instance.GetFog(Direction.East), t.Position);
                    }
                    if (!Human.Visible(t.Tile, Direction.South))
                    {
                        AddLayer(Resources.Instance.GetFog(Direction.South), t.Position);
                    }
                }

                foreach (RenderTile t in renderTiles)
                {
                    if (!Settings.RevealWorld && !t.Visible)
                    {
                        continue;
                    }

                    if (t.Tile.City != null)
                    {
                        continue;
                    }

                    IUnit[] units = t.Tile.Units.Where(u => !u.Moving).ToArray();
                    if (t.Tile.Type == Terrain.Ocean)
                    {
                        // Always show naval units first at sea
                        units = units.OrderBy(u => (u.Class == UnitClass.Water) ? 1 : 0).ToArray();
                    }
                    if (units.Length == 0)
                    {
                        continue;
                    }

                    IUnit drawUnit = units.FirstOrDefault(u => u == Game.ActiveUnit);

                    if (drawUnit == null)
                    {
                        // No active unit on this tile, show top unit
                        if (t.Tile.IsOcean)
                        {
                            drawUnit = units.OrderBy(x => x.Class == UnitClass.Land ? 1 : 0).FirstOrDefault();
                        }
                        else
                        {
                            drawUnit = units[0];
                        }
                    }
                    else if (!Common.HasScreenType <Input>() && ((gameTick % 4) >= 2 || drawUnit.Moving))
                    {
                        // Active unit on this tile or unit is currently moving. Drawing happens later.
                        continue;
                    }

                    if (t.Tile.IsOcean && drawUnit.Class != UnitClass.Water && drawUnit.Sentry)
                    {
                        // Do not draw sentried land units at sea
                        continue;
                    }

                    AddLayer(drawUnit.GetUnit(drawUnit.Owner), t.Position);
                    if (units.Length == 1)
                    {
                        continue;
                    }
                    AddLayer(drawUnit.GetUnit(drawUnit.Owner), t.Position.X - 1, t.Position.Y - 1);
                }

                foreach (RenderTile t in renderTiles.Reverse())
                {
                    if (!Settings.RevealWorld && !t.Visible)
                    {
                        continue;
                    }

                    City city = t.Tile.City;
                    if (city == null)
                    {
                        continue;
                    }

                    AddLayer(Icons.City(city), t.Position);

                    if (t.Y == 11)
                    {
                        continue;
                    }
                    int labelX = (t.X == 0) ? t.Position.X : t.Position.X - 8;
                    int labelY = t.Position.Y + 16;
                    _canvas.DrawText(city.Name, 0, 5, labelX, labelY + 1, TextAlign.Left);
                    _canvas.DrawText(city.Name, 0, 11, labelX, labelY, TextAlign.Left);
                }

                foreach (RenderTile t in renderTiles)
                {
                    if (!Settings.RevealWorld && !t.Visible)
                    {
                        continue;
                    }

                    IUnit[] units = t.Tile.Units.Where(u => !u.Moving).ToArray();
                    if (units.Length == 0)
                    {
                        continue;
                    }

                    IUnit drawUnit = units.FirstOrDefault(u => u == Game.ActiveUnit);

                    if (drawUnit == null)
                    {
                        continue;
                    }

                    // Active unit on this tile

                    if (drawUnit.Moving)
                    {
                        // Unit is currently moving, do not draw the unit here.
                        continue;
                    }

                    if (Human == drawUnit.Owner && (gameTick % 4) >= 2 && !GameTask.Any())
                    {
                        // Unit is owned by human player, blink status is off and no tasks are running. Do not draw unit.
                        continue;
                    }

                    if (t.Tile.City != null && units.Length == 1 && !GameTask.Any())
                    {
                        AddLayer(drawUnit.GetUnit(units[0].Owner), t.Position.X - 1, t.Position.Y - 1);
                        continue;
                    }

                    AddLayer(drawUnit.GetUnit(units[0].Owner), t.Position);
                    if (units.Length == 1)
                    {
                        continue;
                    }
                    AddLayer(drawUnit.GetUnit(units[0].Owner), t.Position.X - 1, t.Position.Y - 1);
                }

                if (Game.MovingUnit != null && (Settings.RevealWorld || Game.Human == Game.MovingUnit.Owner || Game.Human.Visible(Game.MovingUnit.Tile)))
                {
                    IUnit unit = Game.MovingUnit;
                    if (renderTiles.Any(t => (t.Tile.X == unit.X && t.Tile.Y == unit.Y)))
                    {
                        RenderTile tile = renderTiles.First(t => (t.Tile.X == unit.X && t.Tile.Y == unit.Y));
                        AddLayer(unit.GetUnit(unit.Owner), tile.Position.X + unit.Movement.X, tile.Position.Y + unit.Movement.Y);
                        if (unit is IBoardable && tile.Tile.Units.Any(u => u.Class == UnitClass.Land && (tile.Tile.City == null || (tile.Tile.City != null && unit.Sentry))))
                        {
                            // If there are units on the ship, draw a stack
                            AddLayer(unit.GetUnit(unit.Owner), tile.Position.X + unit.Movement.X - 1, tile.Position.Y + unit.Movement.Y - 1);
                        }
                    }
                    return(true);
                }

                _update = false;
                return(true);
            }

            return(false);
        }
Exemplo n.º 40
0
            public Shop GetShops()
            {
                var listVendor   = new Vendor().GetListVendor();
                var baseUrl      = Settings.PriceSettings.BaseURL;
                var list         = new List <Shop>();
                var listCategory = new CategoryB().GetListCategory().Select(x => x.Id).ToList <int>();
                var shop         = new Shop()
                {
                    Name       = Settings.PriceSettings.Name,
                    Company    = Settings.PriceSettings.CopanyName,
                    Url        = Settings.PriceSettings.URL,
                    Currencies = new Currencies()
                    {
                        Currency = new Currency()
                        {
                            Id = "UAH", Rate = "1"
                        }
                    },
                };

                var listAddParams  = new AddParam().GetListAddParam();
                var listAdd        = new Product().GetNameReplace();
                var listPictureAdd = new Picture().GetListPicture();

                foreach (var categoryId in listCategory)
                {
                    var ListCat    = new CategoryB().GetListcategoryToPrice(categoryId);
                    var categories = new List <Category>();
                    foreach (var cat in ListCat)
                    {
                        if (!listPictureAdd.Select(x => x.category).Contains(cat.Id))
                        {
                            continue;
                        }
                        if (cat.Parent_Id == 0)
                        {
                            categories.Add(new Category()
                            {
                                Id   = cat.Id.ToString(),
                                Text = cat.Name.ToString()
                            });
                        }
                        else
                        {
                            categories.Add(new Category()
                            {
                                Id       = cat.Id.ToString(),
                                Text     = cat.Name.ToString(),
                                ParentId = cat.Parent_Id.ToString()
                            });
                            var parent = new CategoryB().GetListcategoryToPrice(cat.Parent_Id);
                            categories.Add(new Category()
                            {
                                Id   = parent.FirstOrDefault().Id.ToString(),
                                Text = parent.FirstOrDefault().Name.ToString()
                            });
                        }
                    }

                    var listOffes = new List <Offer>();

                    var products = new Product().GetListProduct(categoryId);
                    if (products.Count() == 0)
                    {
                        continue;
                    }
                    foreach (var product in products)
                    {
                        if (!listPictureAdd.Where(x => x.link.Contains(product.Url)).Any())
                        {
                            continue;
                        }

                        var skuses = new Skus().GetListSkus(product.Id);

                        if (product.Images.Count() == 0)
                        {
                            continue;
                        }
                        foreach (var skus in skuses)
                        {
                            var parames     = new List <Param>();
                            var listParames = new Paramses().GetListParams(product.Id, skus.Id);
                            foreach (var item in listParames.Where(x => x.Status == true))
                            {
                                parames.Add(
                                    new Param()
                                {
                                    Name = item.Name.ToString(),
                                    Text = item.Text.ToString()
                                });
                            }

                            foreach (var item in listAddParams.Where(z => z.GroupId == categoryId))
                            {
                                parames.Add(
                                    new Param()
                                {
                                    Name = item.ParamName.ToString(),
                                    Text = item.ParamValue.ToString()
                                });
                            }

                            var additname = string.Empty;

                            if (product.addparam > 0)
                            {
                                var addName = listAdd[product.addparam];
                                var add     = parames.Where(x => x.Name == addName).FirstOrDefault();

                                if (add != null)
                                {
                                    additname = " " + add.Text.ToString();
                                }
                            }

                            if (skus.Price == 0)
                            {
                                skus.Price = product.Price;
                            }
                            if (skus.Price == 0)
                            {
                                continue;
                            }

                            var    markup      = listParames.Where(x => x.Status == false).FirstOrDefault()?.Text;
                            double markupValue = 0;
                            var    resM        = double.TryParse(markup, out markupValue);
                            if (resM && markupValue > 0)
                            {
                                markupValue = markupValue / 100;
                                skus.Price  = Math.Round(skus.Price + skus.Price * markupValue, 0);
                            }


                            listOffes.Add(new Offer()
                            {
                                Id             = skus.Id.ToString(),
                                Available      = "true",
                                Url            = baseUrl + product.Url.ToString(),
                                Price          = skus.Price.ToString(),
                                Price_old      = (skus.OldPrice == 0) ? null : skus.OldPrice.ToString(),
                                CurrencyId     = "UAH",
                                CategoryId     = categoryId.ToString(),
                                Picture        = product.Images,
                                Vendor         = listVendor.Where(x => x.Product_id == skus.Product_id)?.FirstOrDefault()?.Name ?? string.Empty,
                                Stock_quantity = product.Count.ToString(),
                                Name           = product.Name.ToString() + additname.ToString(),
                                Description    = product.Description.ToString(),
                                Param          = parames
                            });
                        }
                    }
                    if (listOffes.Count() == 0)
                    {
                        continue;
                    }

                    if (shop.Categories == null)
                    {
                        shop.Categories = new Categories()
                        {
                            Category = categories
                        }
                    }
                    ;
                    else
                    {
                        shop.Categories.Category.AddRange(categories);
                    }

                    if (shop.Offers == null)
                    {
                        shop.Offers = new Offers()
                        {
                            Offer = listOffes
                        }
                    }
                    ;
                    else
                    {
                        shop.Offers.Offer.AddRange(listOffes);
                    }
                    shop.Offers.Offer = shop.Offers.Offer.GroupBy(x => x.Id).Select(x => new Offer
                    {
                        Id             = x.Key,
                        Available      = x.Select(z => z.Available).FirstOrDefault().ToString(),
                        CategoryId     = x.Select(z => z.CategoryId).FirstOrDefault().ToString(),
                        CurrencyId     = x.Select(z => z.CurrencyId).FirstOrDefault().ToString(),
                        Description    = x.Select(z => z.Description).FirstOrDefault().ToString(),
                        Name           = x.Select(z => z.Name).FirstOrDefault().ToString(),
                        Param          = x.Select(z => z.Param).FirstOrDefault(),
                        Picture        = x.Select(z => z.Picture).FirstOrDefault(),
                        Price          = x.Select(z => z.Price).FirstOrDefault(),
                        Price_old      = x.Select(z => z.Price_old).FirstOrDefault(),
                        Stock_quantity = x.Select(z => z.Stock_quantity).FirstOrDefault(),
                        Url            = x.Select(z => z.Url).FirstOrDefault(),
                        Vendor         = x.Select(z => z.Vendor).FirstOrDefault().ToString()
                    }).ToList();

                    var listName = shop.Offers.Offer.GroupBy(x => x.Name);
                    foreach (var item in listName)
                    {
                        if (item.Count() > 1)
                        {
                            Settings.Dublicates.Add(string.Concat(item.Select(x => x.CategoryId).FirstOrDefault(), item.Select(x => x.Url).FirstOrDefault()));
                        }
                    }

                    foreach (var item in shop.Offers.Offer)
                    {
                        if (item.Description.Contains(" href"))
                        {
                            Settings.Urls.Add(item.Url);
                        }
                        if (item.Vendor == string.Empty)
                        {
                            Settings.Errores.Add(string.Format("Не указана торговая марка {0}, {1}", item.Id, string.Empty));
                        }
                    }
                }
                if (shop.Categories == null)
                {
                    return(shop);
                }
                shop.Categories.Category = shop.Categories.Category.GroupBy(x => x.Id).Select(x => new Category {
                    Id = x.Key, ParentId = x.Select(z => z.ParentId).FirstOrDefault(), Text = x.Select(z => z.Text).FirstOrDefault()
                }).ToList();
                return(shop);
            }
Exemplo n.º 41
0
        /// <summary>
        /// Save picture by picture virtual path
        /// </summary>
        /// <param name="picture">Picture instance</param>
        /// <param name="targetSize">The target picture size (longest side)</param>
        protected virtual void SavePictureByVirtualPath(Picture picture, int targetSize = 0)
        {
            if (string.IsNullOrEmpty(picture?.VirtualPath) || string.IsNullOrEmpty(picture.SeoFilename))
            {
                return;
            }

            var pictureBinary = _pictureService.LoadPictureBinary(picture);

            if (pictureBinary == null || pictureBinary.Length == 0)
            {
                return;
            }

            var seoFileName = picture.SeoFilename;

            var lastPart = _pictureService.GetFileExtensionFromMimeType(picture.MimeType);

            var thumbFileName = targetSize == 0 ? $"{seoFileName}.{lastPart}" : $"{seoFileName}_{targetSize}.{lastPart}";

            var thumbsDirectoryPath = _fileProvider.GetAbsolutePath(picture.VirtualPath.TrimStart('~'));

            _fileProvider.CreateDirectory(thumbsDirectoryPath);
            var thumbFilePath = _fileProvider.Combine(thumbsDirectoryPath, thumbFileName);

            if (picture.IsNew)
            {
                // delete old file if exist
                _fileProvider.DeleteFile(thumbFilePath);

                //we do not validate picture binary here to ensure that no exception ("Parameter is not valid") will be thrown
                _pictureService.UpdatePicture(picture.Id,
                                              pictureBinary,
                                              picture.MimeType,
                                              picture.SeoFilename,
                                              picture.AltAttribute,
                                              picture.TitleAttribute,
                                              false,
                                              false);
            }

            //the named mutex helps to avoid creating the same files in different threads,
            //and does not decrease performance significantly, because the code is blocked only for the specific file.
            using var mutex = new Mutex(false, thumbFileName);
            if (_fileProvider.FileExists(thumbFilePath))
            {
                return;
            }

            mutex.WaitOne();

            //check, if the file was created, while we were waiting for the release of the mutex.
            if (!_fileProvider.FileExists(thumbFilePath))
            {
                byte[] pictureBinaryResized;
                if (targetSize != 0)
                {
                    //resizing required
                    using var image = Image.Load <Rgba32>(pictureBinary, out var imageFormat);
                    var size = image.Size();

                    image.Mutate(imageProcess => imageProcess.Resize(new ResizeOptions
                    {
                        Mode = ResizeMode.Max,
                        Size = CalculateDimensions(size, targetSize)
                    }));

                    pictureBinaryResized = EncodeImage(image, imageFormat);
                }
                else
                {
                    //create a copy of pictureBinary
                    pictureBinaryResized = pictureBinary.ToArray();
                }

                //save
                _fileProvider.WriteAllBytes(thumbFilePath, pictureBinaryResized);
            }

            mutex.ReleaseMutex();
        }
Exemplo n.º 42
0
        public IActionResult PostNewOrders([FromBody] PostManageOrdersVM _pmovm)
        {
            List <string> result = _pmovm.idService.Split(',').ToList();

            foreach (var item in result)
            {
                var _OrderDetailsNueva = new OrderDetails();
                var quotationLocal     = new Quotation();

                quotationLocal.Tasks = new List <TaskModel>();
                //_OrderDetailsNueva.Id = Guid.NewGuid();
                _OrderDetailsNueva.Order   = _context.Order.FirstOrDefault(o => o.Id == _pmovm.orderId);
                _OrderDetailsNueva.Service = _context.ServiceModel.FirstOrDefault(s => s.ID.ToString() == item);

                var quotation = _context.Quotation
                                .AsNoTracking()
                                .Include(q => q.OrderDetailsModel)
                                .ThenInclude(q => q.Order)
                                .Include(q => q.Tasks)
                                .ThenInclude(t => t.ListMaterial)
                                .FirstOrDefault(q => q.OrderDetailsModel.Order.Id == _pmovm.orderId);

                var pics = _context.Quotation
                           .AsNoTracking()
                           .Include(q => q.OrderDetailsModel)
                           .ThenInclude(q => q.Order)
                           .Include(q => q.Tasks)
                           .ThenInclude(t => t.Pictures)
                           .FirstOrDefault(q => q.OrderDetailsModel.Order.Id == _pmovm.orderId);

                var piclist = new List <Picture>();

                for (int i = 0; i < quotation.Tasks.Count; i++)
                {
                    var _taskLocal = new TaskModel();

                    for (int f = 0; f < quotation.Tasks[i].ListMaterial.Count; f++)
                    {
                        if (_taskLocal.ListMaterial == null)
                        {
                            _taskLocal.ListMaterial = new List <Material>();
                        }
                        var mat = new Material();
                        mat.Description = quotation.Tasks[i].ListMaterial[f].Description;
                        mat.Name        = quotation.Tasks[i].ListMaterial[f].Name;
                        mat.Price       = 0;
                        _taskLocal.ListMaterial.Add(mat);
                    }

                    if (_taskLocal.Pictures == null)
                    {
                        _taskLocal.Pictures = new List <Picture>();
                    }

                    for (int e = 0; e < pics.Tasks[i].Pictures.Count; e++)
                    {
                        var picLocal = new Picture();
                        picLocal.PictureBytes = pics.Tasks[i].Pictures[e].PictureBytes;
                        _taskLocal.Pictures.Add(picLocal);
                    }
                    _taskLocal.Name        = quotation.Tasks[i].Name;
                    _taskLocal.Duration    = quotation.Tasks[i].Duration;
                    _taskLocal.Description = quotation.Tasks[i].Description;
                    quotationLocal.Tasks.Add(_taskLocal);
                }

                quotationLocal.Description       = quotation.Description;
                quotationLocal.Status            = 0;
                quotationLocal.OrderDetailsModel = _OrderDetailsNueva;

                _context.OrderDetails.Add(_OrderDetailsNueva);
                _context.Quotation.Add(quotationLocal);
            }
            try
            {
                _context.SaveChanges();
            }
            catch (Exception ex)
            {
            }
            return(Ok());
        }
Exemplo n.º 43
0
        private static void SeedAlbumsAndPictures(SocialNetworkDbContext db)
        {
            const int totalAlbums    = 100;
            const int totallPictures = 500;

            var biggestAlbumId = db
                                 .Albums
                                 .OrderByDescending(a => a.Id)
                                 .Select(a => a.Id)
                                 .FirstOrDefault() + 1;
            var userIds = db
                          .Users
                          .Select(u => u.Id)
                          .ToList();

            var albums = new List <Album>();

            for (int i = biggestAlbumId; i < biggestAlbumId + totalAlbums; i++)
            {
                var album = new Album
                {
                    Name       = $"Album {i}",
                    Background = $"Color {i}",
                    IsPublic   = random.Next(0, 1) == 0 ? true : false,
                    UserId     = userIds[random.Next(0, userIds.Count)]
                };

                db.Albums.Add(album);
                albums.Add(album);
            }

            db.SaveChanges();

            var biggestPictureId = db
                                   .Pictures
                                   .OrderByDescending(p => p.Id)
                                   .Select(u => u.Id)
                                   .FirstOrDefault() + 1;

            var pictures = new List <Picture>();

            for (int i = biggestPictureId; i < biggestPictureId + totallPictures; i++)
            {
                var picture = new Picture
                {
                    Title   = $"Picture {i}",
                    Caption = $"Caption {i}",
                    Path    = $"Path {i}"
                };

                pictures.Add(picture);
                db.Pictures.Add(picture);
            }

            db.SaveChanges();


            var albumIds = albums.Select(a => a.Id).ToList();

            for (int i = 0; i < pictures.Count; i++)
            {
                var picture = pictures[i];

                var numberOfAlbums = random.Next(1, 20);

                for (int j = 0; j < numberOfAlbums; j++)
                {
                    var albumId = albumIds[random.Next(0, albumIds.Count)];

                    var pictureExist = db
                                       .Pictures
                                       .Any(p => p.Id == picture.Id && p.Albums.Any(a => a.AlbumId == albumId));

                    if (pictureExist)
                    {
                        j--;
                        continue;
                    }
                    picture.Albums.Add(new AlbumPicture
                    {
                        AlbumId = albumId,
                    });
                    db.SaveChanges();
                }
            }
        }
Exemplo n.º 44
0
 public TryResult TryMove(Picture picture, string fullFolderPath) =>
 _fileService.MoveTo(picture.FullFileName, fullFolderPath);
Exemplo n.º 45
0
        /// <summary>
        ///    Performs the actual parsing of the raw data.
        /// </summary>
        /// <remarks>
        ///    Because of the high parsing cost and relatively low usage
        ///    of the class, <see cref="ParseFields" /> only stores the
        ///    field data so it can be parsed on demand. Whenever a
        ///    property or method is called which requires the data,
        ///    this method is called, and only on the first call does it
        ///    actually parse the data.
        /// </remarks>
        protected void ParseRawData()
        {
            if (file != null)
            {
                Load();
            }

            if (raw_data == null)
            {
                return;
            }

            data     = raw_data;
            raw_data = null;

            int pos = 0;
            int offset;

            encoding = (StringType)data[pos++];

            ByteVector delim = ByteVector.TextDelimiter(encoding);

            if (header.FrameId == FrameType.APIC)
            {
                // Retrieve an ID3v2 Attached Picture (APIC)

                if (raw_version > 2)
                {
                    offset = data.Find(ByteVector.TextDelimiter(StringType.Latin1), pos);

                    if (offset < pos)
                    {
                        return;
                    }

                    mime_type = data.ToString(StringType.Latin1, pos, offset - pos);
                    pos       = offset + 1;
                }
                else
                {
                    ByteVector ext = data.Mid(pos, 3);
                    mime_type = Picture.GetMimeFromExtension(ext.ToString());
                    pos      += 3;
                }

                Type = (PictureType)data[pos++];

                offset = data.Find(delim, pos, delim.Count);
            }
            else if (header.FrameId == FrameType.GEOB)
            {
                // Retrieve an ID3v2 General Encapsulated Object (GEOB)

                offset = data.Find(ByteVector.TextDelimiter(StringType.Latin1), pos);

                if (offset < pos)
                {
                    return;
                }

                mime_type = data.ToString(StringType.Latin1, pos, offset - pos);

                pos    = offset + 1;
                offset = data.Find(delim, pos, delim.Count);

                if (offset < pos)
                {
                    return;
                }

                filename = data.ToString(encoding, pos, offset - pos);
                pos      = offset + delim.Count;
                offset   = data.Find(delim, pos, delim.Count);

                Type = PictureType.NotAPicture;
            }
            else
            {
                throw new InvalidOperationException("Bad Frame type");
            }

            if (offset < pos)
            {
                return;
            }

            description = data.ToString(encoding, pos, offset - pos);
            pos         = offset + delim.Count;

            data.RemoveRange(0, pos);
        }
Exemplo n.º 46
0
 public Svg(Picture pPicture, RectF pBounds, RectF pComputedBounds)
 {
     Picture        = pPicture;
     Bounds         = pBounds;
     ComputedBounds = pComputedBounds;
 }
Exemplo n.º 47
0
 public TryResult TryChangePictureName(Picture picture, string newName) =>
 _fileService.ChangeFileName(picture.FullFileName,
                             $"{picture.FolderPath}\\{newName}{picture.FileExtension}");
Exemplo n.º 48
0
        /// <summary>
        /// Get product picture (for shopping cart and order details pages)
        /// </summary>
        /// <param name="product">Product</param>
        /// <param name="attributesXml">Atributes (in XML format)</param>
        /// <param name="pictureService">Picture service</param>
        /// <param name="productAttributeParser">Product attribute service</param>
        /// <returns>Picture</returns>
        public static async Task <Picture> GetProductPicture(this Product product, string attributesXml,
                                                             IProductService productService, IPictureService pictureService,
                                                             IProductAttributeParser productAttributeParser)
        {
            if (product == null)
            {
                throw new ArgumentNullException("product");
            }
            if (pictureService == null)
            {
                throw new ArgumentNullException("pictureService");
            }
            if (productAttributeParser == null)
            {
                throw new ArgumentNullException("productAttributeParser");
            }

            Picture picture = null;

            //first, let's see whether we have some attribute values with custom pictures
            if (!String.IsNullOrEmpty(attributesXml))
            {
                var comb = product.ProductAttributeCombinations.Where(x => x.AttributesXml == attributesXml).FirstOrDefault();
                if (comb != null)
                {
                    if (!string.IsNullOrEmpty(comb.PictureId))
                    {
                        var combPicture = await pictureService.GetPictureById(comb.PictureId);

                        if (combPicture != null)
                        {
                            picture = combPicture;
                        }
                    }
                }
                if (picture == null)
                {
                    var attributeValues = productAttributeParser.ParseProductAttributeValues(product, attributesXml);
                    foreach (var attributeValue in attributeValues)
                    {
                        var attributePicture = await pictureService.GetPictureById(attributeValue.PictureId);

                        if (attributePicture != null)
                        {
                            picture = attributePicture;
                            break;
                        }
                    }
                }
            }
            //now let's load the default product picture
            if (picture == null)
            {
                var pp = product.ProductPictures.FirstOrDefault();
                if (pp != null)
                {
                    picture = await pictureService.GetPictureById(pp.PictureId);
                }
            }

            //let's check whether this product has some parent "grouped" product
            if (picture == null && !product.VisibleIndividually && !String.IsNullOrEmpty(product.ParentGroupedProductId))
            {
                var parentProduct = await productService.GetProductById(product.ParentGroupedProductId);

                if (parentProduct != null)
                {
                    if (parentProduct.ProductPictures.Any())
                    {
                        picture = await pictureService.GetPictureById(parentProduct.ProductPictures.FirstOrDefault().PictureId);
                    }
                }
            }

            return(picture);
        }
Exemplo n.º 49
0
        /// <summary>
        /// Get a picture URL
        /// </summary>
        /// <param name="picture">Picture instance</param>
        /// <param name="targetSize">The target picture size (longest side)</param>
        /// <param name="showDefaultPicture">A value indicating whether the default picture is shown</param>
        /// <param name="storeLocation">Store location URL; null to use determine the current store location automatically</param>
        /// <param name="defaultPictureType">Default picture type</param>
        /// <returns>Picture URL</returns>
        public virtual string GetPictureUrl(Picture picture,
                                            int targetSize                 = 0,
                                            bool showDefaultPicture        = true,
                                            string storeLocation           = null,
                                            PictureType defaultPictureType = PictureType.Entity)
        {
            var url = string.Empty;

            byte[] pictureBinary = null;
            if (picture != null)
            {
                pictureBinary = LoadPictureBinary(picture);
            }
            if (picture == null || pictureBinary == null || pictureBinary.Length == 0)
            {
                if (showDefaultPicture)
                {
                    url = GetDefaultPictureUrl(targetSize, defaultPictureType, storeLocation);
                }
                return(url);
            }

            if (picture.IsNew)
            {
                DeletePictureThumbs(picture);

                //we do not validate picture binary here to ensure that no exception ("Parameter is not valid") will be thrown
                picture = UpdatePicture(picture.Id,
                                        pictureBinary,
                                        picture.MimeType,
                                        picture.SeoFilename,
                                        picture.AltAttribute,
                                        picture.TitleAttribute,
                                        false,
                                        false);
            }

            var seoFileName = picture.SeoFilename; // = GetPictureSeName(picture.SeoFilename); //just for sure

            var    lastPart = GetFileExtensionFromMimeType(picture.MimeType);
            string thumbFileName;

            if (targetSize == 0)
            {
                thumbFileName = !string.IsNullOrEmpty(seoFileName)
                    ? $"{picture.Id:0000000}_{seoFileName}.{lastPart}"
                    : $"{picture.Id:0000000}.{lastPart}";
            }
            else
            {
                thumbFileName = !string.IsNullOrEmpty(seoFileName)
                    ? $"{picture.Id:0000000}_{seoFileName}_{targetSize}.{lastPart}"
                    : $"{picture.Id:0000000}_{targetSize}.{lastPart}";
            }
            var thumbFilePath = GetThumbLocalPath(thumbFileName);

            //the named mutex helps to avoid creating the same files in different threads,
            //and does not decrease performance significantly, because the code is blocked only for the specific file.
            using (var mutex = new Mutex(false, thumbFileName))
            {
                if (!GeneratedThumbExists(thumbFilePath, thumbFileName))
                {
                    mutex.WaitOne();

                    //check, if the file was created, while we were waiting for the release of the mutex.
                    if (!GeneratedThumbExists(thumbFilePath, thumbFileName))
                    {
                        byte[] pictureBinaryResized;
                        if (targetSize != 0)
                        {
                            //resizing required
                            using (var image = Image.Load(pictureBinary, out var imageFormat))
                            {
                                image.Mutate(imageProcess => imageProcess.Resize(new ResizeOptions
                                {
                                    Mode = ResizeMode.Max,
                                    Size = CalculateDimensions(image.Size(), targetSize)
                                }));

                                pictureBinaryResized = EncodeImage(image, imageFormat);
                            }
                        }
                        else
                        {
                            //create a copy of pictureBinary
                            pictureBinaryResized = pictureBinary.ToArray();
                        }

                        SaveThumb(thumbFilePath, thumbFileName, picture.MimeType, pictureBinaryResized);
                    }

                    mutex.ReleaseMutex();
                }
            }
            url = GetThumbUrl(thumbFileName, storeLocation);
            return(url);
        }
Exemplo n.º 50
0
        public IActionResult Get(int id)
        {
            Picture picture = _directorySystemFacade.GetPictureById(id);

            return(base.File(picture.BinaryData, "image/jpg"));
        }
        protected override void Seed(HotelReservationAPI.Models.DatabaseContext context)
        {
            Hotel octodureHotel = new Hotel
            {
                Name        = "Octodure",
                Description = "Idéalement situé à la sortie de l’autoroute, à mi-chemin entre l’Italie et la France, l’hôtel se trouve à quelques minutes en voiture de la Fondation Gianadda.",
                Location    = "Martigny",
                Category    = 1,
                HasWifi     = true,
                HasParking  = true,
                Phone       = "+41 (0)27 722 71 21",
                Email       = "*****@*****.**",
                Website     = "http://www.porte-octodure.ch/"
            };

            Room singleOctodure1 = new Room()
            {
                Hotel        = octodureHotel,
                Number       = 1,
                Description  = "Nos chambres simples sont toutes non-fumeur.",
                Type         = 1,
                Price        = 85,
                HasTv        = true,
                HasHairDryer = true
            };
            Room singleOctodure2 = new Room()
            {
                Hotel        = octodureHotel,
                Number       = 2,
                Description  = "Cette chambre insonorisée dispose d'une télévision par câble à écran plat et d'une salle de bains. ",
                Type         = 1,
                Price        = 85,
                HasTv        = false,
                HasHairDryer = false
            };
            Room singleOctodure3 = new Room()
            {
                Hotel        = octodureHotel,
                Number       = 3,
                Description  = "Chambre simple style typique de l'octodure.",
                Type         = 1,
                Price        = 75,
                HasTv        = true,
                HasHairDryer = true
            };
            Room singleOctodure4 = new Room()
            {
                Hotel        = octodureHotel,
                Number       = 4,
                Description  = "La chambre la plus calme  de notre hotel. Reposé vous sans TV.",
                Type         = 1,
                Price        = 85,
                HasTv        = false,
                HasHairDryer = true
            };

            Room doubleRoom1 = new Room()
            {
                Hotel        = octodureHotel,
                Number       = 5,
                Description  = "Nos chambres double standard offrent une bonne solution d\'hébergement economique avec tout le confort. ",
                Type         = 2,
                Price        = 100,
                HasTv        = true,
                HasHairDryer = true,
            };

            Room doubleRoom2 = new Room()
            {
                Hotel        = octodureHotel,
                Number       = 6,
                Description  = "Chambres calmes et spacieuses, elles offrent une superficie de 25m2. Idéales pour un séjour confortable, elles sont également pourvues d’une grande salle de bain avec baignoire ainsi que d’un dressing. ",
                Type         = 2,
                Price        = 120,
                HasTv        = true,
                HasHairDryer = true
            };

            Room doubleRoom3 = new Room()
            {
                Hotel        = octodureHotel,
                Number       = 7,
                Description  = "Chambre double standard de l'octodure. ",
                Type         = 2,
                Price        = 90,
                HasTv        = true,
                HasHairDryer = true
            };
            Room doubleRoom4 = new Room()
            {
                Hotel        = octodureHotel,
                Number       = 8,
                Description  = "Cette chambre avec balcon est non fumeur.",
                Type         = 2,
                Price        = 115,
                HasTv        = true,
                HasHairDryer = true
            };
            Room doubleRoom5 = new Room()
            {
                Hotel        = octodureHotel,
                Number       = 9,
                Description  = "Parfait pour une nuit en couple. ",
                Type         = 2,
                Price        = 95,
                HasTv        = true,
                HasHairDryer = true
            };

            Picture singleOctodure1Picture = new Picture()
            {
                Room = singleOctodure1,
                Url  = "https://www.swisshotels.com/catalog/images/hotels/12333/details/668x370/suite.jpg"
            };
            Picture singleOcto2Picture = new Picture()
            {
                Room = singleOctodure2,
                Url  = "https://media-cdn.tripadvisor.com/media/photo-s/02/e8/09/a3/la-porte-d-octodure-hotel.jpg"
            };


            // Add hotel
            context.Hotels.Add(octodureHotel);
            // Add rooms to list
            List <Room> roomsOctoList = new List <Room>();

            roomsOctoList.Add(singleOctodure1);
            roomsOctoList.Add(singleOctodure2);
            roomsOctoList.Add(singleOctodure3);
            roomsOctoList.Add(singleOctodure4);
            roomsOctoList.Add(doubleRoom1);
            roomsOctoList.Add(doubleRoom2);
            roomsOctoList.Add(doubleRoom3);
            roomsOctoList.Add(doubleRoom4);
            roomsOctoList.Add(doubleRoom5);

            context.SaveChanges();

            // Add rooms
            context.Rooms.Add(singleOctodure1);
            context.Rooms.Add(singleOctodure2);
            context.Rooms.Add(singleOctodure3);
            context.Rooms.Add(singleOctodure4);

            context.Rooms.Add(doubleRoom1);
            context.Rooms.Add(doubleRoom2);
            context.Rooms.Add(doubleRoom3);
            context.Rooms.Add(doubleRoom4);
            context.Rooms.Add(doubleRoom5);
            context.SaveChanges();

            // Add pictures
            context.Pictures.Add(singleOctodure1Picture);
            context.Pictures.Add(singleOcto2Picture);
            context.SaveChanges();

            octodureHotel.Rooms = roomsOctoList;
            context.SaveChanges();



            // Hotel #2 in Martigny
            Hotel constantinPalace = new Hotel
            {
                Name        = "Constantin Palace",
                Description = "Cet hotel est à l'image de son patron, guide, seigneur Constantin. Incontournable.",
                Location    = "Martigny",
                Category    = 3,
                HasWifi     = true,
                HasParking  = true,
                Phone       = "+41 (0)27 722 60 20",
                Email       = "*****@*****.**",
                Website     = "http://www.christian-constantin.ch/?portfolio=hotel-clerc"
            };

            Room singleConstRoom1 = new Room()
            {
                Hotel        = constantinPalace,
                Number       = 1,
                Description  = "Chambre simple, mais pas si simple. Petite, mais pas si petite. Prix abordable, mais pas bon marché. ",
                Type         = 1,
                Price        = 150,
                HasTv        = false,
                HasHairDryer = false
            };
            Room singleConstRoom2 = new Room()
            {
                Hotel        = constantinPalace,
                Number       = 2,
                Description  = "Venez découvrir la chambre ou les amis politiciens du patron viennent prendre l'apéritif et plus encore. ",
                Type         = 1,
                Price        = 150,
                HasTv        = false,
                HasHairDryer = false
            };

            Room doubleConstRoom1 = new Room()
            {
                Hotel        = constantinPalace,
                Number       = 3,
                Description  = "Doublement plus grande qu une chambre simple. Elle saura vous ravir et vous égayer. ",
                Type         = 2,
                Price        = 200,
                HasTv        = true,
                HasHairDryer = true,
            };

            Room doubleConstRoom2 = new Room()
            {
                Hotel        = constantinPalace,
                Number       = 4,
                Description  = "Cette chambre est spacieuse, formidable comme son patron. ",
                Type         = 2,
                Price        = 200,
                HasTv        = true,
                HasHairDryer = true
            };


            Room doubleConstRoom3 = new Room()
            {
                Hotel        = constantinPalace,
                Number       = 5,
                Description  = "Trois fois plus spacieuse, avec 3 écrans de télévision avec une commande. Elle saura vous inspirez et vous saurez l'aimer. ",
                Type         = 2,
                Price        = 300,
                HasTv        = true,
                HasHairDryer = true
            };

            Room doubleConstRoom4 = new Room()
            {
                Hotel        = constantinPalace,
                Number       = 6,
                Description  = "Quatre fois plus spacieuse, avec 3 baignoires et une grande armoire. Cette chambre est pour les clients exigeants. ",
                Type         = 2,
                Price        = 400,
                HasTv        = true,
                HasHairDryer = true
            };


            Room doubleConstRoom5 = new Room()
            {
                Hotel        = constantinPalace,
                Number       = 7,
                Description  = "Cinq fois plus grande que les plus petites. Un lavabo de luxe, un sèche de cheuveux en bois et une ambiance hors de prix. ",
                Type         = 2,
                Price        = 500,
                HasTv        = true,
                HasHairDryer = true
            };

            Room doubleConstRoom6 = new Room()
            {
                Hotel        = constantinPalace,
                Number       = 8,
                Description  = "Constantin Palace Double Luxe Suite Senior. Cette oeuvre central démontre tout le génie de l'architecture du maître. ",
                Type         = 2,
                Price        = 1000,
                HasTv        = false,
                HasHairDryer = false
            };

            Room doubleConstRoom7 = new Room()
            {
                Hotel        = constantinPalace,
                Number       = 9,
                Description  = "Constantin Palace Double Luxe Suite Senior. Cette oeuvre central démontre tout le génie de l'architecture du maître. ",
                Type         = 2,
                Price        = 10,
                HasTv        = false,
                HasHairDryer = false
            };

            Picture singleConstPicture1 = new Picture()
            {
                Room = singleConstRoom1,
                Url  = "https://foto.hrsstatic.com/fotos/0/3/694/390/80/000000/https%3A%2F%2Ffoto-origin.hrsstatic.com%2Ffoto%2F7%2F8%2F1%2F8%2F%2Fteaser_781883.jpg/VCy%2BEVFh%2B2zi2WDiRsqKcw%3D%3D/2300,1533/6/Marconi_Hotel-Rende-Ecomomy_Zimmer_Einzel-781883.jpg"
            };
            Picture singleConstPicture2 = new Picture()
            {
                Room = singleConstRoom2,
                Url  = "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTDNvUEohRDzm6w6190qU8Hm0EgSyE8fwDlg_mIFMdlKkVss5acJw"
            };

            Picture doubleConstPicture1 = new Picture()
            {
                Room = doubleConstRoom1,
                Url  = "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRn7B-pyLHkNZW0MRLcvtm5IWwkM-t-yc74oYYt-7F5IUYtZayi"
            };
            Picture doubleConstPicture2 = new Picture()
            {
                Room = doubleConstRoom2,
                Url  = "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSe7ACjLeU4mr4YkmRzK4OcDdDUY7wHv9jE23KOevxTA619MEId"
            };
            Picture doubleConstPicture3 = new Picture()
            {
                Room = doubleConstRoom3,
                Url  = "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQcCqoYvIHOBXxbl1Ss03igY70jDnrku86uoJV-JrB5v6mQpMVd3A"
            };
            Picture doubleConstPicture4 = new Picture()
            {
                Room = doubleConstRoom4,
                Url  = "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRWqLPA1UVXJIfT6pfJGQ69jYK6rwxoGUrFW9xQTsk4bISeRxa-"
            };
            Picture doubleConstPicture5 = new Picture()
            {
                Room = doubleConstRoom5,
                Url  = "https://www.hotel-valaisia.ch/fileadmin/media_resources/_processed_/9/9/csm_valaisia_zimmer_viererzimmer_c8df722540.jpg"
            };
            Picture doubleConstPicture6 = new Picture()
            {
                Room = doubleConstRoom6,
                Url  = "https://www.berliner-zeitung.de/image/5174222/max/600/450/bedc4f395e763c9e3aa9326d11dd3275/Zk/10-brinker-original2-jpg.jpg"
            };

            Picture doubleConstPicture7 = new Picture()
            {
                Room = doubleConstRoom7,
                Url  = "http://9d994bf6ac625bf5bc55-a77ff3994ac009fc59203500350c3ae4.r92.cf1.rackcdn.com/XLGallery/Four-Points-by-Sheraton-Sihlcity-Zurich-Hotel-Superior-Zimmer-King.jpg"
            };


            // Add hotel
            context.Hotels.Add(constantinPalace);

            // Add rooms to list
            List <Room> constantinRoomsList = new List <Room>();

            constantinRoomsList.Add(singleConstRoom1);
            constantinRoomsList.Add(singleConstRoom2);
            constantinRoomsList.Add(doubleConstRoom1);
            constantinRoomsList.Add(doubleConstRoom2);
            constantinRoomsList.Add(doubleConstRoom3);
            constantinRoomsList.Add(doubleConstRoom4);
            constantinRoomsList.Add(doubleConstRoom5);
            constantinRoomsList.Add(doubleConstRoom6);
            constantinRoomsList.Add(doubleConstRoom7);
            context.SaveChanges();

            // Add rooms
            context.Rooms.Add(singleConstRoom1);
            context.Rooms.Add(singleConstRoom2);
            context.Rooms.Add(doubleConstRoom1);
            context.Rooms.Add(doubleConstRoom2);
            context.Rooms.Add(doubleConstRoom3);
            context.Rooms.Add(doubleConstRoom4);
            context.Rooms.Add(doubleConstRoom5);
            context.Rooms.Add(doubleConstRoom6);
            context.Rooms.Add(doubleConstRoom7);
            context.SaveChanges();

            // Add pictures
            context.Pictures.Add(singleConstPicture1);
            context.Pictures.Add(singleConstPicture2);
            context.Pictures.Add(doubleConstPicture1);
            context.Pictures.Add(doubleConstPicture2);
            context.Pictures.Add(doubleConstPicture3);
            context.Pictures.Add(doubleConstPicture4);
            context.Pictures.Add(doubleConstPicture5);
            context.Pictures.Add(doubleConstPicture6);
            context.Pictures.Add(doubleConstPicture7);
            context.SaveChanges();

            constantinPalace.Rooms = constantinRoomsList;
            context.SaveChanges();


            //Hotel #1 Sion
            Hotel valaisPalace = new Hotel
            {
                Name        = "Valais Palace",
                Description = "Laissez-vous enchanter par le calme et la nature de Sion. Sion est l’endroit idéal pour oublier, pour quelques jours, le stress quotidien et pour laisser l’âme retrouver la sérénité. Vous appréciez ici l’air pur de la ville tout en jouissant d’un panorama unique. ",
                Location    = "Sion",
                Category    = 3,
                HasWifi     = true,
                HasParking  = true,
                Phone       = "+41 (0)27 456 10 20",
                Email       = "*****@*****.**",
                Website     = "https://www.grand-hotel-du-golf.ch/"
            };

            Room singleVsPalaceRoom1 = new Room()
            {
                Hotel        = valaisPalace,
                Number       = 1,
                Description  = "Chambre simple avec télévision et vue sur la montagne. ",
                Type         = 1,
                Price        = 50,
                HasTv        = true,
                HasHairDryer = true
            };
            Room singleVsPalaceRoom2 = new Room()
            {
                Hotel        = valaisPalace,
                Number       = 2,
                Description  = "Petit chambre lumineuse avec télévision et mini-bar. ",
                Type         = 1,
                Price        = 50,
                HasTv        = true,
                HasHairDryer = true
            };
            Room singleVsPalaceRoom3 = new Room()
            {
                Hotel        = valaisPalace,
                Number       = 3,
                Description  = "Un véritable petit studio avec son lit douillé. ",
                Type         = 1,
                Price        = 50,
                HasTv        = true,
                HasHairDryer = true
            };

            Room doubleVsPalaceRoom1 = new Room()
            {
                Hotel        = valaisPalace,
                Number       = 4,
                Description  = "Grande chambre idéal pour une nuit en couple. ",
                Type         = 2,
                Price        = 100,
                HasTv        = true,
                HasHairDryer = true,
            };

            Room doubleVsPalaceRoom2 = new Room()
            {
                Hotel        = valaisPalace,
                Number       = 5,
                Description  = "Chambre double classique avec vue sur la montagne. ",
                Type         = 2,
                Price        = 100,
                HasTv        = true,
                HasHairDryer = true
            };


            Room doubleVsPalaceRoom3 = new Room()
            {
                Hotel        = valaisPalace,
                Number       = 6,
                Description  = "Cette chambre double à un accès direct à la piscine. ",
                Type         = 2,
                Price        = 100,
                HasTv        = true,
                HasHairDryer = true
            };

            Room doubleVsPalaceRoom4 = new Room()
            {
                Hotel        = valaisPalace,
                Number       = 7,
                Description  = "Double lit avec écran géant.",
                Type         = 2,
                Price        = 100,
                HasTv        = true,
                HasHairDryer = true
            };


            Room doubleVsPalaceRoom5 = new Room()
            {
                Hotel        = valaisPalace,
                Number       = 8,
                Description  = "Grand espace pour deux personnes. ",
                Type         = 2,
                Price        = 100,
                HasTv        = true,
                HasHairDryer = true
            };

            Room doubleVsPalaceRoom6 = new Room()
            {
                Hotel        = valaisPalace,
                Number       = 9,
                Description  = "Un lit deux places de luxe avec accès au sauna. ",
                Type         = 2,
                Price        = 100,
                HasTv        = true,
                HasHairDryer = false
            };

            Room doubleVsPalaceRoom7 = new Room()
            {
                Hotel        = valaisPalace,
                Number       = 10,
                Description  = "Grande chambre deux places lumineuse. ",
                Type         = 2,
                Price        = 100,
                HasTv        = true,
                HasHairDryer = true
            };

            Room doubleVsPalaceRoom8 = new Room()
            {
                Hotel        = valaisPalace,
                Number       = 11,
                Description  = "Junior suite pour une nuit dans les étoiles. ",
                Type         = 2,
                Price        = 200,
                HasTv        = true,
                HasHairDryer = false
            };

            Picture singleVsPicture1 = new Picture()
            {
                Room = singleVsPalaceRoom1,
                Url  = "https://foto.hrsstatic.com/fotos/0/3/694/390/80/000000/https%3A%2F%2Ffoto-origin.hrsstatic.com%2Ffoto%2F7%2F8%2F1%2F8%2F%2Fteaser_781883.jpg/VCy%2BEVFh%2B2zi2WDiRsqKcw%3D%3D/2300,1533/6/Marconi_Hotel-Rende-Ecomomy_Zimmer_Einzel-781883.jpg"
            };
            Picture singleVsPicture2 = new Picture()
            {
                Room = singleVsPalaceRoom2,
                Url  = "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTDNvUEohRDzm6w6190qU8Hm0EgSyE8fwDlg_mIFMdlKkVss5acJw"
            };

            Picture singleVsPicture3 = new Picture()
            {
                Room = singleVsPalaceRoom3,
                Url  = "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTDNvUEohRDzm6w6190qU8Hm0EgSyE8fwDlg_mIFMdlKkVss5acJw"
            };

            Picture doubleVsPicture1 = new Picture()
            {
                Room = doubleVsPalaceRoom1,
                Url  = "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRn7B-pyLHkNZW0MRLcvtm5IWwkM-t-yc74oYYt-7F5IUYtZayi"
            };
            Picture doubleVsPicture2 = new Picture()
            {
                Room = doubleVsPalaceRoom2,
                Url  = "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSe7ACjLeU4mr4YkmRzK4OcDdDUY7wHv9jE23KOevxTA619MEId"
            };
            Picture doubleVsPicture3 = new Picture()
            {
                Room = doubleVsPalaceRoom3,
                Url  = "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQcCqoYvIHOBXxbl1Ss03igY70jDnrku86uoJV-JrB5v6mQpMVd3A"
            };
            Picture doubleVsPicture4 = new Picture()
            {
                Room = doubleVsPalaceRoom4,
                Url  = "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRWqLPA1UVXJIfT6pfJGQ69jYK6rwxoGUrFW9xQTsk4bISeRxa-"
            };
            Picture doubleVsPicture5 = new Picture()
            {
                Room = doubleVsPalaceRoom5,
                Url  = "https://www.hotel-valaisia.ch/fileadmin/media_resources/_processed_/9/9/csm_valaisia_zimmer_viererzimmer_c8df722540.jpg"
            };
            Picture doubleVsPicture6 = new Picture()
            {
                Room = doubleVsPalaceRoom6,
                Url  = "https://www.berliner-zeitung.de/image/5174222/max/600/450/bedc4f395e763c9e3aa9326d11dd3275/Zk/10-brinker-original2-jpg.jpg"
            };

            Picture doubleVsPicture7 = new Picture()
            {
                Room = doubleVsPalaceRoom7,
                Url  = "http://9d994bf6ac625bf5bc55-a77ff3994ac009fc59203500350c3ae4.r92.cf1.rackcdn.com/XLGallery/Four-Points-by-Sheraton-Sihlcity-Zurich-Hotel-Superior-Zimmer-King.jpg"
            };
            Picture doubleVsPicture8 = new Picture()
            {
                Room = doubleVsPalaceRoom8,
                Url  = "http://9d994bf6ac625bf5bc55-a77ff3994ac009fc59203500350c3ae4.r92.cf1.rackcdn.com/XLGallery/Four-Points-by-Sheraton-Sihlcity-Zurich-Hotel-Superior-Zimmer-King.jpg"
            };

            // Add hotel
            context.Hotels.Add(valaisPalace);

            // Add rooms to list
            List <Room> valaisPalaceRoomsList = new List <Room>();

            valaisPalaceRoomsList.Add(singleVsPalaceRoom1);
            valaisPalaceRoomsList.Add(singleVsPalaceRoom2);
            valaisPalaceRoomsList.Add(singleVsPalaceRoom3);
            valaisPalaceRoomsList.Add(doubleVsPalaceRoom1);
            valaisPalaceRoomsList.Add(doubleVsPalaceRoom2);
            valaisPalaceRoomsList.Add(doubleVsPalaceRoom3);
            valaisPalaceRoomsList.Add(doubleVsPalaceRoom4);
            valaisPalaceRoomsList.Add(doubleVsPalaceRoom5);
            valaisPalaceRoomsList.Add(doubleVsPalaceRoom6);
            valaisPalaceRoomsList.Add(doubleVsPalaceRoom7);
            valaisPalaceRoomsList.Add(doubleVsPalaceRoom8);

            context.SaveChanges();

            // Add rooms
            context.Rooms.Add(singleVsPalaceRoom1);
            context.Rooms.Add(singleVsPalaceRoom2);
            context.Rooms.Add(singleVsPalaceRoom3);
            context.Rooms.Add(doubleVsPalaceRoom1);
            context.Rooms.Add(doubleVsPalaceRoom2);
            context.Rooms.Add(doubleVsPalaceRoom3);
            context.Rooms.Add(doubleVsPalaceRoom4);
            context.Rooms.Add(doubleVsPalaceRoom5);
            context.Rooms.Add(doubleVsPalaceRoom6);
            context.Rooms.Add(doubleVsPalaceRoom7);
            context.Rooms.Add(doubleVsPalaceRoom8);
            context.SaveChanges();

            // Add pictures
            context.Pictures.Add(singleVsPicture1);
            context.Pictures.Add(singleVsPicture2);
            context.Pictures.Add(singleVsPicture3);
            context.Pictures.Add(doubleVsPicture1);
            context.Pictures.Add(doubleVsPicture2);
            context.Pictures.Add(doubleVsPicture3);
            context.Pictures.Add(doubleVsPicture4);
            context.Pictures.Add(doubleVsPicture5);
            context.Pictures.Add(doubleVsPicture6);
            context.Pictures.Add(doubleVsPicture7);
            context.Pictures.Add(doubleVsPicture8);
            context.SaveChanges();

            valaisPalace.Rooms = valaisPalaceRoomsList;
            context.SaveChanges();



            //Hotel #2 Sion
            Hotel GrandDuc = new Hotel
            {
                Name        = "Grand Duc",
                Description = "Installé à seulement vingt minutes à pied de la Gare de Sion, l'hôtel fournit un endroit pratique à ses clients lors de leur visite des châteaux. Il met à disposition des salles de réunion, une consigne à bagage et une réception ouverte 24h/24. ",
                Location    = "Sion",
                Category    = 3,
                HasWifi     = true,
                HasParking  = true,
                Phone       = "+41 (0)27 456 27 27",
                Email       = "*****@*****.**",
                Website     = "http://www.christian-constantin.ch/?portfolio=hotel-clerc"
            };

            Room singleGrandDucRoom1 = new Room()
            {
                Hotel        = GrandDuc,
                Number       = 1,
                Description  = "Les chambres simples sont composées d'un lit de 100*200 et idéales pour les séjours entre 1 et 3 nuits. ",
                Type         = 1,
                Price        = 50,
                HasTv        = true,
                HasHairDryer = true
            };
            Room singleGrandDucRoom2 = new Room()
            {
                Hotel        = GrandDuc,
                Number       = 2,
                Description  = "Les chambres simples sont composées d'un lit de 100*200 et idéales pour les séjours entre 1 et 3 nuits. ",
                Type         = 1,
                Price        = 50,
                HasTv        = true,
                HasHairDryer = true
            };
            Room singleGrandDucRoom3 = new Room()
            {
                Hotel        = GrandDuc,
                Number       = 3,
                Description  = "Les chambres simples sont composées d'un lit de 100*200 et idéales pour les séjours entre 1 et 3 nuits. ",
                Type         = 1,
                Price        = 50,
                HasTv        = true,
                HasHairDryer = true
            };
            Room singleGrandDucRoom4 = new Room()
            {
                Hotel        = GrandDuc,
                Number       = 4,
                Description  = "Les chambres simples sont composées d'un lit de 100*200 et idéales pour les séjours entre 1 et 3 nuits. ",
                Type         = 1,
                Price        = 50,
                HasTv        = true,
                HasHairDryer = true
            };

            Room doubleGrandDucRoom1 = new Room()
            {
                Hotel        = GrandDuc,
                Number       = 5,
                Description  = "Les chambres doubles sont composées de 2 lits jumeaux côte à côte et séparables de 90*200 et idéales pour  tous les séjours de tourismes ou d'affaire. Ces chambres peuvent également être loués en occupation individuelle pour 1 personne. ",
                Type         = 2,
                Price        = 100,
                HasTv        = true,
                HasHairDryer = true,
            };

            Room doubleGrandDucRoom2 = new Room()
            {
                Hotel        = GrandDuc,
                Number       = 6,
                Description  = "Les chambres doubles sont composées de 2 lits jumeaux côte à côte et séparables de 90*200 et idéales pour  tous les séjours de tourismes ou d'affaire. Ces chambres peuvent également être loués en occupation individuelle pour 1 personne. ",
                Type         = 2,
                Price        = 100,
                HasTv        = true,
                HasHairDryer = true,
            };


            Picture singleGranDucPicture1 = new Picture()
            {
                Room = singleGrandDucRoom1,
                Url  = "https://foto.hrsstatic.com/fotos/0/3/694/390/80/000000/https%3A%2F%2Ffoto-origin.hrsstatic.com%2Ffoto%2F7%2F8%2F1%2F8%2F%2Fteaser_781883.jpg/VCy%2BEVFh%2B2zi2WDiRsqKcw%3D%3D/2300,1533/6/Marconi_Hotel-Rende-Ecomomy_Zimmer_Einzel-781883.jpg"
            };
            Picture singleGranDucPicture2 = new Picture()
            {
                Room = singleGrandDucRoom2,
                Url  = "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTDNvUEohRDzm6w6190qU8Hm0EgSyE8fwDlg_mIFMdlKkVss5acJw"
            };

            Picture singleGranDucPicture3 = new Picture()
            {
                Room = singleGrandDucRoom3,
                Url  = "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTDNvUEohRDzm6w6190qU8Hm0EgSyE8fwDlg_mIFMdlKkVss5acJw"
            };

            Picture singleGranDucPicture4 = new Picture()
            {
                Room = singleGrandDucRoom4,
                Url  = "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRn7B-pyLHkNZW0MRLcvtm5IWwkM-t-yc74oYYt-7F5IUYtZayi"
            };
            Picture doubleGrandDUcPicture1 = new Picture()
            {
                Room = doubleGrandDucRoom1,
                Url  = "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSe7ACjLeU4mr4YkmRzK4OcDdDUY7wHv9jE23KOevxTA619MEId"
            };
            Picture doubleGrandDUcPicture2 = new Picture()
            {
                Room = doubleGrandDucRoom2,
                Url  = "https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcQcCqoYvIHOBXxbl1Ss03igY70jDnrku86uoJV-JrB5v6mQpMVd3A"
            };


            // Add hotel
            context.Hotels.Add(GrandDuc);

            // Add rooms to list
            List <Room> grandDucRoomsList = new List <Room>();

            grandDucRoomsList.Add(singleGrandDucRoom1);
            grandDucRoomsList.Add(singleGrandDucRoom2);
            grandDucRoomsList.Add(singleGrandDucRoom3);
            grandDucRoomsList.Add(singleGrandDucRoom4);
            grandDucRoomsList.Add(doubleGrandDucRoom1);
            grandDucRoomsList.Add(doubleGrandDucRoom2);

            context.SaveChanges();

            // Add rooms
            context.Rooms.Add(singleGrandDucRoom1);
            context.Rooms.Add(singleGrandDucRoom2);
            context.Rooms.Add(singleGrandDucRoom3);
            context.Rooms.Add(singleGrandDucRoom4);
            context.Rooms.Add(doubleGrandDucRoom1);
            context.Rooms.Add(doubleGrandDucRoom2);

            context.SaveChanges();

            // Add pictures
            context.Pictures.Add(singleGranDucPicture1);
            context.Pictures.Add(singleGranDucPicture2);
            context.Pictures.Add(singleGranDucPicture3);
            context.Pictures.Add(singleGranDucPicture4);
            context.Pictures.Add(doubleGrandDUcPicture1);
            context.Pictures.Add(doubleGrandDUcPicture2);

            context.SaveChanges();

            GrandDuc.Rooms = grandDucRoomsList;
            context.SaveChanges();


            //Hotel #1 Brig

            Hotel walliserPalace = new Hotel
            {
                Name        = "Walliser Palace",
                Description = "Das 3-Sterne-Hotel Garni Europe ist ein moderner Familienbetrieb mit neu renovierten Zimmern, einer gemütlichen Hotelbar und hoteleigenen Gratisparkplätzen. Direkt gegenüber der Matterhorn-Gotthard-Bahn und dem Glacier Express erwartet Sie das Hotel Europe. Sie wohnen 200 m vom Zentrum des Ortes Brig entfernt. Kostenfrei profitieren Sie von dem Parkmöglichkeiten vor Ort und vom WLAN. ",
                Location    = "Brig",
                Category    = 3,
                HasWifi     = true,
                HasParking  = true,
                Phone       = "+41 (0)27 923 13 21",
                Email       = "*****@*****.**",
                Website     = "http://www.hotel-europe-brig.ch/?skd-language-code=de"
            };

            Room singleWalliserRoom1 = new Room()
            {
                Hotel        = walliserPalace,
                Number       = 1,
                Description  = "Die Zimmer des Hotels Unterellmau bieten herrliche Ausblicke in die Bergwelt rund um Brig Hinterglemm. ",
                Type         = 1,
                Price        = 65,
                HasTv        = true,
                HasHairDryer = true
            };
            Room singleWalliserRoom2 = new Room()
            {
                Hotel        = walliserPalace,
                Number       = 2,
                Description  = "Diese individuell eingerichteten Zimmer bieten Ihnen den optimalen Komfort für einen gelungenen Kurzaufenthalt. Sei es für den Geschäftstrip oder das traute Wochenende zu zweit. ",
                Type         = 1,
                Price        = 70,
                HasTv        = true,
                HasHairDryer = true
            };
            Room singleWalliserRoom3 = new Room()
            {
                Hotel        = walliserPalace,
                Number       = 3,
                Description  = "Klein, aber fein: Unsere beiden Classic-Einzelzimmer bieten Ihnen alles, was es für einen gelungenen Aufenthalt braucht. Schön kompakt zu fairen Preisen. ",
                Type         = 1,
                Price        = 60,
                HasTv        = true,
                HasHairDryer = true
            };
            Room singleWalliserRoom4 = new Room()
            {
                Hotel        = walliserPalace,
                Number       = 4,
                Description  = "Diese individuell eingerichteten Zimmer bieten Ihnen den optimalen Komfort für einen gelungenen Kurzaufenthalt. Sei es für den Geschäftstrip oder das traute Wochenende zu zweit. ",
                Type         = 1,
                Price        = 50,
                HasTv        = true,
                HasHairDryer = true
            };

            Room doubleWalisserRoom1 = new Room()
            {
                Hotel        = walliserPalace,
                Number       = 5,
                Description  = "Historisch angehauchter Charme für wenig Geld. Die originellen Retro-Zimmer mit dem externen Bad über den Flur versprühen einen Hauch von Geschichte. ",
                Type         = 2,
                Price        = 100,
                HasTv        = true,
                HasHairDryer = true,
            };

            Room doubleWalisserRoom2 = new Room()
            {
                Hotel        = walliserPalace,
                Number       = 6,
                Description  = "Luxuriöses und elegantes Zimmer mit Hydromassagedusche im Bad. ",
                Type         = 2,
                Price        = 200,
                HasTv        = true,
                HasHairDryer = true,
            };

            Room doubleWalisserRoom3 = new Room()
            {
                Hotel        = walliserPalace,
                Number       = 7,
                Description  = "Lässt Herzen höher schlagen: Wer unsere wunderbare Suite mit Wohn- und Schlafbereich erst einmal bezogen hat, will so schnell nicht mehr heraus. Für Geniesser, die gern mit offenen Augen träumen. ",
                Type         = 2,
                Price        = 125,
                HasTv        = true,
                HasHairDryer = true,
            };


            Picture singleWalisserPicture1 = new Picture()
            {
                Room = singleWalliserRoom1,
                Url  = "https://www.auberge-langenthal.ch/images/content/zimmer/Einzelzimmer_Retro_2_Hotel_Auberge_Langenthal.jpg"
            };
            Picture singleWalisserPicture2 = new Picture()
            {
                Room = singleWalliserRoom2,
                Url  = "https://www.auberge-langenthal.ch/images/content/zimmer/Doppelzimmer_Classic_Grandlit_Hotel_Auberge_Langenthal.jpg"
            };

            Picture singleWalisserPicture3 = new Picture()
            {
                Room = singleWalliserRoom3,
                Url  = "https://www.auberge-langenthal.ch/images/content/zimmer/Doppelzimmer_Superior_Bad_2_Hotel_Auberge_Langenthal.jpg"
            };

            Picture singleWalisserPicture4 = new Picture()
            {
                Room = singleWalliserRoom4,
                Url  = "https://www.auberge-langenthal.ch/images/content/zimmer/Einzelzimmer_Retro_Hotel_Auberge_Langenthal.jpg"
            };
            Picture doubleWalisserPicture1 = new Picture()
            {
                Room = doubleWalisserRoom1,
                Url  = "https://www.auberge-langenthal.ch/images/content/zimmer/Doppelzimmer_Retro_6_Hotel_Auberge_Langenthal.jpg"
            };
            Picture doubleWalisserPicture2 = new Picture()
            {
                Room = doubleWalisserRoom2,
                Url  = "https://www.auberge-langenthal.ch/images/content/zimmer/Doppelzimmer_Retro_5_Hotel_Auberge_Langenthal.jpg"
            };

            Picture doubleWalisserPicture3 = new Picture()
            {
                Room = doubleWalisserRoom1,
                Url  = "https://www.auberge-langenthal.ch/images/content/zimmer/Doppelzimmer_Superior_3_Hotel_Auberge_Langenthal.jpg"
            };

            // URLs
            //https://www.auberge-langenthal.ch/images/content/zimmer/Einzelzimmer_Classic_13_Hotel_Auberge_Langenthal.jpg

            // Add hotel
            context.Hotels.Add(walliserPalace);

            // Add rooms to list
            List <Room> wallisserRoomsList = new List <Room>();

            wallisserRoomsList.Add(singleWalliserRoom1);
            wallisserRoomsList.Add(singleWalliserRoom2);
            wallisserRoomsList.Add(singleWalliserRoom3);
            wallisserRoomsList.Add(singleWalliserRoom4);
            wallisserRoomsList.Add(doubleWalisserRoom1);
            wallisserRoomsList.Add(doubleWalisserRoom2);
            wallisserRoomsList.Add(doubleWalisserRoom3);

            context.SaveChanges();

            // Add rooms
            context.Rooms.Add(singleWalliserRoom1);
            context.Rooms.Add(singleWalliserRoom2);
            context.Rooms.Add(singleWalliserRoom3);
            context.Rooms.Add(singleWalliserRoom4);
            context.Rooms.Add(doubleWalisserRoom1);
            context.Rooms.Add(doubleWalisserRoom2);
            context.Rooms.Add(doubleWalisserRoom3);

            context.SaveChanges();

            // Add pictures
            context.Pictures.Add(singleWalisserPicture1);
            context.Pictures.Add(singleWalisserPicture2);
            context.Pictures.Add(singleWalisserPicture3);
            context.Pictures.Add(singleWalisserPicture4);
            context.Pictures.Add(doubleWalisserPicture1);
            context.Pictures.Add(doubleWalisserPicture2);
            context.Pictures.Add(doubleWalisserPicture3);

            context.SaveChanges();

            walliserPalace.Rooms = wallisserRoomsList;
            context.SaveChanges();



            //Hotel #2 Brig
            Hotel mattherhorn = new Hotel
            {
                Name        = "Mattherhorn",
                Description = "Grandiose Suite Matterhorn mit Balkon und Blick auf die atemberaubende Bergwelt. ",
                Location    = "Brig",
                Category    = 4,
                HasWifi     = true,
                HasParking  = true,
                Phone       = "+41 (0)27 923 08 88",
                Email       = "*****@*****.**",
                Website     = "https://www.matterhorn-focus.ch/de/"
            };

            Room singleMattherRoom1 = new Room()
            {
                Hotel        = mattherhorn,
                Number       = 1,
                Description  = "Geniessen Sie alpin-modernes Design und die fantastische Aussicht auf das Matterhorn. ",
                Type         = 1,
                Price        = 75,
                HasTv        = true,
                HasHairDryer = true
            };
            Room singleMattherRoom2 = new Room()
            {
                Hotel        = mattherhorn,
                Number       = 2,
                Description  = "Den Sonnenaufgang und den Sonnenuntergang am Matterhorn beobachten. ",
                Type         = 1,
                Price        = 80,
                HasTv        = true,
                HasHairDryer = true
            };
            Room singleMattherRoom3 = new Room()
            {
                Hotel        = mattherhorn,
                Number       = 3,
                Description  = "Naturschauspiel bietet sich Ihnen in Ihren komfortablen Zimmer mit Südbalkon. ",
                Type         = 1,
                Price        = 85,
                HasTv        = true,
                HasHairDryer = true
            };
            Room singleMattherRoom4 = new Room()
            {
                Hotel        = mattherhorn,
                Number       = 4,
                Description  = "Lassen Sie sich in einen Sessel sinken und finden Sie Erholung im traditionellen Ambiente mit warmen Farben und viel Holz. ",
                Type         = 1,
                Price        = 90,
                HasTv        = true,
                HasHairDryer = true
            };
            Room singleMattherRoom5 = new Room()
            {
                Hotel        = mattherhorn,
                Number       = 5,
                Description  = "Wahrer Luxus ist Raum – im Doppelzimmer Design zur Alleinbenützung.  ",
                Type         = 1,
                Price        = 120,
                HasTv        = true,
                HasHairDryer = true
            };

            Room doubleWMatherRoom1 = new Room()
            {
                Hotel        = mattherhorn,
                Number       = 6,
                Description  = "Erleben Sie alpin-modernes Design in Perfektion – eine Harmonie aus Stein, Glas und Holz.   ",
                Type         = 2,
                Price        = 140,
                HasTv        = true,
                HasHairDryer = true,
            };

            Room doubleWMatherRoom2 = new Room()
            {
                Hotel        = mattherhorn,
                Number       = 7,
                Description  = "Luxuriöses und elegantes Zimmer mit Hydromassagedusche im Bad. ",
                Type         = 2,
                Price        = 200,
                HasTv        = true,
                HasHairDryer = true,
            };


            Picture singleMatherPicture1 = new Picture()
            {
                Room = singleMattherRoom1,
                Url  = "http://www.eden-spiez.ch/media/img/galleries/komfort-dorf-zimmer/weblication/wThumbnails/Hotel-Eden-Spiez-MOD1QM-315-02-aabe28d66a1e383g5649483053f7d1a9.jpg"
            };
            Picture singleMatherPicture2 = new Picture()
            {
                Room = singleMattherRoom2,
                Url  = "https://europe-zermatt.ch/wp-content/uploads/2016/04/Europe_Zermatt_Doppelzimmer_Design_BadZi.jpg"
            };

            Picture singleMatherPicture3 = new Picture()
            {
                Room = singleMattherRoom3,
                Url  = "http://www.eden-spiez.ch/media/img/galleries/komfort-dorf-zimmer/weblication/wThumbnails/Hotel-Eden-Spiez-MOD1QM-116-01-c72f00dc1bf15e7g9950b6c52f2785e7.jpg"
            };

            Picture singleMatherPicture4 = new Picture()
            {
                Room = singleMattherRoom4,
                Url  = "https://europe-zermatt.ch/wp-content/uploads/2016/04/Europe_Zermatt_Doppelzimmer_Matterhorn_Bad.jpg"
            };
            Picture singleMatherPicture5 = new Picture()
            {
                Room = singleMattherRoom5,
                Url  = "https://europe-zermatt.ch/wp-content/uploads/2016/04/Europe_Zermatt_Doppelzimmer_Matterhorn_View.jpg"
            };
            Picture doubleMatherPicture1 = new Picture()
            {
                Room = doubleWMatherRoom1,
                Url  = "https://europe-zermatt.ch/wp-content/uploads/2016/04/Europe_Zermatt_Doppelzimmer_Design.jpg"
            };

            Picture doubleMatherPicture2 = new Picture()
            {
                Room = doubleWMatherRoom2,
                Url  = "https://europe-zermatt.ch/wp-content/uploads/2016/04/Europe_Zermatt_Doppelzimmer_Standard.jpg"
            };

            //Komfortables Doppelzimmer mit Blick auf die atemberaubende Bergwelt.

            // Add hotel
            context.Hotels.Add(mattherhorn);

            // Add rooms to list
            List <Room> matterhornRoomsList = new List <Room>();

            matterhornRoomsList.Add(singleMattherRoom1);
            matterhornRoomsList.Add(singleMattherRoom2);
            matterhornRoomsList.Add(singleMattherRoom3);
            matterhornRoomsList.Add(singleMattherRoom4);
            matterhornRoomsList.Add(singleMattherRoom5);
            matterhornRoomsList.Add(doubleWMatherRoom1);
            matterhornRoomsList.Add(doubleWMatherRoom2);


            context.SaveChanges();

            // Add rooms
            context.Rooms.Add(singleMattherRoom1);
            context.Rooms.Add(singleMattherRoom2);
            context.Rooms.Add(singleMattherRoom3);
            context.Rooms.Add(singleMattherRoom4);
            context.Rooms.Add(singleMattherRoom5);
            context.Rooms.Add(doubleWMatherRoom1);
            context.Rooms.Add(doubleWMatherRoom2);

            context.SaveChanges();

            // Add pictures
            context.Pictures.Add(singleMatherPicture1);
            context.Pictures.Add(singleMatherPicture2);
            context.Pictures.Add(singleMatherPicture3);
            context.Pictures.Add(singleMatherPicture4);
            context.Pictures.Add(singleMatherPicture5);
            context.Pictures.Add(doubleMatherPicture1);
            context.Pictures.Add(doubleMatherPicture2);

            context.SaveChanges();

            mattherhorn.Rooms = matterhornRoomsList;
            context.SaveChanges();
        }
Exemplo n.º 52
0
 /// <summary>
 /// Gets the loaded picture binary depending on picture storage settings
 /// </summary>
 /// <param name="picture">Picture</param>
 /// <returns>Picture binary</returns>
 public virtual byte[] LoadPictureBinary(Picture picture)
 {
     return(LoadPictureBinary(picture, StoreInDb));
 }
Exemplo n.º 53
0
 public virtual Size GetPictureSize(Picture picture)
 {
     byte[] pictureBinary = LoadPictureBinary(picture);
     return(GetPictureSize(pictureBinary));
 }
Exemplo n.º 54
0
 public int Edit([FromBody] Picture picture)
 {
     return(pictureService.UpdatePicture(picture));
 }
Exemplo n.º 55
0
                /// <summary>
                /// Displays a <see cref="T:Gadgeteer.Picture"/> image on the screen.
                /// </summary>
                /// <param name="picture">The <see cref="T:Gadgeteer.Picture"/> to display.</param>
                /// <param name="x">Horizontal position of the left edge of the bitmap on the display.</param>
                /// <param name="y">Vertical position of the top edge of the bitmap on the display.</param>
                public void DisplayImage(Picture picture, uint x, uint y)
                {
                    var bitmap = picture.MakeBitmap();

                    DisplayImage(bitmap, x, y, 0, 0, (uint)bitmap.Width, (uint)bitmap.Height);
                }
Exemplo n.º 56
0
 public int Create([FromBody] Picture picture)
 {
     return(pictureService.AddPicture(picture));
 }
Exemplo n.º 57
0
 /// <summary>
 /// Displays a <see cref="T:Gadgeteer.Picture"/> image on the screen.
 /// </summary>
 /// <param name="picture">The <see cref="T:Gadgeteer.Picture"/> to display.</param>
 /// <param name="x">Horizontal position of the left edge of the image on the display.</param>
 /// <param name="y">Vertical position of the top edge of the image on the display.</param>
 /// <param name="xSrc">Source X coordinate. Use this parameter to specify cropping from the left edge of the image. Use 0 to display full image.</param>
 /// <param name="ySrc">Source Y coordinate. Use this parameter to specify cropping from the top edge of the image. Use 0 to display full image.</param>
 /// <param name="width">Source width. Use this parameter to specify cropping to the right of the image.</param>
 /// <param name="height">Source height. Use this parameter to specify cropping to the right of the image.</param>
 public void DisplayImage(Picture picture, uint x, uint y, uint xSrc, uint ySrc, uint width, uint height)
 {
     DisplayImage(picture.MakeBitmap(), x, y, xSrc, ySrc, width, height);
 }
Exemplo n.º 58
0
 public RoxyFilemanFormFile(Picture picture, PictureBinary pictureBinary, string fileExtension)
 {
     _picture       = picture;
     _pictureBinary = pictureBinary;
     _fileExtension = fileExtension;
 }
Exemplo n.º 59
0
        protected override void Seed(PhotographyContext context)
        {
            Photographer dragan = new Photographer()
            {
                Username     = "******",
                Password     = "******",
                Email        = "*****@*****.**",
                BirthDate    = new DateTime(1992, 01, 08),
                RegisterDate = new DateTime(2010, 10, 10)
            };

            Photographer stamen = new Photographer()
            {
                Username     = "******",
                Password     = "******",
                Email        = "*****@*****.**",
                BirthDate    = new DateTime(1992, 01, 08),
                RegisterDate = new DateTime(2010, 10, 10)
            };

            context.Photographers.AddOrUpdate(p => p.Username, dragan, stamen);
            context.SaveChanges();

            Picture picture = new Picture()
            {
                Title            = "Mountain",
                Caption          = "Peak",
                PathOnFileSystem = "../pictures/mountains"
            };

            Picture picture2 = new Picture()
            {
                Title            = "River",
                Caption          = "Water",
                PathOnFileSystem = "../pictures/rivers"
            };

            context.Pictures.AddOrUpdate(pic => pic.Title, picture, picture2);
            context.SaveChanges();

            Tag tag = new Tag()
            {
                Name = "rocks"
                       // Tag name doesn't start with '#' but it's transformed to valid tag with the 'TagTansformer' class;
            };

            Tag tag2 = new Tag()
            {
                Name = "#   fishes"
                       //Tag name contains white spaces but it's transformed to valid tag with the 'TagTansformer' class;
            };

            List <Tag> tags = new List <Tag>();

            tags.Add(tag);
            tags.Add(tag2);

            foreach (var currentTag in tags)
            {
                currentTag.Name = TagTansformer.Transform(currentTag.Name);
            }

            foreach (var currentTag in tags)
            {
                context.Tags.AddOrUpdate(t => t.Name, currentTag);
            }

            context.SaveChanges();

            Album album = new Album()
            {
                Name            = "Mountains",
                BackgroundColor = "Green and Brown",
                IsPublic        = true
            };

            Album album2 = new Album()
            {
                Name            = "Rivers",
                BackgroundColor = "Green and Blue",
                IsPublic        = true
            };

            context.Albums.AddOrUpdate(a => a.Name, album, album2);

            context.SaveChanges();

            PhotographerAlbum photographerAlbumDragan = new PhotographerAlbum()
            {
                Album_Id        = album.Id,
                Photographer_Id = dragan.Id,
                Role            = Role.Owner
            };

            PhotographerAlbum photographerAlbumStamen = new PhotographerAlbum()
            {
                Album_Id        = album2.Id,
                Photographer_Id = stamen.Id,
                Role            = Role.Owner
            };

            PhotographerAlbum photographerAlbumDragan2 = new PhotographerAlbum()
            {
                Album_Id        = album2.Id,
                Photographer_Id = dragan.Id,
                Role            = Role.Viewer
            };

            PhotographerAlbum photographerAlbumStamen2 = new PhotographerAlbum()
            {
                Album_Id        = album.Id,
                Photographer_Id = stamen.Id,
                Role            = Role.Viewer
            };

            // After executing the Seed method:
            // In the first album Dragan is an owner and Stamen is a viewer;
            // In the second album Stamen is an owner and Dragan is a viewer;
            context.PhotographerAlbums.AddOrUpdate(pa => new { pa.Photographer_Id, pa.Album_Id },
                                                   photographerAlbumDragan, photographerAlbumStamen,
                                                   photographerAlbumDragan2, photographerAlbumStamen2);

            // Album-Pictures many-to-many relationship it's working - table [dbo].[PictureAlbums] it's filling with data;
            album.Pictures.Add(picture);
            album2.Pictures.Add(picture2);

            // Album-Tags many-to-many relationship it's working - table [dbo].[TagAlbums] it's filling with data;
            album.Tags.Add(tag);
            album2.Tags.Add(tag2);

            context.SaveChanges();
        }
Exemplo n.º 60
0
        public ActionResult Publish(AssetImages model)
        {
            if (!ModelState.IsValid)
            {
                return(View("Publish", model));
            }
            model.asset.Publisher   = User.Identity.Name;
            model.asset.ReleaseDate = DateTime.Now.ToString();
            if (!model.File.FileName.EndsWith("rar") && !model.File.FileName.EndsWith("zip"))
            {
                return(View("Publish", model));
            }
            string[] formats = new string[] { ".jpg", ".png", ".jpeg" };
            bool     Wrong   = true;

            foreach (var image in model.Files)
            {
                foreach (var item in formats)
                {
                    if (image.FileName.Contains(item))
                    {
                        Wrong = false;
                        break;
                    }
                }
            }
            if (Wrong)
            {
                return(View("Publish", model));
            }

            foreach (var file in model.Files)
            {
                if (file == null)
                {
                    //at least 1 photo per asset
                    return(View(model));
                }
                else if (file.ContentLength > 0)
                {
                    Picture c = new Picture();
                    c.ImageData = new byte[file.ContentLength];
                    file.InputStream.Read(c.ImageData, 0, c.ImageData.Length);

                    _photoContext.AssetsPhotos.Add(c);
                    _photoContext.SaveChanges();
                    if (model.asset.imagesId == null)
                    {
                        model.asset.imagesId = c.Id.ToString();
                    }
                    else
                    {
                        model.asset.imagesId += "," + c.Id.ToString();
                    }
                }
            }

            if (model.File.ContentLength > 0)
            {
                MemoryStream target = new MemoryStream();
                model.File.InputStream.CopyTo(target);
                byte[] data = target.ToArray();
                model.asset.assetZip = data;
            }
            model.asset.Size = model.asset.assetZip.Count() / 1048576f;

            //////
            if (model.asset.Type == "2D")
            {
                Asset2D asset2D = new Asset2D(model.asset);
                _context.Assets2D.Add(asset2D);
            }
            else if (model.asset.Type == "3D")
            {
                Asset3D asset3D = new Asset3D(model.asset);
                _context.Assets3D.Add(asset3D);
            }
            else if (model.asset.Type == "Audio")
            {
                AssetAudio assetAudio = new AssetAudio(model.asset);
                _context.AssetsAudio.Add(assetAudio);
            }
            else if (model.asset.Type == "Tools")
            {
                AssetTools assetTools = new AssetTools(model.asset);
                _context.AssetsTools.Add(assetTools);
            }
            else
            {
                return(HttpNotFound());
            }

            try
            {
                _context.SaveChanges();
            }
            catch (DbEntityValidationException e)
            {
                foreach (var eve in e.EntityValidationErrors)
                {
                    Debug.WriteLine("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:",
                                    eve.Entry.Entity.GetType().Name, eve.Entry.State);
                    foreach (var ve in eve.ValidationErrors)
                    {
                        Debug.WriteLine("- Property: \"{0}\", Error: \"{1}\"",
                                        ve.PropertyName, ve.ErrorMessage);
                    }
                }
                Debug.WriteLine(model.asset.Type);
            }


            AllAssets allAssets = new AllAssets();

            allAssets.assets2D    = _context.Assets2D.ToList();
            allAssets.assets3D    = _context.Assets3D.ToList();
            allAssets.assetsAudio = _context.AssetsAudio.ToList();
            allAssets.assetsTools = _context.AssetsTools.ToList();

            return(RedirectToAction("Index", allAssets));
        }