Beispiel #1
0
        public File_t UploadImage(int userId, int albumId, string fileName, Stream s)
        {
            File_t file = null;

            using (MemoryStream ms = new MemoryStream())
            {
                s.CopyTo(ms);
                s.Position = 0;
                var fileId = SaveFileInAlbum(userId, albumId, fileName, ms.ToArray());
                if (fileId > 0)
                {
                    file = _fr.GetById(fileId);
                    file.InitialisePaths(_serverPath);
                    PictureHelper.SaveImageToDirectory(s, file);
                }
                s.Close();
            }
            return(file);
        }
Beispiel #2
0
        private void DisplaySeries(Series series)
        {
            this.series             = series;
            lbl_series_name.Text    = series.SeriesName;
            lbl_description.Text    = series.Description;
            pb_series_picture.Image = PictureHelper.BitmapFromByteArray(series.Picture);
            lbl_seasons.Text        = series.Seasons.Count.ToString();

            foreach (Genre genre in series.Genres)
            {
                Label label = new Label();
                label.Text        = genre.Description;
                label.BorderStyle = BorderStyle.FixedSingle;
                label.TextAlign   = ContentAlignment.MiddleCenter;
                fp_genres.Controls.Add(label);
            }

            FillRatingAffiliatedElements();
        }
        private void ZoomImage(object sender, EventArgs e)
        {
            object current = CurrentObject;

            if (PropertyValue != null)
            {
                Image image = PictureHelper.ImageFromByteArray((byte[])PropertyValue);
                //TODO hier das Main Image anzeigen
                if (image != null)
                {
                    if (zoomForm != null)
                    {
                        // Hide image
                        zoomForm.Close();
                        zoomForm = null;
                    }
                    else
                    {
                        zoomForm = new Form()
                        {
                            FormBorderStyle       = FormBorderStyle.Sizable,
                            ShowInTaskbar         = false,
                            TopMost               = true,
                            ShowIcon              = false,
                            MinimizeBox           = false,
                            Text                  = "Click anywhere on image to close",
                            BackgroundImage       = image,
                            BackgroundImageLayout = ImageLayout.Zoom,
                            BackColor             = Color.White,
                            // ClientSize = image.Size,
                            ClientSize = new Size(1024, 768),

                            StartPosition = FormStartPosition.CenterScreen
                        };
                        // zoomForm.AutoSize = true;
                        zoomForm.FormClosed += ZoomImage;
                        zoomForm.Click      += ZoomImage;
                        zoomForm.Show();
                    }
                }
            }
        }
Beispiel #4
0
        public ActionResult PrintInvoice(int orderID)
        {
            PrintInvoiceViewModel model = new PrintInvoiceViewModel();

            model.OrderID = orderID;

            model.Order = OrdersService.Instance.GetOrderByID(orderID);

            if (model.Order == null)
            {
                return(HttpNotFound());
            }

            model.PageTitle       = string.Format("Print Invoice Order : {0}", model.Order.ID);
            model.PageDescription = "Print invoice for your order.";
            model.PageURL         = Url.PrintInvoice(orderID).ToSiteURL();
            model.PageImageURL    = PictureHelper.PageImageURL("orders.jpg");

            return(PartialView("_PrintInvoice", model));
        }
Beispiel #5
0
        public static void TestQuantization()
        {
            var input  = PictureHelper.GenerateRandomChannel(32, 32);
            var output = Transformation.TransformArai(input);

            Console.WriteLine(output.ToString(32, 32));
            var result = Quantization.Quantisize(output, QTType.CHROMINANCE);

            var rowLength    = result.GetLength(0);
            var columnLength = result.GetLength(1);

            for (int i = 0; i < rowLength; i++)
            {
                for (int j = 0; j < columnLength; j++)
                {
                    Console.Write(result[i, j] + ", ");
                }
                Console.WriteLine();
            }
        }
Beispiel #6
0
        public SeriesElement(Series serie)
        {
            InitializeComponent();
            Series = serie;
            lbl_series_name.Text    = serie.SeriesName;
            pb_series_picture.Image = PictureHelper.BitmapFromByteArray(serie.Picture);
            if (serie.AverageRating.AverageRatingValue > 0)
            {
                lbl_points.Text = serie.AverageRating.AverageRatingValue.ToString();
            }
            else
            {
                lbl_points.Text = "";
            }

            lbl_series_name.Click   += new System.EventHandler(this.on_series_element_Click);
            pb_series_picture.Click += new System.EventHandler(this.on_series_element_Click);

            pnl_content.Left = (pnl_content.Parent.Width - pnl_content.Width) / 2;
            pnl_content.Top  = (pnl_content.Parent.Height - pnl_content.Height) / 2;
        }
        public static List <DouYinModel> GetTable(string source, string path)
        {
            List <DouYinModel> result = new List <DouYinModel>();

            try
            {
                HtmlDocument doc = new HtmlDocument();
                doc.LoadHtml(source);
                HtmlNode           rootNode     = doc.DocumentNode;
                HtmlNode           table        = rootNode.SelectSingleNode("//table[@class='table user-list']/tbody");
                HtmlNodeCollection trCollection = table.SelectNodes("./tr");
                if (trCollection == null)
                {
                    return(null);
                }
                foreach (var tr in trCollection)
                {
                    DouYinModel        model        = new DouYinModel();
                    HtmlNodeCollection tdCollection = tr.SelectNodes("./td");
                    string             headPicture  = tdCollection[1].SelectSingleNode("img").Attributes["src"].Value;
                    string             nickname     = tdCollection[2].SelectSingleNode("a").InnerText;
                    string             sex          = tdCollection[3].InnerText;
                    string             fans         = PictureHelper.SaveBase64ToImage(tdCollection[4].SelectSingleNode("img").Attributes["src"].Value, path, DateTimeHelper.GetMillisecondsSpan());
                    string             zans         = PictureHelper.SaveBase64ToImage(tdCollection[5].SelectSingleNode("img").Attributes["src"].Value, path, DateTimeHelper.GetMillisecondsSpan());
                    model.HeadPicture = headPicture;
                    model.NickName    = nickname;
                    model.Sex         = sex;
                    model.FanNum      = fans;
                    model.ZanNum      = zans;
                    result.Add(model);
                }
            }
            catch (Exception ex)
            {
            }
            finally
            {
            }
            return(result);
        }
