I am a Software Engineer by profession. I do have a lot of time to think about things normal people (or so they like to call themselves) usually don’t and probably don’t discuss as much. I have been in the IT world for a good 7 years professionally, I have heard a lot about Microsoft being a Software evil but why ? The argument I heard countless times was how they included IE as a part of their operating system to kill Netscape and how they don’t encourage competition by bullying the moms and pops software developers out the market .. It is seriously comical to me. Really ? It is a corporation, a business that aim to drives the profit higher for the company. I don’t mind if its providing great application software at the same time. Microsoft made it ridiculously simple to operate computer. Good luck trying to use the Good Ole “*ix” and actually learn anything besides the operating system. But they are evil because they are rich and have money and everybody with money is evil and so Microsoft is evil. Yes I agree to any hater’s point of view. No I have not been paid by Microsoft to defend them. In fact their are a number of things that are very irritating (there have to be once you are that big). Lately its being going down and the slope is more then 45 degrees. Everything Microsoft does feels like is late in the market.  In my opinion a lot of it has to do with DENIAL and the company just denying that there is anything else but windows in the market and we will just continue to sell Windows and Office. I mean come on guys ! For how long you are going to repackage the same operating system, throw in some changed look and feel and some features that no one cares about. There are bigger avenues that Windows 7 and Windows 8 and Windows 9 and Windows 2015. Now that the management has realized that, there seems to be an absence of creative thinking or may be they are still in denial. All the Microsoft products seem to be late it the industry. They seem to be hell excited about the upcoming new and ground breaking technology that they are working on (nothing wrong there) and when it comes out scrap them and pull the plug on them in a matter of some months. Does not seem like there is any major design consideration when things come out and fanatics jump on to just use them. These days its HTML5 and scrapping of Silverlight/WPF. It was not too long ago that Microsoft could not stop singing praises of Silverlight. But as an application provider I have no problem with Microsoft what so ever. So sissy companies with sucky operating systems and cry all they want that no one wants to purchase their operating system.

Now there is Google. Yes do no evil Google. Google was much smarter than Microsoft. They are also a company and not a charitable organization. They pay really world class salaries and state of the art work conditions for their employees. How is it possible if they are not even selling their services. THEY Just want to display ads to you. Google goes a long way to display ads and millions of hours worth of effort by the masterminds are spent to make the ads more relevant. Yes there is much more to it than you think. Ever wondered how the ads are very relevant to the message you are reading from your mom on Gmail. No ? Try sending a message to your mom and tell her that you would like to buy a Mustang. When she responds, ignore the message and focus at the top , left , right and down in your window. They will certainly make buying Mustang much easier for you. Did their bot just read your email ? OH NO Its not a security concern (its just a bot who means no harm). OK If Google is such a nice guy, Why I don’t have the option to turn all ads off whenever I want to ? Perhaps I should have the option. Its simple to implement (I would be happy to implement it for Google if they would like for free). The problem is not how they are showing you ads, I totally understand that. They are a company and they make their money by ads, its their business model and I dont have a a problem with that. The problem is with calling other companies evil for negative business practices. I would much rather pay 50 bux for a license from google, never to see any ad again once I sign in to my google account.

Noticed lately how many Google products have failed ( HINT : social networking). Looks like thats the biggest irritation they have these days. I cannot even count. I guess they realized that the TRAFFIC seems to be eye opening on FACEBOOK and they are missing out. Facebook has the same business model and instead of Google Ads they have Facebook Ads. They bought ORKUT, created Google Wave, Google Buzz, Google Plus and I will update the list after i Google it ! They just want a piece of it. Just trying desperately to get people to use something other than Facebook. Hey Masterminds ! people wont switch. Why ? Because all their friends are there, Its easy enough to use and we dont need another password or a re engineering of a service we already have.

HERE Is 1 brilliant IDEA for you if you are willing to be evil.

Pay every Facebook account $20 to delete that facebook account and join Google +. I can bet that this will go viral. I am pretty sure you can make muchhhhhh more than $20 for every account that signs up and hey you will get 1 more account than you have for sure. I will delete my facebook and Join Google + if they pay me $20 for that !

 

