ChatClient.java
import java.net.*;
import java.io.*;
public class ChatClient implements Runnable
{
static String command;
Socket socket;
static final int portNumber=1666;
Thread commReader=null;
BufferedReader input;
PrintStream output;
String alias=null;
boolean logging=true;
public static void main(String[] argv) throws IOException
{
InetAddress clientAddr;
if(argv.length==0)
clientAddr=InetAddress.getLocalHost();
else
clientAddr=InetAddress.getByName(argv[0]);
System.out.println("Connecting to Chat Server at "+clientAddr);
ChatClient cc=new ChatClient(clientAddr);
Thread t=new Thread(cc);
t.start();
}
public ChatClient(InetAddress adx)
{
CommandReader cr=new CommandReader(this);
commReader=new Thread(cr);
command="xXx";
try
{
socket=new Socket(adx,portNumber);
input=new BufferedReader(new InputStreamReader(socket.getInputStream()));
output=new PrintStream(socket.getOutputStream());
commReader.start();
}
catch(IOException e)
{
System.out.println("Abnormal chat client socket condition:"+e);
}
}
public void run()
{
try
{
doLoop();
input.close();
output.close();
socket.close();
System.exit(0);
}
catch(IOException e)
{
System.out.println("Abnormal chat client socket condition:"+e);;
}
}
public void doLoop() throws IOException
{
String nullString=new String("xXx");
String data=nullString;
while(true)
{
synchronized(command)
{
if(!command.equals("xXx"))
{
data=command;
//reset
command="xXx";
}
} //end synch
if(!data.equals("xXx"))
{
if(logging)
{
//first msg
logging=false;
alias=data;
System.out.println(">>Logging as:"+alias);
output.println("S"+alias); //Starting new chat
}
else
{
if(data.equals("exit"))
{
System.out.println(">>Exiting Chat.");
output.println("X"+alias);
break;
}
else if(data.equals("/list"))
{
System.out.println(">>list of connected users:");
output.println("L"+alias);
break;
}
else if(data.equals("/help"))
{
System.out.println(">>Help on Chat commands:");
output.println("H"+alias);
break;
}
else
{
System.out.println(">>Sending msg:"+data);
output.println("D"+data); //sending data
}
}
}
data=input.readLine();
if(!data.equals("xXx"))
{
System.out.println("<<"+data);
}
data=nullString;
}
}
}
ChatDaemon.java
import java.net.*;
import java.io.*;
public class ChatDaemon implements Runnable
{
static final int maxClients=20;
static final int portNumber=1666;
static int numClients=0;
ChatServer[] chatters;
Thread me;
SharedMsg sharedMsg;
public static void main(String[] argv)
{
ChatDaemon cd=new ChatDaemon();
}
public ChatDaemon()
{
sharedMsg=new SharedMsg(this);
chatters=new ChatServer[maxClients];
//start sending
me=new Thread(this);
me.start();
try
{
listen();
}
catch(IOException e)
{
System.out.println("Abnormal socket condition:"+e);
}
}
public void listen() throws IOException
{
ServerSocket ss=null;
ss=new ServerSocket(portNumber);
Socket chatSocket=null;
System.out.println("...listening for connections..");
while(true)
{
chatSocket=ss.accept();
ChatServer ct=allocThread(chatSocket);
synchronized(System.out)
{
System.out.println("Allocated new chat server");
}
}
}
ChatServer allocThread(Socket s)
{
if(numClients<maxClients)
{
ChatServer ct=new ChatServer(s,sharedMsg,numClients);
chatters[numClients]=ct;
Thread t=new Thread(ct);
t.start();
numClients++;
return ct;
}
else
return null;
}
public void run()
{
char broad=(char)-1;
String dataNull=new String(broad+"xXx");
while(true)
{
for(int i=0;i<numClients;i++)
if(chatters[i].alive())
chatters[i].newMsg(dataNull);
}
}
public void refresh()
{
String data=sharedMsg.get();
synchronized(System.out)
{
System.out.println("RECEIVED:"+data);
}
for(int i=0;i<numClients;i++)
{
if(chatters[i].alive())
chatters[i].newMsg(data);
}
}
}
ChatServer.java
import java.net.*;
import java.io.*;
public class ChatServer implements Runnable
{
int index=-1;
SharedMsg sharedMsg;
Socket socket;
DataInputStream input;
PrintStream output;
String alias="";
boolean running=false;
boolean alive()
{
return running;
}
public ChatServer(Socket s,SharedMsg sm,int idx)
{
index=idx;
sharedMsg=sm;
socket=s;
try
{
input=new DataInputStream(socket.getInputStream());
output=new PrintStream(socket.getOutputStream(),true);
}
catch(IOException e)
{
System.out.println("Abnormal chat server socket condition 1:"+e);;
}
}
public void run()
{
try
{
doLoop();
input.close();
output.close();
socket.close();
}
catch(IOException e)
{
System.out.println("Abnormal chat server socket condition 2:"+e);;
}
}
public void doLoop() throws IOException
{
String line=null;
String data=null;
char command='W';
char ind=(char)index; //index of sender of msg
char broad=(char)-1; //goes to everybody
running=true;
while(true)
{
//loop: reads in msg, write it onto sharedmsg
line=input.readLine();
command=line.charAt(0);
data=line.substring(1);
if(command=='X')
{
sharedMsg.put(broad+"User: "+data+" Logged Out");
break;
}
else if(command=='S')
{
//first msg
alias=data;
sharedMsg.put(broad+"New User Logged: "+alias);
}
else
{
sharedMsg.put(ind+"From "+alias+": "+data);
}
}
//exiting
running=false;
}
//new message arrived, send it over the socket
public void newMsg(String msg)
{
char mitt=msg.charAt(0);
String data=msg.substring(1);
if(mitt!=(char)index)
{
//send
output.println(data);
output.flush();
synchronized(System.out)
{
System.out.print(".\b");
System.out.flush();
}
}
}
}
CommandReader.java
import java.io.*;
/**
* Reads from keyboard (STDIN)
*/
class CommandReader implements Runnable
{
ChatClient chatClient;
DataInputStream user;
public CommandReader(ChatClient cc)
{
chatClient=cc;
user=new DataInputStream(System.in);
}
public void run()
{
System.out.println("Waiting for client side commands...");
String com=null;
while(true)
{
//reads from keyboard
try
{
com=user.readLine();
}
catch(IOException e)
{
System.out.println("Abnormal reading from user:"+e);
}
synchronized(chatClient.command)
{
chatClient.command=com;
}
}
}
}
SharedMsg.java
public class SharedMsg
{
String data="";
ChatDaemon chatDaemon=null;
SharedMsg(ChatDaemon cd)
{
chatDaemon=cd;
}
synchronized String get()
{
return data;
}
synchronized void put(String s)
{
data=s;
chatDaemon.refresh();
}
}
Sunday, July 20, 2008
Saturday, July 12, 2008
Creating 2D Shapes in Java
The Java2D API provides advanced two-dimensional graphics capabilities for programmers who require detailed and complex graphical manipulations. it includes features for processing line art, text and images in packages java.awt, java.awt.image, java.awt.color, java.awt.font, java.awt.geom, java.awt.print and java.awt.image.renderable.
The code shown below constructs a ring of five pointed stars constructed from straight lines and complex curves.
The code shown below constructs a ring of five pointed stars constructed from straight lines and complex curves.
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.geom.GeneralPath;
import javax.swing.JFrame;
public class shapes extends JFrame{
//set window's title bar string, background color and dimensions
public shapes(){
super("Drawing 2D shapes");
getContentPane().setBackground(Color.WHITE);
setSize(400,400);
setVisible(true);
}
//draw general paths
public void paint(Graphics g){
super.paint(g);
int xPoints[]={55,67,109,73,83,55,27,37,1,43};
int yPoints[]={0,36,36,54,96,72,96,54,36,36};
Graphics2D g2d = (Graphics2D)g;
//create a star from a series of points
GeneralPath star = new GeneralPath();
//set the initials coordinates of the General Path
star.moveTo(xPoints[0],yPoints[0]);
//create the star
for(int count =1; count<xPoints.length; count++)
star.lineTo(xPoints[count],yPoints[count]);
//close the shape
star.closePath();
//translate the origin to (200,200)
g2d.translate(200,200);
//rotate around origin and draw stars in random colors
for(int count =1; count<=20; count++){
//rotate coordinate system
g2d.rotate(Math.PI/10.0);
//set random drawing color
g2d.setColor(new Color(
(int)(Math.random()*256),
(int)(Math.random()*256),
(int)(Math.random()*256)));
//draw filled star
g2d.fill(star);
}
}
public static void main(String args[]){
shapes application = new shapes();
application.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
Run the program and view the result!!!
Friday, July 11, 2008
Kerberos... providing strong cryptography
The Internet is an insecure place as we all know. Many of the protocols used in the Internet do not provide any security. Tools to identify passwords off of the network are in common use by malicious hackers. Thus, applications which send an unencrypted password over the network are extremely vulnerable. Some sites attempt to use firewalls to solve their network security problems. Unfortunately, firewalls assume that hackers are on the outside, which is often a very bad assumption. Most of the really damaging incidents of computer crime are carried out by insiders.Kerberos was created by MIT as a solution to these network security problems. The Kerberos protocol uses strong cryptography so that a client can prove its identity to a server (and vice versa) across an insecure network connection. After a client and server has used Kerberos to prove their identity, they can also encrypt all of their communications to assure privacy and data integrity as they go about their business.Lets see how it works.
Auth - Authenticator , SK1 - Session Key , TGT - Ticket
The client asks the authentication server for a ticket to the ticket-granting server(TGS). The authentication server looks up the client in its database, then generates a session key (SK1) for use between the client and the TGS. Kerberos encrypts the SK1 using the client’s secret key. The authentication server also uses the TGS’s secret key (known only to the authentication server and the TGS) to create and send the user a ticket-granting ticket (TGT).
The client decrypts the message and recovers the session key, then uses it to create an authenticator containing the user’s name, IP address and a time stamp. The client sends this authenticator, along with the TGT, to the TGS, requesting access to the target server. The TGS decrypts the TGT, then uses the SK1 inside the TGT to decrypt the authenticator. It verifies information in the authenticator, the ticket, the client’s network address and the time stamp. If everything matches, it lets the request proceed. Then the TGS creates a new session key (SK2) for the client and target server to use, encrypts it using SK1 and sends it to the client. The TGS also sends a new ticket containing the client’s name, network address, a time stamp and an expiration time for the ticket — all encrypted with the target server’s secret key — and the name of the server.
The client decrypts the message and gets the SK2. Finally ready to approach the target server, the client creates a new authenticator encrypted with SK2. The client sends the session ticket (already encrypted with the target server’s secret key) and the encrypted authenticator. Because the authenticator contains plaintext encrypted with SK2, it proves that the client knows the key. The encrypted time stamp prevents an eavesdropper from recording both the ticket and authenticator and replaying them later. The target server decrypts and checks the ticket, authenticator, client address and time stamp. For applications that require two-way authentication, the target server returns a message consisting of the time stamp plus 1, encrypted with SK2. This proves to the client that the server actually knew its own secret key and thus could decrypt the ticket and the authenticator.
The target server knows that the client is who he claims to be, and the two now share an encryption key for secure communications. Because only the client and target server share this key, they can assume that a recent message encrypted in that key originated with the other party.
Wednesday, July 9, 2008
Combination Generator program in java
This is a problem related to computability and complexity in computer science...Some problems in computer science cannot be resolved completely. Finding a correct solution might be impossible at some circumstances. Have you heard of these problems? Sorting, Partition problem, Halting problem. Here i present a case regarding partition problem.
The program takes numbers at run time and breaks it in to two sets where the sum of the elements in the two sets are equal. It should display the result, or it should say there are no such two sets in the given numbers. The time taken to get the solution against the numbers entered at run time is calculated. I started with 10 numbers and waited for the result. Then increased it to 14,16 and so on.. I hope you got a clear picture of what is happening now. Below is the program written in java. The timer runs in the program itself.
import java.math.BigInteger;
import java.io.*;
import java.awt.event.*;
import java.util.*;
import java.text.*;
public class CombinationGenerator {
private int[] a;
private int n;
private int r;
private BigInteger numLeft;
private BigInteger total;
// Constructor
public CombinationGenerator (int n, int r) {
if (r > n) {
throw new IllegalArgumentException ();
}
if (n < 1) {
throw new IllegalArgumentException ();
}
this.n = n;
this.r = r;
a = new int[r];
BigInteger nFact = getFactorial (n);
BigInteger rFact = getFactorial (r);
BigInteger nminusrFact = getFactorial (n - r);
total = nFact.divide (rFact.multiply (nminusrFact));
reset ();
}
// Reset
public void reset () {
for (int i = 0; i < a.length; i++) {
a[i] = i;
}
numLeft = new BigInteger (total.toString ());
}
// Return number of combinations not yet generated
public BigInteger getNumLeft () {
return numLeft;
}
// Are there more combinations?
public boolean hasMore () {
return numLeft.compareTo (BigInteger.ZERO) == 1;
}
// Return total number of combinations
public BigInteger getTotal () {
return total;
}
// Compute factorial
private static BigInteger getFactorial (int n) {
BigInteger fact = BigInteger.ONE;
for (int i = n; i > 1; i--) {
fact = fact.multiply (new BigInteger (Integer.toString (i)));
}
return fact;
}
// Generate next combination (algorithm from Rosen p. 286)
public int[] getNext () {
if (numLeft.equals (total)) {
numLeft = numLeft.subtract (BigInteger.ONE);
return a;
}
int i = r - 1;
while (a[i] == n - r + i) {
i--;
}
a[i] = a[i] + 1;
for (int j = i + 1; j < r; j++) {
a[j] = a[i] + j - i;
}
numLeft = numLeft.subtract (BigInteger.ONE);
return a;
}
public static void main(String d[]) throws IOException{
long startTime; // Starting time of program, in milliseconds.
long endTime; // Time when computations are done, in milliseconds.
double time; // Time difference, in seconds.
//get the number of numbers in set
InputStreamReader reader = new InputStreamReader (System.in);
BufferedReader input = new BufferedReader(reader);
System.out.print("Enter the numer of numbers in you set=");
String p = input.readLine();
int q =Integer.parseInt(p);
//put the elements to an array
int sum_of_array=0;
int[] indices;
int elements[]=new int[q];
int half_of_set=0;
int sum_of_elm=0;
for(int r=0; r<q; r++){
System.out.print("Enter the numbers of your set=");
String c = input.readLine();
int e =Integer.parseInt(c);
elements[r]= e;
}
//get the sum of array
for(int x=0; x<elements.length; x++){
sum_of_array=sum_of_array+elements[x];
}
int reminder=sum_of_array % 2;
half_of_set=sum_of_array/2;
//
if(reminder==0){
startTime = System.currentTimeMillis();
for(int len_of_array=1;len_of_array<=elements.length;len_of_array++ ){
CombinationGenerator x = new CombinationGenerator (elements.length, len_of_array);
StringBuffer combination;
while (x.hasMore ()) {
combination = new StringBuffer ();
indices = x.getNext ();
for (int i = 0; i < indices.length; i++) {
sum_of_elm=sum_of_elm+elements[indices[i]];
}
if(half_of_set==sum_of_elm){
//print the sub set element
for(int g=0; g<indices.length; g++){
System.out.println("numbers in your one sub set are ="+elements[indices[g]]+",");
}
endTime = System.currentTimeMillis();
time = (endTime - startTime) / 1000.0;
System.out.println(time);
return;
}
sum_of_elm=0;//set the sum of elm to 0
}
}
endTime = System.currentTimeMillis();
time = (endTime - startTime) / 1000.0;
System.out.println(time);
}else{
System.out.println("given number set can not divide to two equal sets:Sorry");
}
}
}
The program takes numbers at run time and breaks it in to two sets where the sum of the elements in the two sets are equal. It should display the result, or it should say there are no such two sets in the given numbers. The time taken to get the solution against the numbers entered at run time is calculated. I started with 10 numbers and waited for the result. Then increased it to 14,16 and so on.. I hope you got a clear picture of what is happening now. Below is the program written in java. The timer runs in the program itself.
import java.math.BigInteger;
import java.io.*;
import java.awt.event.*;
import java.util.*;
import java.text.*;
public class CombinationGenerator {
private int[] a;
private int n;
private int r;
private BigInteger numLeft;
private BigInteger total;
// Constructor
public CombinationGenerator (int n, int r) {
if (r > n) {
throw new IllegalArgumentException ();
}
if (n < 1) {
throw new IllegalArgumentException ();
}
this.n = n;
this.r = r;
a = new int[r];
BigInteger nFact = getFactorial (n);
BigInteger rFact = getFactorial (r);
BigInteger nminusrFact = getFactorial (n - r);
total = nFact.divide (rFact.multiply (nminusrFact));
reset ();
}
// Reset
public void reset () {
for (int i = 0; i < a.length; i++) {
a[i] = i;
}
numLeft = new BigInteger (total.toString ());
}
// Return number of combinations not yet generated
public BigInteger getNumLeft () {
return numLeft;
}
// Are there more combinations?
public boolean hasMore () {
return numLeft.compareTo (BigInteger.ZERO) == 1;
}
// Return total number of combinations
public BigInteger getTotal () {
return total;
}
// Compute factorial
private static BigInteger getFactorial (int n) {
BigInteger fact = BigInteger.ONE;
for (int i = n; i > 1; i--) {
fact = fact.multiply (new BigInteger (Integer.toString (i)));
}
return fact;
}
// Generate next combination (algorithm from Rosen p. 286)
public int[] getNext () {
if (numLeft.equals (total)) {
numLeft = numLeft.subtract (BigInteger.ONE);
return a;
}
int i = r - 1;
while (a[i] == n - r + i) {
i--;
}
a[i] = a[i] + 1;
for (int j = i + 1; j < r; j++) {
a[j] = a[i] + j - i;
}
numLeft = numLeft.subtract (BigInteger.ONE);
return a;
}
public static void main(String d[]) throws IOException{
long startTime; // Starting time of program, in milliseconds.
long endTime; // Time when computations are done, in milliseconds.
double time; // Time difference, in seconds.
//get the number of numbers in set
InputStreamReader reader = new InputStreamReader (System.in);
BufferedReader input = new BufferedReader(reader);
System.out.print("Enter the numer of numbers in you set=");
String p = input.readLine();
int q =Integer.parseInt(p);
//put the elements to an array
int sum_of_array=0;
int[] indices;
int elements[]=new int[q];
int half_of_set=0;
int sum_of_elm=0;
for(int r=0; r<q; r++){
System.out.print("Enter the numbers of your set=");
String c = input.readLine();
int e =Integer.parseInt(c);
elements[r]= e;
}
//get the sum of array
for(int x=0; x<elements.length; x++){
sum_of_array=sum_of_array+elements[x];
}
int reminder=sum_of_array % 2;
half_of_set=sum_of_array/2;
//
if(reminder==0){
startTime = System.currentTimeMillis();
for(int len_of_array=1;len_of_array<=elements.length;len_of_array++ ){
CombinationGenerator x = new CombinationGenerator (elements.length, len_of_array);
StringBuffer combination;
while (x.hasMore ()) {
combination = new StringBuffer ();
indices = x.getNext ();
for (int i = 0; i < indices.length; i++) {
sum_of_elm=sum_of_elm+elements[indices[i]];
}
if(half_of_set==sum_of_elm){
//print the sub set element
for(int g=0; g<indices.length; g++){
System.out.println("numbers in your one sub set are ="+elements[indices[g]]+",");
}
endTime = System.currentTimeMillis();
time = (endTime - startTime) / 1000.0;
System.out.println(time);
return;
}
sum_of_elm=0;//set the sum of elm to 0
}
}
endTime = System.currentTimeMillis();
time = (endTime - startTime) / 1000.0;
System.out.println(time);
}else{
System.out.println("given number set can not divide to two equal sets:Sorry");
}
}
}
The maximum number of numbers i could enter was 36..i couldn't go beyond that..the program stopped running....it explains the complexity of the problem. Finally the output was shown in a graph as below..
Monday, July 7, 2008
ISD Models..Systematic Approach vs Evolutionary
Instructional Systems Design, the most widely used methodology for developing new training programs. Today most of the e-learning programs are designed based on ISD. It is also known as Instructional Systems Design & Development (ISDD), the Systems Approach to Training (SAT), or just Instructional Design (ID). There are many ISD models that are used widely, like ADDIE, ASSURE, Dick & Carey Model etc. These are based on a systematic approach to online training.
But what do you think is the most effective approach? Systematic approach or the Evolutionary one? Some of the benefits of a system approach are characteristic of all systematic approaches. The ISD model is a management tool that makes courseware production more efficient. Effective training programs are more likely because the ISD model increases the probability that the courseware will match the objectives and not veer off in a different direction. Approach is scientific as it is empirical and can be replicated. The courseware can be improved and strengthened through data collection and analysis.
The figure shows the ADDIE model used widely for the systematic ISD approach..
Even though it has so many advantages they say it’s too systematic. A frequent criticism is that it is too time-consuming to be practical in the real world. There are practical challenges with a purely systemic design approach in the management of resources. In most cases, training programs must be developed under a fixed -- and often limited -- budget and schedule. While it is very easy to allocate people and time to each step in the ISD model, it is harder to plan deliverables when there are no distinct steps in the process.
Introducing Evolutionary & Rapid Prototyping Approach
An evolutionary approach includes both deterministic and incremental systems, in contrast to the systems approach, which is entirely deterministic. This approach is particularly appropriate for situations where there is limited past experience from which to draw guidance. A major benefit is that it enables a designer to test new ideas without making a long term commitment. A major disadvantage is that it lacks a defined set of steps. Also, it is difficult to specify in advance the amount of time and money that will be needed to complete significant events and it is logically impossible to specify the outcome of an evolutionary process.
Rapid Prototyping Design (RPD) uses a more formative model that is based on usability testing of prototypes. Results of usability tests on the prototypes are used to modify and improve the product. This model shares many attributes in common with the ISD model, and stresses the importance of iterative analysis and evaluation.
The conclusion is, if you know exactly what you are doing and exactly what needs to be built, then you are using the ISD (static or waterfall) method (however, this rarely happens in the real training world). When the subject is new, controversial, etc., then more prototypes are going to be built, hence you are more into RPD.
But what do you think is the most effective approach? Systematic approach or the Evolutionary one? Some of the benefits of a system approach are characteristic of all systematic approaches. The ISD model is a management tool that makes courseware production more efficient. Effective training programs are more likely because the ISD model increases the probability that the courseware will match the objectives and not veer off in a different direction. Approach is scientific as it is empirical and can be replicated. The courseware can be improved and strengthened through data collection and analysis.
The figure shows the ADDIE model used widely for the systematic ISD approach..
Even though it has so many advantages they say it’s too systematic. A frequent criticism is that it is too time-consuming to be practical in the real world. There are practical challenges with a purely systemic design approach in the management of resources. In most cases, training programs must be developed under a fixed -- and often limited -- budget and schedule. While it is very easy to allocate people and time to each step in the ISD model, it is harder to plan deliverables when there are no distinct steps in the process.
Introducing Evolutionary & Rapid Prototyping Approach
An evolutionary approach includes both deterministic and incremental systems, in contrast to the systems approach, which is entirely deterministic. This approach is particularly appropriate for situations where there is limited past experience from which to draw guidance. A major benefit is that it enables a designer to test new ideas without making a long term commitment. A major disadvantage is that it lacks a defined set of steps. Also, it is difficult to specify in advance the amount of time and money that will be needed to complete significant events and it is logically impossible to specify the outcome of an evolutionary process.
Rapid Prototyping Design (RPD) uses a more formative model that is based on usability testing of prototypes. Results of usability tests on the prototypes are used to modify and improve the product. This model shares many attributes in common with the ISD model, and stresses the importance of iterative analysis and evaluation.
The conclusion is, if you know exactly what you are doing and exactly what needs to be built, then you are using the ISD (static or waterfall) method (however, this rarely happens in the real training world). When the subject is new, controversial, etc., then more prototypes are going to be built, hence you are more into RPD.
Tuesday, July 1, 2008
Write exceptions into error log(C#.net)
Try this console application code to write exceptions in to a log file.
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
namespace ConsoleApplication1
{
class errorlogs
{
String filepath = "C:/Documents and Settings/error/log.txt"; //path of errorlog file
static void Main(string[] args)
{
errorlogs er = new errorlogs();
object i = new IOException();
er.writelog(i); //passing the ioexception
}
public void writelog(object a){
try{
StreamWriter logWriter;
if(File.Exists(filepath)){
logWriter = File.AppendText(filepath);
}
else{
logWriter = File.CreateText(filepath);
}
logWriter.WriteLine();
logWriter.WriteLine("------"+ DateTime.Now +"--------");
logWriter.WriteLine();
logWriter.WriteLine(a);
logWriter.WriteLine();
logWriter.WriteLine("--------------------------------");
logWriter.Close();
}
catch(Exception e){
Console.Out.WriteLine("Error in writing errorlog:" +e.Message);
}
}
}
}
using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
namespace ConsoleApplication1
{
class errorlogs
{
String filepath = "C:/Documents and Settings/error/log.txt"; //path of errorlog file
static void Main(string[] args)
{
errorlogs er = new errorlogs();
object i = new IOException();
er.writelog(i); //passing the ioexception
}
public void writelog(object a){
try{
StreamWriter logWriter;
if(File.Exists(filepath)){
logWriter = File.AppendText(filepath);
}
else{
logWriter = File.CreateText(filepath);
}
logWriter.WriteLine();
logWriter.WriteLine("------"+ DateTime.Now +"--------");
logWriter.WriteLine();
logWriter.WriteLine(a);
logWriter.WriteLine();
logWriter.WriteLine("--------------------------------");
logWriter.Close();
}
catch(Exception e){
Console.Out.WriteLine("Error in writing errorlog:" +e.Message);
}
}
}
}
Subscribe to:
Posts (Atom)