Finding common elements using Linq

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] arr1 = { 5, 20, 3, 5, 6, 89, 9, 2, 1 };
            int[] arr2 = { 23, 34, 65, 65, 67, 2, 9 };
            List<int> list1 = new List<int>(arr1);
            List<int> list2 = new List<int>(arr2);
            IEnumerable<int> intersect = list1.Intersect<int>(list2);
            foreach (int i in intersect)
            {
                Console.WriteLine(i);
            }
        }
    }
}

Generating Prime Numbers with WCF using Visual Web Developer Express

Visual Web Developer
Create a new project with template “WCF Service Application” in Visual Web Developer Express.
Rename name IService.cs and Service.svc to IPrimeNumber.cs and PrimeNumber.cs

IPrimeNumber.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;

namespace PrimeNumberLib
{
    [ServiceContract]
    public interface IPrimeNumber
    {
        [OperationContract]
        bool isPrime(int n);

        [OperationContract]
        List<long> ListOfPrimes(int n);
    }
}

PrimeNumber.svc.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;

namespace PrimeNumberLib
{
    public class PrimeNumber : IPrimeNumber
    {
        public bool isPrime(int n)
        {
            if (n == 1)
                return false;
            else if (n < 4)
                return true;
            else if (n % 2 == 0)
                return false;
            else if (n < 9)
                return true;
            else if (n % 3 == 0)
                return false;
            else
            {
                int r = (int)Math.Floor(Math.Sqrt(n));
                int f = 5;
                while (f <= r)
                {
                    if (n % f == 0)
                        return false;
                    if (n % (f + 2) == 0)
                        return false;
                    f = f + 6;
                }
            }
            return true;
        }

        public List<long> ListOfPrimes(int n)
        {
            List<long> temp = new List<long>();
            int i = 2;

            for (; i <= n; i++)
            {
                if (isPrime(i))
                    temp.Add(i);
            }
            return temp;
        }
    }
}

Web.config

<?xml version="1.0"?>
<configuration>

  <system.web>
    <compilation debug="true" targetFramework="4.0" />
  </system.web>
  <system.serviceModel>
    <behaviors>
      <serviceBehaviors>
        <behavior>
          <!-- To avoid disclosing metadata information, set the value below to false and remove the metadata endpoint above before deployment -->
          <serviceMetadata httpGetEnabled="true"/>
          <!-- To receive exception details in faults for debugging purposes, set the value below to true.  Set to false before deployment to avoid disclosing exception information -->
          <serviceDebug includeExceptionDetailInFaults="false"/>
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <serviceHostingEnvironment multipleSiteBindingsEnabled="true">
      <serviceActivations>
        <add relativeAddress="PrimeNumber.svc" service="PrimeNumberLib.PrimeNumber" />
      </serviceActivations>
    </serviceHostingEnvironment>
  </system.serviceModel>
 <system.webServer>
    <modules runAllManagedModulesForAllRequests="true"/>
  </system.webServer>
  
</configuration>

The highlighted is the modification needed to tell IIS to look for PrimeNumber service

Right click on PrimeNumber.svc and select “View in Browser” to start IIS Express

Create PrimeNumber Proxy
Run

SvcUtil.exe /language:cs /out:GeneratedProxy.cs /config:App.config http://localhost:53031/PrimeNumber.svc

My path

"C:\Program Files\Microsoft SDKs\Windows\v7.1\Bin\SvcUtil.exe" /language:cs /out:GeneratedProxy.cs /config:App.config http://localhost:53031/PrimeNumber.svc

2 files are generated.
1) GeneratedProxy.cs
2) App.config

Create PrimeNumber Client Test
Create new project in Visual C# with template “Console Application”. Be sure to add “System.ServiceModel”, “GeneratedProxy.cs”, and “App.Config”.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace PrimeNumberTest
{
    class Program
    {
        static void Main(string[] args)
        {
            PrimeNumberClient c = new PrimeNumberClient();
            long[] l = c.ListOfPrimes(1000);
            foreach (long prime in l)
                Console.WriteLine(prime);
            c.Close();
        }
    }
}

Generating Prime Numbers with WCF

Create PrimeNumber library
Create new project in Visual C# with template “Class Library”. Be sure to add “System.ServiceModel” to References. PrimeNumberLib.dll is produced.
IPrimeNumber.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;

