Java Reporting With MS Word

Isn't it wonderful if we can generate MS Word documents as reports from our Java application.... There are number of way to generate MS Word documents from Java such as using Jakarta POI (Poor Obfuscation Implementation) from the Apache Jakarta Project.
But there is a much easier way to do it, by using WordprocessingML. It is an XML schema developed my Microsoft to create word documents and their formating. Using the XML tags in WordprocessingML we can create our word document very easily.
Here is a small code fragment that displays "Hello World"...

<?xml version="1.0"?>
<?mso-application progid="Word.Document"?>
<w:wordDocument
xmlns:w="http://schemas.microsoft.com/office/word/2003/wordml">
<w:body>
<w:p>
<w:r>
<w:t>Hello World.</w:t>
</w:r>
</w:p>
</w:body>
</w:wordDocument>

Save this as .xml and open using MS word. You will be able to see output like in this figure.















Lets analyze important tags in the code.
  • <?mso-application progid="Word.Document"?> is a processing instruction that tells Windows to treat this XML file as a Word document. You must put it in the document for it to be recognized by Word and Windows. The text-related elements for WordprocessingML have the prefix w.
  • <wordDocument/> defines a Word document. You can see that w's namespace is defined here.
  • <body> is a container for text in the document.
  • <p> defines a paragraph.
  • <r> defines a run of other elements. Inside this tag, you should place tags like <t>, <br>, and so on. All elements inside a <r> element can have a common set of properties.
  • <t> is the element that encloses actual text.
You can find the complete Office 2003 XML Reference Schemas from the Microsoft web site.
http://www.microsoft.com/downloads/details.aspx?familyid=fe118952-3547-420a-a412-00a2662442d9&displaylang=en

Now you know the basics of WordprocessingML. Next thing to do is to use some king of XML library and generate the XML document according to WordprocessingML Reference Schema. Here I'm using dom4j XML library.



import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.HashMap;

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.Namespace;
import org.dom4j.QName;

/**
* @author sandarenu
*
*/
public class WordMLTest
{
/**
* Create the xml for head part of the word xml
* Add processing and schema info.
* Created on: Jun 23, 2007
* @Author sandarenu
* @return
*/
public static Document createDocument()
{
Document doc = DocumentHelper.createDocument();
HashMap pmap = new HashMap();
pmap.put("progid","Word.Document");
doc.addProcessingInstruction("mso-application",pmap);

Element root = DocumentHelper.createElement("w:wordDocument");
//Set up the necesary namespaces
root.setQName(new QName("wordDocument",new Namespace("w","http://schemas.microsoft.com/office/word/2003/wordml")));

Element e2 = DocumentHelper.createElement("w:body");
Element e = DocumentHelper.createElement("w:p");
Element e1 = DocumentHelper.createElement("w:r");
Element e3 = DocumentHelper.createElement("w:t");

root.add(e2);
doc.add(root);
e3.setText("Hello World");
e1.add(e3);
e.add(e1);
e2.add(e);

return doc;
}

/**
* Created on: Sep 29, 2007
* @Author sandarenu
* @param args
*/
public static void main(String[] args)
{
try
{
Document doc = createDocument();
File outputFile = new File("c:\\hello.xml");
FileWriter out = new FileWriter(outputFile);
doc.write(out);
out.flush();
out.close();
}
catch (IOException e)
{
e.printStackTrace();
}

}

}

Using this simple logic you can generate very complex word reports using Java. Have fun....

You can download the source code.

 

One Stop for Keyboard Shortcuts........

Are you using keyboard shortcuts when using applications? If not you better start using them because they can save lot of time and make the work much easy.
In one of my previous posts I've put some shortcuts that you can use with Windows key. Today I found a wonderful website that contains huge list of shortcuts for various applications. It's called KeyXL. Hope you'll find it very useful.
 

I'm Back...

It has been more than 1 1/2 months since I've done my previous post. It has been very tough time for me with all of the academic activities in the university. Last semester was the toughest semester yet. Had to complete back to back assignments without break ant then had to prepare for the exam. Now it’s all finished.
With this exam our general degree finishes. But I’m planning to do the special as well, so I’ve another year to go before finishing. There is going to be two months break before start of 4th year. So I can have little bit of break and do few more blog posts :)

 

Got the Last one...

Guess what..... I got the last book, Harry Potter and Deathly Hallows.