I was writing some games using the windows phone 7 tools and I found out that its a pretty cool sdk with .Net framework 4.0. For games you can either do silverlight or XNA. The first decision that you will have to make is to whether go Silverlight or go XNA ? If you plan to have 3D graphics/ animation, extensive control on drawing and coloring, show lot of images or trying to process rapid user input then go with XNA, otherwise silverlight is also pretty powerful if all you have to do is to manipulate windows phone controls and write a little logic to create your app. What I found out is you will need to read data files as there is no support or built in database in the phone. For me its a good thing, I do not want to write database wrappers or start a war with entity framework. File processing and Handling is kind of neat and you can pretty much do everything 90% of the time that you would with a database. I don’t think it is a cool idea to write “Payroll Management System” for a cell phone, I mean common ? what is the computer for ??
So coming from the Web/desktop/laptop world its very simple to read a file in .Net. Here is what you would do normally in ASP.Net or a C# Windows Application.

// Assuming file is in the same directory or your project
StreamReader sr = new StreamReader(“file.txt”);
string str = sr.ReadLine();

Pretty Simple huh !! It is a little tricky with XNA 4.0. Primarily you should have the files in the ContentProject and not your game project. If you look at the Game project references, you will see a reference to the ContentProject. So place the files in the Content Project, then change the file properties. You should change the Build Action property to “NONE” and “Copy to Output directory” to “Copy always”. This would put the files in your executable’s path. XNA provides a TileContainer Class and you can call the static method OpenStream and pass in the path (Content Project).

Stream testpath = TitleContainer.OpenStream(“Content/Test.txt”);
StreamReader reader = new StreamReader(testpath);
string line = reader.ReadLine();

For silverlight since you do not have the content project and the files possibly are included in your project you can do:

Stream testpath = Application.GetResourceStream(new Uri(“Test.txt”, UriKind.Relative)).Stream;
StreamReader reader = new StreamReader(testpath);
string line = reader.ReadLine();

I found this the google way, just putting it out there, it may save some time for someone trying to read files in their windows 7 applications. You can pretty much apply the same logic for StreamWriter to create and write to files.

Happy Coding and Best of luck :)

Network Question

Posted: July 3, 2010 in Uncategorized

I would really appreciate if anyone can help me out with this networking scenario. I am not upto date with any networking products and dont have extensive knowledge, would appreciate your feedback.

Please see the attached diagram. Here is the explanation.

Client 1 and Client 2 are connected to Server 1 in Location 1. They are a part of a Corporate Network (WAN)
Client 3 is at Location 2. Client 3 is also connected to Corporate Network (WAN)
Location 1 and Location 2 are connected through
Client 3 wants to Connect to Server 1 (so that client 3 feels that it is on the same LAN as Client 1 and Client 2) . What would be a good mechanism to achieve this ?

I did some research on this and found that this can be achieved using VPN. So I am thinking in terms of setting a vpn at location 1 and making Server 1 the VPN Server. Configure Client 3 to connect to this VPN. All communication would be over the internet.

Server1 : Windows Server 2003
Client 3: Windows XP.

If you are aware of any third party products that are reliable or might help to set up a VPN I would appreciate your expert feedback.
Thank you very much.

I wasted some 3 hours to set it up. Did not exactly waste, I always find the setting the development environment the most annoying, difficult step in my development efforts. Here are some step by step instructions you can follow to save your time. This will include JDK, Eclipse, ADT Plugin and some configuration.

1. Install the Java Development Kit. I installed JDK 1.6. It can be installed from JDK DOWNLOAD . Make sure it is installed by going to command prompt and executing java -version

2. Download the Eclipse and Unzip it to a directory. I installed Version: Helios Release Build id: 20100617-1415 from http://eclipse.org/

3. Install the Android SDK. I downloaded the SDK from ANDROID SDK . To install unzip the directory and run the setup. It should bring up a utility where available packages and libraries would be downloaded. Create a test virtual device with 32 MB as your storage. Here is a screenshot after installation:

4. Add the Android SDK location to your Path (Go to Environment Variables and edit the path variable). In my scenario I added “C:\android-sdk_r06-windows\android-sdk-windows” to my path.