Beispiel #8
0
        private void btnChangeWeb_Click(object sender, EventArgs e)
        {
            // Load the diary and search and replace the original file with the new one.
            var diaryXmlContents = File.ReadAllText(DiaryXmlPath);

            var(_, newFilename) = PictureHelper.GetImagePathParts(this.lblNewFilePath.Text);
            var year = BadImageItem.Year;

            // Copy file to _BestOf folder (if not already there)
            var bestOfDestination = Path.Combine(PictureHelper.BaseImagePath, year, "_BestOf", newFilename);

            File.Copy(this.lblNewFilePath.Text, bestOfDestination, true);
            Debug.WriteLine($"Copied '{this.lblNewFilePath.Text}' to '{bestOfDestination}'");

            // Now upload the image.
            var fileContent    = File.ReadAllBytes(this.lblNewFilePath.Text);
            var targetFilePath = $"images/years/{year}/{newFilename}";

            UploadMultipart(fileContent,
                            targetFilePath,
                            "image/jpeg",
                            UploadImageUrl);
            Debug.WriteLine($"Uploaded new image: {targetFilePath}");

            var newDiaryXmlContents = diaryXmlContents.Replace(BadImageItem.Filename, newFilename);

            File.WriteAllText(DiaryXmlPath, newDiaryXmlContents);
            Debug.WriteLine("Change diary.xml");

            if (BadImageItem.Filename != newFilename)
            {
                var deleteUrl = string.Format(DeleteImageUrl, year, BadImageItem.Filename);
                using (var webClient = new System.Net.WebClient())
                {
                    webClient.DownloadString(deleteUrl);
                }
                Debug.WriteLine($"Removed old file from web: {BadImageItem.Filename}");
            }
        }
Beispiel #9
0
        public bool Validate()
        {
            DirectoryInfo actionDir = new DirectoryInfo(GetPath());

            if (actionDir.Exists)
            {
                FileInfo thumbFile = new FileInfo(GetThumbPath());
                if (thumbFile.Exists)
                {
                    FileStream fs    = new FileStream(thumbFile.FullName, FileMode.Open);
                    Image      Thumb = Image.FromStream(fs);
                    Thumbnail = (Image) new Bitmap(Thumb);
                    fs.Close();
                }
                else
                {
                    Thumbnail = (Image)PictureHelper.CreateBitmapImage(TK_ActionLibrary.THUMBSIZE, TK_ActionLibrary.THUMBSIZE, "Image not found", Color.Gray, Color.White);
                }
            }

            return(Thumbnail != null);
        }