It took me around 6 hours to read through 607 pages of true magic. I have to admit that I skip through some pages (got to read the book again). I was so anxious to find out what will happen at the endJ.K had stated that 2 main charters would die at the end; I always feared that one would be from the trio, Harry, Ron or Hermione. But I was wrong. It had a much better ending that expected. Snape proved to be a good guy; Harry defeats the dark Load.Finally Harry-Ginny and Ron-Hermione got married and J.K. finished the great magical story with “All was well”.

 

The Two F-Words You Should Love

This is a very nice article I saw at lifehack.org. Hope it will be useful to you.....


Lincoln


Make Failure and Frustration Your Friends: A History Lesson

We all experience failure and the subsequent frustration. But how you handle those tormentors makes all the difference in your final outcomes. Oftentimes the peak of frustration comes right before a major breakthrough. That's if you don't quit. So don't quit! Instead use the energy behind that frustration to break through to a new level of strategy. Make failure the friend that brought you to breakthrough's doorstep! Let frustration be the energy that propels your leap across the chasm!

What follows are several success stories from history where failure was a frequent companion throughout these great people's lives. Let's all take some inspiration from their stories.

Read the complete article >>>



 

FIT wins Imagine Cup again.....

It was an unbelievable atmosphere yesterday at Galadari Colombo as FIT guys and gals won the Imagine Cup Sri Lanka Competition for the 3rd Consecrative time. Yeh!.. that's right it was for the 3rd Consecrative time that FIT won this most prestiges software competition in Sri Lanka.
This time it was team "SARA" presenting the Application "ISECED", who did the magic for our faculty. And again it was the same wining combination as last 2 yeas, one girl and 3 guys;"Ruwindi", "Sanju","Amila", and "Anurudha".

They will fly to S.Korea to participate for the Imagine Cup 2007 global competition soon.
Good luck team and congratulations.

There is more good news, in addition to the championship FIT won the 2nd runners up as well. That was team Team "Sanhitha" presenting the application "Irrdhipada" who did that.

Congratulations to them as well.
And also there was one more team team from Faculty of Information Technology who participated for this year finals, team "Rawana" presenting the application "Virtual Desk". Even though they couldn't make it to the top 3 teams they also gave a good fight and there application was wonderful.


Congregational to Rawana as well.
 

Good Bye Navantis.....

Last week I said good bye to Navantis.
It was a very difficult decision to be made, but I had to do that since I have to put my full effort for my academics. My nine month experience at Navantis was great. I learn a lot during my internship and part time period.
I'd like to thank all my colleagues at Navantis who helped me a lot during last nine months. Especially CEO Indaka, Duneel and Irzana.

 

How to use the Windows key....


Are you using the Windows Key in your keyboard? It comes very handy on occasions. Followings are some few useful short cuts that can be used with Windows key.

W = Windows Key

W: Opens Start Menu
W+ E: Opens up Windows Explorer
W+ R: Opens the Run command.
W+ U: Opens Utility Manager
W+ L: Log Off
W+ F: Search files on your computer
W+ D: Show Desktop [will switch back and forth from all minimized and back again]
W+ F1: Help Menu
W+ Pause/Break: System Properties
W + Ctrl + Tab: Cycles through Tabs in your current app [eg. Firefox’s last focused tabs]
W+ Tab: Cycles Through Buttons in Taskbar
W+ M: Minimize all open windows.
W+ Shift+M: Maximize the windows you had open before minimizing
W+B: Set focus to the first System Tray Icon [which is the arrow if you enable the Hide Inactive Icons option]
CTRL+W +F: Search for computers

 

Debugging SQL Server Stored Procedures

Did you know that we can debug SQL Server Stored Procedures....
Yes we can debug SPs from Visual Studio. We can put break points, can execute statement by statement and much more...


Read this article for more >>

 

How to create easy-to-use Outlook e-mail templates?

Do you usually send same type of outlook email message over and over again with just small changes to the content? So how do you do that? Type same thing all the time or copy and paste content from old message? I think most of the times you are using the copy and paste method. I also did the same thing till I found out how to create email templates in Outlook.
With few simple steps we can create a menu of email templates in outlook. So you never have to find old message, copy-paste-edit. Just select from the mail templates menu edit and send.

If you have configured outlook to use Word as default email editor you have to change that temporally. You have to use outlook email editor to create the templates. To do that;
1. Go to Tools | Options and click the Mail Format tab.
2. De select the Use Microsoft Word To Edit E-mail Messages check box (Figure A) and click OK.


To switch back to using Word as your editor, just go back to the Mail Format tab and reselect that option.

Creating Email Templates