5. Install the ADT Plugin. Here is how:

Start Eclipse, then select Help > Software Updates…. In the dialog that appears, click the Available Software tab.

Click Add Site…

In the Add Site dialog that appears, enter this URL in the “Location” field:

https://dl-ssl.google.com/android/eclipse/Note: If you have trouble acquiring the plugin, try using “http” in the Location URL, instead of “https” (https is preferred for security reasons).

Click OK.

Back in the Available Software view, you should see the plugin listed by the URL, with “Developer Tools” nested within it. Select the checkbox next to Developer Tools and click Install…

On the subsequent Install window, “Android DDMS” and “Android Development Tools” should both be checked. Click Next.
Read and accept the license agreement, then click Finish.

Restart Eclipse.

6. Now you have installed JDK, Eclipse, Android SDK and the ADT Plugin and updated your PATH to have the location of Android SDK. Open Eclipse –> Create New Project –> Android Project , Select a name for your application and a suitable API Version to be safe I chose (1.6)

7. After the new project is created try and build it. Ideally it should build fine but it did not. It had issues with the build path (the sdk libraries were not included in the build path). In the package explorer right click on your project and select properties. In the left pane click on “Java Build Path” and check the “Android 1.6″ or whatever you selected as your API version.

8. Clean the project and build it again. If it builds fine go ahead and run it “Run As – Android Application”.

9. HOORAY !! Time for victory dance. Here is a snapshot of ANDROID App running in the emulator.

I am also a beginner in android application development and pretty excited about it since I can test and deploy my applications in my DROID. Cheers and have a great rest of the day. I am heading to the JAVA BAR.

I had a lot of time one beautiful Saturday morning and I started watching VIRAL VIDEOS. If you dont know what’s a viral video its a video on the internet that becomes very very popular and spreads on the internet like a Virus (you see the analogy). Soon I realized that its not easy to search for viral videos on YouTube. How do I view only the videos which are highly popular, Most Viewed, Most discussed, Most Responded ? I wanted to answer questions like:

What are the top viral videos of this month ? It can be the top music video or a comedy video or an Entertainment Video.
What are the top viral videos of the day ?
What is the most viewed comedy video of the day ?
Which music video has the most views in the US this week ?
What video in the Autos category has the most number of comments for the past month?
What is the most popular video on the internet of all times ?
What are the top 10 US comedy videos in the US for today ?

The site brings you the most viewed video content on the internet . The data and searching is based on youtube and It can retrieve the most viral videos given a region, category and time. Here is a screenshot of the webpage and you can check it out at www.whowentviral.com

Screenshot

Whowentviral

You see what I am getting at ? I did the application using HTTP REQUEST , YouTube API and an algorithm. You can check it out at Who went viral ? . www.whowentviral.com not only lets you view your selected content but also lets you watch it youtube style. YouTube ftw !! :) ….. I would love to hear your feedback, comments and suggestions on it and appreciate your time. Hope you like it !!

Stupid Decisions by ICC

Posted: May 4, 2010 in Uncategorized

This is not really a rant, I cant understand why the International Cricket Council makes such stupid decisions. I am not saying that I am very smart and ICC should hire me to consult them, I am just an average fan and I like the sport, have a lot of memories associated with it. One Question that I think of again and again as we are in the middle of the “ICC World T20 2010” in the West Indies, is loss of game after game after game due to rain. Unfair advantage to teams batting second usually due to “D/L” System kicks in and totally changes the equation. Please when scheduling such tournaments and assigning venues for international tournaments consider the weather and the nature of the game and the facilities available. Primarily I do believe that T20 is designed for more entertainment, by entertainment i means the batsmen dominating the bowlers, lot of big hits and stumps flying around, thats action. I dont get it when the batting team is 80 – 5 in 12 overs and are consolidating for the next 5 overs in a 20 over game ??? Are we talking world T20 or World Test match Series ?? I would highly suggest ICC to open up their eyes and save the sport from loosing fans and popularity. It would have been far so better if the “World T20″ would have been scheduled at any of the venues listed below:

