Thursday, May 14, 2009

Read resources (xml, text, images) from JAR



 

JAR

The Java Archive (JAR) file format enables you to bundle multiple files into a single archive file. Typically a JAR file contains the class files and auxiliary resources associated with applets and applications.

Get Resource from JAR

Use java.lang.Class class's method : getResource() and getResourceAsStream() - The simplest way to retrieve a resource from JAR file.

  1. URL getResource(String name) - Finds a resource with a given name.
  2. InputStream getResourceAsStream(String name) - Finds a resource with a given name.

EXAMPLE – Source code

This example demonstrate how to read an XML file which is packed into the JAR. This is a java-console application.


 

XML File

Std.xml

<?xml version="1.0" ?>

<Students>

<Std ClassName="1st">

<Roll>10</Roll>

<Name>Mr. Raj</Name>

</Std>

<Std ClassName="3rd">

<Roll>11</Roll>

<Name>Mr. Rohan</Name>

</Std>

</Students>

JAVA source code

ReadStd.java

import org.w3c.dom.*;

import javax.xml.parsers.*;

import java.io.*;


 

public class ReadStd {

public static void main(String []args) throws Exception {

// Read Resource

InputStream ii=ReadStd.class.getResourceAsStream("Std.xml");


 

DocumentBuilderFactory fact=DocumentBuilderFactory.newInstance();

DocumentBuilder build=fact.newDocumentBuilder();


 

Document doc=build.parse(ii);


 

Element root=doc.getDocumentElement();

System.out.println(root.getTagName());


 

NodeList list=root.getChildNodes();

System.out.println("Total Nodes : " + list.getLength());


 

int i;


 

for(i=0;i<list.getLength();i++) {

Node t=list.item(i);

if(t.hasAttributes())

System.out.print("Node has an attribute");

System.out.println(t.getNodeName() + " " + t.getNodeType() + " " + t.getNodeValue());

if(t.hasChildNodes()) {

NodeList p=t.getChildNodes();

for(int j=0;j<p.getLength();j++) {

                Node t1=p.item(j);

        System.out.println(t1.getNodeName() + " " + t1.getNodeType() + " " + t1.getNodeValue());

}

}

}

}

}

MANIFEST File

m.mf

Main-Class: ReadStd

 

NOTE: All three files namely Std.xml, ReadStd.xml and m.mf must be reside in the same directory/folder.


 

COMPILE & PACKAGE

> javac ReadStd.java

> jar –cvfm kk.jar m.mf .

[

Read more about Packaging & Deployment of Java application.


http://java.sun.com/docs/books/tutorial/deployment/jar/index.html


 

]

DEPLOY & EXECUTE

Copy the kk.jar anywhere or any folder and issue following command to execute it.

> java -jar kk.jar


 


 


 


 

Tuesday, April 21, 2009

Language Integrated Query Part - I

LINQ

LANGUAGE-INTEGRATED QUERY is the name of technologies based on the integration of query capabilities in .NET compliant languages.

With LINQ, a query is now a language construct. By using query syntax, you can perform complex filtering, ordering, and grouping operation of data sources with minimum code. You use the same basic query expression patterns to query and transform data in SQL databases, ADO.NET Datasets, XML documents and streams, and .NET collections.

LINQ Parts

There are three parts of Query operation

  1. The Data source
  2. The Query (Query Expression)
  3. Execute the Query

The Data Source

Types that support IEnumerable(T) or a derived interface such as the generic IQueryable(T) are called Queryable Types. A Queryable Types requires no modification or special treatment to serve as a LINQ data source. If the source data is not already in memory as a queryable type, the LINQ provider must represent it as such.

LINQ provider

A library that implements the functionality of the standard query operators for a specific kind of data source. A LINQ provider translates queries expressed in Visual Basic or C# into the native language of the data source.

LINQ to ADO.NET

A technology that enables you to query over any enumerable object in ADO.NET by using the LINQ programming model. LINQ to ADO.NET consists of two related LINQ technologies: LINQ to DataSet and LINQ to SQL.

LINQ to DataSet

A LINQ technology that makes it easier and faster to query over data cached in a DataSet object. The queries are expressed in the programming language itself and not as string literals embedded in the application code.

LINQ to Objects

The use of LINQ to query in-memory data such as arrays and lists.