namespace PrimeNumberLib
{
    [ServiceContract]
    public interface IPrimeNumber
    {
        [OperationContract]
        bool isPrime(int n);

        [OperationContract]
        List<long> ListOfPrimes(int n);
    }
}

PrimeNumber.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace PrimeNumberLib
{
    public class PrimeNumber : IPrimeNumber
    {
        public bool isPrime(int n)
        {
            if (n == 1)
                return false;
            else if (n < 4)
                return true;
            else if (n % 2 == 0)
                return false;
            else if (n < 9)
                return true;
            else if (n % 3 == 0)
                return false;
            else
            {
                int r = (int)Math.Floor(Math.Sqrt(n));
                int f = 5;
                while (f <= r)
                {
                    if (n % f == 0)
                        return false;
                    if (n % (f + 2) == 0)
                        return false;
                    f = f + 6;
                }
            }
            return true;
        }

        public List<long> ListOfPrimes(int n)
        {
            List<long> temp = new List<long>();
            int i = 2;

            for (; i <= n; i++)
            {
                if (isPrime(i))
                    temp.Add(i);
            }
            return temp;
        }
    }
}

Create PrimeNumber Host (Web Server)
Create new project in Visual C# with template “Console Application”. Be sure to add “System.ServiceModel” and “PrimeNumberLib.dll” to References. http://localhost:8000/PrimeNumber/ should show a webpage on how to test the service.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel;
using System.ServiceModel.Description;
using PrimeNumberLib;

namespace PrimeNumberHost
{
    class Program
    {
        static void Main(string[] args)
        {
            Uri baseAddress = new Uri("http://localhost:8000/PrimeNumber/");

            ServiceHost selfHost = new ServiceHost(typeof(PrimeNumber), baseAddress);
            try
            {
                selfHost.AddServiceEndpoint(typeof(IPrimeNumber), new WSHttpBinding(), "PrimeNumberService");

                ServiceMetadataBehavior smb = new ServiceMetadataBehavior();
                smb.HttpGetEnabled = true;
                selfHost.Description.Behaviors.Add(smb);

                selfHost.Open();
                Console.WriteLine("The service is ready.");
                Console.WriteLine("Press <ENTER> to terminate service.");
                Console.WriteLine();
                Console.ReadLine();

                selfHost.Close();
            }
            catch (CommunicationException ce)
            {
                Console.WriteLine("An exception occurred: {0}", ce.Message);
                selfHost.Abort();
            }
        }
    }
}

Create PrimeNumber Proxy
Run

SvcUtil.exe /language:cs /out:GeneratedProxy.cs /config:App.config http://localhost:8000/PrimeNumber/

My path

"C:\Program Files\Microsoft SDKs\Windows\v7.1\Bin\SvcUtil.exe" /language:cs /out:GeneratedProxy.cs /config:App.config http://localhost:8000/PrimeNumber/

2 files are generated.
1) GeneratedProxy.cs
2) App.config

Create PrimeNumber Client Test
Create new project in Visual C# with template “Console Application”. Be sure to add “System.ServiceModel”, “GeneratedProxy.cs”, and “App.Config”. Be sure that “PrimeNumber Host” is running.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace PrimeNumberTest
{
    class Program
    {
        static void Main(string[] args)
        {
            PrimeNumberClient c = new PrimeNumberClient();
            long[] l = c.ListOfPrimes(1000);
            foreach (long prime in l)
                Console.WriteLine(prime);
            c.Close();
        }
    }
}

Generating Prime Numbers with Java RMI using HTTP Server

Create simple HTTP Server

package http;

import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.URI;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;

import com.sun.net.httpserver.Headers;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;

public class HttpServerLite {
  public static void main(String[] args) throws IOException {
    InetSocketAddress addr = new InetSocketAddress(9876);
    HttpServer server = HttpServer.create(addr, 0);

    server.createContext("/", new MyHandler());
    server.start();
    System.out.println("Server is listening on port 9876" );
  }
}