Australia
South Africa
India
England
Sharjah
NewZealand

I am totally not suggesting that a cricketing nation like WestIndies should be ignored, not at all, but for hosting international tournaments Like “T20 Word cup” ICC needs to put in some effort to raise the pitch standard (atleast even bounced wickets), the grounds (may be roof and lights) and if nothing please check the weather forecast and history before making the schedule. God dammit !! RawRRrrrrrrr !!

But Why ?

Posted: February 8, 2010 in 1

These are the questions that I really want the answers of but for some reason either I cant ask the concerned authorities or it is really difficult to find the answer of :

1/ Why is it odd ?????????? (Yeah not everybody is gonna understand this question, If u dont move on and never mind ;) )

2/ Why is not everyone created equal ?

3/ Why is Muhammad Yusuf the captain of Pakistan cricket team ? Why is Yunis Khan even selected ??

4/ What good is Asif Zardari for. Why cant anybody else be the president ?

5/ Why vegetables dont taste as good ?

6/ Why all the things that I like are so caloric ?

7/ Why do people hate BING with a passion ?

8/ Why do I hate everything (LOL) ??

9/ Why didnt I get my Mail in Rebate for the stupid*  Video Card I bought 5 months back ?

10/ Why cant I spend money :O ?

11/ Why are you still reading this post ?

I will keep adding as I get more and more…. Feel free to do so if u know the answers of any or want to add ur own issues …. Tata

I just happened to create a webservice and a client using ASIX for a web service class. As I know that in the environment it is difficult to get things to work and minor issues can halt the process. I am posting a simple Service, Client and my configurations just in case they are helpful to any one. In my environment TOMCAT is the web container and I compile it with AXIS jar files in my classpath, deploy.wsdd is used for deployment:
I use the variable %AXISCLASSPATH% which is set in my environment variables to following:

%AXIS_LIB%\axis.jar;%AXIS_LIB%\commons-discovery-0.2.jar;%AXIS_LIB%\commons-logging-1.0.4.jar;%AXIS_LIB%\jaxrpc.jar;%AXIS_LIB%\saaj.jar;%AXIS_LIB%\log4j-1.2.8.jar;%AXIS_LIB%\wsdl4j-1.5.1.jar;%AXIS_LIB%\xml-apis.jar;%AXIS_LIB%\xercesImpl.jar;

AXIS_LIB is set to: %AXIS_HOME%\lib
AXIS_HOME is set to : C:\axis-1_4

Step 1 is to code the service: In the given scenario the service expects an integer passed to it in the GetDynamicArrayOfRandomNumbers method and it will return an array with the number of elements equal to the number passed in. It will populate the array with random numbers.

import java.util.Random;

/**
 * @author Muhammad Asad Siddiqi
 * 06/13/2009
 *  This class is used as the web service and the .class has to be copied under Tomcat/axis/webapps
 *  deploy.wsdd has to be used for deployment
 */

public class DynamicArrayGeneratorService
{   
    /*
     * This is the remote method that would be called by the client
     */
    public int [] GetDynamicArrayOfRandomNumbers (int nArraySize) throws Exception
    {
        int []arrRandomNumbers = new int[nArraySize];
       
        for (int nCount=0; nCount < nArraySize; nCount++)
        {
            Random randomGenerator = new Random();
            arrRandomNumbers[nCount] = randomGenerator.nextInt((nCount * 4) + 10);           
        }
       
        return arrRandomNumbers;       
    }
}

Step 2: Compiling the service can be done by running the following commands from where your code is:

javac -classpath %AXISCLASSPATH% DynamicArrayGeneratorService.java

Step 3 is coding the client, I am copying and pasting the code for the client below:

import java.lang.*;
import javax.xml.namespace.QName;
import javax.xml.rpc.ParameterMode;
import java.net.URL;
import org.apache.axis.client.Service;
import org.apache.axis.encoding.XMLType;
import org.apache.axis.utils.Options;
import org.apache.axis.AxisFault;
import org.apache.axis.client.Call;

/**
 *
 * @author Asad Siddiqi
 * Assignment # 2 Web services
 * This class is the client for the service running on localhost
 */
 