LINQ to SQL

A LINQ technology that provides a run-time infrastructure for managing relational data as objects. In LINQ to SQL, the data model of a relational database is mapped to an object model expressed in the programming language of the developer.


 

LINQ to XML

An in-memory programming interface that enables you to work with XML from within the .NET Framework programming languages. You can query and modify a document, and then, after modifying it, you can save it to a file or serialize the result and send it over the Internet.

The Query

The query specifies what information to retrieve from the data source or sources. Optionally, a query also specifies how that information should be sorted, grouped, and shaped before it is returned. A query is stored in a query variable and initialized with a query expression.

Query Operators

The standard query operators are the methods that form the Language-Integrated Query (LINQ) pattern. Most of these methods operate on sequences, where a sequence is an object whose type implements the IEnumerable<(Of <(T>)>) interface or the IQueryable<(Of <(T>)>) interface. The standard query operators provide query capabilities including filtering, projection, aggregation, sorting and more.

Two Sets of LINQ Operator

There are two sets of LINQ standard query operators:

  1. One that operates on objects of type IEnumerable<(Of <(T>)>).
  2. The other that operates on objects of type IQueryable<(Of <(T>)>).

The methods that make up each set are static members of the Enumerable and Queryable classes, respectively. They are defined as extension methods of the type that they operate on. This means that they can be called by using either static method syntax or instance method syntax.

The standard query operators differ in the timing of their execution, depending on whether they return a singleton value or a sequence of values. Those methods that return a singleton value (for example, Average and Sum) execute immediately. Methods that return a sequence defer the query execution and return an enumerable object.

Query Expression

  1. Query expressions can be used to query and to transform data from any LINQ-enabled data source.
  2. Query expressions are easy to learn because they use many familiar C# language constructs.
  3. The variables in a query expression are all strongly typed, although in many cases you do not have to provide the type explicitly because the compiler can infer it.
  4. A query is not executed until you iterate over the query variable in a foreach statement.
  5. At compile time, query expressions are converted to Standard Query Operator method calls according to the rules set forth in the C# specification. Any query that can be expressed by using query syntax can also be expressed by using method syntax. However, in most cases query syntax is more readable and concise.
  6. As a rule when you write LINQ queries, use query syntax whenever possible and method syntax whenever necessary. There is no semantic or performance difference between the two different forms. Query expressions are often more readable than equivalent expressions written in method syntax.
  7. Some query operations, such as Count or Max, have no equivalent query expression clause and must therefore be expressed as a method call. Method syntax can be combined with query syntax in various ways.
  8. Query expressions can be compiled to expression trees or to delegates, depending on the type that the query is applied to. IEnumerable<(Of <(T>)>) queries are compiled to delegates. IQueryable and IQueryable<(Of <(T>)>) queries are compiled to expression trees.

Iteration Statement: foreach

The foreach statement repeats a group of embedded statements for each element in an array or an object collection. The foreach statement is used to iterate through the collection to get the information that you want, but should not be used to change the contents of the collection to avoid unpredictable side effects.

At any point within the foreach block, you can break out of the loop by using the break keyword, or step to the next iteration in the loop by using the continue keyword. A foreach loop can also be exited by the goto, return, or throw statements.

Snippet


 

// Traverse a one-dim array

int []a={11,22,33};

foreach(int p in a) {

Console.WriteLine(p);

}


 

// Traverse a two-dim array

int [,]a={{11,22,33},{22,33,44},{66,77,88}};

foreach (int p in a){

Console.WriteLine(p);

}


 

// Generic List

List<float> p = new List<float>();

p.Add(100f);

p.Add(100.23f);

p.Add(56.44f);

foreach (float t in p){

Console.WriteLine(t);

}


 

// Generic Set

HashSet<int> p = new HashSet<int>();

p.Add(11);

p.Add(40);

p.Add(3);

foreach (int t in p){

Console.WriteLine(t);

}


 

// Generic Stack

Stack<int> p = new Stack<int>();

p.Push(33);

p.Push(44);

p.Push(55);


 

foreach (int t in p){

Console.WriteLine(t);

}


 

// Traverse an ArrayList

ArrayList a = new ArrayList();

a.Add(100);

a.Add("Hello");

a.Add(10.44d);

a.Add(34.44f);

