Osama's Weblog

The place where you get updated!
  • rss
  • Home
  • Who am I?
  • RSS Feeds

Passing parameters to an other page in VisualForce using JavaScript

Osama | October 22, 2009

There is a general requirement of passing parameters from one page to another through queryString using GET Method. The same thing was required in a project. Below is the code showing ho did I do that in Visual Force page using apex.

This is the page FROM which the parameter has to be sent

<apex:page>
<body>
<form name="myForm" method="get" action="nextPageURL">
<input type="hidden" value="SampleValue" name="name"/>
<input type="submit" value="Submit"/>

</body> </apex:page>

According to this code, there is a hidden input with value “SampleValue” and when we submit, this value is passed to next page in query string. The url would look like “nextPageURL?name=SampleValue.

The code blow how to retrieve the receved paramter. The code below has to be in the other page.

<apex:page>
<head>

<script type="text/javascript">
function getValue(varname)
{
  var url = window.location.href;
  var qparts = url.split("?");
  if (qparts.length == 0)
  {
    return "";
  }
  var query = qparts[1];
  var vars = query.split("&");
  var value = "";
  for (i=0;i<vars.length;i++)
  {
    var parts = vars[i].split("=");
    if (parts[0] == varname)
    {
      value = parts[1];
      break;
    }
  }
  value = unescape(value);
  value.replace(/\+/g," ");
  return value;
}
</script>

</head>
<body>
<script type="text/javascript">
   var name = getValue("name");
   alert(name);
</body>
</apex:page>

The getValue() method search for “name” and decrypt the received paramter from the query string. It worked for me. Feel free to ask any questions

  • Share/Bookmark
Comments
7 Comments »
Categories
VisualForce
Tags
APEX, GET, JavaScript, Visual Force, VisualForce
Comments rss Comments rss
Trackback Trackback

Form Validation using JQuery

Osama | October 12, 2009

Doing a project I had to use form validation to make sure the user enters all the required fields. I used JQuery for form validation.

“jQuery is a fast and concise JavaScript Library that simplifies HTML document traversing, event handling, animating, and Ajax interactions for rapid web development. Query is designed to change the way that you write JavaScript.” This is what the jQuery.com says about it.

And in practive it really makes life easier. You dont have to write a large code. The code below shows what I did for form validation.

<script type=”text/javascript”>

$(document).ready(function() {
$(“#form1″).validate({  //HTML Form ID
rules: {
Fname: “required”,//  It Makes the Fname required, Fname is the “name” of HTML input type
email: {// compound rule
required: true, // Set email required
email: true  // Check whether the entered string is in the correct e-mail form
},
url: {
url: true// URL is not required but it checks for the correct URL form
},
comment: {
required: true
}
},
messages: {
comment: “Please enter a comment.”  //This message is particularly for “comment” input. As shown above, it is required, if left blank this message would be shown
}
});
});
</script>

Feel free to ask any question

  • Share/Bookmark
Comments
No Comments »
Categories
Uncategorized
Comments rss Comments rss
Trackback Trackback

XML Parsing Techniques

Osama | October 9, 2009

There are many XML parsers that are available. Choosing a right one for your situation might be challenging. There are three XML parsing techniques which are extremely popular and are used for Java and it also guides you to choose the correct make right choice of method based on the application and its requirements.

An Extensive Markup Language parser takes a serialized string which is raw as input and performs a series of operations with it. First and foremost the XML data is checked for syntax errors and how well it formed is, and it also makes sure that the start tags will have end tags that match and that there are no elements which are overlapping with each other. Many parsers implement first validate the Document Type Definition (DTD) or even the XML Schema sometimes to verify if the structure along with the content are correctly specified by you. In the end the output after parsing is provided access to the XML document’s content through the APIs programming modules.

The three XML parsing that are popularly used with techniques for Java is, Document Object Model (DOM), it is w3c provided mature standard, and Simple API for XML (SAX), it was one of the first to be widely adapted form of API for XML in Java and has become the standard, the third one is Streaming API for XML (StAX), which is a new model for parsing in XML but is very efficient and has a promising future. Each one of the mentioned techniques has their advantages and disadvantages.

Parsing with DOM 

Data Object Model or the DOM technique that based on the tree structure parsing and it builds an entire parsing tree in the memory. It also lets the DOM have complete access to the entire XML document dynamically.

The data object model is a tree like structure. So the document is considered to be the root from which all the DOM trees take birth, and the root will have one child node at the least, and the root element, which usually catalogues elements keeps it in the sample code. Another node that is created is the Document Type, which is used for the Document Type Data declarations. The elements in the catalog usually have child nodes, and these Child nodes are used as elements.

The DOM program takes the XML filename, and then creates the DOM tree. It uses the function called getElementsByTagName() for finding all the Data Object Model element nodes that can be used as the title elements. After this it finally prints the information in the text that is associated with the title elements. It achieves this by inspecting the list of title elements and then it examines the first child separately. The first child element is usually located between the start and end tags of the element, and it also uses the function getFirstChild() method to achieve this.

 

