internal UserPhotoLocalQuery(ClientContext clientContext, DateTime deadline, PhotoRequest photoRequest, PhotosConfiguration configuration, ITracer upstreamTracer) : base(clientContext, deadline) { this.photoRequest = photoRequest; this.tracer = ExTraceGlobals.UserPhotosTracer.Compose(upstreamTracer); this.upstreamTracer = upstreamTracer; this.photosConfiguration = configuration; }
private void InternalUploadPhoto() { PhotoUploadPipeline photoUploadPipeline = new PhotoUploadPipeline(new PhotosConfiguration(ExchangeSetupContext.InstallPath), this.mailboxSession, this.adSession, GroupMailboxDefaultPhotoUploader.Tracer); string text = this.group.DisplayName; if (string.IsNullOrWhiteSpace(text)) { text = this.group.Name; } using (Stream stream = InitialsImageGenerator.GenerateAsStream(text, 1024)) { PhotoRequest request = new PhotoRequest { TargetPrimarySmtpAddress = this.group.PrimarySmtpAddress.ToString(), UploadTo = this.group.ObjectId, Preview = true, RawUploadedPhoto = stream, UploadCommand = UploadCommand.Upload }; photoUploadPipeline.Upload(request, Stream.Null); request = new PhotoRequest { TargetPrimarySmtpAddress = this.group.PrimarySmtpAddress.ToString(), UploadTo = this.group.ObjectId, Preview = false, UploadCommand = UploadCommand.Upload }; photoUploadPipeline.Upload(request, Stream.Null); } }
protected override void InternalProcessRecord() { TaskLogger.LogEnter(); try { ExchangePrincipal exchangePrincipal = ExchangePrincipal.FromADUser(this.DataObject, null); using (MailboxSession mailboxSession = MailboxSession.OpenAsAdmin(exchangePrincipal, CultureInfo.InvariantCulture, "Client=Management;Action=Set-UserPhoto")) { PhotoRequest request = this.CreateRequest(exchangePrincipal); PhotoUploadPipeline photoUploadPipeline = new PhotoUploadPipeline(SetUserPhoto.PhotosConfiguration, mailboxSession, (IRecipientSession)base.DataSession, this.tracer); photoUploadPipeline.Upload(request, Stream.Null); if (!this.Save && !this.Cancel && !this.Preview) { photoUploadPipeline.Upload(this.CreateSavePreviewRequest(exchangePrincipal), Stream.Null); } } } catch (WrongServerException ex) { this.LogFailedToUploadPhotoEvent(ex); this.WriteError(new CannotModifyPhotoBecauseMailboxIsInTransitException(ex), ExchangeErrorCategory.ServerTransient, this.DataObject, true); } catch (Exception e) { this.LogFailedToUploadPhotoEvent(e); throw; } finally { this.tracer.Dump(new PhotoRequestLogWriter(SetUserPhoto.RequestLog, SetUserPhoto.GenerateRequestId())); } TaskLogger.LogExit(); }
public IHttpActionResult SetFoto(PhotoRequest people) { db.Configuration.ProxyCreationEnabled = false; var pessoa = db.pessoas.Find(people.Id); if (pessoa == null) { return(BadRequest("A pessoa não existe")); } var stream = new MemoryStream(people.Array); var folder = "~/Content/Imagens"; var file = string.Format("{0}.jpg", people.Id); var fullPath = string.Format("{0}/{1}", folder, file); var response = FileHelpers.UploadPhoto(stream, folder, file); if (!response) { return(BadRequest("Foto não enviada")); } pessoa.Imagem = fullPath.Replace("~", ""); db.Entry(pessoa).State = EntityState.Modified; db.Entry(pessoa.Chamada).State = EntityState.Modified; db.SaveChanges(); return(Ok("foto enviada")); }
private PhotoResponse ServePhotoWhenClientDisconnected(PhotoRequest request, PhotoResponse response) { response.Served = true; response.Status = HttpStatusCode.InternalServerError; request.PerformanceLogger.Log("RemoteForestHandlerServed", string.Empty, 1U); return(response); }
private PhotoResponse RespondWithAccessDenied(PhotoRequest request, PhotoResponse response) { response.Served = true; response.Status = HttpStatusCode.Forbidden; request.PerformanceLogger.Log("RemoteForestHandlerServed", string.Empty, 1U); return(response); }
internal async Task <bool> SetPhoto(int idPessoa, Stream stream) { try { var array = ReadFully(stream); var photoRequest = new PhotoRequest { Id = idPessoa, Array = array, }; var request = JsonConvert.SerializeObject(photoRequest); var body = new StringContent(request, Encoding.UTF8, "application/json"); var client = new HttpClient(); var urlSetfoto = "SetFoto"; var response = await client.PostAsync(URL + urlSetfoto, body); if (!response.IsSuccessStatusCode) { return(false); } return(true); } catch { return(false); } }
private static int AddPhoto(string path, int userId) { using (var client = new HttpClient()) { PhotoRequest photo = new PhotoRequest() { UserId = userId, Date = DateTime.Today, Image = ReadImageFromFile(path) }; string jsonString = JsonConvert.SerializeObject(photo); var request = new HttpRequestMessage { Method = HttpMethod.Post, RequestUri = new Uri(UriBasePhotos + "AddPhoto"), Content = new StringContent(jsonString, Encoding.UTF8, "application/json") }; var response = client.SendAsync(request); Console.WriteLine(response.Result.StatusCode); string str = response.Result.Content.ReadAsStringAsync().GetAwaiter().GetResult(); return(int.Parse(str)); } }
public UserPhotoApplication(PhotoRequest photoRequest, PhotosConfiguration configuration, bool traceRequest, ITracer upstreamTracer) : base(false) { this.photoRequest = photoRequest; this.photosConfiguration = configuration; this.traceRequest = traceRequest; this.upstreamTracer = upstreamTracer; this.tracer = ExTraceGlobals.UserPhotosTracer.Compose(upstreamTracer); }
private PhotoResponse RespondWithErrorBecauseQueryReturnedInvalidStatusCode(PhotoRequest request, PhotoResponse response) { this.tracer.TraceError((long)this.GetHashCode(), "REMOTE FOREST HANDLER: HTTP status code in query is invalid. Overwriting with InternalServerError."); request.PerformanceLogger.Log("RemoteForestHandlerError", string.Empty, 1U); response.Served = false; response.Status = HttpStatusCode.InternalServerError; return(response); }
public IAsyncResult BeginGetUserPhoto(PhotoRequest request, PhotosConfiguration configuration, AsyncCallback callback, object asyncState) { ArgumentValidator.ThrowIfNull("request", request); ArgumentValidator.ThrowIfNull("configuration", configuration); HttpWebRequest request2 = new HttpPhotoRequestBuilder(configuration, this.tracer).Build(this.targetUri, request, new PhotoRequestOutboundWebProxyProviderUsingLocalServerConfiguration(this.tracer), this.traceRequest); this.httpPhotoRequest = this.ConfigureRequest(request2); return(this.AuthenticateAndBeginInvoke(this.httpPhotoRequest, () => this.httpPhotoRequest.BeginGetResponse(callback, asyncState))); }
public ActionResult Photo(HttpPostedFileBase file) { var request = new PhotoRequest(file.InputStream, "image/png", null); var photo = PhotoManager.Provider.SavePhotoForAllSizes(request, true); _userService.SetProfilePicture(UserProfile.Current.Tenant, UserProfile.Current.Username, photo[0].Id); return(View()); }
public ActionResult Photo(HttpPostedFileBase file) { var request = new PhotoRequest(file.InputStream, "image/png", null); var photo = PhotoManager.Provider.SavePhotoForAllSizes(request, true); _userService.SetProfilePicture(UserProfile.Current.Tenant, UserProfile.Current.Username, photo[0].Id); return View(); }
public GetUserPhotoQuery(ClientContext clientContext, PhotoRequest photoRequest, HttpResponse httpResponse, bool isRequestFromExternalOrganization, PhotosConfiguration configuration, ITracer upstreamTracer) : base(clientContext, httpResponse, CasTraceEventType.Ews, UserPhotoApplication.UserPhotoIOCompletion, UserPhotosPerfCounters.UserPhotosCurrentRequests) { ArgumentValidator.ThrowIfNull("photoRequest", photoRequest); ArgumentValidator.ThrowIfNull("configuration", configuration); this.tracer = ExTraceGlobals.UserPhotosTracer.Compose(upstreamTracer); this.upstreamTracer = upstreamTracer; this.photoRequest = photoRequest; this.isRequestFromExternalOrganization = isRequestFromExternalOrganization; this.photosConfiguration = configuration; }
public IActionResult AddPhoto([FromBody] PhotoRequest request) { var result = _photoService.AddPhoto(request); if (String.IsNullOrEmpty(result.Error)) { return(Ok(result.Id)); } return(BadRequest(result.Error)); }
public override async Task SayHello(PhotoRequest request, IServerStreamWriter <PhotoReply> responseStream, ServerCallContext context) { var path = Path.Combine("Assets", "image.png"); using (FileStream file = new FileStream(path, FileMode.Open, System.IO.FileAccess.Read)) { PhotoReply reply = new PhotoReply(); reply.Message = await Google.Protobuf.ByteString.FromStreamAsync(file, context.CancellationToken); await responseStream.WriteAsync(reply); } }
public IAsyncResult BeginGetUserPhoto(PhotoRequest request, PhotosConfiguration configuration, AsyncCallback callback, object asyncState) { base.HttpHeaders.Add("If-None-Match", request.ETag); if (this.traceRequest) { PhotosDiagnostics.Instance.StampGetUserPhotoTraceEnabledHeaders(base.HttpHeaders); } return(base.BeginInvoke("GetUserPhoto", new GetUserPhotoRequestType[] { Service.ConvertPhotoRequestToGetUserPhotoRequestType(request) }, callback, asyncState)); }
// Token: 0x06001B73 RID: 7027 RVA: 0x00068B1C File Offset: 0x00066D1C protected override UploadPhotoResponse InternalExecute() { PhotoRequest request = new PhotoRequest { TargetPrimarySmtpAddress = base.CallContext.AccessingPrincipal.MailboxInfo.PrimarySmtpAddress.ToString(), UploadTo = base.CallContext.AccessingPrincipal.ObjectId, Preview = true, UploadCommand = UploadCommand.Upload, RawUploadedPhoto = this.fileStream }; new PhotoUploadPipeline(UploadPhotoFromForm.PhotosConfiguration, base.MailboxIdentityMailboxSession, base.CallContext.ADRecipientSessionContext.GetADRecipientSession(), ExTraceGlobals.UserPhotosTracer).Upload(request, Stream.Null); return(new UploadPhotoResponse()); }
public async Task <Request> Add(RequestContract contract) { if (contract == null) { return(null); } var requestId = Guid.NewGuid(); var request = new Request { Id = requestId, ArtObjectCreationDate = contract.ArtObjectCreationDate, ArtObjectDescription = contract.ArtObjectDescription, ArtObjectId = contract.ArtObjectId, ArtObjectLatitude = contract.ArtObjectLatitude, ArtObjectLongitude = contract.ArtObjectLongitude, ArtObjectName = contract.ArtObjectName, ArtObjectType = contract.ArtObjectType, Date = contract.Date, Reason = contract.Reason, RequestType = contract.RequestType, RequestStatus = (int)RequestStatus.Active, UserId = contract.UserId }; var photoRequests = new List <PhotoRequest>(); var photoRequestContracts = contract.PhotoRequest ?? new List <PhotoRequestContract>(); foreach (var photoRequestContract in photoRequestContracts) { var photoRequest = new PhotoRequest { Id = Guid.NewGuid(), RequestId = requestId, PhotoId = photoRequestContract.PhotoId, PhotoPath = photoRequestContract.PhotoPath, PhotoRequestType = photoRequestContract.PhotoRequestType }; photoRequests.Add(photoRequest); } await context.Request.AddAsync(request); await context.PhotoRequest.AddRangeAsync(photoRequests); await context.SaveChangesAsync(); return(await context.Request.FirstOrDefaultAsync(x => x.Id == request.Id)); }
public (int Id, string Error) AddPhoto(PhotoRequest photo) { try { _context.Photos.Add(new Photo { DateCreated = photo.Date, ImageSource = photo.Image, UserId = photo.UserId }); _context.SaveChanges(); return(_context.Photos.ToList().Last().Id, null); } catch (Exception e) { return(-1, e.Message); } }
public async Task <bool> EnviarFoto(PhotoRequest photoRequest) { var request = JsonConvert.SerializeObject(photoRequest); var body = new StringContent(request, Encoding.UTF8, "application/json"); var client = new HttpClient(); var urlSetfoto = "SetFoto"; var response = await client.PostAsync("http://www.igrejadeusbom.somee.com/" + urlSetfoto, body); if (!response.IsSuccessStatusCode) { return(false); } return(true); }
public async Task <Response> SetFirmaAsync(int multaId, Stream stream) { try { var array = ReadFully(stream); var photoRequest = new PhotoRequest { Id = multaId, Array = array, }; var request = JsonConvert.SerializeObject(photoRequest); var body = new StringContent(request, Encoding.UTF8, "application/json"); var client = new HttpClient(); client.BaseAddress = new Uri(URL_ws); var url = "simed/api/Informes/Subir"; var response = await client.PostAsync(url, body); if (!response.IsSuccessStatusCode) { return(new Response { IsSuccess = false, Message = response.StatusCode.ToString(), }); } var result = await response.Content.ReadAsStringAsync(); var imagen = JsonConvert.DeserializeObject <Response>(result); return(new Response { IsSuccess = true, Message = imagen.Message, }); } catch (Exception ex) { return(new Response { IsSuccess = false, Message = ex.Message, }); } }
protected override UploadPhotoResponse InternalExecute() { DisposeGuard disposeGuard = default(DisposeGuard); Action action = null; ExchangePrincipal exchangePrincipal; MailboxSession mailboxSession; if (this.IsRequestForCurrentUser()) { exchangePrincipal = base.CallContext.AccessingPrincipal; mailboxSession = base.CallContext.SessionCache.GetMailboxSessionBySmtpAddress(this.uploadPhotoRequest.EmailAddress); } else { ProxyAddress proxyAddress = ProxyAddress.Parse(this.uploadPhotoRequest.EmailAddress); ADUser groupAdUser = this.adRecipientSession.FindByProxyAddress(proxyAddress) as ADUser; if (groupAdUser == null) { throw FaultExceptionUtilities.CreateFault(new OwaInvalidRequestException(), FaultParty.Sender); } if (groupAdUser.RecipientTypeDetails != RecipientTypeDetails.GroupMailbox || !this.IsOwnedModernGroup(groupAdUser)) { OwaInvalidOperationException exception = new OwaInvalidOperationException(string.Format("User does not have sufficient privileges on {0}", this.uploadPhotoRequest.EmailAddress)); throw FaultExceptionUtilities.CreateFault(exception, FaultParty.Sender); } if (groupAdUser.IsCached) { this.adRecipientSession = DirectorySessionFactory.Default.GetTenantOrRootOrgRecipientSession(groupAdUser.OriginatingServer, false, ConsistencyMode.IgnoreInvalid, this.adRecipientSession.SessionSettings, 102, "InternalExecute", "f:\\15.00.1497\\sources\\dev\\clients\\src\\Owa2\\Server\\Core\\ServiceCommands\\UploadPhoto.cs"); } exchangePrincipal = ExchangePrincipal.FromADUser(groupAdUser, null); mailboxSession = MailboxSession.OpenAsAdmin(exchangePrincipal, base.CallContext.ClientCulture, "Client=OWA;Action=GroupPhotoUpload"); action = delegate() { DirectorySessionFactory.Default.GetTenantOrRootRecipientReadOnlySession(this.adRecipientSession, groupAdUser.OriginatingServer, 125, "InternalExecute", "f:\\15.00.1497\\sources\\dev\\clients\\src\\Owa2\\Server\\Core\\ServiceCommands\\UploadPhoto.cs").FindByProxyAddress(proxyAddress); }; disposeGuard.Add <MailboxSession>(mailboxSession); } using (disposeGuard) { PhotoRequest request = this.CreateRequest(exchangePrincipal); new PhotoUploadPipeline(UploadPhoto.PhotosConfiguration, mailboxSession, this.adRecipientSession, ExTraceGlobals.UserPhotosTracer).Upload(request, Stream.Null); if (action != null) { action(); } } return(new UploadPhotoResponse()); }
public ActionResult Photo(HttpPostedFileBase file) { var request = new PhotoRequest(file.InputStream, "image/png", null); var photo = PhotoManager.Provider.SavePhotoForAllSizes(request, true); var user = UserProfile.Current; user.PhotoId = photo[0].Id; if (ModelState.Process(_userService.SaveOrUpdate(user))) { TempData.AddSuccessMessage("Profile photo was successfully updated"); return RedirectToAction("Photo"); } return View(); }
public IActionResult UploadPhotoAndStartSession([FromBody] PhotoRequest photoRequest, [FromServices] UserManager <ApplicationUser> userManager, [FromServices] SessionTracker sessionTracker, [FromServices] IImageDecryptor imageDecryptor, [FromServices] RecognitionTaskQueue taskQueue, [FromServices] IConfiguration configuration, [FromServices] AnalyticsAgent agent) { using (_logger.BeginScope(nameof(UploadPhotoAndStartSession))) { //validate request if (photoRequest == null) { _logger.LogError("Attempt to start a session because of null mobile photo request."); return(BadRequest(new { message = "Error: something in your request is empty" })); } try { //try start new session var session = sessionTracker.StartSession(Convert.ToInt32(userManager.GetUserId(HttpContext.User)), photoRequest.TimeStamp); //decrypt image and send to db _logger.LogInformation($"Trying decrypt image..."); var decrypredImage = imageDecryptor.Decrypt(Convert.FromBase64String(photoRequest.Image)); var image = new Photo(session.SessionID, decrypredImage, photoRequest.TimeStamp); _photoRepository.Add(image); _logger.LogInformation($"Ecrypted image was decrypted and saved to db."); //send to analytics task queue _logger.LogInformation($"Trying send photoId to RecognitionTaskQueue"); string modelName = configuration.GetSection("ModelName").Value; // get model name for analytics taskQueue.Enqueue(new RecognitionTask(modelName, image.PhotoID)); _logger.LogInformation("Photo was sent to RecognitionTaskQueue"); var sessionResponse = new SessionResponse(session.SessionID); return(Ok(sessionResponse)); } catch (Exception ex) { _logger.LogError("Exception caught: {0}, {1}", ex.Message, ex.StackTrace); return(StatusCode(409, new { message = ex.Message })); } } }
public static PhotoModerationStatus GetPhotoModerationStatus(PluckConfigElement pluckConfig, string photoKey) { var pluckService = new PluckService(pluckConfig.apiUrl); var authToken = new UserAuthenticationToken(pluckConfig.userKey, pluckConfig.userNickname, pluckConfig.userEmail, pluckConfig.sharedSecret); var requests = new RequestBatch(); var photorequest = new PhotoRequest { PhotoKey = new PhotoKey { Key = photoKey } }; requests.AddRequest(photorequest); ResponseBatch responseBatch = pluckService.SendRequest(requests, authToken); var photo = (PhotoResponse)responseBatch.Envelopes[0].GetResponse(); return(DetermineModerationStatus(photo)); }
public async Task <Response> SetPhoto(int customerId, Stream stream) { try { var array = Utilities.ReadFully(stream); var photoRequest = new PhotoRequest { Id = customerId, Array = array, }; var request = JsonConvert.SerializeObject(photoRequest); var body = new StringContent(request, Encoding.UTF8, "application/json"); var client = new HttpClient(); client.BaseAddress = new Uri("http://zulu-software.com"); var url = "/ECommerce/api/Customers/SetPhoto"; var response = await client.PostAsync(url, body); if (!response.IsSuccessStatusCode) { return(new Response { IsSuccess = false, Message = response.StatusCode.ToString(), }); } return(new Response { IsSuccess = true, Message = "Foto asignada Ok", }); } catch (Exception ex) { return(new Response { IsSuccess = false, Message = ex.Message, }); } }
public static void ClearGroupPhoto(IRecipientSession adSession, IMailboxSession mailboxSession, ADUser group) { PhotoUploadPipeline photoUploadPipeline = new PhotoUploadPipeline(new PhotosConfiguration(ExchangeSetupContext.InstallPath), mailboxSession, adSession, GroupMailboxDefaultPhotoUploader.Tracer); PhotoRequest request = new PhotoRequest { TargetPrimarySmtpAddress = group.PrimarySmtpAddress.ToString(), UploadTo = group.ObjectId, Preview = true, UploadCommand = UploadCommand.Clear }; photoUploadPipeline.Upload(request, Stream.Null); request = new PhotoRequest { TargetPrimarySmtpAddress = group.PrimarySmtpAddress.ToString(), UploadTo = group.ObjectId, Preview = false, UploadCommand = UploadCommand.Clear }; photoUploadPipeline.Upload(request, Stream.Null); }
public async Task <PhotoResponse> UploadPhoto([FromBody] PhotoRequest request) { CloudStorageAccount storageAccount; if (CloudStorageAccount.TryParse(webConfig.StorageConnectionString, out storageAccount)) { var baseUrl = webConfig.StorageBaseUrl; var containerName = webConfig.StorageContainerName; var blobName = $"{request.IdCard}.png"; var cloudBlobClient = storageAccount.CreateCloudBlobClient(); var cloudBlobContainer = cloudBlobClient.GetContainerReference(containerName); await cloudBlobContainer.CreateIfNotExistsAsync(); var permissions = new BlobContainerPermissions { PublicAccess = BlobContainerPublicAccessType.Blob }; await cloudBlobContainer.SetPermissionsAsync(permissions); var cloudBlockBlob = cloudBlobContainer.GetBlockBlobReference(blobName); cloudBlockBlob.Properties.ContentType = "image/png"; await cloudBlockBlob.UploadFromByteArrayAsync(request.PhotoRaw, 0, request.PhotoRaw.Length); return(new PhotoResponse { IsSuccess = true, Path = $"{baseUrl}/{containerName}/{blobName}", }); } else { return(new PhotoResponse { IsSuccess = false, ErrorMessage = "The connection string isn't valid", }); } }
/// <summary> /// The route handler for the request, increments vote counts. /// </summary> /// <param name="context">The request and response context.</param> public override void ProcessRequest(HttpContext context) { Photo voteTarget = null; VotesHelper votesHelper = new VotesHelper(); if (context.Request.RequestType.Equals("PUT")) { StreamReader stream = new StreamReader(context.Request.InputStream); string voteJson = stream.ReadToEnd(); PhotoRequest photoRequest = (PhotoRequest) new PhotoRequest().FromJson(voteJson); voteTarget = votesHelper.DoVote(context, photoRequest.photoId); } if (voteTarget == null) { SendError(context.Response, 401, "Unauthorized request."); } else { SendResponse(context, voteTarget); } }
public IActionResult AddPhoto([FromBody] PhotoRequest photo) { string profilePictureUrl = null; string result = Regex.Replace(photo.url, "^data:image/[a-zA-Z]+;base64,", string.Empty); if (photo.url != null) { profilePictureUrl = $"images/{photo.randomWord}_{Guid.NewGuid().ToString()}.jpg"; var profilePictureFilePath = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", profilePictureUrl); System.IO.File.WriteAllBytes(profilePictureFilePath, Convert.FromBase64String(result)); } var x = new Photo() { dayId = photo.dayId, url = profilePictureUrl }; _appRepository.Add(x); _appRepository.SaveAll(); return(Ok("İşlem Başarılı")); }
public async Task <Unit> Handle(Command request, CancellationToken cancellationToken) { var photorequest = new PhotoRequest { // Id = request.Id, CreatedAt = DateTime.Now, UpdatedAt = DateTime.Now, Item = request.Item, Type = request.Type, Activity = request.Activity, Request = request.Request, }; _context.PhotoRequests.Add(photorequest); var success = await _context.SaveChangesAsync() > 0; if (success) { return(Unit.Value); } throw new Exception("Problem saving changes"); }
public static void GetPhotoModerationStatus(PluckConfigElement pluckConfig, List<string> photoKeys) { if (photoKeys.Count == 0) return; var pluckService = new PluckService(pluckConfig.apiUrl); var authToken = new UserAuthenticationToken(pluckConfig.userKey, pluckConfig.userNickname, pluckConfig.userEmail, pluckConfig.sharedSecret); RequestBatch requests = null; int numBatches = photoKeys.Count / PLUCK_BATCH_SIZE; if (photoKeys.Count % PLUCK_BATCH_SIZE > 0) numBatches++; int photoKeyIndex = 0; for (int batchNumber = 1; batchNumber <= numBatches; batchNumber++) { requests = new RequestBatch(); #region build requests batch for (int i = 0; i < PLUCK_BATCH_SIZE; i++) { photoKeyIndex = (batchNumber * PLUCK_BATCH_SIZE) - PLUCK_BATCH_SIZE + i; if (photoKeyIndex == photoKeys.Count) break; var photorequest = new PhotoRequest() { PhotoKey = new PhotoKey { Key = photoKeys[photoKeyIndex] } }; requests.AddRequest(photorequest); } #endregion ResponseBatch responseBatch = pluckService.SendRequest(requests, authToken); Dictionary<string, bool> photoStatus = new Dictionary<string, bool>(); #region build responses batch if (responseBatch != null) { foreach (var envelope in responseBatch.Envelopes) { var photo = (PhotoResponse)envelope.GetResponse(); var status = DetermineModerationStatus(photo); if (status == PhotoModerationStatus.Pending || status == PhotoModerationStatus.Unknown) continue; try { //var photokey = photoKeys[photoKeyIndex]; //UserSubmitDB.SetModerationStatus(photo.Photo.PhotoKey.Key, (status == PhotoModerationStatus.Approved)); if (status == PhotoModerationStatus.Approved) { photoStatus.Add(photo.Photo.PhotoKey.Key, true); } else { string photokey = photo.ResponseStatus.Exceptions.Where(e => e.Name == "PhotoKey").Select(e => e.Value).FirstOrDefault(); photoStatus.Add(photokey, false); } } catch { continue; } } } #endregion } }
public ActionResult Photo(string button, HttpPostedFileBase file) { switch (button) { case "Remove": { #region REMOVE PHOTO IDictionary<string, Photo> photoSizes = PhotoManager.Provider.GetAllPhotoResizes(UserProfile.Current.PhotoId); foreach (var photoSize in photoSizes) System.IO.File.Delete(Server.MapPath(photoSize.Value.Url)); UserProfile.Current.PhotoId = null; _userService.SetProfilePicture(UserProfile.Current.Tenant, UserProfile.Current.Username, null); break; #endregion } case "Upload": { #region UPLOAD PHOTO if (file != null) { // GET UPLOAD PHOTO REQUEST var request = new PhotoRequest(file.InputStream, "image/png", null); // UPLOAD PHOTO TO SERVER var photoResult = PhotoManager.Provider.SavePhotoForAllSizes(request, true); // VALIDATE PHOTO WAS UPLOADED TO SERVER if (photoResult != null && photoResult.Count > 0) { var photo = PhotoManager.Provider.GetPhotoResize(photoResult[0].Id, "Medium"); // SAVE PHOTOID ON ACCOUNT if (photo != null && _userService.SetProfilePicture(UserProfile.Current.Tenant, UserProfile.Current.Username, photo.Id)) { // DELETE ALL SIZES OF OLD PHOTO if (!string.IsNullOrEmpty(UserProfile.Current.PhotoId)) { IDictionary<string, Photo> photoSizes = PhotoManager.Provider.GetAllPhotoResizes(UserProfile.Current.PhotoId); foreach (var photoSize in photoSizes) System.IO.File.Delete(Server.MapPath(photoSize.Value.Url)); } // ASSIGN NEW PHOTOID TO CURRENT USER AND RETURN VIEW UserProfile.Current.PhotoId = photo.Id; return View(photo); } } } else { // IF USER HAS A PHOTOID SET, DISPLAY IT if (!string.IsNullOrWhiteSpace(UserProfile.Current.PhotoId)) { var photo = PhotoManager.Provider.GetPhotoResize(UserProfile.Current.PhotoId, "Medium"); return View(photo); } } break; #endregion } } return View(new Photo { Url = Url.Content("~/Content/images/Medium/Male.jpg") }); }
public static PhotoModerationStatus GetPhotoModerationStatus(PluckConfigElement pluckConfig, string photoKey) { var pluckService = new PluckService(pluckConfig.apiUrl); var authToken = new UserAuthenticationToken(pluckConfig.userKey, pluckConfig.userNickname, pluckConfig.userEmail, pluckConfig.sharedSecret); var requests = new RequestBatch(); var photorequest = new PhotoRequest{PhotoKey = new PhotoKey { Key = photoKey }}; requests.AddRequest(photorequest); ResponseBatch responseBatch = pluckService.SendRequest(requests, authToken); var photo = (PhotoResponse)responseBatch.Envelopes[0].GetResponse(); return DetermineModerationStatus(photo); }