public class DynamicArrayGeneratorClient
 {
 public static void main(String args[])
 {
     try
  {
   int nSizeToReturn = 0;
   
   if ( args == null || args.length != 1 )
   {
    System.out.println(“The client utility has to pass in the exactly 1 parameter [size of the array]“);
    System.exit(1);
   }
   
   nSizeToReturn = Integer.parseInt(args[0]);   

   // Create an instance of the service
          Service serArrayGenerator = new Service();
   
   // Create an instance of the Call to call the method
   Call call = (Call) serArrayGenerator.createCall();
   
   // Set the Address for connection
   call.setTargetEndpointAddress(new java.net.URL(“http://localhost:8080/axis/services/DynamicArrayGeneratorService“));
   
   // Specify the method to call
   call.setOperationName(“GetDynamicArrayOfRandomNumbers”);
   
   // Call the remote method
   int [] arrReturned = (int[]) call.invoke(new Object [] {new Integer(nSizeToReturn)});

   // Print the output

   System.out.println(“PRINTING THE NUMBERS RETURNED BY SERVICE :”);
   System.out.println(“——————————————”);
   
   for (int i = 0; i < arrReturned.length; i++)
   {
    System.out.println(arrReturned[i]);
   }
     }
     catch( Exception e )
  {
   // Error occured during processing
   System.out.println(“Error Occured during processing …”);
   e.printStackTrace();
     }
 }
};

Step 4: Compiling the Client can be done by executing the following command from the same directory as your client code:

javac -classpath %AXISCLASSPATH% DynamicArrayGeneratorClient.java

Step 5 : In your command prompt navigate to the directory where your deploy.wsdd file is located. Once you are in the right directory execute the following command:

java -cp %AXISCLASSPATH% org.apache.axis.client.AdminClient -lhttp://localhost:8080/axis/services/AdminService deploy.wsdd

Step 6: The client can be executed by again changing the directory to where the .class files were generated for the client and executing the following command:

java -cp .;%AXISCLASSPATH% edu.jhu.webservices.Siddiqui.Asad.DynamicArrayGeneratorClient 20

I am also posting the contents of deploy.wsdd file:

<deployment name=”hw2″ xmlns=”http://xml.apache.org/axis/wsdd/
    xmlns:java=”http://xml.apache.org/axis/wsdd/providers/java“>

  <service name=”DynamicArrayGeneratorService” provider=”java:RPC”>
    <parameter name=”className” value=”DynamicArrayGeneratorService”/>
    <parameter name=”allowedMethods” value=”GetDynamicArrayOfRandomNumbers”/>
    <parameter name=”wsdlServicePort” value=”GetDynamicArrayOfRandomNumbers”/>
  </service>

  </deployment>

If you find it useful or I was able to help you out or you have a question, feel free to comment and I will make sure to reply. Being a .Net developer this was a real pain and it sucks, I just posted to help anyone in the same boat as me.

DOM and SAX Parsing using JAVA

Posted: July 26, 2009 in 1

I am not a very proficient java developer but I can find my way after spending some time. This might help save some time who is just like me and not a real pro at JAVA :) . I am posting a sample XML and the parser to parse it in DOM and SAX using Java.

Here is the xml:

<?xml version=”1.0″?>
<!DOCTYPE Syllabus SYSTEM “Syllabus.dtd”>
<Syllabus xmlns:xsi=”http://www.w3.org/2001/XMLSchema” xsi:schemaLocation=”http://www.w3schools.com note.xsd”>
  <Lecture SerialNo=”1″>
    <Week>1</Week>
    <Date>Jun 3</Date>
    <Material>Sample Material</Material>
    <Reading>Sample Reading </Reading>
    <AssignedHW>Sample Text</AssignedHW>
    <DueHW></DueHW>
  </Lecture>
  <Lecture SerialNo=”2″>
    <Week>2</Week>
    <Date>Jun 10</Date>
    <Material>Some Text</Material>
    <Reading>Some Boring Text </Reading>
    <AssignedHW>HW2</AssignedHW>
    <DueHW>HW1</DueHW>
  </Lecture>
  <Lecture SerialNo=”3″>
    <Week>3</Week>
    <Date>Jun 17</Date>
    <Material>Some Lame material</Material>
    <Reading>Lame reading</Reading>
    <AssignedHW>HW4</AssignedHW>
    <DueHW>HW3</DueHW>
  </Lecture>
</Syllabus>

Here is the code:

import java.io.File;
import javax.xml.parsers.*;
import org.w3c.dom.*;
import org.xml.sax.*;
import org.xml.sax.helpers.*;

public class Parser
{   
   
    public Parser()
    {
    }   
   
    public void doDOMParsing(String strFileName)
    {
        try
        {           
            java.io.File file = new File(strFileName);
            DocumentBuilder builder =   DocumentBuilderFactory.newInstance().newDocumentBuilder();
            Document doc = builder.parse(file);

            NodeList nodes = doc.getElementsByTagName(“Lecture”);
            for (int i = 0; i < nodes.getLength(); i++)
            {
                System.out.println(“PARSED LECTURE DATA”);
                System.out.println(“————-”);
               
                Element element = (Element) nodes.item(i);
               
                NodeList weekData = element.getElementsByTagName(“Week”);
                Element line = (Element) weekData.item(0);               
                String strWeekData = getCharacterDataFromElement(line);
                System.out.println(“Week : ” + strWeekData);

                NodeList dateData = element.getElementsByTagName(“Date”);
                line = (Element)dateData.item(0);
                String strDateDate = getCharacterDataFromElement(line);
                System.out.println(“Date : ” + strDateDate);
               
                NodeList materialData = element.getElementsByTagName(“Material”);
                line = (Element)materialData.item(0);
                String strMaterial = getCharacterDataFromElement(line);
                System.out.println(“Material : ” + strMaterial);
               
                NodeList readingData = element.getElementsByTagName(“Reading”);
                line = (Element)readingData.item(0);
                String strReading = getCharacterDataFromElement(line);
                System.out.println(“Reading : ” + strReading);
               
                NodeList assignedHWData = element.getElementsByTagName(“AssignedHW”);
                line = (Element)assignedHWData.item(0);
                String strAssignedHW = getCharacterDataFromElement(line);
                System.out.println(“Assigned HomeWork : ” + strAssignedHW);
               
                NodeList dueHWData = element.getElementsByTagName(“DueHW”);
                line = (Element)dueHWData.item(0);
                String strDueHW = getCharacterDataFromElement(line);
                System.out.println(“Due HomeWork : ” + strDueHW);        
               
                System.out.println(“——————————–”);
            }
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }     
    }   
   
    /* This is the helper function to get Element Data in DOM Parsing */
    private String getCharacterDataFromElement(Element e)
    {
        try
        {
            Node child = e.getFirstChild();
            if(child instanceof CharacterData)
            {
                CharacterData cd = (CharacterData) child;
                return cd.getData();
            }
 }
        catch(Exception ex)
        {
            ex.printStackTrace();
        }
       
 return “”;
    }
   
    /* This is the innerclass that inherits from Default Handler for SAX Parsing */
    class SAXHandler extends DefaultHandler
    {
        boolean bWeek = false;
        boolean bDate   = false;
        boolean bMaterial = false;
        boolean bReading = false;
        boolean bAssignedHW = false;
        boolean bDueHW = false;
       
        public void startElement(String nsURI, String strippedName,String tagName, Attributes attributes)      throws SAXException
        {
            if (tagName.equalsIgnoreCase(“Week”))
                bWeek = true;
            if (tagName.equalsIgnoreCase(“Date”))
                bDate = true;
            if (tagName.equalsIgnoreCase(“Material”))
                bMaterial = true;
            if (tagName.equalsIgnoreCase(“Reading”))
                bReading = true;
            if (tagName.equalsIgnoreCase(“AssignedHW”))
                bAssignedHW = true;
            if (tagName.equalsIgnoreCase(“DueHW”))
                bDueHW = true;
        }
       
   
        public void characters(char[] ch, int start, int length)
        {
            if (bWeek)
            {
                System.out.println(“Week : ” + new String(ch, start, length));
                bWeek = false;
            }
            else if (bDate)
            {
                System.out.println(“Date :  ” + new String(ch, start,length));
                bDate = false;
            }
            else if (bMaterial)
            {
                System.out.println(“Material :  ” + new String(ch, start,length));
                bMaterial = false;
            } 
            else if (bReading)
            {
                System.out.println(“Reading :  ” + new String(ch, start,length));
                bReading = false;
            } 
            else if (bAssignedHW)
            {
                System.out.println(“Assigned Homework :  ” + new String(ch, start,length));
                bAssignedHW = false;
            } 
            else if (bDueHW)
            {
                System.out.println(“Due Homework  :  ” + new String(ch, start,length));
                bDueHW = false;
            } 
        }
    }
   
    /* This is the entry point where SAX Parsing starts */
    public void doSAXParsing(String strFileName )
    {
        try
        {
            SAXParserFactory saxFactory = SAXParserFactory.newInstance();
            SAXParser saxParser = saxFactory.newSAXParser();   
            SAXHandler handler = new SAXHandler();
            saxParser.parse(new File(strFileName),handler);
       
        }
        catch (Exception ex)
        {
            ex.printStackTrace();
        }
    }
   
    /* This is the driver function from where the DOM AND SAX parsing has to be called
       The file name has to be passed in like “Syllabus.xml”
     */
    public static void main(String []args)
    {
        try
        {  
            String strFileName = “..\\resources\\Syllabus.xml”;
            String strParsingMode=”";
           
            if (args.length != 1)
            {
                System.out.println(“The valid values of the parameter passed in are DOM and SAX. Press any key to continue:”);
                int a = System.in.read();           
                System.exit(0);
            }       
           
            Parser driverParser = new Parser();
           
            strParsingMode =  args[0];                   
            if (strParsingMode.equalsIgnoreCase(“dom”))
            {
                System.out.println(“DOM PARSING”);
                driverParser.doDOMParsing(strFileName);
            }
            else if (strParsingMode.equalsIgnoreCase(“sax”))
            {
                System.out.println(“SAX PARSING”);
                driverParser.doSAXParsing(strFileName);
            }
            else
            {
                System.out.println(“The parsing mode can be DOM or SAX”);
                System.exit(0);
            }           
       
        }
        catch(Exception ex)
        {
            System.out.println(“Error Occured while processing”);
            ex.printStackTrace();
        }
       
    }
}

To me how SAX parsing is implemented using Inner classes was really interesting . I hope it helps someone looking for some help and finds it :)

 

