La llamada de carga cloudinaria toma demasiado tiempo -- # campo con performance campo con asp.net-mvc camp codereview Relacionados El problema

Cloudinary upload call takes too long


3
vote

problema

Español

Tengo el siguiente async ActionResult .

  public async Task<ActionResult> most_loved_pix() {      var access_token = HttpContext.Items["access_token"].ToString();     if (!string.IsNullOrEmpty(access_token))     {         Account account = new Account();         account.Cloud = ConfigurationManager.AppSettings["CloudName"];         account.ApiKey = ConfigurationManager.AppSettings["CloudinaryAPI"];         account.ApiSecret = ConfigurationManager.AppSettings["CloudinarySecret"];          Cloudinary cloudinary = new Cloudinary(account);          var appsecret_proof = access_token.GenerateAppSecretProof();          var fb = new FacebookClient(access_token);          #region FacebookUser Name and Picture plus other Info         //Get current user's profile         dynamic myInfo = await fb.GetTaskAsync("me?fields=id,first_name,last_name,link,locale,email,name,birthday,gender,location,age_range,about".GraphAPICall(appsecret_proof));          dynamic myinfojson = JsonConvert.DeserializeObject(myInfo.ToString());          string userName = myinfojson.name;         string userId = myinfojson.id;         string firstName = myinfojson.first_name;          //get current picture         dynamic profileImgResult = await fb.GetTaskAsync("{0}/picture?width=200&height=200&redirect=false".GraphAPICall((string)myInfo.id, appsecret_proof));          ViewBag.ProfilePictureURL = profileImgResult.data.url;         #endregion          dynamic myAlbums = await fb.GetTaskAsync(                 ("me/albums?fields = id,name")                 .GraphAPICall(appsecret_proof));         string result = myAlbums.ToString();           var jsonResult = JsonConvert.DeserializeObject<AlbumsRootObject>(result);         if (jsonResult.data.Count < 1)         {             return RedirectToAction("Index", "Home");         }          foreach (var AlbumItems in jsonResult.data.Where(i => i.name == "Profile Pictures"))         {              string albumIdstring = AlbumItems.id.ToString();              string AlbumId = albumIdstring.Trim('"');              dynamic myProfilePictures = await fb.GetTaskAsync(                 (string.Format("{0}/photos", AlbumId)                 + "?fields=images,likes.summary(total_count),comments.summary(total_count),reactions.type(LOVE).summary(true)&limit=10")                 .GraphAPICall(appsecret_proof));              string pictures = myProfilePictures.ToString();              var picturesResult = JsonConvert.DeserializeObject<ProfilePicturesRootObject>(pictures);              #region MostLiked             var likesSummary = new List<ProfilePicturesSummary>();             var likesImages = new List<ProfilePicturesImage>();              foreach (var LikesItems in picturesResult.data)             {                 likesSummary.Add(LikesItems.likes.summary);                 foreach (var imagesLiked in LikesItems.images)                 {                     likesImages.Add(imagesLiked);                     break;                 }             }             var maxLikeCount = likesSummary.Max( l => l.total_count);              var maxlikecountindex = likesSummary.FindIndex(a => a.total_count == maxLikeCount);              var imageindex = likesImages[maxlikecountindex];              string mostlikedImageSourceRawURL = imageindex.source.ToString();              string mostlikedImageSourceTrimedURL = mostlikedImageSourceRawURL.Trim('"');              if (!string.IsNullOrEmpty(mostlikedImageSourceRawURL))             {                 var UsersMostLikedtextParams = new TextParams("دوست داشتنی")                 {                     PublicId = string.Format("MostLiked{0}", userId),                     FontFamily = "Amiri",                     //FontWeight = "regular",                     FontSize = 40,                     TextAlign = "center",                     FontColor = "blue",                     Background = "white",                     Opacity = "60"                 };                 var textResult = cloudinary.Text(UsersMostLikedtextParams);                  var usersMostLikedImage = new ImageUploadParams()                 {                     File = new FileDescription(mostlikedImageSourceTrimedURL),                     PublicId = string.Format("MostLiked{0}", AlbumId),                     Tags = "Most Liked Picture, Facebook",                     Transformation = new Transformation().Border("1px_solid_blue")                     .Width(233).Height(320).Crop("fill")                     .Chain().Overlay("like.png").Flags("relative").Gravity("north_east").Width(65).Height(65)                     .Chain().Overlay(string.Format("text:MostLiked{0}.png", userId)).Radius(20).Gravity("south").Y(20)                 };                 var userMostLikedImageResult = cloudinary.Upload(usersMostLikedImage);             }              #endregion              #region MostLoved              var mostCommentedImageCommentCount = new List<ProfilePicturesSummary2>();             var mostCommentedImageSource = new List<ProfilePicturesImage>();              foreach (var CommentItems in picturesResult.data)             {                 mostCommentedImageCommentCount.Add(CommentItems.comments.summary);                 foreach (var imageCommented in CommentItems.images)                 {                     mostCommentedImageSource.Add(imageCommented);                     break;                 }             }              var mostCommentCount = mostCommentedImageCommentCount.Max(l => l.total_count);              var mostCommentCountIndex = mostCommentedImageCommentCount.FindIndex(a => a.total_count == mostCommentCount);             var commentImageIndex = mostCommentedImageSource[mostCommentCountIndex];              string mostCommentedImageRawURL = commentImageIndex.source.ToString();             string mostCommentedImageTrimmedURL = mostCommentedImageRawURL.Trim('"');              if (!string.IsNullOrEmpty(mostCommentedImageRawURL))             {                 var UsersMostLovedtextParams = new TextParams("دلپذیر")                 {                     PublicId = string.Format("MostLoved{0}", userId),                     FontFamily = "Amiri",                     //FontWeight = "regular",                     FontSize = 40,                     TextAlign = "center",                     FontColor = "red",                     Background = "white",                     Opacity = "60"                 };                 var UserMostLovedtextResult = cloudinary.Text(UsersMostLovedtextParams);                 var usersMostLovedImage = new ImageUploadParams()                 {                     File = new FileDescription(mostCommentedImageTrimmedURL),                     PublicId = string.Format("MostLoved{0}", AlbumId),                     Tags = "Most Commented, Facebook",                     Transformation = new Transformation().Border("1px_solid_red")                     .Width(233).Height(320).Crop("fill")                     .Chain().Overlay("love.png").Flags("relative").Gravity("north_east").Width(65).Height(65)                     .Chain().Overlay(string.Format("text:MostLoved{0}.png", userId)).Radius(20).Gravity("south").Y(20)                 };                  var usersMostLovedImageResult = cloudinary.Upload(usersMostLovedImage);             }              #endregion              #region MostCommented             var mostLovedImageCommentCount = new List<ProfilePicturesSummary3>();             var mostLovedImageSource = new List<ProfilePicturesImage>();              foreach (var Loved in picturesResult.data)             {                 mostLovedImageCommentCount.Add(Loved.reactions.summary);                 foreach (var imageLoved in Loved.images)                 {                     mostLovedImageSource.Add(imageLoved);                     break;                 }             }              var mostLovedCount = mostLovedImageCommentCount.Max(l => l.total_count);              var mostLovedCountIndex = mostLovedImageCommentCount.FindIndex(a => a.total_count == mostLovedCount);              var lovedImageIndex = mostLovedImageSource[mostLovedCountIndex];              string mostLovedImageRawURL = lovedImageIndex.source.ToString();              string mostLovedImageTrimmedURL = mostLovedImageRawURL.Trim('"');              if (!string.IsNullOrEmpty(mostLovedImageRawURL))             {                 var UsersMostCommentedtextParams = new TextParams("بیشترین اظهار نظرات")                 {                     PublicId = string.Format("MostComment{0}", userId),                     FontFamily = "Amiri",                     //FontWeight = "regular",                     FontSize = 30,                     TextAlign = "center",                     FontColor = "green",                     Background = "white",                     Opacity = "60"                 };                 var UserMostCommentedtextResult = cloudinary.Text(UsersMostCommentedtextParams);                  var mostCommentImage = new ImageUploadParams()                 {                     File = new FileDescription(mostLovedImageTrimmedURL),                     PublicId = string.Format("MostComment{0}", AlbumId),                     Tags = "Most Comment, Facebook",                     Transformation = new Transformation().Border("1px_solid_green")                     .Width(233).Height(320).Crop("fill")                     .Chain().Overlay("comment.png").Flags("relative").Gravity("north_east").Width(65).Height(65)                     .Chain().Overlay(string.Format("text:MostComment{0}.png", userId)).Radius(20).Gravity("south").Y(20)                 };                 var mostCommentImageResult = cloudinary.Upload(mostCommentImage);             }              #endregion              #region BuildImageFinalURL                  ViewBag.ImageURL = cloudinary.Api.UrlImgUp.Transform(new Transformation()                         .Width(233).Height(320).Overlay(string.Format("MostLiked{0}.jpg", AlbumId)).Gravity("north_west").Y(50).X(0)                         .Chain().Width(233).Height(320).Overlay(string.Format("MostLoved{0}.jpg", AlbumId)).Gravity("north").Y(50).X(0)                         .Chain().Width(233).Height(320).Overlay(string.Format("MostComment{0}.jpg", AlbumId)).Gravity("north_east").Y(50).X(0))                         .BuildUrl("top_three.jpg");             return View();              #endregion         }       }     return View(); }   

Como puede ver por encima de la pieza de código, ¿algunas llamadas API para recuperar los datos formateados JSON y luego serializarlo también hace algunas llamadas API a cloudinary para la manipulación o la carga de la imagen. Probé esta acción con la herramienta de perfiles de GLIMPS y, aparentemente, tomó 34k + MS para ejecutar el resultado. Me gustaría derribarlo a 5k MS. ¿Es posible?

No puedo responder a ninguno de los comentarios a continuación, ya que mi reputación es inferior a 50.

Original en ingles

I have the following async ActionResult.

public async Task<ActionResult> most_loved_pix() {      var access_token = HttpContext.Items["access_token"].ToString();     if (!string.IsNullOrEmpty(access_token))     {         Account account = new Account();         account.Cloud = ConfigurationManager.AppSettings["CloudName"];         account.ApiKey = ConfigurationManager.AppSettings["CloudinaryAPI"];         account.ApiSecret = ConfigurationManager.AppSettings["CloudinarySecret"];          Cloudinary cloudinary = new Cloudinary(account);          var appsecret_proof = access_token.GenerateAppSecretProof();          var fb = new FacebookClient(access_token);          #region FacebookUser Name and Picture plus other Info         //Get current user's profile         dynamic myInfo = await fb.GetTaskAsync("me?fields=id,first_name,last_name,link,locale,email,name,birthday,gender,location,age_range,about".GraphAPICall(appsecret_proof));          dynamic myinfojson = JsonConvert.DeserializeObject(myInfo.ToString());          string userName = myinfojson.name;         string userId = myinfojson.id;         string firstName = myinfojson.first_name;          //get current picture         dynamic profileImgResult = await fb.GetTaskAsync("{0}/picture?width=200&height=200&redirect=false".GraphAPICall((string)myInfo.id, appsecret_proof));          ViewBag.ProfilePictureURL = profileImgResult.data.url;         #endregion          dynamic myAlbums = await fb.GetTaskAsync(                 ("me/albums?fields = id,name")                 .GraphAPICall(appsecret_proof));         string result = myAlbums.ToString();           var jsonResult = JsonConvert.DeserializeObject<AlbumsRootObject>(result);         if (jsonResult.data.Count < 1)         {             return RedirectToAction("Index", "Home");         }          foreach (var AlbumItems in jsonResult.data.Where(i => i.name == "Profile Pictures"))         {              string albumIdstring = AlbumItems.id.ToString();              string AlbumId = albumIdstring.Trim('"');              dynamic myProfilePictures = await fb.GetTaskAsync(                 (string.Format("{0}/photos", AlbumId)                 + "?fields=images,likes.summary(total_count),comments.summary(total_count),reactions.type(LOVE).summary(true)&limit=10")                 .GraphAPICall(appsecret_proof));              string pictures = myProfilePictures.ToString();              var picturesResult = JsonConvert.DeserializeObject<ProfilePicturesRootObject>(pictures);              #region MostLiked             var likesSummary = new List<ProfilePicturesSummary>();             var likesImages = new List<ProfilePicturesImage>();              foreach (var LikesItems in picturesResult.data)             {                 likesSummary.Add(LikesItems.likes.summary);                 foreach (var imagesLiked in LikesItems.images)                 {                     likesImages.Add(imagesLiked);                     break;                 }             }             var maxLikeCount = likesSummary.Max( l => l.total_count);              var maxlikecountindex = likesSummary.FindIndex(a => a.total_count == maxLikeCount);              var imageindex = likesImages[maxlikecountindex];              string mostlikedImageSourceRawURL = imageindex.source.ToString();              string mostlikedImageSourceTrimedURL = mostlikedImageSourceRawURL.Trim('"');              if (!string.IsNullOrEmpty(mostlikedImageSourceRawURL))             {                 var UsersMostLikedtextParams = new TextParams("xd8xafxd9x88xd8xb3xd8xaa xd8xafxd8xa7xd8xb4xd8xaaxd9x86xdbx8c")                 {                     PublicId = string.Format("MostLiked{0}", userId),                     FontFamily = "Amiri",                     //FontWeight = "regular",                     FontSize = 40,                     TextAlign = "center",                     FontColor = "blue",                     Background = "white",                     Opacity = "60"                 };                 var textResult = cloudinary.Text(UsersMostLikedtextParams);                  var usersMostLikedImage = new ImageUploadParams()                 {                     File = new FileDescription(mostlikedImageSourceTrimedURL),                     PublicId = string.Format("MostLiked{0}", AlbumId),                     Tags = "Most Liked Picture, Facebook",                     Transformation = new Transformation().Border("1px_solid_blue")                     .Width(233).Height(320).Crop("fill")                     .Chain().Overlay("like.png").Flags("relative").Gravity("north_east").Width(65).Height(65)                     .Chain().Overlay(string.Format("text:MostLiked{0}.png", userId)).Radius(20).Gravity("south").Y(20)                 };                 var userMostLikedImageResult = cloudinary.Upload(usersMostLikedImage);             }              #endregion              #region MostLoved              var mostCommentedImageCommentCount = new List<ProfilePicturesSummary2>();             var mostCommentedImageSource = new List<ProfilePicturesImage>();              foreach (var CommentItems in picturesResult.data)             {                 mostCommentedImageCommentCount.Add(CommentItems.comments.summary);                 foreach (var imageCommented in CommentItems.images)                 {                     mostCommentedImageSource.Add(imageCommented);                     break;                 }             }              var mostCommentCount = mostCommentedImageCommentCount.Max(l => l.total_count);              var mostCommentCountIndex = mostCommentedImageCommentCount.FindIndex(a => a.total_count == mostCommentCount);             var commentImageIndex = mostCommentedImageSource[mostCommentCountIndex];              string mostCommentedImageRawURL = commentImageIndex.source.ToString();             string mostCommentedImageTrimmedURL = mostCommentedImageRawURL.Trim('"');              if (!string.IsNullOrEmpty(mostCommentedImageRawURL))             {                 var UsersMostLovedtextParams = new TextParams("xd8xafxd9x84xd9xbexd8xb0xdbx8cxd8xb1")                 {                     PublicId = string.Format("MostLoved{0}", userId),                     FontFamily = "Amiri",                     //FontWeight = "regular",                     FontSize = 40,                     TextAlign = "center",                     FontColor = "red",                     Background = "white",                     Opacity = "60"                 };                 var UserMostLovedtextResult = cloudinary.Text(UsersMostLovedtextParams);                 var usersMostLovedImage = new ImageUploadParams()                 {                     File = new FileDescription(mostCommentedImageTrimmedURL),                     PublicId = string.Format("MostLoved{0}", AlbumId),                     Tags = "Most Commented, Facebook",                     Transformation = new Transformation().Border("1px_solid_red")                     .Width(233).Height(320).Crop("fill")                     .Chain().Overlay("love.png").Flags("relative").Gravity("north_east").Width(65).Height(65)                     .Chain().Overlay(string.Format("text:MostLoved{0}.png", userId)).Radius(20).Gravity("south").Y(20)                 };                  var usersMostLovedImageResult = cloudinary.Upload(usersMostLovedImage);             }              #endregion              #region MostCommented             var mostLovedImageCommentCount = new List<ProfilePicturesSummary3>();             var mostLovedImageSource = new List<ProfilePicturesImage>();              foreach (var Loved in picturesResult.data)             {                 mostLovedImageCommentCount.Add(Loved.reactions.summary);                 foreach (var imageLoved in Loved.images)                 {                     mostLovedImageSource.Add(imageLoved);                     break;                 }             }              var mostLovedCount = mostLovedImageCommentCount.Max(l => l.total_count);              var mostLovedCountIndex = mostLovedImageCommentCount.FindIndex(a => a.total_count == mostLovedCount);              var lovedImageIndex = mostLovedImageSource[mostLovedCountIndex];              string mostLovedImageRawURL = lovedImageIndex.source.ToString();              string mostLovedImageTrimmedURL = mostLovedImageRawURL.Trim('"');              if (!string.IsNullOrEmpty(mostLovedImageRawURL))             {                 var UsersMostCommentedtextParams = new TextParams("xd8xa8xdbx8cxd8xb4xd8xaaxd8xb1xdbx8cxd9x86 xd8xa7xd8xb8xd9x87xd8xa7xd8xb1 xd9x86xd8xb8xd8xb1xd8xa7xd8xaa")                 {                     PublicId = string.Format("MostComment{0}", userId),                     FontFamily = "Amiri",                     //FontWeight = "regular",                     FontSize = 30,                     TextAlign = "center",                     FontColor = "green",                     Background = "white",                     Opacity = "60"                 };                 var UserMostCommentedtextResult = cloudinary.Text(UsersMostCommentedtextParams);                  var mostCommentImage = new ImageUploadParams()                 {                     File = new FileDescription(mostLovedImageTrimmedURL),                     PublicId = string.Format("MostComment{0}", AlbumId),                     Tags = "Most Comment, Facebook",                     Transformation = new Transformation().Border("1px_solid_green")                     .Width(233).Height(320).Crop("fill")                     .Chain().Overlay("comment.png").Flags("relative").Gravity("north_east").Width(65).Height(65)                     .Chain().Overlay(string.Format("text:MostComment{0}.png", userId)).Radius(20).Gravity("south").Y(20)                 };                 var mostCommentImageResult = cloudinary.Upload(mostCommentImage);             }              #endregion              #region BuildImageFinalURL                  ViewBag.ImageURL = cloudinary.Api.UrlImgUp.Transform(new Transformation()                         .Width(233).Height(320).Overlay(string.Format("MostLiked{0}.jpg", AlbumId)).Gravity("north_west").Y(50).X(0)                         .Chain().Width(233).Height(320).Overlay(string.Format("MostLoved{0}.jpg", AlbumId)).Gravity("north").Y(50).X(0)                         .Chain().Width(233).Height(320).Overlay(string.Format("MostComment{0}.jpg", AlbumId)).Gravity("north_east").Y(50).X(0))                         .BuildUrl("top_three.jpg");             return View();              #endregion         }       }     return View(); } 

As you can see above piece of code does some API Calls to retrieve Json formatted data and then serialize it also does some API calls to Cloudinary for manipulation or image upload. I tested this action with Glimps profiling tool and apparently it took 34k+ ms to execute the result. I would like to bring it down to 5k ms. Is it possible?

I cannot reply to any of the comments below as my reputation is under 50.

        
     
     

Lista de respuestas

1
 
vote

USO ptr3 's se discute contraversión, pero el uso de regiones dentro de un método es una señal clara de que el método debe dividirse en múltiples métodos.

¡Está gritando en voz alta "Violación del principio de la responsabilidad única"!

 

Using region's is discussed contraversial but using regions inside a method is a clear sign that the method should be broken into multiple methods.

It is screaming loudly "Violation of single responsibility principle"!

 
 
1
 
vote

Es muy difícil decirle lo que debe mejorarse. Este método hace mucho y deberá a través del cuello de botella de rendimiento a algo más específico. Para hacer esto, tiene las siguientes opciones:

  • Mida cada una de las características de este método con el ptr4 (realmente no debería hacerlo, pero, es una opción).
  • Ejecute este código con un perfilador: le dirá lo que la ralentiza.
  • Refactor Este método en piezas más pequeñas que puede medir / perfilar mejor y luego optimizar (esta es la opción preferida ).

Probé esta acción con la herramienta de perfiles de GLIMPS y, aparentemente, tomó 34k + MS para ejecutar el resultado. Me gustaría derribarlo a 5k MS. es posible?

Probablemente ningún cuerpo puede decirle esto. Usted realiza algunas solicitudes web. Si necesitan varios segundos para completar, casi no hay nada que se pueda hacer sobre ellos. Tal vez intentas obtener demasiados datos o la conexión a Internet es lenta? Quién sabe. Medirlo primero.

 

It's very hard to tell you what needs to be improved. This method does a lot and you'll need to norrow down the performance bottleneck to something more specific. In order to do this you have the following options:

  • Measure each feature of this method with the Stopwatch (you really shouldn't do it - but, it's an option).
  • Run this code with a profiler - it'll tell you what slows it down.
  • Refactor this method into smaller pieces that you can better measure/profile and then optimize (this is the preferred option).

I tested this action with Glimps profiling tool and apparently it took 34k+ ms to execute the result. I would like to bring it down to 5k ms. Is it possible?

Probably no body can tell you this. You perform some web-requests. If they need several seconds to complete there's hardly anything that can be done about them. Maybe you try to get too much data or you internet connection is slow? Who knows. Measure it first.

 
 

Relacionados problema

1  Vista parcial para listas desplegables de uso frecuente  ( Partial view for frequently used drop down lists ) 
Tengo una entrada que se necesita en muchas formas, así que creé una vista parcial para eso. En la vista parcial, consulta la base de datos y generaré una lis...

6  Mono alrededor con mono encuesta y ASP.NET MVC  ( Monkeying around with survey monkey and asp net mvc ) 
Intro He sido un desarrollo de escritorio durante mucho tiempo, y nunca he tenido que Mono con el desarrollo web hasta hace muy poco. Tengo la necesidad de ...

3  Master Detalle Insertar en Entity Framework 6 Base de datos Primer MVC 5  ( Master detail insert in entity framework 6 database first mvc 5 ) 
Tengo un DB con una tabla maestra llamada "Facturas" y otra tabla de detalles "Facturas_Detalle". Me gustaría insertarlos, por lo que esta es una "base de dat...

14  Pruebas de repositorio y controlador  ( Repository and controller tests ) 
últimamente he estado investigando cómo la mejor unidad prueba un repositorio de EF y le ha dado un repositorio adecuadamente probado, qué para probar en el...

23  ¿Cómo escribir elegantes trozos condicionales de marcado en vistas a la pista de afeitar?  ( How to write elegant conditional bits of markup in razor views ) 
Supongamos el siguiente modelo: static void Main(string[] args) { var subject = new Subject<string>(); var my = subject.GroupBy(x => x); my.S...

1  Guardar datos a una sesión  ( Saving data to a session ) 
Estoy un poco confundido Si ahorrar la información al código de sesión a continuación, pertenece a la acción del controlador como se muestra a continuación o ...

3  Carro de la compra AJAX con cantidad +/- Botones  ( Ajax shopping cart with quantity buttons ) 
Soy un desarrollador junior (Pareja de años) y muy nuevo en AJAX. Estoy escribiendo una solicitud de inventario interna construida en MVC y en este momento ...

3  Seguimiento simple de usuarios en línea en ASP.NET  ( Simple tracking online users in asp net ) 
Escribí un seguimiento de usuarios simples en línea para mi proyecto ASP.NET MVC. en global.asax, agregué: protected void Session_Start(Object sender, ...

2  Lógica de negocios en controlador  ( Business logic in controller ) 
LED por la premisa recientemente leída "Controladores magros y modelos de grasa" He llegado a la conclusión de que mi controlador podría ser demasiado gordo ...

5  Repositorio genérico para aplicaciones web  ( Generic repository for web apps ) 
Estaba desarrollando una aplicación web usando entity Framework 6 y MVC 5. Para la capa de acceso a datos, alivié el trabajo y escribí un repositorio genérico...




© 2022 respuesta.top Reservados todos los derechos. Centro de preguntas y respuestas reservados todos los derechos