вторник, 29 сентября 2009 г.

ASP.NET white space cleaning with no runtime cost

I think many asp.net developer looking at the markup generated by a ASP.NET pages wanted to get rid of those white space without necessity of changing nice indents of their pages and user controls.

Existing solutions of the problem based on one of the two methods: implementing a cleaning HtmlTextWriter and returning an instance of it in Page.CreateHtmlTextWriter  override, or implementing a cleaning Stream and setting the HttpResponse.Filter property to an instance of the Stream.

But both methods incur runtime performance costs (I am going to show in a next post why that happens).
In my solution white space in generated markup removed at pages’ compile time, so that at runtime it looks as if white space was removed manually by the developers.

One would say that it is not actually a solution because it relies on Reflection and depends on implementation details of the particular version of ASP.NET. I would answer – Thanks God that I haven’t had to resort to the help of unsafe code and pointer arithmetic :)

Let’s start with the beginning. When ASP.NET generates C#/VB code for an ASP.NET page it uses ControlBuilders representing almost every entity (except text) in the page tree. Besides holding information about the part of the page it represents, they let controls creators change different aspects of generated code (in .NET 3.5 SP1 including ability to change generated CodeDom). For regular pages control builders exist at compile time only, but in “no compile” pages they actually create at runtime the parts they are responsible for.
As a page at runtime time is a tree of controls, server side code and text , the page at compile time is a tree of control builders. Each builder holds a collection of subbuilders in an ArrayList. Untyped collection is used because literal strings are placed in subbuilders collection not being wrapped in control builders.

Knowing all that we can traverse control builder tree from the root, iterate over the each builder’s subbuilders collection, find instances of strings and replace them with cleaned versions.

Getting access to the root control builder at right time was not easy. I tried different ways but all had shortcomings or inconveniences. But then examining .NET sources by Reflector I found the perfect way - PageParserFilter. PageParserFilter “provides an abstract base class for a page parser filter that is used by the ASP.NET parser to determine whether an item is allowed in the page at parse time”. This ability (among other useful things) was added to ASP.NET 2.0 as a result of cooperation between ASP.NET team and SharePoint team poring their product to ASP.NET. The only method of interest now is PageParserFilter.ParseComplete(ControlBuilder rootBuilder) and it is the right place and time for accessing the root builder. The remaining part is easy. See the attached web site project. Compile the classes in a dll, drop it in  Bin folder, small change to web.config and voilà– ASP.NET white space cleaning with no runtime cost!

BTW the code has been working for a few projects in the wild with no problems.

UPDATE (17 Aug 2010):  I’ve  updated the sample to work with MVC 2  and MVC 3 Preview 1 (including support of Razor view engine).

UPDATE (9 Oct 2010):  Now it works with MVC 3 Beta.

UPDATE (4 May 2011):  Finally with MVC 3 RTW

