Sending a fax using Windows Faxing in C#

Leave a comment

Adding a reference to FAXCOMLib.dll (COM/Fax Services) in Windows XP provides access to the Windows Fax Service, which you can use to send a fax as follows:

FAXCOMLib.FaxServer faxServer = new FAXCOMLib.FaxServerClass();
if (FaxNumber != “”)
{
try
{
faxServer.Connect(MachineName);
faxServer.Retries = Retries;
faxServer.RetryDelay = RetryDelay;
FAXCOMLib.FaxDoc faxDoc = (FAXCOMLib.FaxDoc)faxServer.CreateDocument(FileName);
faxDoc.RecipientName = RecipientName;
faxDoc.FaxNumber = FaxNumber;
faxDoc.DisplayName = DocumentName;
int Response = faxDoc.Send();
success = true;
}
catch{}
finally
{
faxServer.Disconnect();
} // disconnect
} // send fax

Read JSON data using Ruby

Leave a comment

require 'open-uri'
require 'json'

url = 'http://search.twitter.com/trends.json'

buffer = open(url, "UserAgent" => "Ruby-Wget").read

# convert JSON data into a hash
result = JSON.parse(buffer)

trends = result['trends']
trends.each do |subject|
  puts subject['name'] + ' ' + subject['url']
end

output:
Clay Aiken http://search.twitter.com/search?q=Clay+Aiken
Sarah Palin http://search.twitter.com/search?q=Sarah+Palin
Heroes http://search.twitter.com/search?q=Heroes
McCain http://search.twitter.com/search?q=McCain
iPhone http://search.twitter.com/search?q=iPhone
Obama http://search.twitter.com/search?q=Obama
Apple http://search.twitter.com/search?q=Apple
T-Mobile G1 http://search.twitter.com/search?q=T-Mobile+G1
AT&T http://search.twitter.com/search?q=AT%26T
CS4 http://search.twitter.com/search?q=CS4

Socket Example in Java

Leave a comment

Here is the example of socket application in java that server communicates with the client by localhost in port 2004.

Socket Server:

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;

/**
 *
 * @author Administrator
 */
public class Provider {
    
    ServerSocket providerSocket;
    Socket connection = null;
    ObjectOutputStream out;
    ObjectInputStream in;
    String message;
    Provider(){}
    void run() {
        try{
            //1. creating a server socket
            providerSocket = new ServerSocket(2004, 10);
            
            //2. Wait for connection
            System.out.println("Waiting for connection");
            connection = providerSocket.accept();
            System.out.println("Connection received from " + connection.getInetAddress().getHostName());
            //3. get Input and Output streams
            out = new ObjectOutputStream(connection.getOutputStream());
            out.flush();
            in = new ObjectInputStream(connection.getInputStream());
            sendMessage("Connection successful");
            //4. The two parts communicate via the input and output streams
            do{
                try{
                    message = (String)in.readObject();
                    System.out.println("client> reply " + message);
                    sendMessage("Server> reply " + message.replaceAll("server", "client"));
                    if (message.equals("bye"))
                        sendMessage("bye");
                } catch(ClassNotFoundException classnot){
                    System.err.println("Data received in unknown format");
                }
            }while(!message.equals("bye"));
        } catch(IOException ioException){
            ioException.printStackTrace();
        } finally{
            //4: Closing connection
            try{
                in.close();
                out.close();
                providerSocket.close();
            } catch(IOException ioException){
                ioException.printStackTrace();
            }
        }
    }
    void sendMessage(String msg) {
        try{
            out.writeObject(msg);
            out.flush();
            System.out.println("server>" + msg);
        } catch(IOException ioException){
            ioException.printStackTrace();
        }
    }
    public static void main(String args[]) {
        Provider server = new Provider();
        while(true){
            server.run();
        }
    }
}

Socket Client


import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.net.UnknownHostException;

/**
 *
 * @author Administrator
 */
public class Requester {
    