Create a new email message as normally we do. Enter the text into the body of the message. If the message template will contain the same words in the subject line, fill in the Subject field as well. You can also fill in the To, Cc, and Bcc fields with addresses if you will always be sending the
message to some of the same people. After finishing it, go to File | Save As to open the Save As dialog box and choose Outlook Template (*.oft) from the Save As Type drop-down list.


Close new message window.(Click no when asked to save changes)

Creating the Menu

To create the menu, right-click on an Outlook tool bar and choose Customize from the shortcut menu to open the dialog box.


Now, click on the Commands tab, scroll to the bottom of the Categories list box, and choose New Menu. The New Menu item will appear in the Commands list box.


Drag the New Menu item to the Menu bar where you want menu to appear. Once the New Menu item appears on the Menu bar, right-click on the item and Replace the default name in the Name field with E-mail Templates and press [Enter].



Adding Templates to the Menu

To add your template as menu item to the newly created menu, from Customize dialog box, choose File from the Categories list box. Then, select Mail Message from the Commands list box and drag it to the E-mail Templates menu. When the menu opens, drop the Mail Message item on it.


Right-click on the item and replace the default Name field entry with the name of one of your templates. Then, click Assign Hyper link at the bottom of the menu and select the Open command. In the Assign Hyper link: Open dialog box, locate and select your template file and click OK.



Just repeat these steps to add any other templates you want on the menu. When you're finished, close the Customize dialog box. Now, anytime you need to compose an e-mail message that will include a specific version of email text, pull down the E-mail Templates menu and select the appropriate template.

Technorati Tags:
 

How to Say NO....

How hard it is to say no to someone?... For me it is a very difficult thing. How about you? I think most of you also have the same problem.
Today I came across a nice article on Lifehack.org on "The Gentle Art of Saying No". It explains 10 tips on how to say no.
  1. Value your time. Know your commitments, and how valuable your precious time is. Then, when someone asks you to dedicate some of your time to a new commitment, you’ll know that you simply cannot do it. And tell them that: “I just can’t right now … my plate is overloaded as it is.”
  2. Know your priorities. Even if you do have some extra time (which for many of us is rare), is this new commitment really the way you want to spend that time? For myself, I know that more commitments means less time with my wife and kids, who are more important to me than anything.
  3. Practice saying no. Practice makes perfect. Saying “no” as often as you can is a great way to get better at it and more comfortable with saying the word. And sometimes, repeating the word is the only way to get a message through to extremely persistent people. When they keep insisting, just keep saying no. Eventually, they’ll get the message.
  4. Don’t apologize. A common way to start out is “I’m sorry but …” as people think that it sounds more polite. While politeness is important, apologizing just makes it sound weaker. You need to be firm, and unapologetic about guarding your time.
  5. Stop being nice. Again, it’s important to be polite, but being nice by saying yes all the time only hurts you. When you make it easy for people to grab your time (or money), they will continue to do it. But if you erect a wall, they will look for easier targets. Show them that your time is well guarded by being firm and turning down as many requests (that are not on your top priority list) as possible.
  6. Say no to your boss. Sometimes we feel that we have to say yes to our boss — they’re our boss, right? And if we say “no” then we look like we can’t handle the work — at least, that’s the common reasoning. But in fact, it’s the opposite — explain to your boss that by taking on too many commitments, you are weakening your productivity and jeopardizing your existing commitments. If your boss insists that you take on the project, go over your project or task list and ask him/her to re-prioritize, explaining that there’s only so much you can take on at one time.
  7. Pre-empting. It’s often much easier to pre-empt requests than to say “no” to them after the request has been made. If you know that requests are likely to be made, perhaps in a meeting, just say to everyone as soon as you come into the meeting, “Look guys, just to let you know, my week is booked full with some urgent projects and I won’t be able to take on any new requests.”
  8. Get back to you. Instead of providing an answer then and there, it’s often better to tell the person you’ll give their request some thought and get back to them. This will allow you to give it some consideration, and check your commitments and priorities. Then, if you can’t take on the request, simply tell them: “After giving this some thought, and checking my commitments, I won’t be able to accommodate the request at this time.” At least you gave it some consideration.
  9. Maybe later. If this is an option that you’d like to keep open, instead of just shutting the door on the person, it’s often better to just say, “This sounds like an interesting opportunity, but I just don’t have the time at the moment. Perhaps you could check back with me in [give a time frame].” Next time, when they check back with you, you might have some free time on your hands.
  10. It’s not you, it’s me. This classic dating rejection can work in other situations. Don’t be insincere about it, though. Often the person or project is a good one, but it’s just not right for you, at least not at this time. Simply say so — you can compliment the idea, the project, the person, the organization … but say that it’s not the right fit, or it’s not what you’re looking for at this time. Only say this if it’s true — people can sense insincerity.
 