The Data object model is a direct model and very straight forward in its functions. XML document can be accessed randomly at any time because the memory stores the entire tree. DOM APIs also modify the nodes like for example appending a child or restructuring and updating or removing or deleting a node. There is a lot of support for navigating the memory tree in the DOM; but simultaneously there are issues related to parsing that have to be considered. It is essential in this system that the entire document has to be parsed at one single shot and the same time, it cannot be parsed partially or in intervals. If the XML document is huge then building the entire tree in the memory will become an extensive and an expensive process. The Data object model tree can actually consume a lot of memory. Though the DOM is very interoperable and interoperability is the biggest positive point it can offer at the same time it is not very good with binding and this proves to be its draw back when it comes to object binding.

 

There are a lot of applications which are well suited for DOM parsing. If the application needs to have immediate access to the XML document randomly then in such cases the DOM parsing is appropriate. For example an Extensive Style Language processor always has the need to navigate through an entire file and this becomes a repeated process while it is processing templates. Dom is dynamic when it comes to updating or modifying data so this feature is extremely convenient for applications, like the XML editors, which need to frequently modify data.

 

Parsing with SAX

SAX processing model is entirely based on stream of events and is an event-driven model for the processing of XML documents. Unlike the DOM where it builds an entire tree to represent the data, the SAX parser streams a series of events while it reads the document. These events are forwarded to event handlers, which also provide access to the data of the document. There are three basic types of event handlers the DTD Handler which is used for accessing the data of XML DTD’s. The error handlers which are used for creating a low-level access to the errors created while parsing. The last but not the least Content handler which is used for accessing the content in the document.

The difference between the DOM and the SAX parser offers a great benefit in terms of performance. It provides a low-level access which is efficient at the same time to the XML documents contents. Whereas the SAX model while having the major advantage of consuming extremely low memory, mainly because the document in its entirety does not have the need to be loaded into the memory slot at one time, and this feature enables a SAX parser to be able to parse a document which is much larger than the system’s own memory component. In addition to this, you don’t have the need to create objects for each and every node, unlike the DOM environment. SAX “push” model finally can be used in a broad context, when it comes to multiple content handlers which can be registered and used to receive events in a parallel way, instead of receiving them one by one in a pipeline in a series.

One of the disadvantages of SAX can be that you will have to implement all the event handlers to handle each and every incoming event. The application code must be maintained in this state of events. The SAX parser is incapable of processing the events when it comes to the DOM’s element supports, and you also have to keep track of the parsers position in the document hierarchy. The application logic gets tougher as the document gets complicated and bigger. It may not be required that the entire document be loaded but a SAX parser still requires to parse the whole document, similar to the DOM.

 

Parsing with STax

Stax is a brand new parsing technique which is very similar to SAX and also an improvisation to it. The STAX uses a model that is event-driven. The only difference between sax and STAAX here is that the sax uses a push model and the STAX uses a pull model for event processing. And also another notable feature is instead of using call back options the STAX parser returns events which are requested by the applications in use.

————————————–

As per of  my requirement, DOM was a perfect choice as I wanted to dynamically access the XML response and get the value out of  desired tag. Here is what I did:

 

TagName is the name of the tag which you require and “i” is the number of occurance of the tag. for e.g. if in XML message MyTag is occuring 3 times and you want to get the value of 2nd occurance of the tag then replace “i” with 2.

 

Feel free to ask any questions.

 

(XMLDom Class is available for download in Java or Apex)
String xml = //XML message
XMLDom d;
d = new xmldom(xml);        
String result3 =  d.getElementsByTagName(TagName)[i].nodeValue;
       
  • Share/Bookmark
Comments
2 Comments »
Categories
Uncategorized
Tags
XML PARSING DOM SAX STAX
Comments rss Comments rss
Trackback Trackback

API integration using Apex

Osama | October 6, 2009

Since few days I was trying to call Fedex webservice to get the shipping rates on Apex for a shopping cart project. The problem with Apex is it doesnt support WSDL. As in .net and java it is simple to call these services using WSDL or DLL provided by Fedex. I, with my colleagues worked hard to solve the problem. We found a way to solve the problem.

Luckily Apex has Http class so we could send the soap message in XML in the Http request and get the desired response. Though things seemed to be pretty simple but they were not.

We were sending the fedex rate request in soap envelope and getting tthe same envelope in the response. After negotiating with the Fedex technical support we found that the soap envelope we were making was not correct. XML being a hierarichal language needs to match its nodes of the soap envelope on the server. If any of the nodes are missing or even if the order is not correct it won’t give the desired response.

Below is the code that we implemented.

 

Http h = new Http();

 

 HttpRequest req = new HttpRequest();

 

String url = 'https://gateway.fedex.com:443/web-services/rate';
String soapXML = //soap envelope in XML

 