Beispiel #10
0
        /// <summary>
        /// 接受客户端视频数据,保存图片
        /// </summary>
        /// <param name="videoString">视频流字符(Base64格式)</param>
        /// <param name="videoThumb">视频缩略图(Base64格式)</param>
        /// <param name="recordtype">类型</param>
        /// <param name="recordid">编号(订单ID)</param>
        public int SaveRecordVideo(string videoString, string videoThumb, TableRecordType recordtype, int recordid)
        {
            int imgcount = 0;

            if (!string.IsNullOrEmpty(videoString))
            {
                string rootpath = ConfigHelper.GetConfigValueByKey("resource_physical_path");
                string savedir  = recordtype.ToString().ToLower();
                string datepath = DateTime.Now.ToString("yyyyMMdd");
                string path     = string.Format("{0}\\videos\\{1}\\{2}\\", rootpath, savedir, datepath);  //路径
                string savepath = string.Format("/videos/{0}/{1}/", savedir, datepath);                   //保存数据路径
                //判断目录是否存在,不存在则创建目录
                Utils.CreateDir(Utils.GetMapPath(path));

                imgcount++;
                var    videoBytes    = NH.Commons.PictureHelper.ConvertBase64ToByte(videoString);
                string videoFileName = string.Format("{0}_{1}.mp4", recordid, DateTime.Now.ToString("yyMMddHHmmssfff"));

                //保存视频文件
                var fs = new System.IO.FileStream(string.Concat(path, videoFileName), System.IO.FileMode.Create, System.IO.FileAccess.Write, System.IO.FileShare.None);
                fs.Write(videoBytes, 0, videoBytes.Length);
                fs.Close();

                //视频截图
                if (!string.IsNullOrEmpty(videoThumb))
                {
                    System.Drawing.Image image = null;
                    try
                    {
                        image = NH.Commons.PictureHelper.ConvertBase64ToImage(videoThumb);
                        string imageFilename = string.Concat(path, System.IO.Path.ChangeExtension(videoFileName, ".jpg"));
                        PictureHelper.SaveImage(image, imageFilename, 90L);
                    }
                    catch { }
                }
            }
            return(imgcount);
        }
        public JsonResult GetUserInfo()
        {
            try
            {
                var userId = User.Claims.FirstOrDefault(C => C.Type == ClaimTypes.NameIdentifier).Value;

                var user = _context.Users.Where(u => u.Id == int.Parse(userId))
                           .Include(u => u.Picture)
                           .Include(u => u.RatingStatus)
                           .FirstOrDefault();

                if (user != null)
                {
                    UserInfo uInfo = new UserInfo
                    {
                        Id               = user.Id,
                        FirstName        = user.FirstName,
                        LastName         = user.LastName,
                        Email            = user.Email,
                        PhoneNumber      = user.PhoneNumber,
                        RoleName         = user.Role != null ? user.Role.Name : "Guest",
                        AvailableFrom    = user.AvailableFrom,
                        AvailableTill    = user.AvailableTill,
                        BirthDate        = user.BirthDate,
                        RegisteredOn     = user.RegisteredOn,
                        RatingStatusName = user.RatingStatus != null ? user.RatingStatus.Name : null,
                        PhotoinBinary    = user.Picture != null?PictureHelper.ConvertToString(user.Picture.ImageData) : null
                    };

                    return(Json(uInfo));
                }
                return(Json("Error"));
            }
            catch (Exception ex)
            {
                return(Json("Error"));
            }
        }
        public HttpResponseMessage ChangePhoto(string photoInBinary)
        {
            try
            {
                if (photoInBinary == null)
                {
                    return(new HttpResponseMessage(HttpStatusCode.NotAcceptable));
                }

                byte[] ImageData = PictureHelper.ConvertToImage(photoInBinary);


                var userId = User.Claims.FirstOrDefault(C => C.Type == ClaimTypes.NameIdentifier).Value;

                var user = _context.Users.FirstOrDefault(u => u.Id == int.Parse(userId));

                if (user != null)
                {
                    user.Picture           = new Picture();
                    user.Picture.ImageData = ImageData;
                    _context.SaveChanges();

                    return(new HttpResponseMessage(HttpStatusCode.OK));
                }
                else
                {
                    return(new HttpResponseMessage(HttpStatusCode.NotAcceptable));
                }
            }
            catch (FormatException ex)
            {
                return(new HttpResponseMessage(HttpStatusCode.NotAcceptable));
            }
            catch (Exception ex)
            {
                return(new HttpResponseMessage(HttpStatusCode.BadRequest));
            }
        }
Beispiel #13
0
        private void LoadImage(Bitmap bitmap)
        {
            if (bitmap == null)
            {
                return;
            }
            PictureHelper.LoadImage(bitmap, out var grid);
            if (grid == null || grid.IsEqual(_grid))
            {
                return;
            }

            _grid = grid;
            if (cbRec.Checked)
            {
                bitmap.Save(_recordFolder + $"\\record_{_recordIndex}.png");
                _recordIndex++;
            }
            if (_grid.WeakSlot >= 0 && cbTitanColor.SelectedIndex >= 0)
            {
                foreach (var i in Enumerable.Range(1, 5))
                {
                    _grid._enemies[i] = (CellColor)cbTitanColor.SelectedItem;
                }
            }
            pbGameGrid.Image = GridDrawer.GetGridImage(grid);
            pbEnemies.Image  = new Bitmap(pbEnemies.Width, pbEnemies.Height);
            GridDrawer.GetGridEnemies(grid, pbEnemies.Image);
            var results = GridAnalyzer.GetPossibleSwaps(grid);

            results = results.OrderByDescending(r => r, new TitanSwapComparer()).ToList();
            clbSwaps.Items.Clear();
            clbSwaps.Items.AddRange(items: results.ToArray());
            if (results.Count > 0)
            {
                clbSwaps.SetSelected(0, true);
            }
        }
Beispiel #14
0
        private async void BtnListAll_Click(object sender, RoutedEventArgs e)
        {
            PictureHelper ph = new PictureHelper();

            try
            {
                if (LvAll.DataContext != null)
                {
                    return;
                }
                var pics = await ph.GetAllPictures(AdminInterface);

                Application.Current.Dispatcher.Invoke(new Action(() =>
                {
                    LvAll.DataContext = pics;
                }));
            }
            catch (Exception ex)
            {
                popup        = ConfigurePopup.Configure(popup, ex.Message, BtnListAll, PlacementMode.Bottom);
                popup.IsOpen = true;
            }
        }