a.Add(DateTime.Now);


 

foreach (object p in a){

Console.WriteLine(p + " " + p.GetType().Name );

}


 

// Traverse Dictionary Object – Hashtable

Hashtable a = new Hashtable();

a.Add("no", 100);

a.Add("name", "Mr. Rajesh");

a.Add("address", "Mehsana");


 

foreach (object p in a){

DictionaryEntry e = (DictionaryEntry)p;

Console.WriteLine(e.Key + " " + e.Value);

}


 


 


 


 

Wednesday, March 4, 2009

C Programming – Memory Management

An Overview of Your Computer

Your computer system consists of two parts: hardware and software. The hardware consists of all the physical parts of the machine. It illustrates that your computer's hardware consists of the physical components of your PC. The software is everything else. Software comprises the programs and data that interact with your hardware. The C language is an example of software.

The System Unit and Memory

The system unit is the large, box-shaped component of the computer. This unit houses the PC's microprocessor. You might hear the microprocessor called the CPU, or central processing unit. The CPU acts like a traffic cop, directing the flow of information throughout your computer system. The CPU is analogous also to the human brain. When you use a computer, you are actually interacting with its CPU. All the other hardware exists so the CPU can send information to you (through the monitor or the printer), and you can give instructions to the CPU (through the keyboard or the mouse).

The CPU also houses the computer's internal memory. Although the memory has several names, it is commonly referred to as RAM (random-access memory). RAM is where the CPU looks for software and data. When you run a C program, for example, you are instructing your computer's CPU to look in RAM for that program and carry out its instructions. C uses RAM space when it is loaded.

RAM is used for many things and is one of the most important components of your computer's hardware. Without RAM, your computer would have no place for its instructions and data. The amount of RAM can also affect the computer's speed. In general, the more RAM your computer has, the more work it can do and the faster it can process data.

The amount of RAM is measured by the number of characters it can hold. A character in computer terminology is called a byte, and a byte can be a letter, a number, or a special character such as an exclamation point or a question mark. If your computer has 640,000 bytes of RAM, it can hold a total of 640,000 characters.

You want as much RAM as possible to hold C, data, and the system programs. Computer RAM is relatively inexpensive, so if your computer has less than 640K bytes of memory, you should consider purchasing additional memory to increase the total RAM to 640K. You can put more than 640K in most PCs. There are two types of additional RAM: extended memory and expanded memory (they both offer memory capacity greater than 640K). You can access this extra RAM with some C systems, but most beginning C programmers have no need to worry about RAM beyond 640K.

RAM is volatile; when you turn the computer off, all RAM is erased. Therefore, you must store the contents of RAM to a nonvolatile, more permanent memory device (such as a disk) before you turn off your computer. Otherwise, you lose your work.

Bell Labs first developed the C programming language in the early 1970s, primarily so Bell programmers could write their UNIX operating system for a new DEC (Digital Equipment Corporation) computer.

Until that time, operating systems were written in assembly language, which is tedious, time-consuming, and difficult to maintain. The Bell Labs people knew they needed a higher-level programming language to implement their project quicker and create code that was easier to maintain.

Because other high-level languages at the time (COBOL, FORTRAN, PL/I, and Algol) were too slow for an operating system's code, the Bell Labs programmers decided to write their own language. They based their new language on Algol and BCPL. Algol is still used in the European markets, but is not used much in America.

BCPL strongly influenced C, although it did not offer the various data types that the makers of C required. After a few versions, these Bell programmers developed a language that met their goals well. C is efficient (it is sometimes called a high, low-level language due to its speed of execution), flexible, and contains the proper language elements that enable it to be maintained over time.

In the 1980s, Bjourn Stroustrup, working for AT&T, took the C language to its next progression. Mr. Stroustrup added features to compensate for some of the pitfalls C allowed and changed the way programmers view programs by adding object-orientation to the language. The object-orientation aspect of programming started in other languages, such as Smalltalk. Mr. Stroustrup realized that C++ programmers needed the flexibility and modularity offered by a true OOP programming language.


 

Tuesday, February 17, 2009

C# Code to read excel book