As a prerequisite you would require to have Microsoft Visual Studio 2008 installed on your system. Alternatively you can also have Microsoft Visual Studio 2005 with AJAX extensions for ASP.Net installed. This would be a very basic example just to get you started and will touch the basics of writing AJAX enabled web applications using Visual Studio and ASP.Net.

 

So What is AJAX  and what is the use ?

 

AJAX is the abbreviation of “Asynchronous JavaScript and XML”. It is a technique in web development that is used to greatly improve the responsiveness and performance of a web application thus resulting in a great user experience. To understand how it works you should understand how the old web applications worked, how it all started, what is java script and what do we exactly mean by AJAX?

 

As web applications were hosted and running on a web server, the browser simply accessed the application on a server and rendered the html produced for the user.

 

Ever wondered why it took a long time after you clicked a button and when you look at the status bar its slowly moving and after some time it comes back with the response”.

 

This was mostly the case not with static websites but web applications where a lot of processing was done on the server side based on events like pressing a button. The page would “postback” and provide the server the necessary input. On the event handler there would be some validations and then some processing and then typically another “postback” updating the user. As more users complained that the application was not responsive enough or too slow, more techniques evolved to process minor data on the client side using javascript. Typically these would be tasks like client side input validations, dynamic menus and conversions displaying time and things like that.