Beispiel #15
0
 private void CarEditForm_Load(object sender, EventArgs e)
 {
     if (labEidt.Text == "编辑")
     {
         txtPlateNumber.Text   = car.PlateNumber;
         txtColor.Text         = car.Color;
         txtCarResource.Text   = car.CarResource;
         txtBrand.Text         = car.Brand;
         txtMotorcyleType.Text = car.MotorcyleType;
         using (MemoryStream memStream = new MemoryStream(PictureHelper.ExportImage(Convert.ToInt32(car.Id), "TB_Car", "CarPicture")))
         {
             if (memStream != null || memStream.Length > 0)
             {
                 this.picCar.Image     = Image.FromStream(memStream);
                 txtUploadFile.Visible = false;
                 btnUploadFile.Visible = false;
             }
         }
     }
     if (labEidt.Text == "新增")
     {
     }
 }
        public HttpResponseMessage EditUserPicture([FromBody] string imageData)
        {
            try
            {
                var userId = User.Claims.FirstOrDefault(C => C.Type == ClaimTypes.NameIdentifier).Value;

                var user = _context.Users.Where(u => u.Id == int.Parse(userId))
                           .Include(u => u.Picture)
                           .FirstOrDefault();

                if (user != null)
                {
                    byte[] ImageData = null;
                    if (imageData != null)
                    {
                        ImageData    = PictureHelper.ConvertToImage(imageData);
                        user.Picture = new Picture()
                        {
                            ImageData = ImageData
                        };

                        _context.SaveChanges();
                    }


                    return(new HttpResponseMessage(HttpStatusCode.OK));
                }
                else
                {
                    return(new HttpResponseMessage(HttpStatusCode.BadRequest));
                }
            }
            catch (Exception ex)
            {
                return(new HttpResponseMessage(HttpStatusCode.BadRequest));
            }
        }
Beispiel #17
0
        /// <summary>
        /// 批量上传图片
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnUploadFiles_Click(object sender, EventArgs e)
        {
            OpenFileDialog ofd = new OpenFileDialog();

            ofd.Multiselect = true;
            ofd.Filter      = "jpeg files(*.jpg)|*.jpg";
            if (ofd.ShowDialog() == DialogResult.OK)
            {
                string[] fileNames = ofd.FileNames;
                byte[]   tempByte  = new byte[] { };
                for (int i = 0; i < fileNames.Length; i++)
                {
                    string   filePath    = fileNames[i];
                    string[] temp        = (System.IO.Path.GetFileName(fileNames[i])).Split('.');//得到文件名
                    string   PlateNumber = temp[0];
                    //driverListBll.UpdateByIdNumber(IdNumber);
                    using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read))
                    {
                        tempByte = new byte[fs.Length];
                        fs.Read(tempByte, 0, tempByte.Length);
                        fs.Close();
                    }

                    try
                    {
                        PictureHelper.UpdateImageByPlateNumber(PlateNumber, tempByte);
                    }
                    catch (Exception)
                    {
                        throw;
                    }
                }
                MessageBox.Show("上传成功");
                //this.Pic.Image = Image.FromFile(txtPicture.Text);
            }
        }