C# code to read excel document.
using System.Collections;
using Microsoft.Office.Interop.Excel;
using System;
using System.Reflection;
class Sample
{
    static void Main()
    {
        string file = @"c:\csnet\jap\ex1\sample1.xlsx";
        Microsoft.Office.Interop.Excel.ApplicationClass ap = new ApplicationClass();
        Missing m=Missing.Value;
       Workbook wb=ap.Workbooks.Open(file, m, m, m, m, m, m, m, m, m, m, m, m, m, m);
       Worksheet sh =(Worksheet) wb.Sheets[1];
       for (int i = 1; i < 10; i++)
       {
           for(int j=1;j<=3;j++)
           {
               Range r =(Range) sh.Cells[i, j];
               Console.Write(r.Value2);
           }
           Console.WriteLine();
       }
        ap.Quit();
      
    }
}

Tuesday, January 20, 2009

PAYMENT GATEWAY

A payment gateway is an e-commerce application service provider service that authorizes payments for e-businesses, online retailers, bricks and clicks, or traditional brick and mortar. It is the equivalent of a physical point of sale terminal located in most retail outlets. Payment gateways encrypt sensitive information, such as credit card numbers, to ensure that information passes securely between the customer and the merchant.


 

How payment gateways work?


 

A payment gateway facilitates the transfer of information between a payment portal (such as a website or IVR service) and the Front End Processor or acquiring bank.


 

When a customer orders a product from a payment gateway enabled merchant, the payment gateway performs a variety of tasks to process the transaction:


 

  • A customer places order on website by pressing the 'Submit Order' or equivalent button, or perhaps enters their card details using an automatic phone answering service. 
  • If the order is via a website, the customer's web browser encrypts the information to be sent between the browser and the merchant's webserver. This is done via SSL (Secure Socket Layer) encryption. 
  • The merchant then forwards the transaction details to their payment gateway. This is another SSL encrypted connection to the payment server hosted by the payment gateway. 
  • The payment gateway forwards the transaction information to the processor used by the merchant's acquiring bank. 
  • The processor forwards the transaction information to the card association (i.e., Visa/MasterCard) 
  • If an American Express or Discover Card was used, then the processor acts as the acquiring bank and directly provides a response of approved or declined to the payment gateway. 
  • The card association routes the transaction to the correct card issuing bank. 
  • The credit card issuing bank receives the authorization request and sends a response back to the processor (via the same process as the request for authorization) with a response code. In addition to determining the fate of the payment, (i.e. approved or declined) the response code is used to define the reason why the transaction failed (such as insufficient funds, or bank link not available).
  • The processor forwards the response to the payment gateway. 
  • The payment gateway receives the response, and forwards it on to the website (or whatever interface was used to process the payment) where it is interpreted and a relevant response then relayed back to the cardholder and the merchant. 
  • The entire process typically takes 2-3 seconds 
  • The merchant must then ship the product prior to being allowed to request to settle the transaction. 
  • The merchant submits all their approved authorizations, in a "batch", to their acquiring bank for settlement. 
  • The acquiring bank deposits the total of the approved funds in to the merchant's nominated account. This could be an account with the acquiring bank if the merchant does their banking with the same bank, or an account with another bank. 
  • The entire process from authorization to settlement to funding typically takes 3 days. 


 


 

Many payment gateways also provide tools to automatically screen orders for fraud and calculate tax in real time prior to the authorization request being sent to the processor. Tools to detect fraud include geo-location, velocity pattern analysis, delivery address verification, computer finger printing technology, identity morphing detection, and basic AVS (Address Verification System) checks.


 


 

Payment Gateway API Integration


 

This API solution is designed for companies that have an existing back-end database and Internet servers for directly connecting to the Payment Online's credit card processing engines through direct connect https POST method (or through
programming).


 

The API offers direct connection methods that can be used for connecting via your order pages which can be a single page or multiple order pages with a shopping cart software and electronic catalog system. 


 

Integration through software from the back end database and Internet servers is more complicated and only proficient individuals should attempt direct connect through software.


 

The process however is straightforward. 


 

On your Internet servers (where your web site and order page is hosted), orders are placed by your customers. The customer order information is stored by your back-end database solutions that you have implemented. The transaction information (credit card type, name, number, date of expiry, total amount, etc.) is POSTed (or server-script submitted) securely to Payment Online processing servers. Our servers will then process the transaction through the banking networks and proceeds from sales are deposited to your business bank account within a day (subject to Internet merchant account regulations).