private PhotoResponse RespondWithAccessDenied(PhotoRequest request, PhotoResponse response) { response.Served = true; response.Status = HttpStatusCode.Forbidden; request.PerformanceLogger.Log("RemoteForestHandlerServed", string.Empty, 1U); return(response); }
private PhotoResponse ServePhotoWhenClientDisconnected(PhotoRequest request, PhotoResponse response) { response.Served = true; response.Status = HttpStatusCode.InternalServerError; request.PerformanceLogger.Log("RemoteForestHandlerServed", string.Empty, 1U); return(response); }
protected void Page_Load(object sender, EventArgs e) { if (IsPostBack) { if (Request.ContentType.Contains("multipart/form-data")) { var photoResponsesList = new List <PhotoResponse>(); foreach (string file in Request.Files) { var hpf = Request.Files[file] as HttpPostedFile; if (hpf.ContentLength == 0) { continue; } string pathPhotos = Path.Combine( AppDomain.CurrentDomain.BaseDirectory, "files"); string savedFileName = Path.Combine( pathPhotos, Path.GetFileName(hpf.FileName)); hpf.SaveAs(savedFileName); //--- make response var photoResponse = new PhotoResponse(); photoResponse.name = Path.GetFileName(hpf.FileName); photoResponse.size = hpf.ContentLength; photoResponse.url = string.Format("{0}://{1}/files/{2}", Request.Url.Scheme, Request.Url.Host, Path.GetFileName(hpf.FileName)); photoResponse.thumbnail_url = savedFileName; photoResponse.delete_url = savedFileName; photoResponse.delete_type = "POST"; photoResponsesList.Add(photoResponse); } //--- save into session if (Session[uploadedPhotosSessionKey] != null) { var list = Session[uploadedPhotosSessionKey] as List <PhotoResponse>; list.AddRange(photoResponsesList); Session[uploadedPhotosSessionKey] = list; } else { Session.Add(uploadedPhotosSessionKey, photoResponsesList); } Response.Clear(); Response.Write(Newtonsoft.Json.JsonConvert.SerializeObject(photoResponsesList)); Response.End(); } } else { Session.Remove(uploadedPhotosSessionKey); } }
// Gets the user's photo public async Task <PhotoResponse> GetPhotoAsync() { HttpClient client = new HttpClient(); client.DefaultRequestHeaders.Add("Authorization", "Bearer " + _token); client.DefaultRequestHeaders.Add("Accept", "application/json"); using (var response = await client.GetAsync("https://graph.microsoft.com/v1.0/me/photo/$value")) { if (!response.IsSuccessStatusCode) { throw new HttpRequestException($"Graph returned an invalid success code: {response.StatusCode}"); } var stream = await response.Content.ReadAsStreamAsync(); var bytes = new byte[stream.Length]; stream.Read(bytes, 0, (int)stream.Length); var photoResponse = new PhotoResponse { Bytes = bytes, ContentType = response.Content.Headers.ContentType?.ToString(), }; if (photoResponse != null) { photoResponse.Base64String = $"data:{photoResponse.ContentType};base64," + Convert.ToBase64String(photoResponse.Bytes); } return(photoResponse); } }
public PhotoResponse GetPhotos(User user) { PhotoResponse response = new PhotoResponse(); try { List <Photo> photos = _photoRepo.Get(t => t.UserID == user.ID).Take(3).ToList(); if (photos == null) { response.SetState(Common.Constants.ERROR_ENUMS.NO_RECORD); return(response); } response.Photos = photos; } catch (Exception ex) { //hatayı loglamam lazım response.SetState(Common.Constants.ERROR_ENUMS.SYSTEM); return(response); //throw ex; } response.SetState(Common.Constants.ERROR_ENUMS.SUCCESS); return(response); }
public static Dictionary <string, string> UpdatePluckPhotoDetails(string appName, Pluck.Config.PluckConfigElement pluckConfig, string description, string title, string tags, string photoKey) { var requests = new RequestBatch(); #region Add UpdatePhotoActionRequest to batch var updateRequest = new UpdatePhotoActionRequest { Description = description, Title = title, Tags = tags, PhotoKey = new PhotoKey { Key = photoKey } }; requests.AddRequest(updateRequest); #endregion #region Add UpdateDiscoveryFilterFlagActionRequest to batch ////Make the photo not discoverable UpdateDiscoveryFilterFlagActionRequest discAction = new UpdateDiscoveryFilterFlagActionRequest(); discAction.BaseKey = updateRequest.PhotoKey; discAction.ExcludeFromDiscovery = true; requests.AddRequest(discAction); #endregion #region Add PhotoRequest to batch requests.AddRequest(new PhotoRequest { PhotoKey = updateRequest.PhotoKey }); #endregion var pluckService = new PluckService(pluckConfig.apiUrl); var authToken = new UserAuthenticationToken(pluckConfig.userKey, pluckConfig.userNickname, pluckConfig.userEmail, pluckConfig.sharedSecret); ResponseBatch responseBatch = pluckService.SendRequest(requests, authToken); Dictionary <string, string> resultURI = new Dictionary <string, string>(); if (responseBatch != null) { if (responseBatch.Envelopes[0].Payload.ResponseStatus.Exceptions != null && responseBatch.Envelopes[0].Payload.ResponseStatus.Exceptions.Length > 0) { throw new ApplicationException(responseBatch.Envelopes[0].Payload.ResponseStatus.Exceptions[0].ExceptionMessage); } IResponse photoObject = responseBatch.Envelopes[2].GetResponse(); PhotoResponse photoDetails = (PhotoResponse)photoObject; resultURI.Add("tiny", photoDetails.Photo.Image.Tiny); resultURI.Add("full", photoDetails.Photo.Image.Full); resultURI.Add("small", photoDetails.Photo.Image.Small); //60x60 resultURI.Add("medium", photoDetails.Photo.Image.Medium); //h=200 } return(resultURI); }
protected override IConfigurable ConvertDataObjectToPresentationObject(IConfigurable dataObject) { if (dataObject == null) { return(null); } ADUser aduser = (ADUser)dataObject; UserPhotoConfiguration userPhotoConfiguration = new UserPhotoConfiguration(dataObject.Identity, Stream.Null, null); if (CmdletProxy.TryToProxyOutputObject(userPhotoConfiguration, base.CurrentTaskContext, aduser, this.Identity == null, this.ConfirmationMessage, CmdletProxy.AppendIdentityToProxyCmdlet(aduser))) { return(userPhotoConfiguration); } IConfigurable result; try { ExchangePrincipal exchangePrincipal = ExchangePrincipal.FromADUser(aduser, null); using (MailboxSession mailboxSession = MailboxSession.OpenAsAdmin(exchangePrincipal, CultureInfo.InvariantCulture, "Client=Management;Action=Get-UserPhoto")) { using (MemoryStream memoryStream = new MemoryStream()) { PhotoManagementRetrievalPipeline photoManagementRetrievalPipeline = new PhotoManagementRetrievalPipeline(GetUserPhoto.PhotosConfiguration, mailboxSession, (IRecipientSession)base.DataSession, this.tracer); PhotoResponse photoResponse = photoManagementRetrievalPipeline.Retrieve(this.CreateRetrievePhotoRequest(exchangePrincipal), memoryStream); HttpStatusCode status = photoResponse.Status; if (status != HttpStatusCode.OK && status == HttpStatusCode.NotFound) { this.WriteError(new UserPhotoNotFoundException(this.Preview), ExchangeErrorCategory.Client, this.Identity, true); throw new InvalidOperationException(); } memoryStream.Seek(0L, SeekOrigin.Begin); result = new UserPhotoConfiguration(dataObject.Identity, memoryStream, photoResponse.Thumbprint); } } } catch (UserPhotoNotFoundException) { throw; } catch (Exception ex) { ExManagementApplicationLogger.LogEvent(ManagementEventLogConstants.Tuple_FailedToRetrievePhoto, new string[] { dataObject.ToString(), ((ADUser)dataObject).UserPrincipalName, ex.ToString() }); throw; } finally { this.tracer.Dump(new PhotoRequestLogWriter(GetUserPhoto.RequestLog, GetUserPhoto.GenerateRequestId())); } return(result); }
private void SavePhotoAPI(byte[] myByteArray, string orintation) { PhotoResponse photoResponse = new PhotoResponse(); SIMSResponseData responseStatus; photoResponse.VehicleID = AppDelegate.appDelegate.vehicleID; photoResponse.StoreID = AppDelegate.appDelegate.storeId; photoResponse.InvtrID = AppDelegate.appDelegate.invtrId; photoResponse.PhotoGuide = AppDelegate.appDelegate.photoButtonClicked; photoResponse.Orientaion = orintation; photoResponse.PhotoURL = ""; photoResponse.Photo = myByteArray; responseStatus = ServiceFactory.ServicePhotoSave.getWebServiceHandle().SavePhoto(photoResponse); }
public static PhotoModerationStatus DetermineModerationStatus(PhotoResponse photo) { //deleted if (photo.ResponseStatus.StatusCode == global::Pluck.SiteLife.SDK.Models.System.ResponseStatusCode.ProcessingException) return PhotoModerationStatus.Deleted; if (photo.ResponseStatus.StatusCode == global::Pluck.SiteLife.SDK.Models.System.ResponseStatusCode.SecurityException) return PhotoModerationStatus.Unknown; if (photo.Photo.IsPendingApproval) return PhotoModerationStatus.Pending; else return PhotoModerationStatus.Approved; //if (photo.Photo.ContentBlockingState = Pluck.SiteLife.SDK.Models.Common.ContentBlockingEnum.BlockedByAdmin) }
// GET: Galery public ActionResult PhotoPage(int?page) { PhotoService photoService = new PhotoService(); UserPhotoModel model = (UserPhotoModel)Session["model"]; if (page == null) { PhotoResponse photoResponse = photoService.GetPhotos(model.User); model.Photos = photoResponse.Photos; } else { PhotoResponse photoResponse = photoService.GetPhotosPartByPart(model.User, (int)page); model.Photos = photoResponse.Photos; } return(View(model)); }
public PhotoResponse GetPhotosPartByPart(User user, int page, int count = 3) { PhotoResponse response = new PhotoResponse(); int index = page * count; try { var photos = _photoRepo.Get().Where(t => t.UserID == user.ID).Take(index).ToList(); if (photos == null) { response.SetState(Common.Constants.ERROR_ENUMS.NO_RECORD); return(response); } response.Photos = photos; } catch (Exception ex) { response.SetState(Common.Constants.ERROR_ENUMS.SYSTEM); throw ex; } response.SetState(Common.Constants.ERROR_ENUMS.SUCCESS); return(response); }
public SIMSResponseData SavePhoto(PhotoResponse photoResponse) { string result = null; HttpResponseMessage responseMessage = null; SIMSResponseData response = new SIMSResponseData(); try { string request = JsonConvert.SerializeObject(photoResponse); RestClient.doPost(Url.SAVE_Photo, request); //if (responseMessage.IsSuccessStatusCode) //{ // result = responseMessage.Content.ReadAsStringAsync().Result; // SIMSResponseData rst = JsonConvert.DeserializeObject<SIMSResponseData>(result); // response = rst; // if (null != response) // { // Utilities.Utility.ShowAlert("Appraisal App", "Photo Done", "OK"); // } //} //else //{ // Utilities.Utility.ShowAlert("Appraisal App", "Photo failed!!", "OK"); //} } catch (Exception exc) { Console.WriteLine("Exception occured :: " + exc.Message); } return(response); }
public static PhotoModerationStatus DetermineModerationStatus(PhotoResponse photo) { //deleted if (photo.ResponseStatus.StatusCode == global::Pluck.SiteLife.SDK.Models.System.ResponseStatusCode.ProcessingException) { return(PhotoModerationStatus.Deleted); } if (photo.ResponseStatus.StatusCode == global::Pluck.SiteLife.SDK.Models.System.ResponseStatusCode.SecurityException) { return(PhotoModerationStatus.Unknown); } if (photo.Photo.IsPendingApproval) { return(PhotoModerationStatus.Pending); } else { return(PhotoModerationStatus.Approved); } //if (photo.Photo.ContentBlockingState = Pluck.SiteLife.SDK.Models.Common.ContentBlockingEnum.BlockedByAdmin) }
public PhotoResponse Retrieve(PhotoRequest request, PhotoResponse response) { ArgumentValidator.ThrowIfNull("request", request); ArgumentValidator.ThrowIfNull("response", response); PhotoResponse result; using (new StopwatchPerformanceTracker("RemoteForestHandlerTotal", request.PerformanceLogger)) { using (new ADPerformanceTracker("RemoteForestHandlerTotal", request.PerformanceLogger)) { if (request.ShouldSkipHandlers(PhotoHandlers.RemoteForest)) { this.tracer.TraceDebug((long)this.GetHashCode(), "REMOTE FOREST HANDLER: skipped by request."); result = response; } else if (response.Served) { this.tracer.TraceDebug((long)this.GetHashCode(), "REMOTE FOREST HANDLER: skipped because photo has already been served by an upstream handler."); result = response; } else { response.RemoteForestHandlerProcessed = true; request.PerformanceLogger.Log("RemoteForestHandlerProcessed", string.Empty, 1U); GetUserPhotoQuery getUserPhotoQuery; using (new StopwatchPerformanceTracker("QueryCreation", request.PerformanceLogger)) { using (new ADPerformanceTracker("QueryCreation", request.PerformanceLogger)) { getUserPhotoQuery = new GetUserPhotoQuery((ClientContext)request.ClientContextForRemoteForestRequests, request, null, request.RequestorFromExternalOrganization, this.configuration, this.tracer); } } try { byte[] array = getUserPhotoQuery.Execute(); if (RemoteForestPhotoHandler.IsInvalidHttpStatusCode(getUserPhotoQuery.StatusCode)) { result = this.RespondWithErrorBecauseQueryReturnedInvalidStatusCode(request, response); } else { response.Served = true; response.Status = getUserPhotoQuery.StatusCode; response.ETag = getUserPhotoQuery.ETag; response.HttpExpiresHeader = getUserPhotoQuery.Expires; response.ContentType = getUserPhotoQuery.ContentType; this.tracer.TraceDebug((long)this.GetHashCode(), "REMOTE FOREST HANDLER: query completed. Result is empty? {0}; HTTP status: {1}; ETag: {2}; Content-Type: {3}; HTTP Expires: {4}", new object[] { array == null || array.Length == 0, response.Status, getUserPhotoQuery.ETag, getUserPhotoQuery.ContentType, getUserPhotoQuery.Expires }); using (MemoryStream memoryStream = new MemoryStream((array == null) ? Array <byte> .Empty : array)) { memoryStream.CopyTo(response.OutputPhotoStream); } request.PerformanceLogger.Log("RemoteForestHandlerServed", string.Empty, 1U); result = response; } } catch (ClientDisconnectedException arg) { this.tracer.TraceDebug <ClientDisconnectedException>((long)this.GetHashCode(), "REMOTE FOREST HANDLER: client disconnected. Exception: {0}", arg); result = this.ServePhotoWhenClientDisconnected(request, response); } catch (AccessDeniedException arg2) { this.tracer.TraceDebug <AccessDeniedException>((long)this.GetHashCode(), "REMOTE FOREST HANDLER: access denied. Requestor does NOT have permission to retrieve this photo. Exception: {0}", arg2); result = this.RespondWithAccessDenied(request, response); } finally { if (getUserPhotoQuery != null && getUserPhotoQuery.RequestLogger != null && getUserPhotoQuery.RequestLogger.LogData != null) { string text = getUserPhotoQuery.RequestLogger.LogData.ToString(); if (!string.IsNullOrEmpty(text)) { this.tracer.TracePerformance <string>((long)this.GetHashCode(), "REMOTE FOREST HANDLER: {0}", text); request.PerformanceLogger.Log("MiscRoutingAndDiscovery", string.Empty, text); } } } } } } return(result); }
public PhotoResponse Retrieve(PhotoRequest request, PhotoResponse response) { return(this.pipeline.Retrieve(request, response)); }
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); }
internal override BaseQueryResult GetData(BaseQuery query) { this.tracer.TraceDebug((long)this.GetHashCode(), "Executing local photo query."); UserPhotoQuery userPhotoQuery = (UserPhotoQuery)query; BaseQueryResult result; try { using (new StopwatchPerformanceTracker("LocalAuthorization", this.photoRequest.PerformanceLogger)) { using (new ADPerformanceTracker("LocalAuthorization", this.photoRequest.PerformanceLogger)) { new PhotoAuthorization(OrganizationIdCache.Singleton, this.upstreamTracer).Authorize(this.photoRequest.Requestor, new PhotoPrincipal { EmailAddresses = new string[] { userPhotoQuery.ExchangePrincipal.MailboxInfo.PrimarySmtpAddress.ToString() }, OrganizationId = userPhotoQuery.ExchangePrincipal.MailboxInfo.OrganizationId }); } } using (MemoryStream memoryStream = new MemoryStream()) { this.CheckDeadline("Retrieving-UserPhoto"); LocalServerPhotoRetrievalPipeline localServerPhotoRetrievalPipeline = new LocalServerPhotoRetrievalPipeline(this.photosConfiguration, "Client=WebServices;Action=UserPhotoTask", this.CreateRecipientSession(userPhotoQuery), XSOFactory.Default, this.upstreamTracer); this.photoRequest.TargetSmtpAddress = userPhotoQuery.ExchangePrincipal.MailboxInfo.PrimarySmtpAddress.ToString(); this.photoRequest.TargetPrincipal = userPhotoQuery.ExchangePrincipal; PhotoResponse photoResponse = localServerPhotoRetrievalPipeline.Retrieve(this.photoRequest, memoryStream); this.CheckDeadline("Reading-Image-Bytes"); byte[] array = memoryStream.ToArray(); this.CheckDeadline("Returning-Result"); this.tracer.TraceDebug((long)this.GetHashCode(), "Local query completed. Returned photo is blank? {0}; Status: {1}; ETag: {2}; Content-type: '{3}'", new object[] { array == null || array.Length == 0, photoResponse.Status, photoResponse.ETag, photoResponse.ContentType }); result = new UserPhotoQueryResult(array, photoResponse.ETag, photoResponse.Status, photoResponse.HttpExpiresHeader, photoResponse.ContentType, this.upstreamTracer); } } catch (IOException ex) { result = this.TraceAndReturnQueryResult(ex, new PhotoRetrievalFailedIOException(Strings.PhotoRetrievalFailedIOError(ex.Message), ex)); } catch (Win32Exception ex2) { result = this.TraceAndReturnQueryResult(ex2, new PhotoRetrievalFailedWin32Exception(Strings.PhotoRetrievalFailedWin32Error(ex2.Message), ex2)); } catch (UnauthorizedAccessException ex3) { result = this.TraceAndReturnQueryResult(ex3, new PhotoRetrievalFailedUnauthorizedAccessException(Strings.PhotoRetrievalFailedUnauthorizedAccessError(ex3.Message), ex3)); } catch (AccessDeniedException ex4) { result = this.TraceAndReturnQueryResult(ex4, ex4); } catch (LocalizedException ex5) { result = this.TraceAndReturnQueryResult(ex5, ex5); } return(result); }