req.setBody(soapXML);
req.setEndpoint(url);
req.setMethod('POST');
req.setHeader('Content-length', '1753' );
req.setHeader('Content-Type', 'text/xml;charset=UTF-8');  
req.setHeader('SOAPAction','getRates');

 

HttpResponse res = h.send(req);
String xml = res.getBody();

The resultant XML can be parsed using XmlStreamReader class.

The solution mentioned above seems pretty simple but it took alot of time for us to solve it as there is not much help available on Apex.

here is the correct soap envelope fedex rate service

<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:v6="http://fedex.com/ws/rate/v6">
 <soapenv:Header/>
 <soapenv:Body>
 <v6:RateRequest>
 <v6:WebAuthenticationDetail>
 <v6:UserCredential>
 <v6:Key></v6:Key>
 <v6:Password></v6:Password>
 </v6:UserCredential>
 </v6:WebAuthenticationDetail>
 <v6:ClientDetail>
 <v6:AccountNumber></v6:AccountNumber>
 <v6:MeterNumber></v6:MeterNumber>
 </v6:ClientDetail>
 <v6:Version>
 <v6:ServiceId>crs</v6:ServiceId>
 <v6:Major>6</v6:Major>
 <v6:Intermediate>0</v6:Intermediate>
 <v6:Minor>0</v6:Minor>
 </v6:Version>
 <v6:RequestedShipment>
 <v6:Shipper>
 <v6:AccountNumber></v6:AccountNumber>
 <v6:Contact>
 <v6:CompanyName></v6:CompanyName>
 <v6:PhoneNumber></v6:PhoneNumber>
 </v6:Contact>
 <v6:Address>
 <v6:StreetLines></v6:StreetLines>
 <v6:StreetLines></v6:StreetLines>
 <v6:City></v6:City>
 <v6:PostalCode></v6:PostalCode>
 <v6:CountryCode></v6:CountryCode>
 </v6:Address>
 </v6:Shipper>
 <v6:Recipient>
 <v6:Contact>
 <v6:PersonName></v6:PersonName>
 <v6:CompanyName></v6:CompanyName>
 <v6:PhoneNumber></v6:PhoneNumber>
 </v6:Contact>
 <v6:Address>
 <v6:StreetLines></v6:StreetLines>
 <v6:StreetLines/>
 <v6:City></v6:City>
 <v6:StateOrProvinceCode></v6:StateOrProvinceCode>
 <v6:PostalCode></v6:PostalCode>
 <v6:CountryCode></v6:CountryCode>
 </v6:Address>
 </v6:Recipient>
 <v6:RateRequestTypes>LIST</v6:RateRequestTypes>
 <v6:PackageCount>1</v6:PackageCount>
 <v6:PackageDetail>INDIVIDUAL_PACKAGES</v6:PackageDetail>
 <v6:RequestedPackages>
 <v6:SequenceNumber>1</v6:SequenceNumber>
 <v6:InsuredValue>
 <v6:Currency>USD</v6:Currency>
 <v6:Amount>0</v6:Amount>
 </v6:InsuredValue>
 <v6:Weight>
 <v6:Units>KG</v6:Units>
 <v6:Value>2.0</v6:Value>
 </v6:Weight>
 <v6:Dimensions>
 <v6:Length>22</v6:Length>
 <v6:Width>16</v6:Width>
 <v6:Height>17</v6:Height>
 <v6:Units>CM</v6:Units>
 </v6:Dimensions>
 </v6:RequestedPackages>
 </v6:RequestedShipment>
 </v6:RateRequest>
 </soapenv:Body>
</soapenv:Envelope>

If you have any queries feel free to ask questions.

Thanks
  • Share/Bookmark
Comments
13 Comments »
Categories
APEX
Tags
APEX, API
Comments rss Comments rss
Trackback Trackback

My status

Categories

  • .NET
  • APEX
  • consulting
  • General
  • Oracle CRM on Demand
  • salesforce
  • Uncategorized
  • VisualForce

MM Did You Know?

The first CD pressed in the US was Bruce Springsteen`s "Born in the USA."
Plugin by mmilan

Its all about cloud

Salesforce

.NET .NET 4.0 beta actionFunction actionSupport administrator android APEX Apex variable API button certification cloud computing consulting controller custom DoDirectPayment force.com GET goggles google html images input inputField JavaScript jquery master-detail matcher Parallel Programming parameters pattern paypal query string REGEX regular expression salesforce search url variable Visual Force VisualForce Visual Studio vmware web service XML PARSING DOM SAX STAX

WP Cumulus Flash tag cloud by Roy Tanck and Luke Morton requires Flash Player 9 or better.

My Tweets

Error: Please make sure the Twitter account is public.

Get Adobe Flash playerPlugin by wpburn.com wordpress themes
rss Comments rss valid xhtml 1.1 design by jide powered by Wordpress get firefox