public void LoadPictures() { IInputProvider iprov = Provider.Instance as IInputProvider; PictureList pl = iprov.GetPictures(new PictureSearch() { SearchProvider = Provider, MaxPictureCount = 10, BannedURLs = Settings.CurrentSettings.BannedImages, PreviewOnly = true }); foreach (Picture p in pl.Pictures) { PictureBox pb = new PictureBox(); Image i = p.GetThumbnail(); if (i == null) { continue; } pb.Image = i; pb.Width = i.Width; pb.Height = i.Height; flowLayoutPanel1.Controls.Add(pb); } }
private void Form1_Load(object sender, EventArgs e) { WallbaseImageSearchSettings wiss = new WallbaseImageSearchSettings(); wiss.SA = "toplist"; PictureSearch ps = new PictureSearch(); ps.SearchProvider = new ActiveProviderInfo("Wallbase") { Active = true, ProviderConfig = wiss.Save() }; ps.MaxPictureCount = 100; string path = System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "TEMP"); Directory.CreateDirectory(path); ps.SaveFolder = path; IInputProvider p = ps.SearchProvider.Instance as IInputProvider; pl = p.GetPictures(ps); Timer t = new Timer(); t.Tick += t_Tick; t.Interval = 5000; t.Enabled = true; }
public Pulse.Base.PictureList GetPictures(Pulse.Base.PictureSearch ps) { PictureList pl = new PictureList() { FetchDate = DateTime.Now }; //general purpose downloader WebClient wc = new WebClient(); //download pictures page var content = wc.DownloadString(_baseURL + "/wallpaper/download"); //get paths to the xml files var xmlPaths = ParseXMLPaths(content); //download and parse each xml file foreach (string xmlFile in xmlPaths) { try { var pics = ParsePictures(xmlFile); //clear out banned images pics = (from c in pics where !ps.BannedURLs.Contains(c.Url) select c).ToList(); pl.Pictures.AddRange(pics); } catch(Exception ex) { Log.Logger.Write(string.Format("Error loading/parsing National Geographic pictures from XML. XML file URL: '{0}'. Exception details: {1}", _baseURL + xmlFile, ex.ToString()), Log.LoggerLevels.Errors); } if (pl.Pictures.Count >= (ps.MaxPictureCount > 0 ? ps.MaxPictureCount : int.MaxValue)) break; } return pl; }
public PictureList GetPictures(PictureSearch ps) { PictureList pl = new PictureList() { FetchDate = DateTime.Now }; LocalDirectorySettings lds = string.IsNullOrEmpty(ps.SearchProvider.ProviderConfig) ? new LocalDirectorySettings() : LocalDirectorySettings.LoadFromXML(ps.SearchProvider.ProviderConfig); //get all files in directory and filter for image extensions (jpg/jpeg/png/bmp?) List<string> files = new List<string>(); foreach (string ext in lds.Extensions.Split(new char[] { ';' })) { files.AddRange(Directory.GetFiles(lds.Directory, "*." + ext, lds.IncludeSubdirectories?SearchOption.AllDirectories:SearchOption.TopDirectoryOnly)); } //distinct list (just in case) files = files.Distinct().ToList(); var maxPictureCount = ps.MaxPictureCount > 0 ? ps.MaxPictureCount : int.MaxValue; maxPictureCount = Math.Min(files.Count, maxPictureCount); //create picture items pl.Pictures.AddRange((from c in files select new Picture() { Id = Path.GetFileNameWithoutExtension(c), Url=c, LocalPath = c }) .OrderBy(x=>Guid.NewGuid()) .Take(maxPictureCount)); return pl; }
public PictureList SelectAll() { lpic = new PictureList(); cmd.CommandText = "SELECT * From Picture"; lpic = new PictureList(base.Select()); return(lpic); }
/// <summary> /// Update pictures. /// </summary> /// <param name="userContext"> /// Information about the user that makes this method call. /// </param> /// <param name="updatePictures">List of pictures to update.</param> /// <param name="updatedBy">User who last updated the picture.</param> /// <returns>Number of updated records.</returns> public virtual Int32 UpdatePictures(IUserContext userContext, PictureList updatePictures, String updatedBy) { return(DataSource.UpdatePictures(userContext, updatePictures, updatedBy)); }
private async Task OnChoosePicture() { try { var cameraStatus = await CrossPermissions.Current.CheckPermissionStatusAsync(Permission.Camera); var storageStatus = await CrossPermissions.Current.CheckPermissionStatusAsync(Permission.Storage); if (cameraStatus != PermissionStatus.Granted || storageStatus != PermissionStatus.Granted) { var statuses = await CrossPermissions.Current.RequestPermissionsAsync(new Permission[] { Permission.Camera, Permission.Storage }); } var b = await CrossMedia.Current.Initialize(); string cameraStr = Translate.Get(nameof(AppResources.Camera)); string galleryStr = Translate.Get(nameof(AppResources.Gallery)); string cancelStr = Translate.Get(nameof(AppResources.Cancel)); var sourceChoice = await AlertService.Instance.DisplayActionSheet( Translate.Get(nameof(AppResources.SelectSource)), cancelStr, null, new[] { cameraStr, galleryStr }); if (sourceChoice == cancelStr) { return; } var mediaFile = (sourceChoice == cameraStr) ? await TakePhoto() : await PickFromGallery(); if (mediaFile == null) { return; } IsBusy = true; var image = new SignatureImage { Base64Content = GetBase64Data(mediaFile), FileName = Path.GetFileName(mediaFile.Path) }; PictureList.Add(image); RaisePropertyChanged(nameof(PictureList)); } catch (Exception ex) { await Alert.DisplayError(ex); } finally { IsBusy = false; } }
/// <summary> /// Constructor /// </summary> public Creatures() { AquaLogCode = string.Empty; DataSource = EnumDataSource.Unknown; Pictures = new PictureList(); CreatureType = CreatureTypes.Unknwon; OtherLiterature = new Lists.BookList(); ReferenceBooks = new Lists.BookList(); }
public void InitPictures() { var rawPicList = BlocksList.FindAll(b => b.BlockHeader.Type == FlacTagBlockHeader.BlockType.PICTURE); foreach (var rawPictureBlock in rawPicList) { PictureList.Add(new FlacTagPicture(rawPictureBlock.ToBytes())); } }
private void OpenFileDialog_Click(object sender, RoutedEventArgs e) { string openArgs = "*#" + @"H:\Mikro-Makro\MeineSammlungen\Eingang"; this.Cursor = System.Windows.Input.Cursors.Wait; PictureList selPicture = new PictureList(openArgs); //lbItem.ItemsSource = selPicture; lbImg.ItemsSource = selPicture; this.Cursor = System.Windows.Input.Cursors.Arrow; }
/// <summary> /// Load the Picture Index /// </summary> private void LoadPictureIndex() { // toolStripStatusLabelInfo.Text = "Loading pictures"; // show the "please wait dialog" and get the results from it FormWaitLoading fwl = new FormWaitLoading(_CurrentDirectory); fwl.ShowDialog(); _PictureList = fwl.Pictures; _PictureList.Saved += new PictureList.OnSaved(_PictureList_Saved); FillListBoxFiles(); }
public static Picture SelectByID(int id) { if (lpic == null) { PictureDB db = new PictureDB(); lpic = db.SelectAll(); } Picture pic = lpic.Find(c => c.ID == id); return(pic); }
public void RemovePicture(ImageSource pic) { int removeInt = PictureListConverted.IndexOf(pic); database.Delete(PictureList[removeInt]); database.Update(PictureList[removeInt]); ClientPictures picRemoved = PictureList[removeInt]; PictureList.RemoveAt(removeInt); PictureListConverted.Remove(pic); RefreshList(); }
private PictureList FetchPictures(List <Picture> wallResults, bool previewOnly) { var result = new PictureList() { FetchDate = DateTime.Now }; try { System.Threading.Tasks.TaskFactory tf = new System.Threading.Tasks.TaskFactory(); wallResults .AsParallel() .WithDegreeOfParallelism(10) .ForAll(delegate(Picture p){ try { //save original URL as referrer p.Properties.Add(Picture.StandardProperties.Referrer, p.Url); p.Properties.Add(Picture.StandardProperties.BanImageKey, Path.GetFileName(p.Url)); p.Properties.Add(Picture.StandardProperties.ProviderLabel, "Wallhaven"); //get actual image URL if this is not a preview if (!previewOnly) { p.Url = GetDirectPictureUrl(p.Url); } p.Id = System.IO.Path.GetFileNameWithoutExtension(p.Url); if (!string.IsNullOrEmpty(p.Url) && !string.IsNullOrEmpty(p.Id)) { result.Pictures.Add(p); } } catch (Exception ex) { Log.Logger.Write(string.Format("Error downloading picture object from '{0}'. Exception details: {0}", ex.ToString()), Log.LoggerLevels.Errors); } finally { } }); } catch (Exception ex) { Log.Logger.Write(string.Format("Error during multi-threaded wallbase.cc image get. Exception details: {0}", ex.ToString()), Log.LoggerLevels.Errors); } finally { } return(result); }
public void GetPicturesByIds_Get100x100Thumbnail() { List <Int64> pictureIds = new List <Int64> { 2, 5, 6, 7, 8, 9, 10, 11 }; PictureList pictures = GetPictureDataSource(true).GetPictures(GetUserContext(), pictureIds, 100, 100, 0, true, string.Empty); Assert.IsNotNull(pictures); Assert.AreEqual(pictureIds.Count, pictures.Count); foreach (IPicture picture in pictures) { Assert.IsNotNull(picture.Image); Assert.IsTrue(picture.Size < picture.OriginalSize); } }
public void GetPicturesByIds_Resized640x480() { List <Int64> pictureIds = new List <Int64> { 2, 5, 6, 7, 8, 9, 10, 11 }; PictureList pictures = GetPictureManager(true).GetPictures(GetUserContext(), pictureIds, 480, 640, 0, true, string.Empty); Assert.IsNotNull(pictures); Assert.AreEqual(pictureIds.Count, pictures.Count); foreach (IPicture picture in pictures) { Assert.IsNotNull(picture.Image); Assert.IsTrue(picture.Size != picture.OriginalSize); } }
public ActionResult List(DateTime bDate, DateTime eDate, string SearchType = "", int codeID = 0, string code = "", int codeID2 = 0) { IEnumerable <picture> PictureList; IEnumerable <picture> GroupPictureList; IEnumerable <picture> RecentPictureList; ViewBag.HasGroupPictures = false; ViewBag.GroupPictures = false; ViewBag.HasRecentPictures = false; if (SearchType == "MinistrySearch") { PictureList = PictureRepository.GetPictureByMinistry(codeID); GroupPictureList = PictureRepository.GetMinistryPictureGroup(codeID); ViewBag.MinistryID = codeID; if (GroupPictureList.Count() > 0) { ViewBag.HasGroupPictures = true; ViewBag.GroupPictures = true; ViewBag.GroupPictureList = GroupPictureList; foreach (picture p in GroupPictureList) { p.GroupDescription = StoryRepository.GetStoryByID((int)p.GroupID).Header; } } RecentPictureList = PictureRepository.GetMinistryRecentPictures(codeID); if (RecentPictureList.Count() > 0) { ViewBag.HasRecentPictures = true; } } else if (SearchType == "StatusSearch") { PictureList = PictureRepository.GetPictureByStatus(code, codeID2, bDate, eDate); } else { PictureList = PictureRepository.GetPictureByDateRange(bDate, eDate); } ViewBag.RecordCount = PictureList.Count(); return(PartialView(PictureList)); }
public void SetCache(PictureList input) { try { string path = Environment.CurrentDirectory; XmlSerializer xs = new XmlSerializer(typeof(PictureList)); TextWriter txtWriter = new StreamWriter(path + @"/PictureCache.xml"); xs.Serialize(txtWriter, input); txtWriter.Close(); } catch (Exception ex) { } }
internal List <PictureModel> GetImages() { List <PictureModel> imgList = null; try { CacheManager cache = new CacheManager(); PictureList pictures = cache.GetCache(); imgList = pictures.Pictures; } catch (Exception) { } return(imgList); }
public async void TakePicture() { clientPics = new ClientPictures { ClientId = Client.Id, Pictures = await TakePic() }; if (clientPics.Pictures != null) { PictureList.Add(clientPics); database.Insert(clientPics); IMG = GetImage(clientPics.Pictures); } database.Update(ClientPics); ConverterAsync(); }
private void Btn_DelImg(object sender, RoutedEventArgs e) { string fileName = System.IO.Path.GetFileName(imgPath); if (ImgHandling.delImg.ImgDel(fileName) == true) { System.Windows.Forms.MessageBox.Show("Bild wurde entfernt"); myImgCount = myImgCount - 1; LblImgCount.Content = "Zugehörige Bilder: " + myImgCount.ToString(); SaveGD(); //imgListBox.Items.Clear(); //if (myImgCount > 0) { PictureList selPicture = new PictureList(myVarID.ToString()); imgListBox.ItemsSource = selPicture; } } }
private void Btn_Img_new(object sender, RoutedEventArgs e) { if (myImgCount == 0) { SaveGD(); } string curName = null; OpenFileDialog ofd = new OpenFileDialog(); ofd.Title = "Bilder einfügen"; ofd.Filter = "Image Files(*.PNG; *.JPG;| *.PNG; *.JPG| All files(*.*) | *.*"; ofd.RestoreDirectory = true; if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK) { //FilePath = ofd.FileName; //System.Windows.Forms.MessageBox.Show(FilePath); Admin.Admin.cName = System.IO.Path.GetFileName(ofd.FileName); myImgCount += 1; String _NewName = myVarID.ToString() + "#" + myImgCount + System.IO.Path.GetExtension(ofd.FileName); string NewName = System.IO.Path.Combine(Admin.Admin.ImgPath, _NewName); // System.Windows.Forms.MessageBox.Show(NewName); try { File.Copy(ofd.FileName, NewName); curName = System.IO.Path.GetFileName(NewName); //den alten FileName speichern //ImgHandling.myIPTCDaten.iSpezial = cFileName; //ImgHandling.IPTCDaten.WriteIPTC(cName); PictureList selPicture = new PictureList(curName); imgListBox.ItemsSource = selPicture; LblImgCount.Content = "Zugehörige Bilder: " + myImgCount.ToString(); } catch (Exception ex) { System.Windows.Forms.MessageBox.Show("Bild bereits vorhaden!" + Environment.NewLine + ex.Message); } string objNr = myModID.ToString() + "-" + myVarID.ToString(); string cImg = System.IO.Path.Combine(Admin.Admin.ImgPath, curName); ShowIPTC iptcchange = new ShowIPTC(cImg + "*" + objNr); iptcchange.ShowDialog(); ShowMetaDaten(curName); } }
public List <string> getPictures() { if (Pictures == null) { Pictures = new List <string>(); } if (Pictures.Count == 0) { if (PictureList != null && !PictureList.Equals("")) { Pictures.Add(PictureList); } if (Product.ImagesString != "") { Pictures.Add(Product.ImagesString); } } return(Pictures); }
private void OnPicturesLoaded(object sender, PropertyChangedEventArgs e) { if (e.PropertyName == "IsSuccessfullyCompleted") { int icount = 0; PictureList.Clear(); var pl = LoadingPictures.Result; foreach (var p in pl) { PictureList.Add(new SongPicture(p)); if (p.selected) { icount++; } } PictureList[0].Current = true; SelectedImagesCount = icount; } }
public String getCover() { if (Pictures == null) { Pictures = new List <string>(); } if (Pictures.Count == 0) { if (PictureList != null && !PictureList.Equals("")) { Pictures.Add(WebUtility.UrlDecode(PictureList)); } if (Product.ImagesString != "") { Pictures.Add(WebUtility.UrlDecode(Product.ImagesString)); } } return(Pictures[0]); }
public PictureList GetCache() { PictureList output = null; string path = Environment.CurrentDirectory; try { XmlSerializer xs = new XmlSerializer(typeof(PictureList)); Stream reader = new FileStream(path + @"/PictureCache.xml", FileMode.Open); output = (PictureList)xs.Deserialize(reader); reader.Close(); } catch (Exception ex) { Console.WriteLine("*** Error reading PictureCache.xml *** -->> " + ex.Message); } return(output); }
private void Form1_Load(object sender, EventArgs e) { WallbaseImageSearchSettings wiss = new WallbaseImageSearchSettings(); wiss.SA="toplist"; PictureSearch ps = new PictureSearch(); ps.SearchProvider = new ActiveProviderInfo("Wallbase") {Active=true, ProviderConfig = wiss.Save()}; ps.MaxPictureCount = 100; string path = System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "TEMP"); Directory.CreateDirectory(path); ps.SaveFolder = path; IInputProvider p = ps.SearchProvider.Instance as IInputProvider; pl = p.GetPictures(ps); Timer t = new Timer(); t.Tick += t_Tick; t.Interval = 5000; t.Enabled = true; }
public Pulse.Base.PictureList GetPictures(Pulse.Base.PictureSearch ps) { PictureList pl = new PictureList() { FetchDate = DateTime.Now }; //general purpose downloader WebClient wc = new WebClient(); //download pictures page var content = wc.DownloadString(_baseURL + "/wallpaper/download"); //get paths to the xml files var xmlPaths = ParseXMLPaths(content); //download and parse each xml file foreach (string xmlFile in xmlPaths) { try { var pics = ParsePictures(xmlFile); //clear out banned images pics = (from c in pics where !ps.BannedURLs.Contains(c.Url) select c).ToList(); pl.Pictures.AddRange(pics); } catch (Exception ex) { Log.Logger.Write(string.Format("Error loading/parsing National Geographic pictures from XML. XML file URL: '{0}'. Exception details: {1}", _baseURL + xmlFile, ex.ToString()), Log.LoggerLevels.Errors); } if (pl.Pictures.Count >= (ps.MaxPictureCount > 0 ? ps.MaxPictureCount : int.MaxValue)) { break; } } return(pl); }
public PictureList GetPictures(PictureSearch ps) { PictureList pl = new PictureList() { FetchDate = DateTime.Now }; LocalDirectorySettings lds = string.IsNullOrEmpty(ps.SearchProvider.ProviderConfig) ? new LocalDirectorySettings() : LocalDirectorySettings.LoadFromXML(ps.SearchProvider.ProviderConfig); //get all files in directory and filter for image extensions (jpg/jpeg/png/bmp?) List <string> files = new List <string>(); foreach (string ext in lds.Extensions.Split(new char[] { ';' })) { files.AddRange(Directory.GetFiles(lds.Directory, "*." + ext, SearchOption.AllDirectories)); } //distinct list (just in case) files = files.Distinct().ToList(); var maxPictureCount = ps.MaxPictureCount > 0 ? ps.MaxPictureCount : int.MaxValue; maxPictureCount = Math.Min(files.Count, maxPictureCount); //create picture items pl.Pictures.AddRange((from c in files select new Picture() { Id = Path.GetFileNameWithoutExtension(c), Url = c, LocalPath = c }) .OrderBy(x => Guid.NewGuid()) .Take(maxPictureCount)); return(pl); }
internal List <PictureModel> Search(string search) { List <PictureModel> imgList = null; try { CacheManager cache = new CacheManager(); PictureList pictures = cache.GetCache(); imgList = new List <PictureModel>(); foreach (var item in pictures.Pictures) { if (!string.IsNullOrEmpty(item.Author)) { if (item.Author.ToLower() == search.ToLower()) { imgList.Add(item); } } if (!string.IsNullOrEmpty(item.Camera)) { if (item.Camera.ToLower() == search.ToLower()) { imgList.Add(item); } } } } catch (Exception ex) { } return(imgList); }
public void UpdatePictures() { Int64 pictureId = 33; IPicture oldPicture = GetPictureManager(true).GetPicture(GetUserContext(), pictureId, 50, 50, 0, false, string.Empty); PictureList updatePictures = new PictureList { new Picture { Id = pictureId, IsPublic = true, IsArchived = true, LastUpdated = DateTime.Now, UpdatedBy = GetUserContext().User.GetPerson(GetUserContext()).FullName } }; String updatedBy = GetUserContext().User.GetPerson(GetUserContext()).FullName; Int32 affectedRows; using (ITransaction transaction = GetUserContext().StartTransaction()) { affectedRows = GetPictureManager().UpdatePictures(GetUserContext(), updatePictures, updatedBy); Assert.IsTrue((affectedRows > 0) && (affectedRows == updatePictures.Count)); IPicture updatedPicture = GetPictureManager().GetPicture(GetUserContext(), pictureId, 50, 50, 0, false, string.Empty); Assert.AreEqual(pictureId, updatedPicture.Id); Assert.AreEqual(updatePictures[0].IsPublic, updatedPicture.IsPublic); Assert.AreEqual(updatePictures[0].IsArchived, updatedPicture.IsArchived); Assert.IsTrue(updatePictures[0].LastUpdated <= updatedPicture.LastUpdated); Assert.AreEqual(updatePictures[0].UpdatedBy, updatedPicture.UpdatedBy); affectedRows = GetPictureManager().UpdatePictures(GetUserContext(), new PictureList { oldPicture }, updatedBy); Assert.IsTrue((affectedRows > 0) && (affectedRows == 1)); } }
private void savePictures(PictureList Pictures, int creatureId) { string updateSQL = "UPDATE `picturelist` SET `creatureAndPlantsId`=@creatureAndPlantsId,`pictureId`=@pictureId WHERE `creatureAndPlantsId`=@creatureAndPlantsId AND `pictureId`=@creatureAndPlantsId;"; string insertSQL = "INSERT INTO `picturelist` (`creatureAndPlantsId`,`pictureId`) VALUES (@creatureAndPlantsId,@pictureId);"; using (MySqlConnection conn = getAConnection()) { if (conn.State != System.Data.ConnectionState.Open) { using (MySqlCommand cmd = new MySqlCommand(updateSQL, conn)) { foreach (Picture pic in Pictures) { cmd.Parameters.AddWithValue("@creaturesAndPlantsId", creatureId); cmd.Parameters.AddWithValue("@pictureId", pic.ID); try { if (cmd.ExecuteNonQuery() == 0) { cmd.CommandText = insertSQL; cmd.Parameters.AddWithValue("@creaturesAndPlantsId", creatureId); cmd.Parameters.AddWithValue("@pictureId", pic.ID); cmd.ExecuteNonQuery(); } } catch (SqlException ex) { handleDBError(new Delegates.DatabaseArgs(ex)); } } } } else { handleDBError(new Delegates.DatabaseArgs("Connection not open")); } } }
private void addAlbumButton_Click(object sender, EventArgs e) { // PopUp that will require the user to define the album albumPopup addAlbum = new albumPopup(); addAlbum.ShowDialog(); // Given the path defined load pictures if (addAlbum.AlbumValid) { PictureList newAlbumList = new PictureList(); newAlbumList = Picture.ExtractListFromPath(addAlbum.path, false); newAlbumList.LoadAll(); // Add to the main AlbumList albums.Add(new Album(newAlbumList, addAlbum.nameField)); } // Refresh _RefreshPictureView(); _RefreshAlbumView(); }
/// <summary> /// Retrieves a random picture from the picture list /// </summary> /// <param name="pl">Picture list from which to retrieve pictures</param> /// <param name="saveFolder">Location where to save the picture</param> /// <param name="currentPicture">(optional) the current picture, to avoid repeates. Pass null if not needed or this is the first picture.</param> public PictureDownload GetPicture(PictureList pl, Picture currentPicture, bool queueForDownload) { Picture pic = null; if (pl == null || pl.Pictures.Count == 0) return null; //pick the next picture at random // only "non-random" bit is that we make sure that the next random picture isn't the same as our current one var index = 0; do { index = rnd.Next(pl.Pictures.Count); } while (currentPicture != null && currentPicture.Url == pl.Pictures[index].Url); pic = pl.Pictures[index]; //download current picture first PictureDownload pd = GetPicture(pic, queueForDownload); return pd; }
public PictureList GetPictures(PictureSearch ps) { var result = new PictureList() { FetchDate = DateTime.Now }; MediaRSSImageSearchSettings mrssiss = string.IsNullOrEmpty(ps.SearchProvider.ProviderConfig) ? new MediaRSSImageSearchSettings() : MediaRSSImageSearchSettings.LoadFromXML(ps.SearchProvider.ProviderConfig); XDocument feedXML = XDocument.Load(mrssiss.MediaRSSURL); XNamespace media = XNamespace.Get("http://search.yahoo.com/mrss/"); var feeds = from feed in feedXML.Descendants("item") let content = feed.Elements(media + "content") let thumb = feed.Element(media + "thumbnail").Attribute("url").Value let img = content.Where(x => x.Attribute("medium").Value == "image").SingleOrDefault() let url = img!=null?img.Attribute("url").Value:thumb let id = System.IO.Path.GetFileNameWithoutExtension(url) select new Picture() { Url = url, Id = id.Length > 50 ? id.Substring(0, 50) : id, Properties = new SerializableDictionary<string,string>(Picture.StandardProperties.Thumbnail,thumb) }; //get up to the maximum number of pictures, excluding banned images result.Pictures.AddRange( feeds.Where(x=> !ps.BannedURLs.Contains(x.Url)) .Take(ps.MaxPictureCount)); ////handle colors //if (!string.IsNullOrEmpty(giss.Color)) //{ // tbs += MediaRSSImageSearchSettings.MediaRSSImageColors.GetColorSearchString((from c in MediaRSSImageSearchSettings.MediaRSSImageColors.GetColors() where c.Value == giss.Color select c).Single()) + ","; //} ////if we have a filter string then add it and trim off trailing commas //if (!string.IsNullOrEmpty(tbs)) tbs = ("&tbs=" + tbs).Trim(new char[]{','}); //do //{ // //build URL from query, dimensions and page index // var url = string.Format(baseURL, ps.SearchString, tbs, (pageIndex * 20).ToString()); // var response = client.DownloadString(url); // var images = imagesRegex2.Matches(response); // //track number of images found for paging purposes // imgFoundCount = images.Count; // //convert images found into picture entries // foreach (Match item in images) // { // var purl = item.Groups[3].Value; // //get id and trim if necessary (ran into a few cases of rediculously long filenames) // var id = System.IO.Path.GetFileNameWithoutExtension(purl); // if (id.Length > 50) id = id.Substring(0, 50); // result.Pictures.Add(new Picture() { Url = purl, Id = id }); // } // //if we have an image ban list check for them // // doing this in the provider instead of picture manager // // ensures that our count does not go down if we have a max // if (ps.BannedURLs != null && ps.BannedURLs.Count > 0) // { // result.Pictures = (from c in result.Pictures where !(ps.BannedURLs.Contains(c.Url)) select c).ToList(); // } // //increment page index so we can get the next 20 images if they exist // pageIndex++; // // Max Picture count is defined in search settings passed in, check for it here too //} while (imgFoundCount > 0 && result.Pictures.Count < maxPictureCount); return result; }
public PictureList GetPictures(PictureSearch ps) { WallbaseImageSearchSettings wiss = string.IsNullOrEmpty(ps.SearchProvider.ProviderConfig) ? new WallbaseImageSearchSettings() : WallbaseImageSearchSettings.LoadFromXML(ps.SearchProvider.ProviderConfig); //if max picture count is 0, then no maximum, else specified max var maxPictureCount = ps.MaxPictureCount > 0?ps.MaxPictureCount : int.MaxValue; int pageSize = wiss.GetPageSize(); int pageIndex = ps.PageToRetrieve; //set page to retreive if one is specified var imgFoundCount = 0; //authenticate to wallbase Authenticate(wiss.Username, wiss.Password); var wallResults = new List <Picture>(); string areaURL = wiss.BuildURL(); //string postParams = wiss.GetPostParams(search); do { //calculate page index. Random does not use pages, so for random just refresh with same url string strPageNum = (pageIndex > 0 && wiss.SA != "random") || (wiss.SA == "toplist" || wiss.SA == "user/collection" || wiss.SA == "user/favorites") ? (pageIndex * pageSize).ToString() : ""; string pageURL = areaURL.Contains("{0}") ? string.Format(areaURL, strPageNum) : areaURL; //string content = HttpPost(pageURL, postParams); string content = string.Empty; using (HttpUtility.CookieAwareWebClient _client = new HttpUtility.CookieAwareWebClient(_cookies)) { try { //if random then don't post values if (wiss.SA == "random") { content = _client.DownloadString(pageURL); } else { byte[] reqResult = _client.UploadValues(pageURL, wiss.GetPostParams()); content = System.Text.Encoding.Default.GetString(reqResult); } } catch (Exception ex) { Log.Logger.Write(string.Format("Failed to download search results from wallbase.cc, error: {0}", ex.ToString()), Log.LoggerLevels.Warnings); } } if (string.IsNullOrEmpty(content)) { break; } //parse html and get count var pics = ParsePictures(content); imgFoundCount = pics.Count(); //if we have an image ban list check for them // doing this in the provider instead of picture manager // ensures that our count does not go down if we have a max if (ps.BannedURLs != null && ps.BannedURLs.Count > 0) { pics = (from c in pics where !(ps.BannedURLs.Contains(c.Url)) select c).ToList(); } wallResults.AddRange(pics); //increment page index so we can get the next set of images if they exist pageIndex++; } while (imgFoundCount > 0 && wallResults.Count < maxPictureCount && ps.PageToRetrieve == 0); PictureList result = FetchPictures(wallResults, ps.PreviewOnly); result.Pictures = result.Pictures.Take(maxPictureCount).ToList(); return(result); }
private PictureList FetchPictures(List <Picture> wallResults, bool previewOnly) { var result = new PictureList() { FetchDate = DateTime.Now }; ManualResetEvent mreThread = new ManualResetEvent(false); ThreadStart threadStarter = () => { //download in parallel var processCounter = 0; try { while (processCounter < wallResults.Count) { var toProcess = wallResults.Skip(processCounter).Take(60).ToList(); processCounter += toProcess.Count; ManualResetEvent[] manualEvents = new ManualResetEvent[toProcess.Count]; // Queue the work items that create and write to the files. for (int i = 0; i < toProcess.Count; i++) { manualEvents[i] = new ManualResetEvent(false); ThreadPool.QueueUserWorkItem(new WaitCallback(delegate(object state) { object[] states = (object[])state; ManualResetEvent mre = (ManualResetEvent)states[0]; Picture p = (Picture)states[1]; try { //save original URL as referrer p.Properties.Add(Picture.StandardProperties.Referrer, p.Url); p.Properties.Add(Picture.StandardProperties.BanImageKey, Path.GetFileName(p.Url)); //get actual image URL if this is not a preview if (!previewOnly) { p.Url = GetDirectPictureUrl(p.Url); } p.Id = System.IO.Path.GetFileNameWithoutExtension(p.Url); if (!string.IsNullOrEmpty(p.Url) && !string.IsNullOrEmpty(p.Id)) { result.Pictures.Add(p); } } catch (Exception ex) { Log.Logger.Write(string.Format("Error downloading picture object from '{0}'. Exception details: {0}", ex.ToString()), Log.LoggerLevels.Errors); } finally { mre.Set(); } }), new object[] { manualEvents[i], toProcess[i] }); } //wait for all items to finish //one minute timeout WaitHandle.WaitAll(manualEvents, 60 * 1000); } } catch (Exception ex) { Log.Logger.Write(string.Format("Error during multi-threaded wallbase.cc image get. Exception details: {0}", ex.ToString()), Log.LoggerLevels.Errors); } finally { mreThread.Set(); } }; var thread = new Thread(threadStarter); thread.SetApartmentState(ApartmentState.MTA); thread.Start(); mreThread.WaitOne(); return(result); }
public void UpdatePicturesTaxon() { Int64 pictureId = 33; IPicture picture; String filename; Int32 affectedRows; DateTime lastModified; String updatedBy; PictureMetaDataList pictureMetaData; IPictureResponse pictureResponse; PictureList pictures; picture = GetPictureManager(true).GetPicture(GetUserContext(), pictureId, null, null, 0, false, string.Empty); filename = @"\Temp\JN_Leiobunum-blackwalli_226679_Hane_new.jpg"; lastModified = DateTime.Now; updatedBy = GetUserContext().User.GetPerson(GetUserContext()).FullName; using (ITransaction transaction = GetUserContext().StartTransaction()) { // Create picture. pictureResponse = GetPictureManager().CreatePictureFilename(GetUserContext(), picture.Image, filename, lastModified, picture.VersionId + 1, updatedBy, null); Assert.AreEqual(pictureResponse.AffectedRows, 1); Assert.IsTrue(pictureResponse.Id > 0); pictureMetaData = GetPictureManager().GetPictureMetaData(GetUserContext(), pictureResponse.Id, null); Assert.IsTrue(pictureMetaData.IsNotEmpty()); picture = GetPictureManager().GetPicture(GetUserContext(), pictureResponse.Id, null, null, 0, false, null); Assert.IsNotNull(picture); Assert.IsNull(picture.Taxon); // Set taxon. picture.Taxon = CoreData.TaxonManager.GetTaxon(GetUserContext(), TaxonId.Bear); pictures = new PictureList(); pictures.Add(picture); GetPictureManager().UpdatePictures(GetUserContext(), pictures, updatedBy); pictureMetaData = GetPictureManager().GetPictureMetaData(GetUserContext(), pictureResponse.Id, null); Assert.IsTrue(pictureMetaData.IsNotEmpty()); picture = GetPictureManager().GetPicture(GetUserContext(), pictureResponse.Id, null, null, 0, false, null); Assert.IsNotNull(picture); Assert.IsNotNull(picture.Taxon); Assert.AreEqual((Int32)(TaxonId.Bear), picture.Taxon.Id); // Remove taxon. picture.Taxon = null; pictures = new PictureList(); pictures.Add(picture); GetPictureManager().UpdatePictures(GetUserContext(), pictures, updatedBy); pictureMetaData = GetPictureManager().GetPictureMetaData(GetUserContext(), pictureResponse.Id, null); Assert.IsTrue(pictureMetaData.IsNotEmpty()); picture = GetPictureManager().GetPicture(GetUserContext(), pictureResponse.Id, null, null, 0, false, null); Assert.IsNotNull(picture); Assert.IsNull(picture.Taxon); // Clean up. affectedRows = GetPictureManager().DeletePictureFilename(GetUserContext(), null, filename, picture.PictureStringId); Assert.IsTrue(0 < affectedRows); } }
private PictureList FetchPictures(List<Picture> wallResults, bool previewOnly) { var result = new PictureList() { FetchDate = DateTime.Now }; ManualResetEvent mreThread = new ManualResetEvent(false); ThreadStart threadStarter = () => { //download in parallel var processCounter = 0; try { while (processCounter < wallResults.Count) { var toProcess = wallResults.Skip(processCounter).Take(60).ToList(); processCounter += toProcess.Count; ManualResetEvent[] manualEvents = new ManualResetEvent[toProcess.Count]; // Queue the work items that create and write to the files. for (int i = 0; i < toProcess.Count; i++) { manualEvents[i] = new ManualResetEvent(false); ThreadPool.QueueUserWorkItem(new WaitCallback(delegate(object state) { object[] states = (object[])state; ManualResetEvent mre = (ManualResetEvent)states[0]; Picture p = (Picture)states[1]; try { //save original URL as referrer p.Properties.Add(Picture.StandardProperties.Referrer, p.Url); p.Properties.Add(Picture.StandardProperties.BanImageKey, Path.GetFileName(p.Url)); //get actual image URL if this is not a preview if(!previewOnly) p.Url = GetDirectPictureUrl(p.Url); p.Id = System.IO.Path.GetFileNameWithoutExtension(p.Url); if (!string.IsNullOrEmpty(p.Url) && !string.IsNullOrEmpty(p.Id)) { result.Pictures.Add(p); } } catch (Exception ex) { Log.Logger.Write(string.Format("Error downloading picture object from '{0}'. Exception details: {0}", ex.ToString()), Log.LoggerLevels.Errors); } finally { mre.Set(); } }), new object[] { manualEvents[i], toProcess[i] }); } //wait for all items to finish //one minute timeout WaitHandle.WaitAll(manualEvents, 60 * 1000); } } catch(Exception ex) { Log.Logger.Write(string.Format("Error during multi-threaded wallbase.cc image get. Exception details: {0}", ex.ToString()), Log.LoggerLevels.Errors); } finally { mreThread.Set(); } }; var thread = new Thread(threadStarter); thread.SetApartmentState(ApartmentState.MTA); thread.Start(); mreThread.WaitOne(); return result; }
public PictureList GetPictures(PictureSearch ps) { var result = new PictureList() { FetchDate = DateTime.Now }; //load provider search settings GoogleImageSearchSettings giss = GoogleImageSearchSettings.LoadFromXML(ps.SearchProvider.ProviderConfig) ?? new GoogleImageSearchSettings(); //if search is empty, return now since we can't search without it if (string.IsNullOrEmpty(giss.Query)) return result; var pageIndex = ps.PageToRetrieve; //set page to retrieve if one specified var imgFoundCount = 0; //if max picture count is 0, then no maximum, else specified max var maxPictureCount = ps.MaxPictureCount > 0?ps.MaxPictureCount : int.MaxValue; //build tbs strring var tbs = "";//isz:ex,iszw:{1},iszh:{2} //handle sizeing if (giss.ImageHeight > 0 && giss.ImageWidth > 0) { tbs += string.Format("isz:ex,iszw:{0},iszh:{1},", giss.ImageWidth, giss.ImageHeight); } //handle colors if (!string.IsNullOrEmpty(giss.Color)) { tbs += GoogleImageSearchSettings.GoogleImageColors.GetColorSearchString((from c in GoogleImageSearchSettings.GoogleImageColors.GetColors() where c.Value == giss.Color select c).Single()) + ","; } //if we have a filter string then add it and trim off trailing commas if (!string.IsNullOrEmpty(tbs)) tbs = ("&tbs=" + tbs).Trim(new char[]{','}); //do safe search setup (off/strict/moderate) this is part of the session and tracked via cookies //SetSafeSearchSetting(giss.GoogleSafeSearchOption); do { //build URL from query, dimensions and page index var url = string.Format(baseURL, giss.Query, tbs, (pageIndex * 20)); var response = string.Empty; using (var client = new HttpUtility.CookieAwareWebClient(_cookies)) { response = client.DownloadString(url); } var images = _imagesRegex2.Matches(response); //track number of images found for paging purposes imgFoundCount = images.Count; //convert images found into picture entries foreach (Match item in images) { var purl = item.Groups["imgurlgrp"].Value; var referrer = item.Groups["imgrefgrp"].Value; var thumbnail = item.Groups["thumbURL"].Value; //get id and trim if necessary (ran into a few cases of rediculously long filenames) var id = System.IO.Path.GetFileNameWithoutExtension(purl); if (id.Length > 50) id = id.Substring(0, 50); //because google images come from so many sites it's not uncommon to have duplicate file names. (we fix this) id = string.Format("{0}_{1}", id, purl.GetHashCode()); var p = new Picture() { Url = purl, Id = id }; p.Properties.Add(Picture.StandardProperties.Thumbnail, thumbnail); p.Properties.Add(Picture.StandardProperties.Referrer, referrer); result.Pictures.Add(p); } //if we have an image ban list check for them // doing this in the provider instead of picture manager // ensures that our count does not go down if we have a max if (ps.BannedURLs != null && ps.BannedURLs.Count > 0) { result.Pictures = (from c in result.Pictures where !(ps.BannedURLs.Contains(c.Url)) select c).ToList(); } //increment page index so we can get the next 20 images if they exist pageIndex++; // Max Picture count is defined in search settings passed in, check for it here too } while (imgFoundCount > 0 && result.Pictures.Count < maxPictureCount && ps.PageToRetrieve == 0); result.Pictures = result.Pictures.Take(maxPictureCount).ToList(); return result; }