class MyHandler implements HttpHandler {
	public void handle(HttpExchange exchange) throws IOException {
		String requestMethod = exchange.getRequestMethod();
		if (requestMethod.equalsIgnoreCase("GET")) {
			try
			{
				URI uri = exchange.getRequestURI();
				Path path = FileSystems.getDefault().getPath("../jar/",uri.getPath().substring(1));
				byte[] b = Files.readAllBytes(path);
				Headers responseHeaders = exchange.getResponseHeaders();
				responseHeaders.set("Content-Type", "application/java-archive");
				responseHeaders.set("Content-Length",
						((Integer) b.length).toString());
				exchange.sendResponseHeaders(200, 0);
	
				OutputStream responseBody = exchange.getResponseBody();
				responseBody.write(b);
				responseBody.close();
			}catch(Exception e)
			{
				Headers responseHeaders = exchange.getResponseHeaders();
				responseHeaders.set("Content-Type", "text/html");
				exchange.sendResponseHeaders(404, 0);
				OutputStream responseBody = exchange.getResponseBody();
				responseBody.write("error: file not found".getBytes());
				responseBody.close();
			}
		}
	}
}

The HTTP server will look for files in a directory called jar which is located one level above current directory.
NOTE: For the http server to compile in Eclipse, make sure the JRE System Library is set to “Workspace default JRE (jre7)”
Create PrimeNumber RMI server

package server;

import java.util.List;

public interface PrimeTask {
	List<Long> getListofPrimes(Long n);
	Boolean isPrime(Long n);
}
package server;

import java.rmi.Remote;
import java.rmi.RemoteException;
import java.util.List;

public interface PrimeCompute extends Remote {
	List<Long> getListofPrimes(PrimeTask t, Long n) throws RemoteException;
	Boolean isPrime(PrimeTask t, Long n) throws RemoteException;
}
package server;

import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.UnicastRemoteObject;
import java.util.List;

public class PrimeComputeEngine implements PrimeCompute{
	public List<Long> getListofPrimes(PrimeTask t, Long n) throws RemoteException
	{
		return t.getListofPrimes(n);
	}

	public Boolean isPrime(PrimeTask t, Long n) throws RemoteException
	{
		return t.isPrime(n);
	}

	public static void main(String[] args) {
		if (System.getSecurityManager() == null) {
            System.setSecurityManager(new SecurityManager());
        }
		try
		{
			String name = "PrimeCompute";
			PrimeCompute engine = new PrimeComputeEngine();
			PrimeCompute stub =
	                (PrimeCompute) UnicastRemoteObject.exportObject(engine, 0);
			Registry registry = LocateRegistry.getRegistry();
	        registry.rebind(name, stub);
	        System.out.println("ComputeEngine bound");
		} catch (Exception e) {
            System.err.println("ComputeEngine exception:");
            e.printStackTrace();
        }
	}
}

Create a jar file called PrimeCompute.jar with the following classes: PrimeCompute and PrimeTask. Make sure to save it to the jar folder because the HTTP server will read from the jar folder.

For step by step instructions, go to Generating Prime Numbers with Java RMI

Create PrimeNumber RMI client

package client;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import server.PrimeTask;

class PrimeObject implements PrimeTask, Serializable
{
	private static final long serialVersionUID = 8954L;

	public PrimeObject()
	{

	}

	@Override
	public List<Long> getListofPrimes(Long n) {
        List<Long> temp = new ArrayList<Long>();

        for (long i = 1; i <= n; i++)
        {
            if (isPrime(i))
                temp.add(i);
        }
        return temp;
	}

	@Override
	public Boolean isPrime(Long n) {
        if (n == 1)
            return false;
        else if (n < 4)
            return true;
        else if (n % 2 == 0)
            return false;
        else if (n < 9)
            return true;
        else if (n % 3 == 0)
            return false;
        else
        {
            int r = (int)Math.floor(Math.sqrt(n));
            int f = 5;
            while (f <= r)
            {
                if (n % f == 0)
                    return false;
                if (n % (f + 2) == 0)
                    return false;
                f = f + 6;
            }
        }
        return true;
	}
}
package client;

import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.util.List;

import server.PrimeCompute;
import server.PrimeTask;