The end user liked the experience as the application was much more responsive and wont go back to the server to process each and every piece of information (postback) .

 

So this idea was refined and the AJAX technologies were introduced and including in all the major web development frameworks. If you are reading this off course you are not an AJAX Expert , you just want to know how you can use AJAX in your application to make it more responsive or just for the heck of it J .

 

So here is how you do it with ASP.Net using Visual Studio 2008.

 

1/  Create a new website and name it as AJAXExample. This can be achieved by File -> New -> Website and selecting ASP.Net Website from the installed templates.

 

2/  Visual Studio .Net will generate the basic skeleton application by generating the following files (pages):

 

Default.aspx

Default.aspx.cs

 

Default.aspx is the actual page where all the controls or (html elements are). The Visual Studio IDE enables you to switch between Design View and Source View. Design view is where you can look how the page looks like and the source view is the html view of the page.

 

3/ Be in the design view and the first control to be dragged and dropped on the page must be “ScriptManager”. This is located under “AJAX Extensions”. Visual studio will rename it as ScriptManager1 and will add the following code when you switch to source view:

 

<asp:ScriptManager ID=”ScriptManager1″ runat=”server”>

</asp:ScriptManager>

 

Note: This should be the first control in the page. It tells the asp.net worker process that this application or page uses AJAX and the required “dlls” have to be loaded in memory.

 

