protected void Page_Load(object sender, EventArgs e) { string sid = Request.QueryString["id"]; int id; if (int.TryParse(sid, out id)) { PhotoBLL pb = new PhotoBLL(); p = pb.GetPhotoById(id); } }
internal PhotosModel ClassToModel(Photos item) { PhotosModel mitem=new PhotosModel(); mitem.PhotoId = item.PhotoId; mitem.ParentId = item.ParentId; mitem.Title = item.Title; mitem.SmallDescription = item.SmallDescription; mitem.AlternativeText = item.AlternativeText; mitem.Photourl ="images/"+item.PhotoId+".jpg"; return mitem; }
private void UpdateStream() { Gtk.Application.Invoke(delegate { DeskFlickrUI.GetInstance().SetStatusLabel("Updating photo stream..."); DeskFlickrUI.GetInstance().SetProgressBarText(""); }); FlickrNet.PhotoSearchOptions options = new PhotoSearchOptions(); options.UserId = "me"; options.Extras = PhotoSearchExtras.LastUpdated; options.PerPage = 500; options.Page = 1; Photos photos = flickrObj.PhotosSearch(options); CheckProceedRoutinePermission(); Gtk.Application.Invoke(delegate { DeskFlickrUI.GetInstance().SetLimitsProgressBar((int)photos.TotalPhotos); }); ArrayList serverphotoids = new ArrayList(); UpdatePhotos(photos.PhotoCollection, ref serverphotoids); for (int curpage = 2; curpage <= photos.TotalPages; curpage++) { options.Page = curpage; photos = flickrObj.PhotosSearch(options); UpdatePhotos(photos.PhotoCollection, ref serverphotoids); CheckProceedRoutinePermission(); } // Delete the photos not present on server. foreach (string photoid in PersistentInformation.GetInstance().GetAllPhotoIds()) { // DeletePhoto method takes care of deleting the tags as well. if (serverphotoids.Contains(photoid)) { continue; } PersistentInformation.GetInstance().DeletePhoto(photoid); } }
public async Task BrowseGalleryAsync() { var storageStatus = await CrossPermissions.Current.CheckPermissionStatusAsync(Plugin.Permissions.Abstractions.Permission.Storage); if (storageStatus != PermissionStatus.Granted) { var results = await CrossPermissions.Current.RequestPermissionsAsync(Plugin.Permissions.Abstractions.Permission.Storage); if (results.ContainsKey(Plugin.Permissions.Abstractions.Permission.Storage)) { storageStatus = results[Plugin.Permissions.Abstractions.Permission.Storage]; } } if (storageStatus == PermissionStatus.Granted) { await CrossMedia.Current.Initialize(); if (!CrossMedia.Current.IsPickPhotoSupported) { return; } var file = await CrossMedia.Current.PickPhotoAsync(new Plugin.Media.Abstractions.PickMediaOptions { SaveMetaData = false, CompressionQuality = 30, MaxWidthHeight = 1024 }); if (file != null) { var imageSource = ImageSource.FromFile(file.Path); Photos.Add(new ImageItemViewModel { ImageSource = imageSource, ImageName = file.Path.Substring(file.Path.LastIndexOf("/") + 1) }); } } }
public async Task <IEnumerable <EventViewModel> > GetEventsWithCommentsAndPhotos(IQueryable <Event> query) { query = query.Include(e => e.User); var result = await query.ToArrayAsync(); var eventsIds = result.Select(e => e.EventId); var comments = await Comments.Where(c => c.EntityType == CommentEntityTypes.Event && eventsIds.Contains(c.EntityId)) .ToListAsync(); var photos = await Photos.Where(p => p.EntityType == PhotoEntityTypes.Event && eventsIds.Contains(p.EntityId)) .ToListAsync(); var photosMap = photos.ToDictionary(p => p.UserFileId); var files = await UserFiles.Where(f => photosMap.Keys.Contains(f.UserFileId)).ToListAsync(); var photoViewModelMap = files .Select(f => new { EntityId = photosMap[f.UserFileId].EntityId, ViewModel = new PhotoViewModel { Url = "/Uploads/" + f.FilePath, UserId = f.UserId, Likes = Enumerable.Empty <SimpleUserProfileViewModel>(), LikesCount = 0, AlbumId = 0 } }) .GroupBy(p => p.EntityId) .ToDictionary(g => g.Key, g => g.Select(p => p.ViewModel).ToArray()); var commentViewModelMap = comments .Select(c => Tuple.Create(c.EntityId, new CommentViewModel(c, null, null))) .GroupBy(c => c.Item1) .ToDictionary(g => g.Key, g => g.Select(t => t.Item2).ToArray());; return(result.Select(e => { return new EventViewModel(e, null, commentViewModelMap.ContainsKey(e.EventId) ? commentViewModelMap[e.EventId] : null, photoViewModelMap.ContainsKey(e.EventId) ? photoViewModelMap[e.EventId] : null, null); })); }
void ShowAlternativePopup(View view, int position) { Android.Support.V7.Widget.PopupMenu popupMenu = new Android.Support.V7.Widget.PopupMenu(_context, view); var menuOpts = popupMenu.Menu; popupMenu.Inflate(Resource.Layout.photo_option); popupMenu.MenuItemClick += async(s1, arg1) => { //if (_nativeMethods.(_context)) //{ if (arg1.Item.TitleFormatted.ToString() == _context.GetString(Resource.String.edit)) { _editPersonalImageViewHolder.ActivityIndicator.Visibility = ViewStates.Visible; _editPersonalImageViewHolder.ImageIv.Visibility = ViewStates.Gone; var uri = await _nativeMethods.ExportBitmapAsJpegAndGetUri(Photos[position]); _editPersonalImageViewHolder.ActivityIndicator.Visibility = ViewStates.Gone; _editPersonalImageViewHolder.ImageIv.Visibility = ViewStates.Visible; try { _editPersonalDataActivity.StartCropActivity(uri, _context, position); } catch (Exception ex) { } } if (arg1.Item.TitleFormatted.ToString() == _context.GetString(Resource.String.removePhoto)) { Photos.RemoveAt(position); this.NotifyDataSetChanged(); } //} //else //_nativeMethods.CheckStoragePermissions(_context); }; popupMenu.Show(); }
private static void SetupGetPhotos() { _mockRepository.Setup(r => r.GetPhotos(It.IsAny <string>(), It.IsAny <int>(), It.IsAny <int>(), It.IsAny <bool>())) .Returns <string, int, int, bool>( (alias, skip, take, includePrivate) => { var memberId = GetAlias(alias); var photos = Photos.Where(x => x.MemberId == memberId) .Skip(skip) .Take(take) .ToList(); if (!includePrivate) { photos = photos.Where(p => p.IsPrivate == false).ToList(); } return(photos); } ); }
/// <summary> /// 【设为壁纸】按钮单击时执行的代码 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void Button_setWall_Click(object sender, RoutedEventArgs e) { HttpHelper httpHelper = new HttpHelper(); Setting setting = new Setting(); ConfigHelper configHelper = new ConfigHelper(); string imagedir = configHelper.GetValue("BINGPHOTO", "DIRPATH"); int idx = httpHelper.GetRequestIdx(Combox_date.Text); string mkt = httpHelper.GetRequestMkt(Combox_country.Text); if (idx < 8) { Photo photo = new Photo(idx, mkt); httpHelper.DownLoadPhoto(photo.HDUrl); setting.SetWallpaper(imagedir + "/" + System.IO.Path.GetFileName(photo.HDUrl)); } else { Photos photos = new Photos(7, 8, mkt); httpHelper.DownLoadPhoto(photos.GetAphotoValue(idx - 7).HDUrl); setting.SetWallpaper(imagedir + "/" + System.IO.Path.GetFileName(photos.GetAphotoValue(idx - 7).HDUrl)); } }
public Photos GetPhoto(int id) { String command = "SELECT * FROM photos WHERE id=" + id; Photos photo = new Photos(); NpgsqlCommand cmd = new NpgsqlCommand(command, conn); NpgsqlDataReader result = cmd.ExecuteReader(); while (result.Read()) { photo.Id = result.GetInt32(0); photo.UserId = result.GetInt32(1); photo.Name = result.GetString(2); photo.Width = result.GetFloat(3); photo.Height = result.GetFloat(4); photo.Size = result.GetFloat(5); photo.Date = result.GetDateTime(6); } conn.Close(); return(photo); }
public async Task <Photo> AddPhoto(StorageFile imageFile, NameCollisionOption option = NameCollisionOption.FailIfExists) { var albumFolder = await GetImagesFolder(); var targetPath = Path.Combine(albumFolder.Path, imageFile.Name); var photo = new Photo(Id, targetPath); if (Photos.Contains(photo)) { throw new DuplicateObjectException(); } var fileCopy = await imageFile.CopyAsync(albumFolder, imageFile.Name, option); photo.Save(); _photos.Add(photo); return(photo); }
public void GenerateThumbnailForVideo(string filename, string fullPathToVideo, FamilyArchiveContext context) { string ReplacingPart = fullPathToVideo.Split('\\').Last(); string fullPathToThumbnail = fullPathToVideo.Replace(ReplacingPart, "temp_thumbnail.png"); if (File.Exists(fullPathToThumbnail)) { File.Delete(fullPathToThumbnail); } string ThumbnailGenerationString = string.Format(@"-ss 3 -i ""{0}"" -vframes 1 -s 1280x960 ""{1}""", fullPathToVideo, fullPathToThumbnail); ProcessStartInfo startInfo = new ProcessStartInfo { WindowStyle = ProcessWindowStyle.Hidden, CreateNoWindow = true, FileName = Path.Combine(Directory.GetCurrentDirectory(), "ffmpeg\\bin\\ffmpeg.exe"), Arguments = ThumbnailGenerationString }; Process process = new Process() { StartInfo = startInfo }; process.Start(); process.WaitForExit(5000); byte[] ThumbnailImage = System.IO.File.ReadAllBytes(fullPathToThumbnail); System.IO.File.Delete(fullPathToThumbnail); Photos photo = new Photos(); photo.Name = filename; photo.IsThumbnail = true; photo.PhotoBase64 = Encoding.ASCII.GetBytes(Convert.ToBase64String(ThumbnailImage)); context.Photos.Add(photo); }
protected void Page_Load(object sender, EventArgs e) { if (!this.Page.User.Identity.IsAuthenticated) { Response.Redirect("Default.aspx"); } else { if (Request.Params.AllKeys.Contains <string>("id")) { photoId = int.Parse(Request.Params.Get("id")); } else { Response.Redirect("browse.aspx"); } } if (!Users.getUserType(System.Web.HttpContext.Current.User.Identity.Name).Equals("user") || (Photos.getUserId(photoId) == Users.getUserId(System.Web.HttpContext.Current.User.Identity.Name))) { Photos.deletePhoto(photoId); Response.Redirect("browse.aspx"); } }
private async void AddPhoto(IEnumerable <FacebookPhoto> photos) { IsLoading = true; WebClient wc = new WebClient(); foreach (var photo in photos) { byte[] buffer; buffer = await wc.DownloadDataTaskAsync(photo.PreviewImage); MemoryStream ms = new MemoryStream(buffer); BitmapImage img = new BitmapImage(); img.BeginInit(); img.CacheOption = BitmapCacheOption.OnLoad; img.StreamSource = ms; img.EndInit(); Photos.Add(img); } wc.Dispose(); IsLoading = false; }
public ActionResult ModelPhoto(int adId) { HttpPostedFileBase file = Request.Files[0]; byte[] imageSize = new byte[file.ContentLength]; file.InputStream.Read(imageSize, 0, (int)file.ContentLength); using (HangerDatabase db = new HangerDatabase()) { Photos p = new Photos(); p.Photo = imageSize; p.FIle_name = file.FileName; if (db.Photos != null && db.Photos.Count() != 0) { p.Id = (from ph in db.Photos select ph.Id).Max() + 1; } else { p.Id = 0; } // p.OwnerId = (Session["CurrentUserEmail"] as User).UserId; // p.AdId = (from ad in db.Ad // select ad.Id).Max(); p.AdId = adId; p.Type = file.ContentType; p.Main_photo = false; p.PhotoSiteId = 2; db.Photos.Add(p); db.SaveChanges(); } //return RedirectToAction("New", "Home"); return(RedirectToAction("Photo", "Ad", new { id = adId })); }
public static List <string> AddPhotosToDatabase(List <PhotoObj> photoLists) { List <string> listOfUrls = new List <string>(); using (var db = new MARSContext()) { foreach (PhotoObj photo in photoLists) { var newPhoto = new Photos(); var data = db.Photos.FirstOrDefault(x => x.Id == photo.id); if (data == null) { newPhoto.Id = photo.id; newPhoto.Sol = photo.sol; newPhoto.ImgSrc = photo.img_src; newPhoto.EarthDate = photo.earth_date.ToString(); listOfUrls.Add(photo.img_src); db.Photos.Add(newPhoto); db.SaveChanges(); } else { data.Id = photo.id; data.Sol = photo.sol; data.ImgSrc = photo.img_src; data.EarthDate = photo.earth_date.ToString(); listOfUrls.Add(photo.img_src); db.Entry(data).State = EntityState.Modified; db.SaveChanges(); } } return(listOfUrls); } }
public async Task <ActionResult> Upload(HttpPostedFileBase image) { if (image != null && image.ContentLength > 0) { string filePath = Path.Combine(Server.MapPath("~/Content"), Path.GetFileName(image.FileName)); image.SaveAs(filePath); var userId = User.Identity.GetUserId(); var db = new ApplicationDbContext(); ApplicationUser umodel = UserManager.FindById(User.Identity.GetUserId()); var pic = new Photos { EmailId = umodel.Id, PathId = image.FileName }; //save pic data to the db db.Photos.Add(pic); var result = db.SaveChanges(); //if the user has no current profile picture set, make this one the default if (umodel.ProfilePic == null) { umodel.ProfilePic = image.FileName; //set data to the db var result1 = await UserManager.UpdateAsync(umodel); //UserManager.UpdateAsync(umodel); } return(RedirectToAction("Photo", "Manage")); } return(RedirectToAction("Photo", "Manage")); }
protected override UIBarButtonItem CreateActionButton() { return(new UIBarButtonItem(UIBarButtonSystemItem.Trash, (s, e) => { var currentIndex = this.CurrentIndex; if (currentIndex >= Photos.Count) { return; } Photos.RemoveAt(currentIndex); _projectImages[currentIndex].Remove(); _projectImages.RemoveAt(currentIndex); this.ShowProgressHUDWithMessage("Deleting..."); this.ShowProgressHUDCompleteMessage("Deleted!"); if (Photos.Count == 0) { //Nothing more to see... DismissViewController(true, null); return; } if (currentIndex == 0) { this.GotoNextPage(); } else { this.GotoPreviousPage(); } this.ReloadData(); })); }
private void InitialiseProperty(property prop) { PropertyId = prop.property_id; Name = prop.name; Area = prop.area; LandPrice = ( double )prop.min_price.plot_price; HousePrice = ( double )prop.min_price.apartment_price; Latitude = prop.latitude; Longitude = prop.longitude; SellerId = prop.seller_id; Category = prop.category; Type = prop.category1.type; Status = prop.propery_status.status; if (null != Photos) { Photos.Clear(); } else { Photos = new List <string>(); } foreach (var image in prop.images) { byte[] photo = image.image1; string imageSrc = null; if (photo != null) { MemoryStream ms = new MemoryStream(); ms.Write(photo, 0, photo.Length); //ms.Write( photo, 78, photo.Length - 78 ); // strip out 78 byte OLE header (don't need to do this for normal images) string imageBase64 = Convert.ToBase64String(ms.ToArray()); imageSrc = string.Format("data:image/gif;base64,{0}", imageBase64); Photos.Add(imageSrc); } } }
public bool UpdatePhoto(int id, Photos photo) { String command = "SELECT * FROM photos WHERE id=" + id; NpgsqlCommand cmd = new NpgsqlCommand(command, conn); NpgsqlDataReader result = cmd.ExecuteReader(); if (result.Read()) { result.Close(); command = "UPDATE photos SET userid = " + photo.UserId.ToString() + ", name = '" + photo.Name + "', width = " + photo.Width.ToString(new CultureInfo("en-US")) + ", height = " + photo.Height.ToString(new CultureInfo("en-US")) + ", size = " + photo.Size.ToString(new CultureInfo("en-US")) + ", date = '" + photo.Date.ToString("yyyy-MM-dd HH:mm:ss") + "' WHERE id =" + id; cmd = new NpgsqlCommand(command, conn); cmd.ExecuteNonQuery(); conn.Close(); return(true); } else { conn.Close(); return(false); } }
public List <Photos> GetPhotos() { String command = "SELECT * FROM photos"; List <Photos> photos = new List <Photos>(); NpgsqlCommand cmd = new NpgsqlCommand(command, conn); NpgsqlDataReader result = cmd.ExecuteReader(); while (result.Read()) { Photos photo = new Photos(); photo.Id = result.GetInt32(0); photo.UserId = result.GetInt32(1); photo.Name = result.GetString(2); photo.Width = result.GetFloat(3); photo.Height = result.GetFloat(4); photo.Size = result.GetFloat(5); photo.Date = result.GetDateTime(6); photos.Add(photo); } conn.Close(); return(photos); }
/// <summary> /// get the list of the photos /// </summary> private void getListPhotos() { List <PhotoWeb> list = new List <PhotoWeb>(); if (DirectoryOutput != null) { string path = cutPath(DirectoryOutput, "C:", 2); string outputDir = @"../../" + path; string[] files = Directory.GetFiles(outputDir, "*", SearchOption.AllDirectories); Photos.Clear(); foreach (string photo in files) { string fileEnding = Path.GetExtension(photo); if (fileEnding.Equals(".png", StringComparison.CurrentCultureIgnoreCase) || fileEnding.Equals(".gif", StringComparison.CurrentCultureIgnoreCase) || fileEnding.Equals(".jpg", StringComparison.CurrentCultureIgnoreCase) || fileEnding.Equals(".bmp", StringComparison.CurrentCultureIgnoreCase)) { numOfPic++; PhotoWeb temp = new PhotoWeb() { PhotoToShow = @"~/" + cutPath(getNamePath(photo), "ImageServiceWeb", 15), Photo = getNamePath(photo), PhotoName = newGetName(photo), PhotoDate = getDataFromPic(photo), ThumbPhoto = @"~/" + cutPath(photo, "ImageServiceWeb", 15), FullPath = photo }; if (Photos != null && temp.ThumbPhoto.Contains("Thumbnail")) { Photos.Insert(0, temp); } } } } }
public HomeViewModel() { Title = "Home"; photoRepository = new PhotoRepository(); Photos = photoRepository.Photos; MessagingCenter.Subscribe <PhotoDetailsPage, Photo>(this, Constants.EDIT_PHOTO, async(obj, photo) => { var editPhoto = photo; var oldPhoto = Photos.Where((Photo arg) => arg.Id == photo.Id).FirstOrDefault(); oldPhoto = editPhoto; photoRepository.UpdatePhoto(editPhoto); }); MessagingCenter.Subscribe <PhotoDetailsPage, Photo>(this, Constants.DELETE_PHOTO, async(obj, photo) => { Photos.Remove(photo); photoRepository.DeletePhoto(photo); }); MessagingCenter.Subscribe <AddNewPhotoPage, Photo>(this, Constants.ADD_NEW_PHOTO, async(obj, photo) => { Photos.Insert(0, photo); Photo newPhoto = new Photo { AlbumId = 5, Id = photo.Id, Title = photo.Title, Url = photo.Url, ThumbnailUrl = photo.ThumbnailUrl }; photoRepository.AddPhoto(newPhoto); }); }
public void Init() { // Photos _photos.ForEach(p => p.RelativeSourceFilePath = MakeRelative(p.SourceFilePath, DirectoryPath)); // Directories ILookup <string, Photo> photosByDirectory = Photos.ToLookup(p => p.SourceDirectory); foreach (IGrouping <string, Photo> group in photosByDirectory) { // Create Directory // TODO: Use C# 9.0 features var directory = new LibraryCatalogDirectory(group.Key); directory.RelativePath = MakeRelative(directory.Path, DirectoryPath); // Iterate through each value in the grouping foreach (Photo photo in group) { directory.Add(photo); } _directories.Add(directory); } }
public async Task GetPhotos() { if (IsBusy) { return; } Exception error = null; try { IsBusy = true; var items = await mobileService.GetPhotos(); Photos.Clear(); foreach (var item in items) { item.Uri = ResizePhoto(item.Uri); Photos.Add(item); } } catch (Exception ex) { Debug.WriteLine("Error: " + ex); error = ex; } finally { IsBusy = false; } if (error != null) { dialogService.ShowError("Error! " + error.Message + " OK"); } }
private async Task RefreshPhotos() { IsRefreshing = true; try { var azureService = DependencyService.Get <IAzureService>(); if (!await azureService.IsLoggedIn()) { return; } var metadata = await azureService.SyncPhotos(); foreach (var item in metadata.Where(p => Photos.All(x => x.FileName != p.BlobName))) { Photos.Add(new PhotoViewModel(item)); } } finally { IsRefreshing = false; } }
public async Task <Result> GetPhotosAsync() { Photos.Clear(); IsBusy = true; var result = await _photoCameraRepository.GetMaxSolAsync(_citizen.NormalizedName); IsBusy = false; if (result.IsFailure) { return(Result.Fail(result.Error)); } _currentSol = result.Value; GetPhotosForCurrentSolAsync(); return(Result.Ok()); }
public IActionResult AddPhoto(Photos NewPhoto) { // int? y=HttpContext.Session.GetInt32("userid"); // if (y==null){ // return RedirectToAction("Index"); // } // bool Exists=dbContext.users.Any(e=>e.UserId==(int)y); // if(Exists==false){ // return RedirectToAction("Index"); // } if (ModelState.IsValid) { CryptoEngine Encrypter = new CryptoEngine(); NewPhoto.Desc = Encrypter.Encrypt(NewPhoto.Desc); NewPhoto.PhotoPath = Encrypter.Encrypt(NewPhoto.PhotoPath); // NewPhoto.CreatorId=Encrypter.Encrypt((string)NewPhoto.CreatorId); dbContext.photos.Add(NewPhoto); dbContext.SaveChanges(); return(RedirectToAction("Success")); } else { // ViewBag.UserId=(int)y; ViewBag.UserId = 5; List <Photos> Allphoto = dbContext.photos.ToList(); foreach (var photo in Allphoto) { CryptoEngine Encrypter = new CryptoEngine(); photo.Desc = Encrypter.Decrypt(photo.Desc); photo.PhotoPath = Encrypter.Decrypt(photo.PhotoPath); } ViewBag.AllPhotos = Allphoto; return(View("Success")); } }
public bool EditPhoto(Photos photo) { try { return(ar.EditPhoto(photo)); } catch (Exception e) { } return(false); }
public Maybe <RemarkPhoto> GetPhoto(string name) => Photos.FirstOrDefault(x => x.Name == name);
public nint IndexOfPhoto(NSPhoto photo) { return(Photos.IndexOf(photo)); }
protected void lBtnVieFullPhoto_Click(object sender, EventArgs e) { MiscellaneousController objMisc = new MiscellaneousController(); Photos objPhotos = new Photos(); string[] getPath = CommonUtilities.GetPath(); StateManager objStateManager = StateManager.Instance; objSessionValue = (SessionValue)objStateManager.Get("objSessionvalue", StateManager.State.Session); if (Request.QueryString["PhotoId"] != null) { if (int.TryParse(Request.QueryString["PhotoId"], out _photoId)) { string strOriginalImage = string.Empty; string DirBigImage = string.Empty; string imagePath = string.Empty; objPhotos.PhotoId = _photoId; objPhotos = objMisc.GetPhotoDetail(objPhotos); Tributes objTributes = objTribute = (Tributes)objStateManager.Get(PortalEnums.SessionValueEnum.TributeSession.ToString(), StateManager.State.Session); if (objTributes != null) { if (string.IsNullOrEmpty(objTributes.TributePackageType)) { _packageId = objMisc.GetTributePackageId(_tributeId); } } bool isAllowedPhotoCheck = false; string tributeEndDate = objMisc.GetTributeEndDate(_tributeId); DateTime date2 = new DateTime(); //MG:Expiry Notice DateTime dt = new DateTime(); if (!tributeEndDate.Equals("Never")) { if (tributeEndDate.Contains("/")) { string[] date = tributeEndDate.Split('/'); date2 = new DateTime(int.Parse(date[2]), int.Parse(date[0]), int.Parse(date[1])); } } isAllowedPhotoCheck = objMisc.IsAllowedPhotoCheck(_photoAlbumId); if (((_packageId == 3) || (_packageId == 6) || (_packageId == 7) || (_packageId == 8)) || ((_packageId == 5) && !isAllowedPhotoCheck && (date2 < DateTime.Now))) { if (Equals(objSessionValue, null))//when not logged in { if (IsCustomHeaderOn) topHeight = 198; else topHeight = 88; } else { if (IsCustomHeaderOn) topHeight = 261; else topHeight = 133; } if (Request.QueryString["PhotoId"] != null) { if (int.TryParse(Request.QueryString["PhotoId"], out _photoId)) Session["PhotoId"] = _photoId.ToString(); } if (WebConfig.ApplicationMode.Equals("local")) { appDomian = WebConfig.AppBaseDomain.ToString(); } else { StateManager stateManager = StateManager.Instance; Tributes objTrib = (Tributes)stateManager.Get("TributeSession", StateManager.State.Session); appDomian = "http://" + objTrib.TypeDescription.ToString().ToLower().Replace("new baby", "newbaby") + "." + WebConfig.TopLevelDomain + "/"; } ScriptManager.RegisterStartupScript(Page, this.GetType(), "awe", "fnReachLimitExpiryPopup('location.href','document.title','UpgradePhoto','" + _tributeUrl + "','" + _tributeId + "','" + appDomian + "','" + topHeight + "');", true); } else if (objTributes != null) { if (Request.QueryString["TributeUrl"] != null) _tributeUrl = Request.QueryString["TributeUrl"].ToString(); string DefaultPath = getPath[0] + "/" + getPath[1] + "/" + _tributeUrl + "_" + objTributes.TypeDescription; //DirectoryInfo objDir = new DirectoryInfo(DirBigImage); DirBigImage = "Big_" + objPhotos.PhotoImage; if (!File.Exists(Path.Combine(DefaultPath, DirBigImage))) { //show big image imagePath = getPath[2] + "/" + _tributeUrl + "_" + objTributes.TypeDescription + "/" + objPhotos.PhotoImage; Page.ClientScript.RegisterStartupScript(GetType(), "open window", "function f(){ window.open('" + imagePath + "'); return false; } f();", true); } else { //show small image imagePath = getPath[2] + "/" + _tributeUrl + "_" + objTributes.TypeDescription + "/" + DirBigImage; Page.ClientScript.RegisterStartupScript(GetType(), "open window", "function f(){ window.open('" + imagePath + "'); return false; } f();", true); } } } } }
private void showResults (Photos photos) { Console.WriteLine ("Total photos: {0}", photos.TotalPhotos); foreach (Photo photo in photos.PhotoCollection) { // Console.WriteLine ("Photo name: {0} {1} {2} {3}", photo.Title, photoURL+photo.PhotoId, photo.LargeUrl, photo.ThumbnailUrl); } }
private List<Photos> GetListOfPhotos() { List<Photos> objPhotoList = new List<Photos>(); //Get total number of uploaded files (all files are uploaded in a single package). int fileCount = Int32.Parse(Request.Form["FileCount"]); for (int i = 1; i <= fileCount; i++) { Photos objPhoto = new Photos(); string fileName = GetSafeFileName("DSC"); //Save file info. If you modify the script.js to send more fields, do not forget to //extract appropriate variables here. // set the ID to the last photo ID uploaded so that we can send the email in PhotoUploadPresenter objPhoto.PhotoId = UploadedPhotoID; objPhoto.PhotoImage = fileName; objPhoto.PhotoCaption = Request.Form["Title_" + i].ToString().Trim(); objPhoto.PhotoDesc = Request.Form["Description_" + i].ToString().Trim(); objPhoto.ModuleTypeName = MODULE_TYPE_NAME; objPhoto.UserTributeId = _tributeId; objPhoto.CreatedBy = _userId; objPhoto.CreatedDate = DateTime.Now; objPhoto.IsActive = true; objPhoto.IsDeleted = false; objPhoto.UserName = _userName; objPhoto.TributeName = _tributeName; objPhoto.TributeType = _tributeType; objPhoto.TributeUrl = _tributeUrl; objPhoto.PathToVisit = Request.ServerVariables["SERVER_NAME"] + Request.ApplicationPath; objPhotoList.Add(objPhoto); } return objPhotoList; }
protected void lBtnDownloadAlbum_Click(object sender, EventArgs e) { MiscellaneousController objMisc = new MiscellaneousController(); string[] getPath = CommonUtilities.GetPath(); StateManager objStateManager = StateManager.Instance; //to get logged in user name from session as user is logged in user objSessionValue = (SessionValue)objStateManager.Get("objSessionvalue", StateManager.State.Session); if (Request.QueryString["PhotoAlbumId"] != null) { if (int.TryParse(Request.QueryString["PhotoAlbumId"], out _photoAlbumId)) { DownloadPhotoAlbumId = _photoAlbumId; Session["PhotoAlbumId"] = _photoAlbumId.ToString(); string imagePath = string.Empty; Tributes objTributes = objTribute = (Tributes)objStateManager.Get(PortalEnums.SessionValueEnum.TributeSession.ToString(), StateManager.State.Session); if (objTributes != null) { if (string.IsNullOrEmpty(objTributes.TributePackageType)) { _packageId = objMisc.GetTributePackageId(_tributeId); } } bool isAllowedPhotoCheck = false; string tributeEndDate = objMisc.GetTributeEndDate(_tributeId); DateTime date2 = new DateTime(); //MG:Expiry Notice DateTime dt = new DateTime(); if (!tributeEndDate.Equals("Never")) { if (tributeEndDate.Contains("/")) { string[] date = tributeEndDate.Split('/'); date2 = new DateTime(int.Parse(date[2]), int.Parse(date[0]), int.Parse(date[1])); } } isAllowedPhotoCheck = objMisc.IsAllowedPhotoCheck(_photoAlbumId); if (((_packageId == 3) || (_packageId == 6) || (_packageId == 7) || (_packageId == 8)) || ((_packageId == 5) && !isAllowedPhotoCheck && (date2 < DateTime.Now))) { #region popup if (Equals(objSessionValue, null))//when not logged in { if (IsCustomHeaderOn) topHeight = 198; else topHeight = 81; } else { if (IsCustomHeaderOn) topHeight = 261; else topHeight = 133; } if (Request.QueryString["PhotoAlbumId"] != null) { if (_photoAlbumId > 0) Session["PhotoAlbumId"] = _photoAlbumId.ToString(); } if (WebConfig.ApplicationMode.Equals("local")) { appDomian = WebConfig.AppBaseDomain.ToString(); } else { StateManager stateManager = StateManager.Instance; Tributes objTrib = (Tributes)stateManager.Get("TributeSession", StateManager.State.Session); appDomian = "http://" + objTrib.TypeDescription.ToString().ToLower().Replace("new baby", "newbaby") + "." + WebConfig.TopLevelDomain + "/"; } ScriptManager.RegisterStartupScript(Page, this.GetType(), "awe", "fnReachLimitExpiryPopup('location.href','document.title','UpgradeAlbum','" + _tributeUrl + "','" + _tributeId + "','" + appDomian + "','" + topHeight + "');", true); #endregion } else { #region allowFunctionality List<Photos> objListPhotos = new List<Photos>(); Photos objPhotos = new Photos(); if (Request.QueryString["PhotoAlbumId"] != null) { int.TryParse(Request.QueryString["PhotoAlbumId"], out DownloadPhotoAlbumId); objPhotos.PhotoAlbumId = DownloadPhotoAlbumId; } objListPhotos = objMisc.GetPhotoImagesList(objPhotos); if ((DownloadPhotoAlbumId > 0) && (objListPhotos.Count > 0)) { // zip up the files try { string sTargetFolderPath = getPath[0] + "/" + getPath[1] + "/" + _tributeUrl.Replace(" ", "_") + "_" + _tributeType.Replace(" ", "_"); //to create directory for image. string galleryPath = getPath[0] + "/" + getPath[1] + "/" + getPath[6]; string sZipFileName = "Album_" + DownloadPhotoAlbumId.ToString(); string[] filenames = Directory.GetFiles(sTargetFolderPath); // Zip up the files - From SharpZipLib Demo Code using (ZipOutputStream s = new ZipOutputStream(File.Create(galleryPath + "\\" + sZipFileName + ".zip"))) { s.SetLevel(9); // 0-9, 9 being the highest level of compression byte[] buffer = new byte[4096]; foreach (Photos objPhoto in objListPhotos) { bool Foundflag = true; string ImageFile = string.Empty; string smallFile = string.Empty; ImageFile = sTargetFolderPath + "\\" + "/Big_" + objPhoto.PhotoImage; smallFile = sTargetFolderPath + "\\" + objPhoto.PhotoImage; foreach (string file in filenames) { if ((file.EndsWith("Big_" + objPhoto.PhotoImage)) && (File.Exists(ImageFile))) { Foundflag = false; //FlagsAttribute set false for small image //Code to zip ZipEntry entry = new ZipEntry(Path.GetFileName(ImageFile)); entry.DateTime = DateTime.Now; s.PutNextEntry(entry); using (FileStream fs = File.OpenRead(ImageFile)) { int sourceBytes; do { sourceBytes = fs.Read(buffer, 0, buffer.Length); s.Write(buffer, 0, sourceBytes); } while (sourceBytes > 0); } //Code to zip till here } } if (Foundflag) // if big image is not found. { foreach (string file in filenames) { if ((file.EndsWith(objPhoto.PhotoImage)) && (File.Exists(smallFile)) && (!(file.EndsWith("Big_" + objPhoto.PhotoImage)))) //(File.Exists(smallFile)) { ZipEntry entry = new ZipEntry(Path.GetFileName(file)); entry.DateTime = DateTime.Now; s.PutNextEntry(entry); using (FileStream fs = File.OpenRead(file)) { int sourceBytes; do { sourceBytes = fs.Read(buffer, 0, buffer.Length); s.Write(buffer, 0, sourceBytes); } while (sourceBytes > 0); } } } } } s.Finish(); s.Close(); } Response.ContentType = "zip"; string sfile = sZipFileName + ".zip"; Response.AppendHeader("Content-Disposition", "attachment; filename=" + sfile); Response.TransmitFile(galleryPath + "\\" + sfile); Response.End(); } catch //Exception ex) // by Ud { } } #endregion } } } }
private void GetValuesFromSession() { StateManager objStateManager = StateManager.Instance; //to get user id from session as user is logged in user objSessionValue = (SessionValue)objStateManager.Get("objSessionvalue", StateManager.State.Session); if (!Equals(objSessionValue, null)) { _userId = objSessionValue.UserId; _userName = objSessionValue.FirstName == string.Empty ? objSessionValue.UserName : (objSessionValue.FirstName + " " + objSessionValue.LastName); } //to get photo id from query string if (Request.QueryString["PhotoId"] != null) //to pick value of selected note from querystring { _photoId = int.Parse(Request.QueryString["PhotoId"].ToString()); objStateManager.Add("PhotoViewSession", _photoId, StateManager.State.Session); } else if (objStateManager.Get("PhotoViewSession", StateManager.State.Session) != null) { _photoId = int.Parse(objStateManager.Get("PhotoViewSession", StateManager.State.Session).ToString()); } objTribute = (Tributes)objStateManager.Get("TributeSession", StateManager.State.Session); pageSize = (int.Parse(WebConfig.Pagesize_Notes_Comments)); //to get current page number, if user clicks on page number in paging it gets tha page number from query string //else page number is 1 if (Request.QueryString["PageNo"] != null) currentPage = int.Parse(Request.QueryString["PageNo"].ToString()); else currentPage = 1; if (Request.QueryString["mode"] != null || Request.QueryString["fbmode"] != null) //if user is coming through link { if (Request.QueryString["TributeId"] != null) _tributeId = int.Parse(Request.QueryString["TributeId"].ToString()); if (Request.QueryString["TributeName"] != null) _tributeName = Request.QueryString["TributeName"].ToString(); if (Request.QueryString["TributeType"] != null) _tributeType = Request.QueryString["TributeType"].ToString(); if (Request.QueryString["TributeUrl"] != null) _tributeUrl = Request.QueryString["TributeUrl"].ToString(); //CreateTributeSession(); //to create the tribute session values if user comes o this page from link or from favorites list. } else if (!Equals(objTribute, null)) { _tributeId = objTribute.TributeId; _tributeName = objTribute.TributeName; _tributeType = objTribute.TypeDescription; _tributeUrl = objTribute.TributeUrl; _isActive = objTribute.IsActive; } else Response.Redirect(Redirect.RedirectToPage(Redirect.PageList.Inner2LoginPage.ToString()), false); if (Session["TributeSession"] == null) CreateTributeSession(); //to create the tribute session values if user comest o this page from link or from favorites list. objPhotoDetails = (Photos)objStateManager.Get("PhotoDetails", StateManager.State.Session); // get package id //TributePackage objpackage = new TributePackage(); //objpackage.UserTributeId = objTribute.TributeId; //object[] param = { objpackage }; //_packageId = _presenter.TriputePackageId(param); }
protected void btnupload_Click(object sender, EventArgs e) { PhotosBLL bll = new PhotosBLL(); Photos photos = new Photos(); if (photoupload.HasFile) { if (photoupload.PostedFile.ContentType.Substring(0, 5) == "image") { try { string serverPath = Server.MapPath("/image/album"); if (!Directory.Exists(serverPath)) { Directory.CreateDirectory(serverPath); } string imgName = photoupload.FileName; string newPath = serverPath + "\\" + imgName; photoupload.SaveAs(newPath); txtinfo.Text = ""; photos.P_Url = img.ImageUrl = "../image/album/" + imgName; DateTime nowadays = DateTime.Now; int y = nowadays.Year; int m = nowadays.Month; int d = nowadays.Day; int h = nowadays.Hour; int mm = nowadays.Minute; int ss = nowadays.Second; string time = y + "-" + m + "-" + d + " " + h + ":" + mm + ":" + ss; txtinfo.Text += "路径:" + photoupload.PostedFile.FileName + "\n大小:" + (photoupload.PostedFile.ContentLength / 1024.0) + "KB\n类型:" + photoupload.PostedFile.ContentType; photos.P_Info = photos_info1.Text; photos.P_UserId = Convert.ToInt32(cookieRead("id")); bll.AddPhotos(photos); tagContent4.Style["display"] = "block"; tagContent0.Style["display"] = "none"; ClientScript.RegisterStartupScript(GetType(), "", "alert('上传成功');", true); } catch (Exception) { ClientScript.RegisterStartupScript(GetType(), "", "alert('上传失败');", true); } } } else { ClientScript.RegisterStartupScript(GetType(), "", "alert('请上传图片');", true); } }
protected void BtnUploadSingle_Click(object sender, EventArgs e) { HttpPostedFile file = fNew.PostedFile; if (file != null) { String extension = Path.GetExtension(file.FileName); string fileExt = extension.ToLower(); string fileName = Path.GetFileName(file.FileName); if (fileName != string.Empty) { try { if (fileExt == ".jpg" || fileExt == ".gif" || fileExt == ".bmp" || fileExt == ".jpeg" || fileExt == ".png") { List<Photos> pList = new List<Photos>(); Photos p = new Photos(); p.Status = 1; p.UpdatedBy = emp.EmpNo; p.AltText = t11.Value; p.GalleryId = (int)ViewState["GalleryId"]; p.PictureUrl = fNew.PostedFile.FileName; int siteId = (int)ViewState["SiteId"]; String regionSite = Utility.GetImageFolder(BllMenu.GetActiveSites(new HttpContextCacheAdapter()).First(x => x.SiteId == siteId).SuperParentId); String folder = ConfigurationManager.AppSettings["PhotoGalleryPath"] + regionSite + @"/" + siteId + @"/" + p.GalleryId.ToString(CultureInfo.InvariantCulture); String folderF = folder + @"/"; file.SaveAs(Server.MapPath(folderF) + fileName); pList.Add(p); BllPhotoGallery.SetGalleryPhotoList(pList); RegisterSuccessScript(); } } catch (Exception ex) { Log.Error("Add Single Image Error: EmpNo: " + emp.EmpNo + "Exception: " + ex.Message); RegisterErrorScript(); } } } }
protected void lbtnPre_Click(object sender, EventArgs e) { try { StateManager stateManager = StateManager.Instance; objPhotoDetails = (Photos)stateManager.Get("PhotoDetails", StateManager.State.Session); if (objPhotoDetails == null) { this._presenter.GetPhotoDetails(); objPhotoDetails = (Photos)stateManager.Get("PhotoDetails", StateManager.State.Session); } int prevPhotoId = int.Parse(objPhotoDetails.PrevRecordCount.ToString()); //to get the previous photo id to be displayed Response.Redirect("~/" + Session["TributeURL"] + "/photo.aspx" + "?PhotoId=" + prevPhotoId, false); //Redirect.RedirectToPage(Redirect.PageList.PhotoView.ToString()) } catch (Exception ex) { throw ex; } }
protected void BtnUpload_Click(object sender, EventArgs e) { div5.Visible = true; Gallery g = new Gallery(); g.SiteId = Convert.ToInt32(dSites.SelectedValue); g.GalleryName = tGalleryName.Text.Trim(); g.Status = 1; g.UpdatedBy = emp.EmpNo; g.IsDefault = chkMakeDefault.Checked; HttpFileCollection uploadFilCol = Request.Files; bool containsFile = false; for (int i = 0; i < uploadFilCol.Count; i++) { HttpPostedFile file = uploadFilCol[i]; string fileName = Path.GetFileName(file.FileName); if (fileName != string.Empty) { containsFile = true; break; } } if (!containsFile) return; int galleryId = BllPhotoGallery.SetPhotoGallery(g); List<Photos> pList = new List<Photos>(); String regionSite = Utility.GetImageFolder( BllMenu.GetActiveSites(new HttpContextCacheAdapter()).First(x => x.SiteId == g.SiteId).SuperParentId); String folder = ConfigurationManager.AppSettings["PhotoGalleryPath"] + regionSite + @"/" + g.SiteId + @"/" + galleryId.ToString(CultureInfo.InvariantCulture); String folderF = folder + @"/"; bool isExists = Directory.Exists(Server.MapPath(folder)); if (!isExists) Directory.CreateDirectory(Server.MapPath(folder)); for (int i = 0; i < uploadFilCol.Count; i++) { HttpPostedFile file = uploadFilCol[i]; string fileExt = Path.GetExtension(file.FileName).ToLower(); string fileName = Path.GetFileName(file.FileName); if (fileName != string.Empty) { try { if (fileExt == ".jpg" || fileExt == ".gif" || fileExt == ".bmp" || fileExt == ".jpeg" || fileExt == ".png") { file.SaveAs(Server.MapPath(folderF) + fileName); Photos p = new Photos(); p.GalleryId = galleryId; p.PictureUrl = fileName; p.UpdatedBy = emp.EmpNo; p.Status = 1; if (i == 0) { Image1.ImageUrl = folderF + fileName; p.AltText = t1.Value; } if (i == 1) { Image2.ImageUrl = folderF + fileName; p.AltText = t2.Value; } if (i == 2) { Image3.ImageUrl = folderF + fileName; p.AltText = t3.Value; } if (i == 3) { Image4.ImageUrl = folderF + fileName; p.AltText = t4.Value; } if (i == 4) { Image5.ImageUrl = folderF + fileName; p.AltText = t5.Value; } if (i == 5) { Image6.ImageUrl = folderF + fileName; p.AltText = t6.Value; } if (i == 6) { Image7.ImageUrl = folderF + fileName; p.AltText = t7.Value; } if (i == 7) { Image8.ImageUrl = folderF + fileName; p.AltText = t8.Value; } if (i == 8) { Image9.ImageUrl = folderF + fileName; p.AltText = t9.Value; } if (i == 9) { Image10.ImageUrl = folderF + fileName; p.AltText = t10.Value; } pList.Add(p); } } catch (Exception ex) { Log.Error("Add Gallery: Error in Image Upload EmpNo: " + emp.EmpNo + " : " + ex.Message + " : " + ex.TargetSite + " : " + ex.StackTrace); RegisterErrorScript(); } } } try { BllPhotoGallery.SetGalleryPhotoList(pList); RegisterSuccessScript(); } catch (Exception ex) { BllPhotoGallery.RemovePhotoGallery(g.GalleryId); RegisterErrorScript(); } }
protected void lbtnCreateAlbum_Click(object sender, EventArgs e) { string[] imageNames; if (Session["ImageUploaded"] != null) { string images = Session["ImageUploaded"].ToString(); imageNames = images.Split(','); } else { imageNames = new string[2]; } try { #region SaveImage objListPhoto = new List<Photos>(); Photos objPhoto = new Photos(); if (Session["PhotoAlbumId"] != null) { int.TryParse(Session["PhotoAlbumId"].ToString(), out _photoAlbumId); PhotoAlbumID = _photoAlbumId; } if (HttpContext.Current.Session["FileCount"] != null && HttpContext.Current.Session["FileCount"] != "") { int.TryParse(HttpContext.Current.Session["FileCount"].ToString(), out filecount); HttpContext.Current.Session["FileCount"] = null; } if (PhotoAlbumID == 0) { _photoAlbumName = txtAlbumName.Text; _presenter.CreateAlbum(); AddPhotoEmail = false; } if (PhotoAlbumID > 0) { foreach (var imageFileName in imageNames) { #region MyRegion string[] desc = imageFileName.Split(':'); string imageName = desc[0]; string photoComment = string.Empty; for (int count = 1; count < desc.Length; count++) { photoComment += " : " + desc[count]; } if (!string.IsNullOrEmpty(imageName)) { //thumbnailNames[i] = thumbnailName; //to get tribute id and name from session if (Session["PhotoAlbumTributeSession"] != null) { objTribute = Session["PhotoAlbumTributeSession"] as Tributes; } if (objTribute != null) { if (objTribute.TributeId > 0) { _tributeId = objTribute.TributeId; _tributeName = objTribute.TributeName; _tributeType = objTribute.TypeDescription; _tributeUrl = objTribute.TributeUrl; } } // set the ID to the last photo ID uploaded so that we can send the email in PhotoUploadPresenter objPhoto.PhotoImage = imageName; objPhoto.PhotoId = UploadedPhotoID; if (objPhoto.PhotoCaption == null) objPhoto.PhotoCaption = string.Empty; objPhoto.PhotoDesc = replaceSpecialCharacter(photoComment); objPhoto.ModuleTypeName = MODULE_TYPE_NAME; objPhoto.UserTributeId = _tributeId; objPhoto.CreatedBy = _userId; objPhoto.CreatedDate = DateTime.Now; objPhoto.IsActive = true; objPhoto.IsDeleted = false; objPhoto.UserName = _userName; objPhoto.TributeName = _tributeName; objPhoto.TributeType = _tributeType; objPhoto.TributeUrl = _tributeUrl; objPhoto.PathToVisit = Request.ServerVariables["SERVER_NAME"] + Request.ApplicationPath; objPhoto.PhotoAlbumId = PhotoAlbumID; _presenter.SaveImageList(objPhoto, AddPhotoEmail); filecount--; if (filecount == 0) { Session["PhotoAlbumId"] = null; Session["PhotoAlbumName"] = null; if (WebConfig.ApplicationMode.Equals("local")) Session["PhotoAlbumTributeSession"] = null; Session["PhotoAlbumobjUserInfo"] = null; } if (UploadedPhotoID > 0) { AddPhotoEmail = false; } // Added by rupendra on June 20, 2011 to redirect on album aftwer updating the page if (Request.QueryString["photoAlbumId"] != null) { _photoAlbumId = 0; int.TryParse(Request.QueryString["photoAlbumId"], out _photoAlbumId); if (PhotoAlbumId > 0) Session["PhotoAlbumID2"] = _photoAlbumId; } } #endregion } } if (_mode == PAGE_MODE_ADD_PHOTOS) { Response.Redirect("~/" + Session["TributeURL"] + "/photoalbum.aspx?photoAlbumId=" + _photoAlbumId, false); } else { Response.Redirect("~/" + Session["TributeURL"] + "/photos.aspx", false); } #endregion } catch (Exception ex) { LogError(ex.Message, ex.StackTrace); if (ex.Message.Contains("The process cannot access the file")) { if (_mode == PAGE_MODE_ADD_PHOTOS) { Response.Redirect("~/" + Session["TributeURL"] + "/photoalbum.aspx?photoAlbumId=" + _photoAlbumId, false); } else { Response.Redirect("~/" + Session["TributeURL"] + "/photos.aspx", false); } } } }
/// <summary> /// Method to fill the Photos object to get the details of photo album /// </summary> /// <returns>Filled Photos entity</returns> private Photos GetPhotoObject() { Photos objPhoto = new Photos(); objPhoto.PhotoAlbumId = photoAlbumId; objPhoto.PageNumber = currentPage; objPhoto.PageSize = pageSize; objPhoto.SortOrder = "asc"; return objPhoto; }
public string GetAvatarPath() { return("~/" + (Photos.Count == 0 ? Media.DefaultAvatarPath : Photos.First().GetPath())); }
protected void AlbumPhotoAdditionFacebookWallPost() { string tributeHome; string photoAlbumUrl; string photoUrlBase; if (TributesPortal.Utilities.WebConfig.ApplicationMode.Equals("local")) { tributeHome = Session["APP_PATH"] + _tributeUrl; } else { tributeHome = "http://" + _tributeType.Replace("New Baby", "newbaby").ToLower() + "." + WebConfig.TopLevelDomain + "/" + _tributeUrl; } tributeHome += "/"; photoAlbumUrl = tributeHome + "photoalbum.aspx"; photoUrlBase = tributeHome + "photo.aspx"; string query_string = string.Empty; if (TributesPortal.Utilities.WebConfig.ApplicationMode.Equals("local")) { query_string = "?TributeType=" + HttpUtility.UrlEncode(_tributeType); photoAlbumUrl = photoAlbumUrl + query_string; tributeHome = tributeHome + query_string; photoUrlBase = photoUrlBase + query_string; } aTributeHome.HRef = tributeHome; StateManager objStateManager = StateManager.Instance; if (Request.QueryString["post_on_facebook"] != null) { if (Request.QueryString["post_on_facebook"].ToString().Equals("True")) { int _newPhotoAlbumID = _photoAlbumID; if (objStateManager.Get("NewPhotoAlbumId", StateManager.State.Session) != null) { _newPhotoAlbumID = int.Parse(objStateManager.Get("NewPhotoAlbumId", StateManager.State.Session).ToString()); } Photos objPhoto = new Photos(); objPhoto.PhotoAlbumId = _newPhotoAlbumID; objPhoto.PageNumber = 1; objPhoto.PageSize = 3; objPhoto.SortOrder = "desc"; PhotoAlbum objAlbumDetails = null; PhotoManager mgr = new PhotoManager(); objAlbumDetails = mgr.GetPhotoAlbumDetail(objPhoto); string[] getPath = CommonUtilities.GetPath(); List<Photos> objPhotoList = mgr.GetPhotos(objPhoto); photoAlbumUrl += (photoAlbumUrl.Contains("?") ? "&" : "?") + "PhotoAlbumId=" + _newPhotoAlbumID.ToString(); StringBuilder sb = new StringBuilder(); sb.Append("<script type=\"text/javascript\">\n"); sb.Append("$(document).addEvent('fb_connected', function() {\n"); sb.Append(" var attachments = {\n"); sb.Append(" name: '"); sb.Append(string.Format("{0} added photos to the: {1} {2} Tribute", _userName, _tributeName, _tributeType)); sb.Append("',\n"); sb.Append(" href: '"); sb.Append(photoAlbumUrl); sb.Append("',\n"); sb.Append(" caption: '<b>Website:</b> "); sb.Append(tributeHome); sb.Append("',\n"); sb.Append(" description: '<b>Photo Album:</b> "); sb.Append(objAlbumDetails.PhotoAlbumCaption); sb.Append("',\n"); sb.Append(" media: [\n"); foreach (Photos obj in objPhotoList) { if (_tributeType != null) { // in my Common\\XML\\PhotoConfiguration.xml file getPath[2] already ends with '/' obj.PhotoImage = getPath[2] + getPath[3] + "/" + _tributeUrl.Replace(" ", "_") + "_" + _tributeType.Replace(" ", "_") + "/" + obj.PhotoImage; string photoUrl = photoUrlBase + (photoUrlBase.Contains("?") ? "&" : "?") + "PhotoId=" + obj.PhotoId.ToString(); sb.Append("{type: 'image', href: '"); sb.Append(photoUrl); sb.Append("', src: '"); sb.Append(obj.PhotoImage); sb.Append("'}"); sb.Append(","); } } if (objPhotoList.Count > 0) { sb.Remove(sb.Length - 1, 1); } sb.Append(" ]\n"); sb.Append(" };\n"); sb.Append(" var action_link = [{\n"); sb.Append(" text: '"); sb.Append(string.Format("Visit {0} Tribute", _tributeType)); sb.Append("',\n"); sb.Append(" href: '"); sb.Append(photoAlbumUrl); sb.Append("'\n"); sb.Append(" }]\n"); sb.Append(" publish_stream('', attachments, action_link, null, null, function() {});"); sb.Append("});\n"); sb.Append("</script>"); ClientScript.RegisterStartupScript(GetType(), "facebook_wall_post", sb.ToString()); } } }
public Image GetImage(int minX, int minY) { Image image = null; while (image == null) { try { if (photos == null || index >= photos.PhotoCollection.Length) { if (photos == null || photos.TotalPhotos == 0 || photos.PageNumber >= photos.TotalPages - 1) { page = 0; } else { ++page; } PhotoSearchOptions op = new PhotoSearchOptions(); op.SortOrder = PhotoSearchSortOrder.DatePostedDesc; op.Page = page; op.PerPage = 100; if (!String.IsNullOrEmpty(tags)) { op.Tags = tags; } op.TagMode = tagsAndLogic ? TagMode.AllTags : TagMode.AnyTag; if (!String.IsNullOrEmpty(userId)) { op.UserId = userId; } if (!String.IsNullOrEmpty(text)) { op.Text = text; } if (String.IsNullOrEmpty(tags) && String.IsNullOrEmpty(userId) && String.IsNullOrEmpty(text)) { op.MinUploadDate = DateTime.Now - TimeSpan.FromDays(10); op.MaxUploadDate = DateTime.Now - TimeSpan.FromHours(1); } photos = f.PhotosSearch(op); if (photos.TotalPhotos == 0) { if (tagsAndLogic) { tagsAndLogic = false; } else if (!String.IsNullOrEmpty(tags)) { tags = null; } else if (!String.IsNullOrEmpty(text)) { text = null; } else if (!String.IsNullOrEmpty(userId)) { userId = null; } else { throw new ImageSourceFailedException("Flickr search returned no images"); } continue; } index = 0; } // choose the smallest photo larger than the requested size Photo photo = photos.PhotoCollection[index++]; FlickrNet.Size[] sizes = f.PhotosGetSizes(photo.PhotoId).SizeCollection; String url = null; for (int i = sizes.Length - 1; i >= 0; --i) { FlickrNet.Size s = sizes[i]; if (!crop && s.Label == "Square") { continue; } if (s.Width >= minX && s.Height >= minY) { url = s.Source; } } if (url == null) { continue; // nothing large enough } image = Image.FromStream(f.DownloadPicture(url)); } catch (Exception ex) { if (++errorCount <= MaxErrorCount) { Log.Instance.Write(string.Format("Failure {0} of {1} loading Flickr photo(s)", errorCount, MaxErrorCount), ex); // try next photo } else { throw new ImageSourceFailedException("Maximum error count reached, failing Flickr image source", ex); } } } errorCount = 0; return(image); }
protected void Page_Load(object sender, EventArgs e) { try { if (Master != null) { HtmlGenericControl currdiv = (HtmlGenericControl)Master.FindControl("divContentSecondary"); currdiv.Style.Add("display", "none"); HtmlGenericControl containerDiv = (HtmlGenericControl)Master.FindControl("cotentPrimaryContainer"); containerDiv.Style.Add("margin-left", "-223px"); } Ajax.Utility.RegisterTypeForAjax(typeof(Photo_ManagePhotoAlbum)); GetPhotoSessionValues(); CreatePath(); var fbWebContext = FacebookWebContext.Current; if (FacebookWebContext.Current.Session != null) { Session["facebookflag"] = "true"; } else { Session["facebookflag"] = "false"; } //Set the Photo Upload Key into the Hidden field hdnPhotoUploaderKey.Value = WebConfig.PhotoUploaderKey; // To Retain last value of text box by UD GetSessionValues(); this._presenter.GetPhotoAlbumList(); if (!this.IsPostBack) { Session["ImageUploaded"] = null; lbtnSavePhoto.Text = "Update photo album"; /* Made sessions to retain the value of albumid & albumname by Ashu ---*/ if (Request.QueryString["albummode"] != null) { if (Request.QueryString["albummode"].ToString() == "Create") { Session["PhotoAlbumId"] = null; Session["PhotoAlbumName"] = null; //HttpContext.Current.Session["AlbumName"] = null; //HttpContext.Current.Session["AlbumDesc"] = null; lbtnSavePhoto.Text = "Create photo album"; } } if (Request.QueryString["photoAlbumId"] != null) { _photoAlbumId = 0; int.TryParse(Request.QueryString["photoAlbumId"], out _photoAlbumId); Session["PhotoAlbumId"] = _photoAlbumId.ToString(); StateManager objStateManager = StateManager.Instance; if (objStateManager.Get("PhotoAlbumName", StateManager.State.Session) != null) Session["PhotoAlbumName"] = objStateManager.Get("PhotoAlbumName", StateManager.State.Session).ToString(); else { Photos objPhotos = new Photos(); objPhotos.PhotoAlbumId = _photoAlbumId; Session["PhotoAlbumName"] = _presenter.GetPhotoAlbumDetails(objPhotos); } } /*--------------------------------*/ AddPhotoEmail = true; SetControlsVisibility(); SetValuesToControls(); if (_mode == PAGE_MODE_ADD_PHOTOS) this._presenter.GetPhotoCount(); else hdnAlbumId.Value = string.Empty; } //if (HttpContext.Current.Session["AlbumName"] != null || HttpContext.Current.Session["AlbumDesc"] != null) //{ // txtAlbumName.Text = HttpContext.Current.Session["AlbumName"].ToString(); // txtAlbumDesc.Text = HttpContext.Current.Session["AlbumDesc"].ToString(); //} UserIsAdminOrOwner(); //to set the visibility of options in side menu. Page.SetFocus(txtAlbumName); } catch (Exception ex) { throw ex; } }