    Socket requestSocket;
    ObjectOutputStream out;
    ObjectInputStream in;
    String message;
    Requester(){}
    void run() {
        try{
            //1. creating a socket to connect to the server
            requestSocket = new Socket("localhost", 2004);
            System.out.println("Connected to localhost in port 2004");
            //2. get Input and Output streams
            out = new ObjectOutputStream(requestSocket.getOutputStream());
            out.flush();
            in = new ObjectInputStream(requestSocket.getInputStream());
            //3: Communicating with the server
            do{
                try{
                    message = (String)in.readObject();
                    System.out.println("server>" + message);
                    sendMessage("Hi my server 1");
                    message = (String)in.readObject();
                    System.out.println(message);
                    sendMessage("Hi my server 2");
                    message = (String)in.readObject();
                    System.out.println(message);
                    sendMessage("Hi my server 3");
                    message = (String)in.readObject();
                    System.out.println(message);
                    sendMessage("Hi my server 4");
                    message = (String)in.readObject();
                    System.out.println(message);
                    sendMessage("Hi my server 5");
                    message = (String)in.readObject();
                    System.out.println(message);
                    
                    message = "bye";
                    sendMessage(message);
                } catch(ClassNotFoundException classNot){
                    System.err.println("data received in unknown format");
                }
            }while(!message.equals("bye"));
        } catch(UnknownHostException unknownHost){
            System.err.println("You are trying to connect to an unknown host!");
        } catch(IOException ioException){
            ioException.printStackTrace();
        } finally{
            //4: Closing connection
            try{
                in.close();
                out.close();
                requestSocket.close();
            } catch(IOException ioException){
                ioException.printStackTrace();
            }
        }
    }
    void sendMessage(String msg) {
        try{
            out.writeObject(msg);
            out.flush();
            System.out.println("client got>" + msg);
        } catch(IOException ioException){
            ioException.printStackTrace();
        }
    }
    public static void main(String args[]) {
        Requester client = new Requester();
        client.run();
    }    
    
}

Code example of using REST in Ruby on Rails

Leave a comment

Now I would like to write code example to manage REST in Ruby on Rails that contains four methods like GET, POST, PUT and DELETE.
Please pay attention to look at the code as below:

require 'rubygems'
require 'net/http'
module MyREST
	def self.get(url)
		uri = URI.parse(url)
		http = Net::HTTP.start(uri.host, uri.port)
		resp = http.send_request('GET', uri.request_uri)
		resp.body
	end

	def self.post(url, data, content_type)
		uri = URI.parse(url)
		http = Net::HTTP.start(uri.host, uri.port)
		resp = http.send_request('POST', uri.request_uri, data, 'Content-Type' => content_type)
	end

	def self.put(url, data, content_type)
		uri = URI.parse(url)
		http = Net::HTTP.start(uri.host, uri.port)
		resp = http.send_request('PUT', uri.request_uri, data, 'Content-Type' => content_type)
	end

	def self.delete(url)
		uri = URI.parse(url)
		http = Net::HTTP.start(uri.host, uri.port)
		resp = http.send_request('DELETE', uri.request_uri)
	end

end

If you want to use this code inside Rails project, you can edit enviroment.rb under config folder and add this one line code

require ‘myrest’

RAILS_GEM_VERSION = '2.3.2' unless defined? RAILS_GEM_VERSION

require File.join(File.dirname(__FILE__), 'boot')

Rails::Initializer.run do |config|
    require 'myrest'
end

And u call MyREST all over in the Rails project.
Here is an example to call MyREST.

MyREST.put url,contentType

Please enjoy your self

Regular Expression In Ruby

Leave a comment

Click here for Regular expression

Using XmlSimple

Leave a comment

Not everyone finds the REXML API intuitive. XmlSimple is the Ruby port of the Perl XML::Simple module.

Let’s try the same web search example using XmlSimple.

require 'net/http'
require 'rubygems'
require 'xmlsimple'

url = 'http://api.search.yahoo.com/WebSearchService/V1/webSearch?appid=YahooDemo&query=madonna&results=2'
xml_data = Net::HTTP.get_response(URI.parse(url)).body

data = XmlSimple.xml_in(xml_data)

data['Result'].each do |item|
   item.sort.each do |k, v|
      if ["Title", "Url"].include? k
         print "#{v[0]}" if k=="Title"
         print " => #{v[0]}\n" if k=="Url"
      end
   end
end

XmlSimple “slurps” the XML data and converts it to a native Ruby data structure.

Using REXML

Leave a comment

In order to illustarte how to use REXML to parse XML data returned by Yahoo! APIs, let us try to extract data returned by a Yahoo! web search:

require 'net/http'
require 'rexml/document'

url = 'http://api.search.yahoo.com/WebSearchService/V1/webSearch?appid=YahooDemo&query=madonna&results=2'

xml_data = Net::HTTP.get_response(URI.parse(url)).body

doc = REXML::Document.new(xml_data)
titles = []
links = []
doc.elements.each('ResultSet/Result/Title') do |ele|
   titles << ele.text
end
doc.elements.each('ResultSet/Result/Url') do |ele|
   links << ele.text
end

titles.each_with_index do |title, idx|
   print "#{title} => #{links[idx]}\n"
end

The above code will print out all the titles and links of all results.