Showing posts with label JavaScript. Show all posts
Showing posts with label JavaScript. Show all posts

Thursday, September 19, 2013

Information from XML without Parsing in Java


Introduction

As you know to gather information from an XML file you have to parse the XML file using DOM, SAX or Stax or any other way. There are ways you can get some information from an XML file using plain String processing. Sometimes it performs well also. But this concept cannot be generalized for any kinds or types of XML document. XML parsing with a particular methodology has its own pros and cons. It is always significant to extract more information and provide to the system for smooth and fast processing. Sometimes developers adopt some different approaches to provide the optimum result to the system. In this small post I will provide a very small trick about how to gather information from an XML file without using any conventional parsing techniques in a particular scenario. I will also show you about the performance of both ways (Using Parsing technique and Using Text processing).

Technicalities

I was working in a project where a destination system used provide the result in the form of an XML file and the source system used to display the exact result to the end system. This is a very particular scenario where we have to employ our own technique to achieve the best result. In order to substantiate the above statements, let me provide you a typical scenario. Think about a situation, you are making a call to an external system which connects to a device like POS (Point of Sale) device which only provides the information about your transaction. The transaction may be a success or a failure one. Your system is only concerned about the core output of the XML contents. Also think that in a second, you perform many transactions. Generally the convention way is to parse the XML file and display the data enclosed inside a tag. There can be a debate on this about which parsing technique to use, whether to use DOM or SAX. It all depends upon the situation. In this particular scenario, the XML document is very small and the source system displays only the data without any pre or post processing. I am not saying that the XML parsing in this situation is wrong, but I can recommend if you can process the text smartly from an XML file, it will be helpful to a greater extent. Let us consider the following source XML files and outcome of the XML file.

Successful Transaction

<Transaction>
      <Status>
            <StatusCode>001</StatusCode>
            <StatusMsg>Transaction Successful</StatusMsg>
            <Date>09:09:2013</Date>
            <Time>14:54:53</Time>
      </Status>
</Transaction>

Failed Transaction
 
<Transaction>
      <Status>
            <StatusCode>009</StatusCode>
            <StatusMsg>Transaction Failed</StatusMsg>
            <Reason>UnExpected Error in reading Card</Reason>
            <Date>09:09:2013</Date>
            <Time>14:54:53</Time>
      </Status>
</Transaction>

Now the source system displays the following information.

001
Transaction Successful
09:09:2013
14:54:53

The above situation is a hypothetical one. The whole objective is to show how you can change your business algorithm to boost the performance of your application. It is not always necessary to follow always the conventional approach to achieve the performance.

In the above case, the text you are displaying to the system is very small. Well you can use conventional parsing technique to show the information. But if you have a pile of XML documents of this structure and you want to gather information using XML parsing technique, there may be slight performance repercussion. To avoid, you can apply plain text processing using a simple regular expression. I provide below the two approaches, let us see below.

XML Parsing Technique

The following steps are required to get the information from the XML file.
  • Get the XML contents as a String
  • Parse the XML contents using DOM parsing
  • Visit each element or tag of the XML doc and extract the contents
  • Display the whole contents to the system
The brief code snippet for XML parsing is given below.
 
public static void processTxn(String contents) {
      DocumentBuilderFactory docBuilderFact = DocumentBuilderFactory
                  .newInstance();
      DocumentBuilder docBuilder = null;
      Document doc = null;
      try {
            docBuilder = docBuilderFact.newDocumentBuilder();
      } catch (ParserConfigurationException e) {
            e.printStackTrace();
      }
      StringReader srReader = new StringReader(contents);
      InputSource inSrc = new InputSource(srReader);
      try {
            doc = docBuilder.parse(inSrc);
      } catch (SAXException e) {
            e.printStackTrace();
      } catch (IOException e) {
            e.printStackTrace();
      }
      System.out.println("---------------Message From System-------------");
      recursiveParsing(doc.getDocumentElement());
}

Text Processing Technique

The following steps are required to get the information from the XML file
  • Get the XML contents as a String
  • Remove all the tags (<Tag>)
  • Display the whole contents to system
The brief code snippet for removal of XML tags is given below.
public static String removeXmlTags(String contents) {
      Pattern tag = Pattern.compile("<.*?>");
      Matcher mtag = tag.matcher(contents);
      while (mtag.find()) {
            contents = mtag.replaceAll("");
      }
      return contents;
}
Comparison

To compare the time taken by both the code structure, let us make an experiment with 10 observations. Let us see the result below.
 
********** Time Taken in TEXT Processing *************
NANOSECONDS     MILLISECONDS    SECONDS        
5919837         5.919837        0.005920 
 
********** Time Taken in XML Processing *************
NANOSECONDS     MILLISECONDS    SECONDS        
35151999        35.151999       0.035152       

If you run the code in profile mode using Netbeans ide, you can see the difference in time consumptions. Let us see the image below.

Monday, September 2, 2013

Creating Tree View Using jQuery




Basics - Understanding Tree View

To create a tree view we will use the following two methods.

Click()

It is used for binding to the click event handler of an element. Whenever the user clicks on an element it will be detected using the click handler. The syntax for the click event is:

jQueryObject.click(handler_function);

Toggle()

It is a jQuery UI method for toggling the display property of an element with the animation effect as well. For our purposes we will use a toggle with a fold effect. The syntax for a toggle is:

jQueryObject.toggle("fold","effect_duration");