152 комментария:

  1. Wow! Thanks. I've been looking for this solution for a long time. Even the excellent 'Ultra-Fast ASP.NET' book doesn't cover this topic (tricks of the compile-time stage).

    ОтветитьУдалить
  2. @thorn: Yes, it seems ControlBuilder mechanism is not that flexible bacause it was created mostly for internal purposes

    ОтветитьУдалить
  3. Let's vote for making this mechanism more open: http://aspnet.uservoice.com/forums/41202-asp-net-webforms/suggestions/488607

    ОтветитьУдалить
  4. how do you make this work? I've changed the web.config, added the classes and pasted using Omari.Web.UI in my page and masterpage. It does noghing yet.

    ОтветитьУдалить
  5. @Flori: Have you set debug="false" in your web.config?

    ОтветитьУдалить
  6. This worked like a charm for me. Basically you just need the three class files in the app_Code and build in the project. My page size went form 142kb to 90kb ~50kb reduction.

    Checkout my live implementation at http://fullmeals.net

    ОтветитьУдалить
  7. this is EXCELLENT. I hope you package it up somehow and sell it, honestly. Make a few small improvements to cleaning up additional whitespace and it will be golden. Well done, great work.

    ewart @ ihug dot co dot nz

    wish I knew which button was send in russian!

    ОтветитьУдалить
  8. What about css and js optimization? Is this posible using this technology?

    ОтветитьУдалить
  9. Kiril, unlike web pages, css and js are static in their nature. They can be easily minimized, combined, zipped and cached.

    ОтветитьУдалить
  10. Hi Omari,

    This project sounds great and I'd really like to try it out, but I'm having trouble getting this to work even for the included WebForms or the MMVC2 example projects (I'm not using MVC3 Beta yet, although I'm looking forward to Razor when it goes RTM). I double checked that debug="false" is set and the binaries are where they are supposed to be, I've tried running it from Visual Studio 2010 and from IIS 7.5, and I've even tried re-downloading and extracting the zip somewhere else and starting from scratch again to get one of the examples to work. But no luck. Am I missing something obvious? Is it possible that the recent MVC3 update broke MVC2 support?

    Looking forward to getting it working! :)

    ОтветитьУдалить
  11. Any chance you can update again to include proper support in RC2? I had an issue here http://stackoverflow.com/questions/4414231/why-am-i-getting-asp-net-mvc3-razor-syntax-errors

    ОтветитьУдалить
  12. Anybody have a working version with ASP.NET MVC 3 RTM ?

    ОтветитьУдалить
  13. Hey, great tool! Any chance of an update since the the latest MVC release?

    ОтветитьУдалить
  14. Very impressive... Was looking for exactly this! Thank you very much!

    ОтветитьУдалить
  15. Does it work with AJAX?

    ОтветитьУдалить
  16. Why do you require debug="true"?

    May I step over this check in you code just to debug it?

    ОтветитьУдалить
  17. www.gourmandia.com - Gourmandia is a culinary website offering videos of world-class Michelin rated chefs exhibiting their techniques. Also features documentaries on fine dining restaurant locations and cities, recipes, forum, and more. At www.gourmetrecipe.com - Gourmet Recipe is the place to find the tastiest, healthiest gourmet recipes. Watch videos of great chefs preparing meals, find easy beginner dishes, and more.

    ОтветитьУдалить
  18. There are many ways to improve your cooking abilities into the whole new level. Try to visit these sites http://www.gourmandia.com , http://www.gourmetrecipe.com , http://www.foodiamond.com , http://www.xdestination.com and their sub-domains. Feel free to suggest and recommend what these sites can offer. Online cooking recipes are never been this good for they have featured recipes that are truly remarkable. In addition, the site offers easy and quick recipes with featured video that are easy to follow from the world-class Michelin. Visit now and have some fun.

    ОтветитьУдалить
  19. I appreciate your time and effort to come up this kind of article. Try to take a glance at gourmetrecipe. A recommendation for you to relax and unwind for a while...In that website you will find many tasty and nutritious dishes for you to choose from and your family. I also assure you, you won't regret it for visiting this site.

    ОтветитьУдалить
  20. This is really cool. Thanks for building it!!

    Please consider making this into a Nuget package so it can be easily installed and discovered.

    ОтветитьУдалить
  21. Such a wonderful post. Asp.net Development is one of the most popular application development now-a-days. We are also providing some good tips related to this post.Great work.

    ОтветитьУдалить
  22. This is the best solution I've seen. I tried recompiling for MVC4 but it fails to load the WhiteSpaceCleaningMvcWebRazorHostFactory. Any pointers on what I might need to do in order for it to work?

    ОтветитьУдалить
  23. Very cool post. Nuget package would be a great idea.

    However, It doesn't seem to work with MVC3. I'm getting "Access is denied: 'System.Web.Mvc.Razor.MvcCSharpRazorCodeGenerator'." errors. Is there a workaround to fix it?

    Thanks.

    ОтветитьУдалить
  24. What about version for MVC4?
    The previous versions works great.

    ОтветитьУдалить
  25. Этот комментарий был удален автором.

    ОтветитьУдалить
  26. Nice work. unfortunately, This is not working at all for me in MVC3.
    Can you upload a working solution.It would helpfil if you have a readme.txt file to demonstrate what steps need to follow to make it work.

    ОтветитьУдалить
  27. Great Solution. It helped me a lot.:)

    ОтветитьУдалить
  28. I can see attached solution. Where can I download the code from?

    ОтветитьУдалить
  29. can anyone tell me where can I download the code?

    ОтветитьУдалить
  30. Анонимный22 июля 2014 г., 12:28

    Hi Omari,

    Could you please re-upload the code? Skydrive embed link is broken :(

    Thanks!

    ОтветитьУдалить
  31. Анонимный30 июля 2016 г., 15:37

    Hey Omari,

    Your site is broken, I would realy like to take a look at this library.

    Thanks!

    ОтветитьУдалить
  32. This is ansuperior writing service point that doesn't always sink in within the context of the classroom. In the first superior writing service paragraph you either hook the reader's interest or lose it. Of course your teacher, who's getting paid to teach you how to write an good essay, 
    This is ansuperior writing service point that doesn't always sink in within the context of the classroom. In the first superior writing service paragraph you either hook the reader's interest or lose it. Of course your teacher, who's getting paid to teach you how to write an good essay, 

    ОтветитьУдалить
  33. Thank you a lot for providing individuals with a very spectacular possibility to read critical reviews from this site.
    Best Devops online Training
    Online DevOps Certification Course - Gangboard

    ОтветитьУдалить
  34. Thank you for excellent article.You made an article that is interesting.
    Tavera car for rent in coimbatore|Indica car for rent in coimbatore|innova car for rent in coimbatore|mini bus for rent in coimbatore|tempo traveller for rent in coimbatore|kodaikanal tour package from chennai

    Keep on the good work and write more article like this...

    Great work !!!!Congratulations for this blog

    ОтветитьУдалить
  35. Thanks for Sharing this useful information. Get sharepoint apps development from veelead solutions

    ОтветитьУдалить
  36. Informative content.
    For the best AWS training in bangalore, Visit:
    AWS training in bangalore

    ОтветитьУдалить
  37. nice blog
    get best placement at VSIPL

    get digital marketing services
    seo network point

    ОтветитьУдалить
  38. Thanks for sharing it.I got Very valuable information from your blog.your post is really very Informatve. I got Very valuable information from your blog.I’m satisfied with the information that you provide for me.

    Python Training in Pune
    Python Classes
    Python Placement
    Python Institute Pune
    Python courses

    ОтветитьУдалить
  39. Thanks for your excellent blog and giving great kind of information. So useful. Nice work keep it up thanks for sharing the knowledge.
    Click Here
    For More Details
    Visit Website
    See More

    ОтветитьУдалить
  40. Thanks for sharing it.I got Very valuable information from your blog.your post is really very Informatve. I got Very valuable information from your blog.I’m satisfied with the information that you provide for me.

    DevOps Training in Pune
    DevOps Training
    DevOps Placement
    DevOps Institute Pune
    devops training in pune with placement


    ОтветитьУдалить
  41. Thanks for Sharing This Article.It is very so much valuable content. I hope these Commenting lists will help to my website
    top angular js online training

    ОтветитьУдалить
  42. I am a regular reader of your blog and I find it really informative. Hope more Articles From You.Best Tableau tutorial videos with Real time scenarios . hope more articles from you.

    ОтветитьУдалить
  43. It's almost that time of the year when you get the hottest deals on Web Hosting, you guessed it right! It's time for the Black Friday Web Hosting Deals 2019. Companies are lining up some of the best deals ever for 2019 buyers will have a lot to pick from in the industry.

    ОтветитьУдалить
  44. Thanks a lot for sharing it, that’s truly has added a lot to our knowledge about this topic. Have a more success ful day. Amazing write-up, always find something interesting and here i want to share some thing about mule 4 training.

    ОтветитьУдалить
  45. Thanks for sharing it.I got Very valuable information from your blog.your post is really very Informatve. I got Very valuable information from your blog.I’m satisfied with the information that you provide for me.

    aws course
    aws certification
    aws syllabus
    aws syllabus

    ОтветитьУдалить
  46. Thanks for your excellent blog and giving great kind of information. So useful. Nice work keep it up thanks for sharing the knowledge.
    Visit us
    Click Here
    For More Details
    Visit Website

    ОтветитьУдалить
  47. I am a regular reader of your blog and I find it really informative. Hope more Articles From You.Best
    Tableau tutorial video available Here. hope more articles from you.

    ОтветитьУдалить
  48. Whatever we gathered information from the blogs, we should implement that in practically then only we can understand that exact thing clearly, but it’s no need to do it, because you have explained the concepts very well. It was crystal clear, keep sharing.. i Want to share Some data regarding the websphere tutorial for beginners with free bundle videos is provided.

    ОтветитьУдалить
  49. Thanks for sharing it.I got Very valuable information from your blog.your post is really very Informatve.I’m satisfied with the information that you provide for me.

    data science course form

    ОтветитьУдалить
  50. We as a team of real-time industrial experience with a lot of knowledge in developing applications in python programming (7+ years) will ensure that we will deliver our best in python training in vijayawada. , and we believe that no one matches us in this context.

    ОтветитьУдалить
  51. Этот комментарий был удален автором.

    ОтветитьУдалить
  52. Этот комментарий был удален автором.

    ОтветитьУдалить

  53. Thank you for sharing such a great information.Its really nice and informative.hope more posts from you. I also want to share some information recently i have gone through and i had find the one of the best mule esb training videos


    ОтветитьУдалить

  54. Class College Education training Beauty teaching university academy lesson teacher master student spa manager skin care learn eyelash extensions tattoo spray

    daythammynet
    daythammynet
    daythammynet
    daythammynet
    daythammynet
    daythammynet
    daythammynet
    daythammynet
    daythammynet

    ОтветитьУдалить
  55. Attend The Machine Learning course Bangalore From ExcelR. Practical Machine Learning course Bangalore Sessions With Assured Placement Support From Experienced Faculty. ExcelR Offers The Machine Learning course Bangalore.
    ExcelR Machine Learning course Bangalore

    ОтветитьУдалить
  56. Learn best practice and get your questions answered with our Expert, Register Now for Demo at Apex Trainings Academy.
    full stack developer course in Hyderabad
    full stack developer course

    ОтветитьУдалить
  57. I wanted to thank you for this great read!! I definitely enjoying every little bit of it I have you bookmarked to check out new stuff you post.
    Please check this Machine Learning Course in Pune

    ОтветитьУдалить

  58. This is a wonderful article, Given so much info in it, These type of articles keeps the users interest in the website, and keep on sharing more ... good luck... Thank you!!! machine learning courses in Bangalore

    ОтветитьУдалить
  59. This is a wonderful article, Given so much info in ExcelR Machine Learning Courses In Pune it, These type of articles keeps the users interest in the website, and keep on sharing more ... good luck.

    ОтветитьУдалить
  60. Thanks for Sharing This Article.It is very so much valuable content. I hope these Commenting lists will help to my website
    microservices online training

    ОтветитьУдалить

  61. Thanks for sharing such a great information.It is really one of the finest article and more informative too. I want to share some informative data about c net training and c# videos . Expecting more articles from you. Expecting more articles from you.

    ОтветитьУдалить
  62. Shopclues lucky draw 2020| Shopclues winner 2020|Get to Know Shopclues Lucky Draw Winner 2020. Call Shopclues Helpline Phone Number+91-9835565523 for Shopclues Online Shopping Lucky Draw.
    Shopclues online lucky draw winner
    Shopclues winner 2020
    shopclues car lucky draw

    ОтветитьУдалить
  63. This is so elegant and logical and clearly explained. Brilliantly goes through what could be a complex process and makes it obvious.... sap bi tutorial

    ОтветитьУдалить
  64. Attend The Machine Learning course Bangalore From ExcelR. Practical Machine Learning course Bangalore Sessions With Assured Placement Support From Experienced Faculty. ExcelR Offers The Machine Learning course Bangalore.
    ExcelR Machine Learning course Bangalore

    ОтветитьУдалить


  65. Pretty article! I found some useful information in your blog, it was awesome to read, thanks for sharing this great content to my vision. i also want to share some infor mation regarding sap online course and sap sd training .keep sharing.

    ОтветитьУдалить
  66. Thank you for sharing the best information
    Snapdeal winner 2020 | Dear customer, you can complain here If you get to call and SMS regarding Snapdeal lucky draw, Mahindra xuv 500, lucky draw contest, contact us at to know the actual Snapdeal prize winners 2020.
    Snapdeal winner 2020
    Snapdeal lucky draw winner 2020
    Snapdeal lucky draw contest 2020
    snapdeal winner prizes 2020

    ОтветитьУдалить
  67. Thank you for sharing the blog information
    Snapdeal online lucky draw Winner List 2020 here came up with an Offer where you can win Snapdeal lottery 2020 and more prize by just playing a game & win prizes
    Snapdeal winner 2020
    Snapdeal lucky draw winner 2020
    Snapdeal lucky draw contest 2020
    snapdeal winner prizes 2020

    ОтветитьУдалить
  68. Great blog !It is best institute.Top Training institute In Velachery
    http://trainingsinvelachery.in/bi-bw-training-in-velachery/
    http://trainingsinvelachery.in/solidworks-training-in-velachery/
    http://trainingsinvelachery.in/autocad-training-in-velachery/
    http://trainingsinvelachery.in/ansys-training-in-velachery/
    http://trainingsinvelachery.in/revit-architecture-training-in-velachery/
    http://trainingsinvelachery.in/primavera-training-in-velachery/

    ОтветитьУдалить
  69. Hello Admin!

    Thanks for the post. It was very interesting and meaningful. I really appreciate it! Keep updating stuffs like this. If you are looking for the Advertising Agency in Chennai | Printing in Chennai , Visit Inoventic Creative Agency Today..

    ОтветитьУдалить
  70. Great blog !It is best institute.Top Training institute In Velachery
    http://trainingsinvelachery.in/bi-bw-training-in-velachery/
    http://trainingsinvelachery.in/solidworks-training-in-velachery/
    http://trainingsinvelachery.in/autocad-training-in-velachery/
    http://trainingsinvelachery.in/ansys-training-in-velachery/
    http://trainingsinvelachery.in/revit-architecture-training-in-velachery/
    http://trainingsinvelachery.in/primavera-training-in-velachery/

    ОтветитьУдалить
  71. Nice blog,I understood the topic very clearly,And want to study more like this.
    Data Scientist Course

    ОтветитьУдалить
  72. Thanks for sharing such a great information..Its really nice and informative..

    sapui5 tutorial

    ОтветитьУдалить
  73. NAGAQQ | AGEN BANDARQ | BANDARQ ONLINE | ADUQ ONLINE | DOMINOQQ TERBAIK

    Yang Merupakan Agen Bandarq, Domino 99, Dan Bandar Poker Online Terpercaya di asia hadir untuk anda semua dengan permainan permainan menarik dan bonus menarik untuk anda semua

    Bonus yang diberikan NagaQQ :
    * Bonus rollingan 0.5%,setiap senin di bagikannya
    * Bonus Refferal 10% + 10%,seumur hidup
    * Bonus Jackpot, yang dapat anda dapatkan dengan mudah
    * Minimal Depo 15.000
    * Minimal WD 20.000

    Memegang Gelar atau title sebagai QQ Online Terbaik di masanya

    Games Yang di Hadirkan NagaQQ :
    * Poker Online
    * BandarQ
    * Domino99
    * Bandar Poker
    * Bandar66
    * Sakong
    * Capsa Susun
    * AduQ
    * Perang Bacarrat (New Game)

    Tersedia Deposit Via pulsa :
    Telkomsel & XL

    Info Lebih lanjut Kunjungi :
    Website : NAGAQQ
    Facebook : NagaQQ Official
    Kontakk : Info NagaQQ
    linktree : Agen Judi Online
    WHATSAPP : +855977509035
    Line : Cs_nagaQQ
    TELEGRAM : +855967014811


    BACA JUGA BLOGSPORT KAMI YANG LAIN:
    agen bandarq terbaik
    Winner NagaQQ
    Daftar NagaQQ
    Agen Poker Online

    ОтветитьУдалить
  74. This is so elegant and logical and clearly explained. Brilliantly goes through what could be a complex process and makes it obvious.

    sap bw tutorials

    ОтветитьУдалить
  75. TiketQQ Agen BandarQ Domino99 Bandar Poker dan Bandar66 Online Terbaik Di Asia

    Website paling ternama dan paling terpercaya di Asia ^^
    Sistem pelayanan 24 Jam Non-Stop bersama dengan CS Berpengalaman respon tercepat :)

    * Minimal DEPOSIT Rp 15.000,-
    * Minimal WITHDRAW Rp 15.000,-
    * Tersedia 9 game dalam 1 USER ID
    * Bonus TO 0,5% Setiap 5 hari
    * Bonus Refferal 20%
    * Proses Deposit & Withdraw PALING CEPAT
    * Sistem keamanan Terbaru & Terjamin
    * Poker Online Terpercaya
    * Live chat yang Responsive
    * Support lebih banyak bank LOKAL


    < Contact Us >
    Website : TiketQQ
    Facebook : TiketQQ
    Twitter : TiketQQ
    Instagram : TiketQQ
    LINE : Tiketqq
    WA : +855885063246
    Kontak : TiketQQ
    Blog : Cerita Dewasa

    Agen Judi Online Aman Dan Terpercaya TiketQQ

    ОтветитьУдалить
  76. It’s hard to come by experienced people about this subject, but you seem like you know what you’re talking about! Thanks.
    Java Training in Bangalore

    ОтветитьУдалить
  77. It’s hard to come by experienced people about this subject, but you seem like you know what you’re talking about! Thanks.
    Java Training in Bangalore
    Python Training In Bangalore

    ОтветитьУдалить