public class PrimeNumberUtils {
	public static void main(String[] args) {
		if (System.getSecurityManager() == null) {
            System.setSecurityManager(new SecurityManager());
        }
		
		try {
			String name = "PrimeCompute";
			Registry registry = LocateRegistry.getRegistry(args[0]);
			PrimeCompute prime = (PrimeCompute) registry.lookup(name);
			PrimeTask o = new PrimeObject();
			Long l = 1000000L;
			List<Long> p = prime.getListofPrimes(o, l);
			for (Long n : p) {
				System.out.println(n);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}

Add reference to the PrimeCompute.jar so the client will compile.

Create a jar file called PrimeObject.jar with the following classes: PrimeObject. Make sure to save it to the jar folder because the HTTP server will read from the jar folder.

Create Security Policy
Create a file called server.policy (and put it in your server project directory). Create a file called client.policy (and put it in your client project directory). Both server.policy and client.policy contains the following:

grant{
permission java.security.AllPermission;
};

Configurations for Java Applications
PrimeNumberServer

Make sure the VM arguments has the following:

-Djava.security.policy=server.policy -Djava.rmi.server.codebase="http://localhost:9876/PrimeCompute.jar http://localhost:9876/PrimeObject.jar"

Replace localhost with your http webserver address.

PrimeNumberClient

Make sure the VM arguments has the following:

-Djava.security.policy=client.policy

HTTPServerLite
No configuration needed.

Running the apps
Run the following in order:
1) rmiregistry
2) HTTP Server
3) PrimeNumberServer
4) PrimeNumberClient

Generating Prime Numbers with Java RMI

Code for server

package server;

import java.util.List;

public interface PrimeTask {
	List<Long> getListofPrimes(Long n);
	Boolean isPrime(Long n);
}
package server;

import java.rmi.Remote;
import java.rmi.RemoteException;
import java.util.List;

public interface PrimeCompute extends Remote {
	List<Long> getListofPrimes(PrimeTask t, Long n) throws RemoteException;
	Boolean isPrime(PrimeTask t, Long n) throws RemoteException;
}
package server;

import java.rmi.RemoteException;
import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.rmi.server.UnicastRemoteObject;
import java.util.List;

public class PrimeComputeEngine implements PrimeCompute{
	public List<Long> getListofPrimes(PrimeTask t, Long n) throws RemoteException
	{
		return t.getListofPrimes(n);
	}

	public Boolean isPrime(PrimeTask t, Long n) throws RemoteException
	{
		return t.isPrime(n);
	}

	public static void main(String[] args) {
		try
		{
			String name = "PrimeCompute";
			PrimeCompute engine = new PrimeComputeEngine();
			PrimeCompute stub =
	                (PrimeCompute) UnicastRemoteObject.exportObject(engine, 0);
			Registry registry = LocateRegistry.getRegistry();
	        registry.rebind(name, stub);
	        System.out.println("ComputeEngine bound");
		} catch (Exception e) {
            System.err.println("ComputeEngine exception:");
            e.printStackTrace();
        }
	}
}

Code for client

package client;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import server.PrimeTask;

class PrimeObject implements PrimeTask, Serializable
{
	private static final long serialVersionUID = 8954L;

	public PrimeObject()
	{

	}

	@Override
	public List<Long> getListofPrimes(Long n) {
        List<Long> temp = new ArrayList<Long>();

        for (long i = 1; i <= n; i++)
        {
            if (isPrime(i))
                temp.add(i);
        }
        return temp;
	}

	@Override
	public Boolean isPrime(Long n) {
        if (n == 1)
            return false;
        else if (n < 4)
            return true;
        else if (n % 2 == 0)
            return false;
        else if (n < 9)
            return true;
        else if (n % 3 == 0)
            return false;
        else
        {
            int r = (int)Math.floor(Math.sqrt(n));
            int f = 5;
            while (f <= r)
            {
                if (n % f == 0)
                    return false;
                if (n % (f + 2) == 0)
                    return false;
                f = f + 6;
            }
        }
        return true;
	}
}
package client;

import java.rmi.registry.LocateRegistry;
import java.rmi.registry.Registry;
import java.util.List;

import server.PrimeCompute;
import server.PrimeTask;