In HTML we will use the following tags.

UL - Unordered List

It declares an unordered list.

<ul> List items </ul>

LI - List Item

It declares list items.

<li> Item name </li>

Logic behind the JavaScript Tree View

  1. First we need to prepare the HTML.
  2. In the tree view we have Parent Nodes, Child Nodes, Nodes.
  3. To create nodes we will use the LI and UL tags of HTML.
  4. To represent the parent node we will use a LI tag just above the UL.
  5. To represent the child node we use the UL tag just below the LI Tag.
Coding the Tree View

It's time to turn our Dreamed Tree View into reality.

To create tree view items, add the following HTML snippet in your HTML File.
<ul>
    <li id="m1">Main 1</li>
    <div id="l1cover">
        <ul>
            <li>1</li>
            <li id="inLst">2</li>
            <div id="inCt1">
                <ul>
                    <li>1</li>
                    <li>2</li>
                    <li>3</li>
                </ul>
            </div>
            <li>3</li>
        </ul>
    </div>
</
ul>
<
ul>
    <li id="m2">Main 2</li>
    <div id="l2cover">
        <ul>
            <li id="inLst2">1</li>
            <div id="inCt2">
                <ul>
                    <li>1</li>
                    <li>2</li>
                    <li>3</li>
                </ul>
            </div>
            <li>2</li>
            <li>3</li>
        </ul>
    </div>
</
ul>

Now to make your tree view work, just add the following jQuery snippet:
$("#m1").click(function () {
    $("#l1cover").toggle("fold", 1000);
    });    $("#m2").click(function () {
        $("#l2cover").toggle("fold", 1000);
    });    $("#inLst").click(function () {
        $("#inCt1").toggle("fold", 1000);
    });    $("#inLst2").click(function () {
        $("#inCt2").toggle("fold", 1000);
});

a1.PNG
Summary

To summarize, we just learned how to create the tree view in jQuery. Here the important point is not about creating the tree view but how to use the power of jQuery intelligently. You can check my other articles about jQuery for more details of how to use it.

Thanks for reading and don't forget to comment and like this article.

Output

Live Demo

Full Tree View

a1.PNG
Minimized 1st sub node
a2.PNG
Minimized 2nd child node
a3.PNG
Minimized child nodes

a4.PNG
Minimized 2nd node

a5.PNG
Minimized 1st node

a6.PNG
All nodes minimized

a7.PNG

Thursday, August 29, 2013

Calling Server Side Function From JavaScript in ASP.Net


In this article we will see how to call a server-side function from JavaScript in ASP.Net. Many developers, when they work on a project, get similar requirements in their projects. To do that you can use AJAX to communicate with the server-side method. I demonstrate the client-side of using AJAX in the following code.
I will now discuss the server-side function and how to call it in JavaScript. 
Server Code (.cs file)
In the following code we create a method named "Name" and his return type is string.
using System;using System.Collections.Generic;using System.Linq;using System.Web;using System.Web.UI;using System.Web.UI.WebControls;using System.Web.Services;
 
public
partial class Default2 : System.Web.UI.Page{
    protected void Page_Load(object sender, EventArgs e)
    {
    }

    [WebMethod]
    public static string Name()
    {
        string Name = "Hello Rohatash Kumar";
        return Name;
    }
}

The preceding server-side code shows the attribute [WebMethod] and Declaration (static).
[WebMethod]
To make use of this "[WebMethod]" attribute you need to use the "System.Web.Services" namespace as shown in the preceding server-side code. The attach the "[WebMethod]" attribute to a server-side method to make the method callable from remote Web clients. To learn More

Static (Declaration)

A static method is callable on a class even when no instance of the class has been created. If any instances of the class are created then they cannot be used to access the static member. Only one copy of static fields and events exist. This static method can be accessed directly by the name of the static method followed by the "." (dot) operator and the class name. So that's why I marked the method as static. It cannot interact with the instance properties and methods of your Page class, because a Page method call creates no instance of the Page or any of its controls.
Client Code( .aspx code)
The client side code has the following control and properties on the page.
ScriptManager Control
The EnablePageMethods property of the ScriptManager Control indicates whether public static page methods in an ASP.NET page can be called from a client script. The EnablePageMethods attribute must be added on the ScriptManager tag as true.
Button Control
Drag and drop a Button control onto the form to show the message when you click on the Button.
OnClientClick Method
The "OnClientClick" event will be associated with the JavaScript function.
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %>

<!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></title>
    <script type='text/javascript'>
        function GetName() {

            PageMethods.Name(Success, Failure);
        }
        function Success(result) {
            alert(result);
        }
        function Failure(error) {
            alert(error);
        }
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <asp:ScriptManager ID='ScriptManager1' runat='server' EnablePageMethods='true' />
    <div>  
        <asp:Button ID="Button1" runat="server" Text="Get Name" OnClientClick='GetName();return false;' />
    </div>
    </form>
</body>
</html>

The code above defines how to call a server-side function named "Name". 
If there are no errors then "Success" will show a pop-up window with our server-side message text.
function Success(result) {
            alert(result);
        }
 
Else, the pop-up will show an exception message.
function Failure(error) {
            alert(error);
        }

Now press F5 to run the application.
Calling-Server-Side-Function-from-JavaScript-1.jpg
Now click on the Button control to see the server-side code message.
Calling-Server-Side-Function-from-JavaScript-2.jpg