Beispiel #18
0
        public ICollection <Album_t> GetAlbums(int?userId = null)
        {
            var listAlbumIdsInfNews = _nr.GetAll().Select(n => n.AlbumId).ToList();


            var result = new Collection <Album_t>();
            var albums = _ar.GetAll().Where(a => a.AlbumTypeId == 2).OrderByDescending(a => a.CreatedDate).ToList();

            foreach (var album in albums)
            {
                // skip album which is not of event
                if (userId == null && !listAlbumIdsInfNews.Contains(album.Id))
                {
                    continue;
                }
                else
                {
                    var queryNew = _nr.GetAll().Where(n => n.AlbumId == album.Id);
                    if (queryNew.Any())
                    {
                        var o = queryNew.First();
                        album.Name = o.Title;
                    }
                }


                var itemResult = new Album_t()
                {
                    Id          = album.Id,
                    CreatedDate = album.CreatedDate,

                    Name = album.Name
                };

                var query = (from f in _entities.File_t
                             where f.Album_Id.Value == album.Id && f.IsOnTopAlbum
                             select new
                {
                    Album_Id = f.Album_Id,
                    CreatedDate = f.CreatedDate,
                    IsOnTopAlbum = f.IsOnTopAlbum,
                    Id = f.Id,
                    Sort = f.Sort,
                    FileName = f.FileName,
                    Title = f.Title,
                    Description = f.Description
                })
                            .ToList()
                            .Select(f => new File_t()
                {
                    Album_Id     = f.Album_Id,
                    CreatedDate  = f.CreatedDate,
                    IsOnTopAlbum = f.IsOnTopAlbum,
                    Id           = f.Id,
                    Sort         = f.Sort,
                    FileName     = f.FileName,
                    Title        = f.Title,
                    Description  = f.Description
                }).ToList();



                if (query.Any())
                {
                    itemResult.File_t = new Collection <File_t>()
                    {
                        query.First()
                    };
                }
                else
                {
                    itemResult.File_t = new Collection <File_t>();
                }

                result.Add(itemResult);
            }
            // save to disk
            foreach (var item in result)
            {
                if (item.File_t.Any())
                {
                    var file = item.File_t.FirstOrDefault();
                    file.InitialisePaths(_serverPath);
                    if (!PictureHelper.CheckFiles(file))
                    {
                        PictureHelper.SaveImageToDirectory(_fr.GetById(file.Id).Image, file);
                    }
                }
            }
            return(result);
        }
        public async Task <JsonResult> CommentExtraBook(BookModel m_extraBook)
        {
            BookModel book    = m_extraBook;
            string    comment = book.LastComment;

            int score = 5, m_bookId = book.Id;


            #region AddBookExtra
            bool result = false;
            if (!string.IsNullOrEmpty(book.Photo))
            {
                var photo = PictureHelper.UploadPicture("FileUpload", book.Photo, configuration, environment);
                book.Photo   = photo.Item2;
                book.PhotoHD = photo.Item1;
            }

            var memberId = GetCurrentUserClaim("Id");

            if (book.Id > 0)
            {
                string sql    = $@"SELECT * FROM book where book.Id=
                        ( select    book_id FROM book_comment
                        where   book_comment.member_id= {memberId}
                          AND   book_comment.book_id={book.Id}
                        )";
                var    m_book = database.Single <BookModel>(sql);
                if (m_book == null || m_book.State != AppLtmConsts.BookType_CommentExtra)
                {
                    return(Json(new { success = result, message = "您无权删除该书评" }));
                }



                System.Text.StringBuilder m_sql = new System.Text.StringBuilder($"UPDATE book SET Name = '{book.Name}', Author = '{book.Author}', last_comment = '{book.LastComment}' ");
                if (!string.IsNullOrEmpty(book.Photo))
                {
                    m_sql.Append($", Photo = '{book.Photo}', PhotoHD = '{book.PhotoHD}'");
                }
                m_sql.Append($" WHERE Id = {book.Id}");
                result = database.ExecuteSQL(m_sql.ToString());
            }
            else
            {
                book.CreateTime = DateTime.Now;
                book.State      = AppLtmConsts.BookType_CommentExtra;

                var m_bookById = await database.CreateAsync <BookModel>(book);

                result = m_bookById > 0;

                if (!result)
                {
                    return(Json(new { success = result, message = "操作失败" }));
                }

                #region AddCommnet
                //    score=(m_extraBook.score==0)?5: m_extraBook.score;
                //string comment= String.IsNullOrWhiteSpace(m_extraBook.comment)?
                //    "默认好评": m_extraBook.comment;

                if (comment.Length < 1 || score < 1)
                {
                    return(Json(new { result = false, msg = "一点评价都没有,你确定读过了?" }));
                }
                string submitComment = $@"INSERT INTO book_comment SET book_id={m_bookId},member_id={memberId},
                                                               comment='{comment}',score={score}";
                result = database.ExecuteSQL(submitComment);

                #endregion
            }


            if (!result)
            {
                return(Json(new { success = result, message = "操作失败" }));
            }

            #endregion



            #region resultOf Comment-score


            string         scoreSql   = $@"SELECT score FROM book_comment WHERE book_id={m_bookId}";
            List <dynamic> scores     = database.QueryListSQL <dynamic>(scoreSql).ToList();
            int            totalScore = 0;

            foreach (var itemscore in scores)
            {
                totalScore += itemscore.score;
            }
            score = (totalScore + score) / (scores.Count + 1);
            string bookSql = $@"UPDATE book SET last_comment='{comment}',average_score={score},
                                                state={AppLtmConsts.BookType_CommentExtra},MemberId=0 WHERE Id={m_bookId}";
            result = database.ExecuteSQL(bookSql);

            #endregion

            //calculate

            return(Json(new { Result = result }));
        }
        public HttpResponseMessage AddBook([FromBody] BookModel incomingBook)
        {
            try
            {
                var userId = User.Claims.FirstOrDefault(C => C.Type == ClaimTypes.NameIdentifier).Value;

                var user = _context.Users.FirstOrDefault(u => u.Id == int.Parse(userId));

                if (user != null)
                {
                    byte[] ImageData = null;
                    if (incomingBook.photoInBinary != null)
                    {
                        ImageData = PictureHelper.ConvertToImage(incomingBook.photoInBinary);
                    }

                    Book book = new Book
                    {
                        CurrentUserId = user.Id,
                        ContributorId = user.Id,
                        Title         = incomingBook.name,
                        Author        = incomingBook.author,
                        Price         = Convert.ToDecimal(incomingBook.price),
                        Picture       = ImageData != null ? new Data.Models.Picture()
                        {
                            ImageData = ImageData,
                            Name      = incomingBook.photo
                        } : null,
                        BookTypeId = 1,                     //incomingBook.type,
                        GenreId    = 1,                     //incomingBook.genre
                        IsUsable   = true,
                        CreatedOn  = DateTime.UtcNow
                    };

                    _context.Books.Add(book);
                    _context.SaveChanges();

                    BookHistory bookHistory = new BookHistory
                    {
                        BookId              = book.Id,
                        GetBookOn           = DateTime.UtcNow,
                        UserId              = user.Id,
                        AltitudeCoordinate  = incomingBook.AltitudeCoordinate,
                        LongtiudeCoordinate = incomingBook.LongitudeCoordinate
                    };

                    _context.BookHistoryRecords.Add(bookHistory);
                    _context.SaveChanges();

                    return(new HttpResponseMessage(HttpStatusCode.Created));
                }
                else
                {
                    return(new HttpResponseMessage(HttpStatusCode.Unauthorized));
                }
            }
            catch (Exception e)
            {
                return(new HttpResponseMessage(HttpStatusCode.BadRequest));
            }
        }