Famous Quotes from Steve Jobs


From the recent challenge on DRM, to the iPhone hype from his presentation, and the popular iPod madness, we know Steve Jobs is a marketing genius. But that’s not the only it, he has his own view of what’s successful and the view of leadership and career. Ririan Project selected 10 quotes from Steve Jobs and describe them in details how you can learn Jobs’ way to be successful:
  • “Innovation distinguishes between a leader and a follower.”
  • “Be a yardstick of quality. Some people aren’t used to an environment where excellence is expected.
  • “The only way to do great work is to love what you do. If you haven’t found it yet, keep looking. Don’t settle. As with all matters of the heart, you’ll know when you find it.”
  • “You know, we don’t grow most of the food we eat. We wear clothes other people make. We speak a language that other people developed. We use a mathematics that other people evolved… I mean, we’re constantly taking things. It’s a wonderful, ecstatic feeling to create something that puts it back in the pool of human experience and knowledge.”
  • “There’s a phrase in Buddhism, ‘Beginner’s mind.’ It’s wonderful to have a beginner’s mind.”
  • “We think basically you watch television to turn your brain off, and you work on your computer when you want to turn your brain on.”
  • “I’m the only person I know that’s lost a quarter of a billion dollars in one year…. It’s very character-building.”
  • “I would trade all of my technology for an afternoon with Socrates.”
  • “We’re here to put a dent in the universe. Otherwise why else even be here?”
  • “Your time is limited, so don’t waste it living someone else’s life. Don’t be trapped by dogma - which is living with the results of other people’s thinking. Don’t let the noise of other’s opinions drown out your own inner voice. And most important, have the courage to follow your heart and intuition. They somehow already know what you truly want to become. Everything else is secondary.”
Technorati Tags:
 

How to Debug Javascripts - Part2 (Firefox)

This is the part of the my How to debug Javascripts artical. This one will explain how to debug on Firefox using Firebug. See my previous artical on how to debug in Internet Explorer.

Firebug is not only a javascript debugger, it is a complete web debugging tool where you can explore the html DOM and much much more. And it is very easy to use. Once you install Firebug you will get a menu item in under the Tools menu. Using that you can enable and disable firebug for selected sites.



Once you open the Firebug you can inspect the javascripts under the Script tab and do the debugging. You can put breakpoints just by clicking the near the line number.



One special thing with Firebug is that you can put conditional break points. To add conditional break points just right click near the line number you want to put the break point and type your condition.



When there are Javascript errors in the page it is shown in the Firefox status bar. Once you click on that it will open all the errors in the console with possible reasons for that error. This will be very useful for you to find bugs in your application.



You can get more information on Firebug for Firebug site.



Technorati Tags: , ,
 

Happy Sinhala and Tamil New Year

 

Navantis Avurudu Festival

It's Sinhala and Tamil New Year time.....
Navantis had organized a wonderful New Year festival last Sunday (8th April) at Brows Beach Hotel Negambo. It was wonderful event. Almost all of the employees and their family members participated for this event.
Festival started with a traditional breakfast which included Kevum(Oil Cakes) and Kiribath(Milk Rice). We had lots of game on that day. I participated for Goni Race(Sack Race) and Kaba Adeema(Tag-o-War). It was very enjoyable day.





































See more photos in my Paccasa albem >>
 

How to get over the fear of public speaking

If you have problems in public speaking (like me), this is a good artical to read. It gives some simple methods to get rid of the fear of public speaking. Techniques described in the artical are;

  • Practice your speech in front of a mirror
  • Practice your speech facing a wall
  • Practice with a friend
  • Practice with a peer (non-friend)
  • Record yourself
  • Do a dry run
  • Don’t only practice in front of your family

How to get over your fear of public speaking - lifehack.org>>

 

Internet Explorer 7 Keyboard shortcuts

If you are using Internet Explorer 7, here are some useful keyboard shortcuts that will make your life easy.

Basic tasks

[F11]

Toggle full screen mode

[Alt]

