A few months ago, I started receiving the following exception on my website for one of my blogs:
System.Web.HttpException: The state information is invalid for this page and might be corrupted. ---> System.Web.UI.ViewStateException: Invalid viewstate
Immediately, I visited the webpage and it displayed fine. So I refreshed a bunch of times without receiving any errors. Then I tried viewing and posting comments with several browsers...nothing wrong. Then I opened up the code and reviewed it...it looked good. Since it was only happening to one blog, I thought it might have to do with the content of that blog...maybe I accidentally dropped a "<form>" or "<__VIEWSTATE>" tag in the content...nope! I was puzzled and kind of dismissed it for awhile.
Then it started happening more and more...on average, I now receive 2-3 of these errors per day. I started getting a little worried that a handful of visitors couldn't post comments to my website...but I had no ideas what to do.
Then I got a call from a customer. They purchased some blog spamming software and asked me to come to their office, figure out how it works and show them how to use it. Before going there, I researched the product and that's when I figured out my problem. The software I was reading up on asks you what keywords to search blog sites for. Next, it asks you for a blog comment. Finally, it searches the blog sites with the keywords you entered and posts the comment you entered. Not only does it get people to read your comment and visit your website, but it also increases your Google "PageRank" over time...genius! But be careful...if Google sniffs this out, you'll be blacklisted.
This is what is happening to my website...people are running software programs to leave spam comments and are causing exceptions to be thrown. The good news is that I now know it's now my software causing the problems and that I'm successfully blocking a lot of spam thanks to my Captcha code.
Below is the full exception message...I'm posting it so that it is indexed is search engines and others having this problem will now have resolution.
Page: Global.asax
Method: Application_Error
Exception: System.Web.HttpException: The state information is invalid for this page and might be corrupted. ---> System.Web.UI.ViewStateException: Invalid viewstate.
Additional Details:
Client IP: 65.88.129.2 Port: 46644 User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 2.0.50727; .NET CLR 1.1.4322) ViewState: sssssss Referer: Path: /BlogEntry.aspx ---> System.FormatException: Invalid length for a Base-64 char array. at System.Convert.FromBase64String(String s) at System.Web.UI.ObjectStateFormatter.Deserialize(String inputString) at System.Web.UI.ObjectStateFormatter.System.Web.UI.IStateFormatter.Deserialize(String serializedState) at System.Web.UI.Util.DeserializeWithAssert(IStateFormatter formatter, String serializedState) at System.Web.UI.HiddenFieldPageStatePersister.Load() --- End of inner exception stack trace --- --- End of inner exception stack trace --- at System.Web.UI.ViewStateException.ThrowError(Exception inner, String persistedState, String errorPageMessage, Boolean macValidationError) at System.Web.UI.HiddenFieldPageStatePersister.Load() at System.Web.UI.Page.LoadPageStateFromPersistenceMedium() at System.Web.UI.Page.LoadAllState() at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) at System.Web.UI.Page.ProcessRequest(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) at System.Web.UI.Page.ProcessRequest() at System.Web.UI.Page.ProcessRequestWithNoAssert(HttpContext context) at System.Web.UI.Page.ProcessRequest(HttpContext context) at ASP.blogentry_aspx.ProcessRequest(HttpContext context) in c:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Temporary ASP.NET Files\root\6486194d\28a90c6b\App_Web_znedlsbn.2.cs:line 0 at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)Inner Exc:System.Web.UI.ViewStateException: Invalid viewstate. Client IP: 65.88.129.2 Port: 46644 User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 2.0.50727; .NET CLR 1.1.4322) ViewState: sssssss Referer: Path: /BlogEntry.aspx ---> System.FormatException: Invalid length for a Base-64 char array. at System.Convert.FromBase64String(String s) at System.Web.UI.ObjectStateFormatter.Deserialize(String inputString) at System.Web.UI.ObjectStateFormatter.System.Web.UI.IStateFormatter.Deserialize(String serializedState) at System.Web.UI.Util.DeserializeWithAssert(IStateFormatter formatter, String serializedState) at System.Web.UI.HiddenFieldPageStatePersister.Load() --- End of inner exception stack trace ---Inner/Inner Exc:System.FormatException: Invalid length for a Base-64 char array. at System.Convert.FromBase64String(String s) at System.Web.UI.ObjectStateFormatter.Deserialize(String inputString) at System.Web.UI.ObjectStateFormatter.System.Web.UI.IStateFormatter.Deserialize(String serializedState) at System.Web.UI.Util.DeserializeWithAssert(IStateFormatter formatter, String serializedState) at System.Web.UI.HiddenFieldPageStatePersister.Load()
I recently had a requirement from a customer to generate a PDF that looked exactly like the webpage. Instead of trying to recreate the webpage in Crystal or SQL Server Reports, I decided it would be much easier, cheaper and maintainable to simply take the webpage's HTML, load it into a 3rd party PDF generator and create a PDF.
Below is the code you need to do this.
The important part is that you need to override the page's "OnPreRenderComplete" event and extract the HTML from the base.
1protectedoverridevoid OnPreRenderComplete(EventArgs e)
2{
3 GeneratePDFFromPageHTML();
4}
5
6protected void GeneratePDFFromPageHTML()
7{
8 StringWriter sw;
9 HtmlTextWriter htmltw;
10
11 try
12 {
13 //Get the current page's HTML
14 sw = new StringWriter();
15 htmltw = new HtmlTextWriter(sw);
16 base.Render(htmltw);
17 StringBuilder html = sw.GetStringBuilder();
18
19 //Generate PDF with HTML here. Code not supplied
20 //since there are so many 3rd party PDF generators.
21 //When done generating PDF, either load it into the
22 //browser or stream it back as an attachment
23 }
24 catch (Exception ex)
25 {
26 //Handle exception
27 }
28 finally
29 {
30 if (htmltw != null)
31 {
32 htmltw.Close();
33 htmltw.Dispose();
34 htmltw = null;
35 }
36 if (sw != null)
37 {
38 sw.Close();
39 sw.Dispose();
40 sw = null;
41 }
42 }
43}
Over the past 10 years, I have had the pleasure to work with some great customers. I also have had the unfortunate honor of working with some "difficult" customers. Below are a few things I have learned and my advice to you if you're looking to build or re-build your company website. Good luck!
1. Do Your HomeworkThe number one complaint from designers and developers is that customers cannot articulate what they want. Designers and developers are not mind readers and often are not very familiar with your industry. You need to specify what features you want exactly with great detail. Visit competitor sites and see what they have. It's OK to copy ideas, but make them unique in your own way if possible. The design process is very important and takes time. There will be several iterations until a finished design is made. But if you have a clear vision, you can save time and money because the designers won't have to keep reworking the design while you figure out what you want.
2. Don't Cut CornersThere are several phases to any website project. A typical life cycle is:
1. Project Inception - Imagine how great the site could be if it were created without limits. Write these ideas down.
2. Project Launch Meeting - Brainstorming session. No decisions will be made, but you'll talk about things like colors, fonts, logos, navigation and who the site will target (very important!).
3. Project Requirements Document - Essentially you want this document to summarize what the team currently thinks the project will look like when it's completed. There's no need to get it all right or feel tied down.
4. Discovery Documents - With these documents, you'll get down to working out who your target audience is, what they want, the sections of the site, and what they will contain. This will become the true roadmap for the project.
5. Prototype - The prototype will turn your documents into a reality. Now is the time to simply produce a visual that the client can see.
6. Development - The designers will give the developers the necessary files and developers will build the website. After some time, a rough website will be produced and give everyone a chance to see where the project now stands...and appreciate how far it has come.
7. Testing and Final Approval - Get lots of people to use your site and make sure they enjoy it. Take their comments into consideration and tweak where appropriate.
8. Go Live - Turn the site onto the world. Monitor the usage, watch for errors and fix them. Get people's reaction.
Maintenance will be necessary. A lot of people think that once the site is live, it's done. Not true at all. I'll discuss this more later (#7 below).
3. You Need To Provide ContentOnce you have your Discovery documents complete, the designers and developers will start working. This is when you need to start building the content for the website. Start early and stay on top of it! Writing content for most people is difficult and takes a lot of time. It's very easy to push it off until the end...this will severely push back your timeline. Also, some customers think the web designers or developers write the content. This doesn't make any sense. It's your business, you're the expert. You have to write the content.
4. Too Flashy = No TrafficWeb sites don't need to be over-the-top to get results. Some clients will ask for lots of animation and cool graphics. They want a splash page built in Flash, and Javascript rollover images for menu items. They don't understand that (a) these things can turn off visitors who don't have a fast Internet connection or up-to-date browsers or extensions; (b) these things eat up bandwidth; (c) these things make a web site much less visible to search engines. In short, they rarely help, and often hurt, the majority of business web sites. The structure should be defined by the content, not the look. The look is important but only to support the content...not to control the content. A lot of designers are user interface experts - listen to them.
5. It Costs More And Takes Longer than You ThinkJust because you can create a website in a few minutes with an off-the-shelf package doesn't mean it's the right solution for your business. These off-the-shelf packages are bought by thousands of people and your website will looked like a cheesy, canned solution. They also only have a limited feature set. If the feature you need isn't there, you will not get it and no developer will be able to add it in.
It's not that the website is hard to build, it's just that it takes time. Good, experienced developers who have built hundreds of websites over that time typically create a library of common code. These developers can help you save a lot of money by reusing their common code...but if you have something unique it needs to be created from scratch. Just remember that you only get what you pay for. If you get something cheap, there is always a catch. The lowest bidder is the lowest bidder for a reason. Also, most people in the Web industry are clueless. The majority of web developers need to update their skills to what is required for the 21st century. Anyone can build a website...but it doesn’t always mean that they should.
6. If You Build It, They Won't Necessarily ComeThere's a commercial where a company launches their website and immediately starts getting millions of sales. That doesn't happen. Your website will not be the first result in any Google search the first day you go live. Getting your website on the first page of Google takes time (it'll take months), commitment and money. Building the site is not the same thing as marketing it. There are hundreds of companies whose sole purpose is to help you market you website. It's not "If we build it, they will come, and throw money at us." For most businesses, it's more like "If we build it, and dedicate effort to keeping it fresh and up to date and interesting, and if we're selling something people really want to buy, and if we think of the web site as only a part of our marketing effort, and if we pay attention to having clean code and optimized pages and tweak our pay-per-click keywords effectively, we should be more successful with a website than without."
7. Maintenance Is A MustI know a lot of developers who do not create maintenance sites for their customers. Whenever the customer needs an update, they have to pay for the developer's services. This nickle-and-diming approach should be avoided. When creating your Project Requirements document, be sure a secure administrative section of your website is developed. Every reasonable feature of your website must be maintainable...meaning products and content, but not the design and most look-and-feel. You also need to have the ability to move your website from one provider to the next without having to contact a developer. All web sites require at least some degree of maintenance. Try to control that maintenance yourself. After a year or two, major changes (i.e. complete website redesign) may be needed.
8. Designers And Developers Are ProfessionalsMany web designers and developers are appalled at assumptions that their skills are basic and valueless. Professional design takes a lot of work, skill, education and ability. Do you think that a professional chef is a person who puts a bunch of ingredients that don't match into a big pan and sticks it in the oven? You should expect to assign one person from your company to interact with the designers and developers. There is nothing that will cause more confusion, anger and disappointment than the fact that one designer has 3 or 4 people calling and e-mailing them every 5 minutes...each person changing what the last person said.
Conclusion
I believe these points are very important. As a developer, I try to have a discussion about these points with all new customers. Almost all "get it" and agree...and it's a pleasure to do business with these people. In fact, if I know they will work this way, I know the process will be faster and easier and, therefore, much more affordable for them. If I know the customer is going to do things the hard way, I will add in the necessary hours to compensate for the extra time needed to complete their project.
Bonus (for Developers): From My Experience...Over the past 10 years, I have built hundreds of websites and still learn new things everyday. Here are some of my practices that allow me to work very fast and efficiently:
Design: I used to use graphic artists, but now use templates whenever possible. Why? A custom design costs between $1,000 and $4,000. Professional templates are about $60. Sure, other people can buy these templates too, but for most small-medium businesses, who cares? It's worth saving the thousands of dollars. Also, you get all of the source files, so you can tweak them to make them your own. All you'd have in common with others is the colors/style...it's your own logo and content...change the graphics. My favorite template site: http://www.templatemonster.com
Development: I write all code in .NET, C# specifically. The .NET 1.0 platform came out in 2001 and has developed into the most amazing development platform. The set of libraries and namespaces is so large and includes everything you could possibly want to do. .NET is by far the fastest development platform and is the future of software. (Bold, but true statement) When appropriate, use the Microsoft Application Blocks... I use several of them in most of my projects.
Development: Build your own library of reusable code. Over the past few years, I have continued to extend my "BrianPautsch" namespace. It contains distinct classes and methods for specific tasks including exception handling, validation, emailing, form helpers, database access, ecommerce, SSL, image handling, captcha, advanced search engines, etc. When I start on a new project, I can complete more than 1/2 the project requirements in less than an hour because of my library of code.
Development: Use a code generator. There are a bunch out there, so you don't have to create your own. I created my own a few years ago and use it to generate parts of the Business layer, the Database layer and all related Stored Procedures. Once I have the database schema completed, I can generate code and stored procedures in seconds with just one click. Not only am I saving hours and hours of work (extremely boring work!), but the code is 100% perfect and ready to be used. Now, with my library of code and the code generator, I can have a website 75% complete in only an hour or so. This is how I can create a fully functional ecommerce site in a weekend.
Search Engines: Create Google Sitemaps with my Google Sitemap Generator (shameless plug). I have seen websites get into the Google index within 24 hours this way. I have also seen sites already in Google jump in the results by simply creating a Google Sitemap.