Beispiel #21
0
 private void btnSave_Click(object sender, EventArgs e)
 {
     try
     {
         if (labType.Text == "编辑")
         {
             driverlist.User_ChineseName       = txtUserChineseName.Text;
             driverlist.User_EnglishName       = txtUserEnglisthName.Text;
             driverlist.Department_ChineseName = txtChineseDepartment.Text;
             driverlist.Department_EnglishName = txEnglishDepartmentName.Text;
             driverlist.Job                   = txtJob.Text;
             driverlist.Sex                   = txtSex.Text;
             driverlist.Birthdy               = txtBirthdy.Text;
             driverlist.Identification_Type   = txtIdType.Text;
             driverlist.Identification_Number = txtIdNumber.Text;
             driverlist.Employer              = txtDepartment.Text;
             driverlist.Telephone             = txtTelephone.Text;
             driverlist.CurrentResidence      = txtCurrentResident.Text;
             driverlist.CensusRegister        = txtHuji.Text;
             try
             {
                 driverBll.UpdateDriver(driverlist);
             }
             catch (Exception ex)
             {
                 MessageBox.Show(ex.Message);
             }
             if (txtPicture.Text != "" || !string.IsNullOrEmpty(txtPicture.Text))
             {
                 try
                 {
                     byte[] temp = new  byte[] {};
                     //driverBll.UpdateByIdNumber(driverlist.Identification_Number);
                     using (FileStream fs = new FileStream(txtPicture.Text, FileMode.Open, FileAccess.Read))
                     {
                         temp = new byte[fs.Length];
                         fs.Read(temp, 0, temp.Length);
                         fs.Close();
                     }
                     PictureHelper.UpdateById(driverlist.Id, temp);
                 }
                 catch (Exception ex)
                 {
                     MessageBox.Show("上传图片错误" + ex.Message);
                 }
             }
             MessageBox.Show("修改成功");
         }
         if (labType.Text == "新增")
         {
             driverlist.User_ChineseName       = txtUserChineseName.Text;
             driverlist.User_EnglishName       = txtUserEnglisthName.Text;
             driverlist.Department_ChineseName = txtChineseDepartment.Text;
             driverlist.Department_EnglishName = txEnglishDepartmentName.Text;
             driverlist.Job                   = txtJob.Text;
             driverlist.Sex                   = txtSex.Text;
             driverlist.Birthdy               = txtBirthdy.Text;
             driverlist.Identification_Type   = txtIdType.Text;
             driverlist.Identification_Number = txtIdNumber.Text;
             driverlist.Employer              = txtDepartment.Text;
             driverlist.Telephone             = txtTelephone.Text;
             driverlist.CurrentResidence      = txtCurrentResident.Text;
             driverlist.CensusRegister        = txtHuji.Text;
             FileStream fs = new FileStream(txtPicture.Text, FileMode.Open, FileAccess.Read);
             driverlist.Photo = new byte[fs.Length];
             fs.Read(driverlist.Photo, 0, driverlist.Photo.Length);
             fs.Close();
             PictureHelper.MemoryImage(driverlist);
             MessageBox.Show("新增成功!");
         }
     }
     catch (Exception ex)
     {
         MessageBox.Show(ex.Message);
     }
 }
Beispiel #22
0
        /// <summary>
        /// 保存文件
        /// </summary>
        /// <param name="files"></param>
        /// <param name="linkid"></param>
        /// <param name="filetype"></param>
        /// <param name="currentUserId"></param>
        /// <param name="width">200</param>
        /// <param name="height">200</param>
        /// <param name="iscut"></param>
        /// <returns></returns>
        public List <BaseFile> SaveBaseFiles(HttpFileCollectionBase files, string linkid, string filetype, string currentUserId)
        {
            List <BaseFile> bf  = new List <BaseFile>();
            Regex           reg = new Regex(@"[^.]+$");

            for (int i = 0; i < files.Count; i++)
            {
                var f       = files[i];
                var name    = f.FileName;
                var newname = DataHelper.GetSystemID();

                if (f.ContentLength > 3 * 1024 * 1024)
                {
                    throw new Exception("上传文件大小超过了3M");
                }

                if (filetype == "image")
                {
                    Regex r = new Regex(@"\.(jpg|jpeg|gif|png)$");
                    if (r.IsMatch(name) == false)
                    {
                        throw new Exception("上传文件格式不正确:" + name);
                    }
                }


                string dir = "/files/" + DateTime.Now.ToString("yyyy-MM") + "/" + DateTime.Now.ToString("dd");

                if (Directory.Exists(HttpContext.Current.Server.MapPath(dir)) == false)
                {
                    Directory.CreateDirectory(HttpContext.Current.Server.MapPath(dir));
                }

                string u = dir + "/" + newname;
                if (reg.IsMatch(name))
                {
                    u += "." + reg.Match(name).ToString();
                }

                f.SaveAs(HttpContext.Current.Server.MapPath(u));
                if (filetype == "image")
                {
                    PictureHelper.MakeThumbnail(HttpContext.Current.Server.MapPath(u), HttpContext.Current.Server.MapPath(u + "_middle.jpg"), 200, 200, "Cut");
                    //PictureHelper.ResetPicture(f, width, height, iscut == 0 ? "cut" : "maxsize", HttpContext.Current.Server.MapPath(u + "_thumb.jpg"));
                }

                BaseFile temp = new BaseFile();
                temp.Id         = newname;
                temp.Length     = f.ContentLength;
                temp.IsDeleted  = 0;
                temp.LinkId     = linkid;
                temp.CreatedBy  = currentUserId;
                temp.CreatedOn  = DateTime.Now;
                temp.ModifiedBy = currentUserId;
                temp.ModifiedOn = DateTime.Now;
                temp.NewName    = newname;
                temp.OldName    = name;
                if (reg.IsMatch(name))
                {
                    temp.SuffixName = reg.Match(name).ToString();
                }
                temp.Url = u;
                _context.BaseFiles.Add(temp);
                _context.SaveChanges();
                bf.Add(temp);
            }

            return(bf);
        }
Beispiel #23
0
 public void MakeRandom()
 {
     ChannelY  = PictureHelper.GenerateRandomChannel(Width, Height);
     ChannelCb = PictureHelper.GenerateRandomChannel(Width, Height);
     ChannelCr = PictureHelper.GenerateRandomChannel(Width, Height);
 }