4/ Add the controls whatever is required in your application. For the sake of simplicity I will add a textbox and 2 buttons in the design view. The visual studio will generate the following code in the source view.

 

<asp:Button ID=”Button1″ runat=”server” Text=”Hello” onclick=”Button1_Click” />

 

<asp:TextBox ID=”TextBox1″ runat=”server”></asp:TextBox>

 

<asp:Button ID=”Button2″ runat=”server” onclick=”Button2_Click” Text=”Clear” />

 

5/ Define the event handlers in “Default.aspx.cs”.

 

protected void Button1_Click(object sender, EventArgs e)

{

    TextBox1.Text = “Hello”;

}

 

protected void Button2_Click(object sender, EventArgs e)

{

    TextBox1.Text = “”;

}

 

6/  Add the following code in your html before and after your controls code. So the controls you want to process without postbacks has to be wrapped around this block:

 

 

<asp:UpdatePanel id=up1 runat=server>

    <ContentTemplate>

 

// Controls here

 

</ContentTemplate>

</asp:UpdatePanel>

 

7/  Run the application and Enjoyeee ! In the same way you can put more controls in a page like gridViews comboboxes and list boxes or even databound controls and use it without causing the application to postback.

 

I am copying and pasting the contents of my code files:

 

 

Default.aspx

 

<%@ Page Language=”C#” AutoEventWireup=”true”  CodeFile=”Default.aspx.cs” Inherits=”_Default” %>

 

<!DOCTYPE html PUBLIC “-//W3C//DTD XHTML 1.0 Transitional//EN” “http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd”>

 

<html xmlns=”http://www.w3.org/1999/xhtml”>

<head runat=”server”>

    <title>Untitled Page</title>

</head>

<body>

    <form id=”form1″ runat=”server”>

    <div style=”height: 295px”>

    <asp:ScriptManager ID=”ScriptManager1″ runat=”server”>

    </asp:ScriptManager>

    <asp:UpdatePanel id=up1 runat=server>

    <ContentTemplate>   

        <asp:Button ID=”Button1″ runat=”server” Text=”Hello” onclick=”Button1_Click” />

        <asp:TextBox ID=”TextBox1″ runat=”server”></asp:TextBox>

        <asp:Button ID=”Button2″ runat=”server” onclick=”Button2_Click” Text=”Clear” />

    </ContentTemplate>

    </asp:UpdatePanel>

    </div>

   

    </form>

</body>

</html>

 

Default.aspx.cs:

 

using System;

using System.Configuration;

using System.Data;

using System.Linq;

using System.Web;

using System.Web.Security;

using System.Web.UI;

using System.Web.UI.HtmlControls;

using System.Web.UI.WebControls;

using System.Web.UI.WebControls.WebParts;

using System.Xml.Linq;

 

public partial class _Default : System.Web.UI.Page

{

    protected void Page_Load(object sender, EventArgs e)

    {

 

    }

    protected void Button1_Click(object sender, EventArgs e)

    {

        TextBox1.Text = “Hello”;

    }

    protected void Button2_Click(object sender, EventArgs e)

    {

        TextBox1.Text = “”;

    }

}