Toggle display of menu bar (if it's not set to display)

[Ctrl]=

Zoom in

[Ctrl]-

Zoom out

[Ctrl]0

100 percent zoom

[Ctrl][F]

Search for selected text on page

[Ctrl]N

Open current page in new window

[Ctrl]A

Select everything on page

[F5]

Refresh current page

[Ctrl][F5]

Refresh cache and current page

[Esc]

Halt downloading page

[Alt]D

Select text in Address bar

[F4]

Display addresses you've typed

[Ctrl][Enter]

Add www and .com to the beginning and end of text entered in Address bar

[Ctrl][Shift][Enter]

Add http://www to the beginning of text entered in Address bar

Navigation

[Alt]Home

Go to your home page

[Alt] Left arrow (or [Backspace])

Go to previous page

[Alt] Right arrow

Go to next page

[Tab]

Move forward through items on page

[Shift][Tab]

Move backward through items on page

Tabs

[Ctrl] Click

Open a link in its own tab in background

[Ctrl][Shift] Click

Open a link in its own tab in foreground

[Ctrl]T

Open new tab in foreground

[Ctrl][Tab] (or [Ctrl][Shift][Tab] to reverse)

Cycle between tabs

[Ctrl]W (or [Alt][F4]

Close current tab

[Ctrl] number

Jump to specific tab by number (1 through 8)

[Ctrl]9

Jump to last tab

[Ctrl][Alt][F4]

Close all but current tab

[Ctrl][Shift]Q

Display Tabs list

[Ctrl]Q

Toggle Quick Tabs view

Searching

[Alt][Enter]

Open search results in new tab after typing search text in Search box or Address bar

[Ctrl]E

Jump to Search box

[Ctrl] Down arrow

Open Search Provider menu (when you're in Search box)

Printing

[Ctrl]P

Open Print dialog box

In print preview…

[Alt][P]

Open Print dialog box

[Alt]U

Open Page Setup dialog box

[Alt]O

Set to portrait orientation

[Alt]L

Set to landscape orientation

[Alt]E

Toggle headers and footers on and off

[Alt]S

Change print size

[Alt]N

Show multiple pages

[Alt]1

View full page

[Alt]W

View page width

[Alt]C

Close Print Preview

Menu access

[Alt]M

Open Home menu

[Alt]R

Open Print menu

[Alt]J

Open Tools menu

[Alt]O

Open RSS menu

[Alt]L

Open Help menu

Favorites, history, feeds

[Ctrl]D

Add current page to Favorites

[Ctrl]B

Open Organize Favorites dialog box

[Alt] Up arrow or Down arrow

Move selected item up or down list in Organize Favorites dialog box

[Alt]C

Open Favorites Center

[Ctrl]I

Open Favorites Center with favorites displayed (Add [Shift] to pin the list open)

[Ctrl]H

Open Favorites Center with history displayed (Add [Shift] to pin the list open)

[Ctrl]J

Open Favorites Center with feeds displayed (Add [Shift] to pin the list open)

[Alt]Z

Display Add To Favorites menu

[Alt]I

Display all feeds in feed view

[Alt]M

Mark feed as read in feed view

[Alt]S

Jump to Search box in feed view



 

How to Debug Javascripts - Part1 (Internet Explorer)

If you are involved with web development then at some point you may wanted to debug Javascripts that you put in to your web pages. The problem is how to debug them. When I first started using Javascripts few month back I didn't knew a debugger to use with Javascripts. So what I did was to put alerts every where to find out the problem. But that was not a good method. So I did a research on Javascript debuggers. After few minutes of Google search I found few good tool that can be used to debug Javascripts. With this post I'll show you how debug in Internet Explorer, and later with another post I'll explain how to debug with Firefox.

With IE you can use Microsoft Script debugger and Visual Studio as debuggers.

You can download it form Microsoft website.
To use the debugger, first you have to enable script debugging. Go to tools- options- tab. Make sure that “Disable Script Debugging (other)” and “Disable Script Debugging (Internet Explorer) are NOT checked.




















Now you are ready to debug. Use View- View- Debugger- at next statement to run Debugger. This will break the execution on the next Javascript call and will open the debugger.

















Alternately, you can put a line like this in your Javascript code.
debugger;
It will create a breakpoint automatically.

















If any exceptions occurred in javascript execution IE will show a message asking whether to debug or not.










Select yes. Then it will display possible set of debuggers.




















Now you are debugging. Just step into as you do in any 0ther debugger.



You can use command window to to execute codes. From this little window you can easily check and re-assign values (at "run-time") to any of the variables that have been defined. Launch it from the View menu of the debugger or by clicking the button on the very right-hand-side of the toolbar.













I created a webpage which contains buggy Javascript. If you wish you can use that to test the debugging.
http://sandarenu.googlepages.com/javascriptdebugg
 

Yahoo Mail Tips and Tricks


Yahoo Mail Beta


While I was browsing the web today I came acrose an interesting blog post on Yahoo mail beta tricks. I'm not using my yahoo mail regularly since internet connection slowness. It is a headaches to use new beta UI with a slow internet connection. It takes lots of time to load a email. But it a nice UI, with very nice use of AJAX.

If you are using Yahoo mail beta this will be a good help to improve your efficiency.



Top 11 Yahoo Mail Tips and Tricks />


Technorati Tags:
 

New Features to My Blog

I added few new features to my blog. I changed my label section in to Tag Cloud. This was a feature I wanted to add to my blog for some time. I finally managed to find a method to do that. I had to modify my template for that. I found the code and the instruction to do it in phydeaux3 blog. He has given all the instructions on how to do it. I just copied and pasted the code.....
Here's the result, Nice ha...
Other new feature I added was showing related post user go to a specific post in my blog. Related items are taken according to the tags given to that post. You can find the method to do it from Hoctro's blog.

Try these hacks and enjoy......

Technorati Tags:
 

End of the Internship period


For last 6 months I was working as an intern at Navantis IT (Pvt.) Rajagiriya, Sri Lanka. My internship ended last Thursday (22nd Feb). It was very exciting and challenging time period. It is at Navantis that I learned what is actually being a software developer means. At the university we learn lot of theory; in last 6 month I learned how those theories are actually used in the industry. I learned a lot about .Net, ASP web application development and MSSQL 2005 during my internship.
When I first came here I had considerable knowledge about .Net and ASP, but I was mainly using the nice GUI of VS2005 to do all the designs. But the project I was put in to at Navantis required to all the web controls as Custom server controls. We have to cut code for every thing, No drag and drops... At the beginning it was difficult but after creating few custom controls it became much easier. Because of that I learned a lot about C# and .Net controls.
We had a excellent team at Navantis. Everybody was very friendly and helpful. I have to thank everyone at Navantis for all support given. Our next semester (Level3 Semester2) is gong to be staring in mid April, that’s two more months. Till then I'm doing part time at Navantis, 3 days per week. I'm planning to spend other time on Patrick’s Project. And I have to prepare a report about our internship as well.
So I guess there won't be any spare time to relax.
 

Determining the ViewState Size

ViewState is one of the 3 way that used by ASP2.0 to retain state information about the web page. ViewState allows the state of objects (serializable) to be stored in a hidden field on the page. It is transported to the client and back to the server, and is not stored on the server or any other external source. I’m not going to go deep in to what is ViewState or how to use it. You can find more about ViewState here>>.

Since ViewState is kept in the webpage itself, it can become a performance bottleneck. If the ViewState is too large then the roundtrip delay for postback can increase significantly, especially if the user is having slow internet link. So it would be wonderful if we can find out the size of the ViewState during the testing phase of the application. So we can get relevant actions to improve the performance.

To do that create a class (I named it as MainPageBase) class that all the other pages in the application need to inherit. The code for the class is as shown below.

public class EmsBasePage : System.Web.UI.Page
{
/// <summary>
/// Get the page name of the current page.
/// </summary>
/// <returns></returns>
private string GetCurrentPageName()
{
string path = System.Web.HttpContext.Current.Request.Url.AbsolutePath;
if (!String.IsNullOrEmpty(path))
{
System.IO.FileInfo oInfo = new System.IO.FileInfo(path);
string name = oInfo.Name;
return name;
}
else
{
return "";
}

}

protected override void SavePageStateToPersistenceMedium(object state)
{
int viewStateSize = 0;

base.SavePageStateToPersistenceMedium(state);
LosFormatter format = new LosFormatter();
StringWriter writer = new StringWriter();
format.Serialize(writer, state);
viewStateSize = writer.ToString().Length;
string pageName = GetCurrentPageName();
HttpContext.Current.Trace.Warn(pageName + ": The ViewState Size is:", viewStateSize.ToString());
}
}

It writes the size of the ViewState to the Trace. To view the Trace you have to enable it first. To do that adds following line of code within the section in the web.config file.

<trace enabled="true" pageOutput="false" requestLimit="40" localOnly="false"/>

That’s all. Compile the code and do the testing of your application. Finally to view the results of what we did open the Trace viewer(Trace.axd page). For example http://yourApplicationroot/Trace.axd.

Technorati Tags: , ,