Beispiel #24
0
 public async void PictureClick(object sender, WeiboPictureClickEventArgs e)
 {
     var items = e.DataContext.PicUrls.Select(item => new ImageModel(item.OriginalPic == null ? PictureHelper.ThumbnailToOriginal(item.ThumbnailPic) : item.OriginalPic)).ToList();
     var dialog = new ImageViewDialog(items, e.DataContext.PicUrls.FindIndex((item=>item.ThumbnailPic == e.ClickedPicture.ThumbnailPic)));
     await dialog.ShowAsync();
 }
Beispiel #25
0
 public Bitmap GetBitmap()
 {
     return(PictureHelper.GetPictureHelper(m_key).Bitmap);
 }
Beispiel #26
0
        /// <summary>
        //  导出至Excel.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ExportToExceltoolStripMenuItem_Click(object sender, EventArgs e)
        {
            DataGridViewRowCollection drRows = this.dgv.Rows;

            if (drRows.Count == 0)
            {
                return;
            }


            //1. 先确定 image path
            if (CmdHelper.ifExistsTheProcessByName("excel") || CmdHelper.ifExistsTheProcessByName("et"))
            {
                Tools.FrmPrompt frmPrompt = new Tools.FrmPrompt("excel.exe|et.exe");
                frmPrompt.ShowDialog();
            }
            //2. 打开Excel
            //先获取时间字符串
            string currTimeStr  = TimeHelper.getCurrentTimeStr();
            string xlsFileName  = "成衣成本汇总_" + currTimeStr + ".xls";
            string srcFilePath  = Application.StartupPath + "\\成本汇总\\ProductsCostSummaryTemplate.xls";
            string destDir      = Application.StartupPath + "\\成本汇总\\";
            string destFileName = xlsFileName;

            CmdHelper.copyFileToDestDirWithNewFileName(srcFilePath, destDir, destFileName);
            //目的文件名为:
            destFilePath = destDir + xlsFileName;
            MyExcel myExcel = new MyExcel(destFilePath);

            myExcel.open(true);
            Usual_Excel_Helper uEHelper = new Usual_Excel_Helper(myExcel.getFirstWorkSheetAfterOpen());

            for (int index = 0; index <= drRows.Count - 1; index++)
            {
                DataGridViewRow currRow = drRows[index];

                string product_name = currRow.Cells["Product_Name"].Value.ToString();
                uEHelper.setSpecificCellValue("A" + (2 + index).ToString(), product_name);
                //(drRow.Cells["product_name"]
                uEHelper.setSpecificCellValue("B" + (2 + index).ToString(), currRow.Cells["total_man_hours"].Value.ToString());
                uEHelper.setSpecificCellValue("C" + (2 + index).ToString(), currRow.Cells["total_labour_cost"].Value.ToString());
                uEHelper.setSpecificCellValue("D" + (2 + index).ToString(), currRow.Cells["supplier"].Value.ToString());
                uEHelper.setSpecificCellValue("E" + (2 + index).ToString(), currRow.Cells["latest_update_time"].Value.ToString());
                //picture
                //保存此图片
                //Image image = ((Image)(currRow.Cells["picture"].Value));
                byte[] pictureByteArray = (byte[])currRow.Cells["picture"].Value;
                Image  image            = PictureHelper.ReturnPhoto(pictureByteArray);

                string picPath = string.Format(@"{0}\{1}.jpg", destDir, product_name);
                image.Save(picPath, image.RawFormat);

                Microsoft.Office.Interop.Excel.Range range = uEHelper.getRange("F" + (2 + index).ToString(), "F" + (2 + index).ToString());
                uEHelper.pastePicture(range, picPath);
            }
            myExcel.saveWithoutAutoFit();
            myExcel.close();

            ShowResult.show(lblResult, string.Format(@"导出完毕,存于:{0}", destFilePath), true);
            timerRestoreLabel.Start();
        }
Beispiel #27
0
 public BitmapImage GetBitmapImage()
 {
     return(PictureHelper.GetPictureHelper(m_key).BitmapImage);
 }