public class PrimeNumberUtils {
	public static void main(String[] args) {
		try {
			String name = "PrimeCompute";
			Registry registry = LocateRegistry.getRegistry(args[0]);
			PrimeCompute prime = (PrimeCompute) registry.lookup(name);
			PrimeTask o = new PrimeObject();
			Long l = 1000000L;
			List<Long> p = prime.getListofPrimes(o, l);
			for (Long n : p) {
				System.out.println(n);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}

Eclipse with all the java files

Create jar for RMI codebase


Start rmiregistry

Create Java Application for server

Make sure the VM Arguments has the following

-Djava.rmi.server.codebase=file:/C:\RMI\PrimeNumbersRMI\PrimeCompute.jar

Replace C:\RMI\PrimeNumbersRMI\PrimeCompute.jar with your path

Create Java Application for Client

Make sure the Program Arguments point to server. In this case, it is localhost because the server and client is run from the same machine.
Make sure the VM Arguments has the following

-Djava.rmi.server.codebase=file:/C:\RMI\PrimeNumbersRMI\PrimeCompute.jar

Replace C:\RMI\PrimeNumbersRMI\PrimeCompute.jar with your path

Run Java Application for server first, then run Java Application for client

Operator Overload in C++

#include<iostream>
using namespace std;

class SuperBigInt
{
private:
int value;
public:
SuperBigInt(int i):
value(i)
{
}
SuperBigInt operator+(const SuperBigInt& a);
SuperBigInt operator*(const SuperBigInt& a);
SuperBigInt operator-(const SuperBigInt& a);
SuperBigInt operator/(const SuperBigInt& a);
friend ostream &operator<<(ostream& out, SuperBigInt c);
};

SuperBigInt SuperBigInt::operator+(const SuperBigInt& a)
{
return SuperBigInt(value + a.value);
}

SuperBigInt SuperBigInt::operator*(const SuperBigInt& a)
{
return SuperBigInt(value * a.value);
}

SuperBigInt SuperBigInt::operator-(const SuperBigInt& a)
{
return SuperBigInt(value – a.value);
}

SuperBigInt SuperBigInt::operator/(const SuperBigInt& a)
{
return SuperBigInt(value / a.value);
}

ostream & operator<<(ostream& out, SuperBigInt c)
{
out<<c.value;
return out;
}

int main()
{
SuperBigInt a(12);
SuperBigInt b(6);
SuperBigInt c = a+b;
cout<<a<<"+"<<b<<"="<<c<<endl;
c = a-b;
cout<<a<<"-"<<b<<"="<<c<<endl;
c = a*b;
cout<<a<<"*"<<b<<"="<<c<<endl;
c = a/b;
cout<<a<<"/"<<b<<"="<<c<<endl;
int sdsdad = 0 ;
}

Posted in C++

Operator Overload in C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace operatorOverload
{
    public class SuperBigInteger
    {
        int value;

        public SuperBigInteger(int value)
        {
            this.value = value;
        }

        public static SuperBigInteger operator +(SuperBigInteger s1, SuperBigInteger s2)
        {
            return new SuperBigInteger(s1.value + s2.value);
        }
        public static SuperBigInteger operator +(SuperBigInteger s1, int s2)
        {
            return new SuperBigInteger(s1.value + s2);
        }
        public static SuperBigInteger operator -(SuperBigInteger s1, SuperBigInteger s2)
        {
            return new SuperBigInteger(s1.value - s2.value);
        }
        public static SuperBigInteger operator -(SuperBigInteger s1, int s2)
        {
            return new SuperBigInteger(s1.value - s2);
        }
        public static SuperBigInteger operator /(SuperBigInteger s1, SuperBigInteger s2)
        {
            return new SuperBigInteger(s1.value / s2.value);
        }
        public static SuperBigInteger operator /(SuperBigInteger s1, int s2)
        {
            return new SuperBigInteger(s1.value / s2);
        }
        public static SuperBigInteger operator *(SuperBigInteger s1, SuperBigInteger s2)
        {
            return new SuperBigInteger(s1.value * s2.value);
        }
        public static SuperBigInteger operator *(SuperBigInteger s1, int s2)
        {
            return new SuperBigInteger(s1.value * s2);
        }
        public static implicit operator SuperBigInteger(Int32 i)
        {
            return new SuperBigInteger(i);
        }

        public override string ToString()
        {
            return value.ToString();
        }
    }
    
    class Program
    {
        static void Main(string[] args)
        {
            SuperBigInteger i = 50;
            i = i + 10;
            i = i - 1;
            i = i * 3;
            i = i / 2;
            i = i + new SuperBigInteger(4);
            i = i - new SuperBigInteger(6);
            i = i / new SuperBigInteger(2);
            i = i * new SuperBigInteger(3);
            Console.WriteLine(i);
        }
    }
}

Posted in C#

Better example using HashCode in C#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections;

namespace problem75
{
    class Num
    {
        public Num(long a, long b, long c, long total)
        {
            this.a = a;
            this.b = b;
            this.c = c;
            this.total = total;
        }

        public long a;
        public long b;
        public long c;
        public long total;

        public override bool Equals(object obj)
        {
            Num n = (Num)obj;
            if (total == n.total)
            {
                if (c == n.c)
                {
                    if (a == n.a && b == n.b)
                        return true;
                    if (b == n.a && a == n.b)
                        return true;
                    return false;
                }
                else
                    return false;
            }
            else
                return false;
        }

        public override int GetHashCode()
        {
            //the hashcode must be the same for 3^2 + 4^2 = 5^2
            //and 4^2 + 3 ^2 = 5^2.
            //the hashcode must be the same for a + b and b + a
            return (int)((a ^ 21) + (b ^ 21) + (c ^ 21));
        }
    }
    class Program
    {
        static void Main(string[] args)
        {
            int[] arr = new int[1500001];
            Hashtable hashT = new Hashtable();
            HashSet<Num> hashset = new HashSet<Num>();
            for (long m = 2; m < 1000; m++)
            {
                for (long n = 1; n < m; n++)
                {
                    for (long k = 1; k < 100000000; k++)
                    {
                        long a = ((m * m) - (n * n)) * k;
                        long b = (2 * m * n) * k;
                        long c = ((m * m) + (n * n)) * k;
                        long total = a + b + c;

                        if (total >= 0 && total <= 1500000)
                        {
                            Num n2 = new Num(a, b, c, total);
                            if (hashset.Add(n2))
                                arr[total]++;
                        }
                        else
                            break;
                    }
                }

            }

            int sum = 0;
            for (int i = 0; i < arr.Length; i++)
            {
                if (arr[i] == 1)
                    sum++;
            }
            Console.WriteLine(sum);
        }
    }
}

Serialization in Java

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

public class SerializationTest {
static class Person implements Serializable
{
private static final long serialVersionUID = 1411808257424672585L;

public Person(String fname, String lname, String title, String ss,
String birthYear) {
this.fname = fname;
this.lname = lname;
this.title = title;
this.ss = ss;
this.birthYear = birthYear;
}
String fname;
String lname;
String title;
transient String ss;
String birthYear;

@Override
public String toString() {
return "Person [fname=" + fname + ", lname=" + lname + ", title="
+ title + ", ss=" + ss + ", birthYear=" + birthYear + "]";
}

}
public static void main(String[] args) throws Exception{
Person p = new Person("John","Doe", "Mr.", "123456789", "1980");
FileOutputStream outStream = new FileOutputStream("Person.bin");
ObjectOutputStream s = new ObjectOutputStream(outStream);
s.writeObject(p);
s.close();

FileInputStream inStream = new FileInputStream("Person.bin");
ObjectInputStream s1 = new ObjectInputStream(inStream);
Person p1 = (Person)s1.readObject();
s1.close();
System.out.println(p1);
}
}

Serialization in C#

[Serializable()]
public class Person
{
    public Person()
    {
    }

    public Person(string fname, string lname, string title, string birthYear, string ss)
    {
        this.fname = fname;
        this.lname = lname;
        this.title = title;
        this.ss = ss;
        this.birthYear = birthYear;
    }

    public string fname;
    public string lname;
    public string title;
    [NonSerializedAttribute()]
    [XmlIgnoreAttribute]       //for xml serialization
    public string ss;
    public string birthYear;

    public override string ToString()
    {
        return title + " " + fname + " " + lname
            + " " + ss + " " + birthYear;
    }
}

class Program
{
    static void Main(string[] args)
    {
        Person p = new Person("John", "Smith", "Mr.", "2005", "123456789");

        XmlSerializer xml = new XmlSerializer(typeof(Person));
        StreamWriter stream = new StreamWriter("PersonXML.xml");
        xml.Serialize(stream, p);
        stream.Close();

        Person p1 = new Person("John", "Doe", "Mr.", "2009", "109999999");

        IFormatter binary = new BinaryFormatter();
        Stream stream1 = new FileStream("PersonBin.bin", FileMode.Create, FileAccess.Write, FileShare.None);
        binary.Serialize(stream1, p1);
        stream1.Close();

        xml = new XmlSerializer(typeof(Person));
        StreamReader reader = new StreamReader("PersonXML.xml");
        Person a = (Person)xml.Deserialize(reader);
        Console.WriteLine(a);

        binary = new BinaryFormatter();
        stream1 = new FileStream("PersonBin.bin", FileMode.Open, FileAccess.Read, FileShare.Read);
        Person b = (Person)binary.Deserialize(stream1);
        Console.WriteLine(b);
    }
}
Posted in C#