Back in the day when i used to debug my code just to inspect what actually the value of variables were, i did it in manual way. Actually that was… what a shame, and if you do too you should know that there is a better way to do that.
Manual way means you write a code to show the value of variable into console or any other interfaces which you as developer can check that value whether it is as you expected or not. Don’t get me wrong, i’m not talking about unit test here.
Visual Studio Debug
Last night i was working on upload image functionality of a web application build on top ASP.NET MVC framework. Like typical of any image form upload , i wrote validation to make sure the image being uploaded by user is only accept jpg,jpeg and png extension. So i wrote this code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
[HttpPost] public ActionResult Create(ArtistDTO artist) { Artist artistToSave = new Artist(); ....................................... ....................................... string imageExtension = Path.GetExtension(artist.Image.FileName).ToLower(); if (!imageExtension.Equals("jpg") && !imageExtension.Equals("jpeg") && !imageExtension.Equals("png")) { ModelState.AddModelError("Image", "Image format only jpg,jpeg and png"); return View(artist); } ........................................ ........................................ repository.Save(artistToSave); return RedirectToAction("Index"); } |
All seems good. I tried to choose zip file to be uploaded and of course the application will complain.
After that i uploaded jpg image but same thing happened, system still complaining. Any idea how this happened?
It happened because the if condition is always true. I began to remember that return value of Path.GetExtension(param) is something with this format “.ExtensionName” so if i choose jpg image that code will return “.jpg” not just “jpg” without dot.
To make sure what is return value of Path.GetExtension(param) i did code debugging. Visual Studio and other modern IDE have this kind of feature.
And yap.. the return value is with dot (.). So i changed the if condition to be like this and everything was good 🙂
1 2 3 4 5 6 |
string imageExtension = Path.GetExtension(artist.Image.FileName).ToLower(); if (!imageExtension.Equals(".jpg") && !imageExtension.Equals(".jpeg") && !imageExtension.Equals(".png")) { ModelState.AddModelError("Image", "Image format only jpg,jpeg and png"); return View(artist); } |