Beispiel #28
0
        public Album_t GetAlbumById(int id, bool checkAllFiles = true)
        {
            var queryAlbum = _ar.GetById(id);


            var listFiles = (from f in _entities.File_t
                             where f.Album_Id == id
                             select new
            {
                Album_Id = f.Album_Id,
                CreatedDate = f.CreatedDate,
                IsOnTopAlbum = f.IsOnTopAlbum,
                Id = f.Id,
                Sort = f.Sort,
                FileName = f.FileName,
                Title = f.Title,
                Description = f.Description
            }).ToList();


            //Where cust.Orders.Count > 0 And
            //      cust.CompanyName.StartsWith("H")
            //Select cust.CustomerID, cust.CompanyName,
            //       OrderCount = cust.Orders.Count,
            //       cust.Country



            var album = new Album_t()
            {
                Id = id
            };
            var list = listFiles.Select(f => new File_t()
            {
                Album_Id     = f.Album_Id,
                CreatedDate  = f.CreatedDate,
                IsOnTopAlbum = f.IsOnTopAlbum,
                Id           = f.Id,
                Sort         = f.Sort,
                FileName     = f.FileName,
                Title        = f.Title,
                Description  = f.Description
            }).ToList();

            if (queryAlbum != null)
            {
                var o = _nr.GetAll().Where(n => n.AlbumId == queryAlbum.Id);

                album.Id          = queryAlbum.Id;
                album.CreatedDate = queryAlbum.CreatedDate;
                album.File_t      = list;
                album.Name        = o.Any() ? o.First().Title : "";
                album.AlbumTypeId = queryAlbum.AlbumTypeId;
            }


            List <File_t> tmplist = null;

            if (checkAllFiles)
            {
                tmplist = album.File_t.OrderBy(f => f.Sort).ToList();
            }
            else
            {
                tmplist = album.File_t.Where(f => f.IsOnTopAlbum).ToList();
            }
            foreach (var item in tmplist)
            {
                item.InitialisePaths(_serverPath);
                if (!PictureHelper.CheckFiles(item))
                {
                    PictureHelper.SaveImageToDirectory(_fr.GetById(item.Id).Image, item);
                }
            }
            return(album);
        }
        public List <WhishListItem> GetRecentVenues(string code)
        {
            List <WhishListItem> recentVenues = new List <WhishListItem>();
            List <WhishListItem> whishlist    = new List <WhishListItem>();
            var whishlistCount = 0;

            if (clientWithToken == null)
            {
                clientWithToken = GetClient(code);
            }

            //get venues already added
            using (var db = new WhishListContext())
            {
                whishlist      = db.WhishList.ToList();
                whishlistCount = db.WhishList.Count();
            }

            //get recent checkins
            string limit  = (int.Parse(ConfigurationManager.AppSettings["limitOfRecentVenues"]) + whishlistCount).ToString();
            var    recent = clientWithToken.GetRecentCheckin(new Dictionary <string, string>
            {
                { "limit", limit }
            });

            foreach (var item in recent)
            {
                //remove those that already are in the whishlist
                if (!whishlist.Any(x => x.VenueId == item.venue.id))
                {
                    var venuePicListAux = clientWithToken.GetVenuePhotos(item.venue.id, null);
                    var pic             = venuePicListAux.Count > 0 ? venuePicListAux.ElementAt(0) : null;
                    var usrPicAux       = PictureHelper.GetUserPictureUrl(item.user);

                    recentVenues.Add(new WhishListItem
                    {
                        UserId           = item.user.id,
                        VenueId          = item.venue.id,
                        VenuePictureUrl  = pic == null ? ConfigurationManager.AppSettings["noImagePath"] : PictureHelper.GetVenuePictureUrl(pic),
                        UserPictureUrl   = usrPicAux,
                        VenueName        = item.venue.name,
                        WhishListItemId  = 0,
                        VenueStreet      = item.venue.location.crossStreet + " - " + item.venue.location.city,
                        VenueDescription = item.venue.description,
                        VenueEmail       = item.venue.contact.email
                    });
                }
            }
            return(recentVenues);
        }
        public ActionResult Search(string category, string q, decimal?from, decimal?to, string sortby, int?pageNo, int?pageSize, bool isPartial = false)
        {
            pageSize = pageSize ?? ConfigurationsHelper.FrontendRecordsSizePerPage;

            ProductsViewModel model = new ProductsViewModel();

            model.Categories = CategoriesService.Instance.GetAllCategories();

            HttpCookie LangCookie = Request.Cookies["LangCookie"];

            if (!string.IsNullOrEmpty(category))
            {
                var selectedCategory = CategoriesService.Instance.GetCategoryByName(category);

                if (selectedCategory == null)
                {
                    return(HttpNotFound());
                }
                else
                {
                    model.CategoryID   = selectedCategory.ID;
                    model.CategoryName = selectedCategory.SanitizedName;

                    model.SearchedCategories = Methods.GetAllCategoryChildrens(selectedCategory, model.Categories);

                    model.PageTitle       = string.Format("{0} Products", selectedCategory.Name);
                    model.PageDescription = selectedCategory.Description;

                    model.PageURL = Url.SearchProducts(selectedCategory.SanitizedName, q).ToSiteURL();
                }
            }
            else
            {
                model.PageTitle       = "Search Products";
                model.PageDescription = "Search Latest Products on Jomlah Jo";

                model.PageURL = Url.SearchProducts().ToSiteURL();
            }

            model.PageImageURL = PictureHelper.PageImageURL("products.jpg");

            model.SearchTerm = q;
            model.PriceFrom  = from;
            model.PriceTo    = to;
            model.SortBy     = sortby;
            model.PageSize   = pageSize;
            model.isPartial  = isPartial;

            var selectedCategoryIDs = model.SearchedCategories != null?model.SearchedCategories.Select(x => x.ID).ToList() : null;

            model.Products = ProductsService.Instance.SearchProducts(selectedCategoryIDs, model.SearchTerm, model.PriceFrom, model.PriceTo, model.SortBy, pageNo, pageSize.Value);
            if (LangCookie != null)
            {
                if (LangCookie.Value == "ar")
                {
                    foreach (var elem in model.Products.ToList())
                    {
                        elem.Name        = elem.ArName;
                        elem.Description = elem.ArDescription;
                        elem.Summary     = elem.ArSummary;
                        //    elem.Category.Name = elem.Category.ArName;
                    }
                }
            }
            var totalProducts = ProductsService.Instance.GetProductCount(selectedCategoryIDs, q, model.PriceFrom, model.PriceTo);

            model.Pager = new Pager(totalProducts, pageNo, pageSize.Value);

            if (model.isPartial)
            {
                return(PartialView(model));
            }
            else
            {
                return(View(model));
            }
        }