Tips&Tricks I trucchi del mestiere

 




Come leggere la data corrente

Sia l'ora che la data corrente, possono essere facilmente recuperati in Java. Nel codice allegato, trovate numerosi esempi delle manipolazioni sulle date possibili in Java.

import java.text.*;
import java.util.*;

public class my_data {

private SimpleDateFormat formatter;
private Date currentdate;

public my_data() {
currentdate=new Date();
formatter=new SimpleDateFormat("EEE MMM dd hh:mm:ss yyyy",
Locale.getDefault());
}
public int getDay() {
formatter.applyPattern("d");
return Integer.parseInt(formatter.format(currentdate));
}
public int getMonth() {
formatter.applyPattern("M");
return Integer.parseInt(formatter.format(currentdate));
}
public int getYear() {
formatter.applyPattern("y");
return Integer.parseInt(formatter.format(currentdate));
}
public int getHour() {
formatter.applyPattern("h");
return Integer.parseInt(formatter.format(currentdate));
}
public int getMinute() {
formatter.applyPattern("m");
return Integer.parseInt(formatter.format(currentdate));
}
}




Come ordinare per colonna una JTable

Il codice riportato consente di realizzare una tabella e riordinarne gli elementi con un semplice clic sulle intestazioni delle colonne. Gli elementi della tabella saranno riordinati in modo da rispettare l'ordine crescente nella colonna indicata dall'utente. Attraverso un doppio clic sull'intestazione di una colonne si ottiene invece un ordinamento inverso.
import javax.swing.table.TableModel;
import javax.swing.event.TableModelEvent;

import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.InputEvent;
import javax.swing.*;
import javax.swing.table.*;
import java.util.*;


public class TabellenModel extends AbstractTableModel
{
private final int columnCount;
private final Vector rows = new Vector ();
private String[] kopfZeile;

public TabellenModel (int columnCount)
{
this.columnCount = columnCount;
}


public TabellenModel(String[] kopfZeile)
{
this(kopfZeile.length);
this.kopfZeile = kopfZeile;
}

public void mausHorchtAufTabelle(JTable table)
{
final JTable tableView = table;
MouseAdapter listMouseListener = new MouseAdapter()
{
public void mouseClicked(MouseEvent e)
{
TableColumnModel columnModel = tableView.getColumnModel();
int viewColumn = columnModel.getColumnIndexAtX(e.getX());
int column = tableView.convertColumnIndexToModel(viewColumn);
if (e.getClickCount() == 1 && column != -1)
{
sortieren(column, true);
}
else if(column != -1)
sortieren(column, false);
}
};
JTableHeader th = tableView.getTableHeader();
th.addMouseListener(listMouseListener);
}// mausHorchtAufTabelle

public void setValues (Collection src)
{
rows.clear ();
rows.addAll (src);
fireTableDataChanged ();
}

public String getColumnName(int columnIndex)
{
return kopfZeile[columnIndex];
}

public void setValues (String [] [] src)
{
setValues (Arrays.asList (src));
}


public String [] [] getValues ()
{
return (String [] []) rows.toArray (new String [rows.size ()] []);
}


/**
Inserisce una nuova riga
*/
public void addRow (int index)
{
String [] newRow = new String [columnCount];

for (int i = 0; i < columnCount; ++i)
newRow [i] = "";

rows.insertElementAt (newRow, index);
fireTableRowsInserted (index, index);
}

/**
Inserisce una nuova riga, aggiunge dei valori
*/
public void addRow (int index, String[] reihe)
{
rows.insertElementAt(reihe, index);
fireTableRowsInserted (index, index);
}

/**
Cancella una riga
*/
public void deleteRow (int index)
{
rows.remove (index);
fireTableRowsDeleted (index, index);
}


/**
Cancella l'intera tabella
*/
public void deleteRows()
{
int anzahl = rows.size();
for(int i=anzahl-1; i>=0; i--)
{
rows.remove(i);
fireTableRowsDeleted(i, i);
}
}

/**
Ordina la tabella
*/
public void sortieren(int spalte, boolean abwaerts)
{
java.util.LinkedList liste = new java.util.LinkedList();
String[] werte = new String[rows.size()];

// Einlesen der Tabelle und in tempVariablen hauen
for(int i=0; i<rows.size(); i++)
{
//System.out.println(i+") " + getValueAt(i, 0));
String[] arr = new String[getColumnCount()];
for(int z=0; z<getColumnCount(); z++)
{
arr[z] = getValueAt(i, z).toString();
}// for z
werte[i] = getValueAt(i, spalte).toString().toLowerCase();
liste.add(arr);
}// for i

// sortieren des String[]
Arrays.sort(werte);

// löschen der Tabelle
deleteRows();

// neu füllen der Tabelle, je nach dem, welche Richtung
if(abwaerts)
{
for(int i = 0; i < werte.length; i++)
{
// alles raushauen, was diesen Wert hat und Liste kürzen
for(int z = 0; z < liste.size(); z++)
{
String[] arr = (String[]) liste.get(z);
if( arr[spalte].compareToIgnoreCase( werte[i] ) == 0)
{
// tabelle füllen
addRow(0, arr);
// Liste kürzen
liste.remove(z);
z--;
}
}// for z
}// for i
}// abwaerts
else
{
for(int i = werte.length-1; i >= 0; i--)
{
// alles raushauen, was diesen Wert hat und Liste kürzen
for(int z = 0; z < liste.size(); z++)
{
String[] arr = (String[]) liste.get(z);
if( arr[spalte].compareToIgnoreCase( werte[i] ) == 0)
{
// tabelle füllen
addRow(0, arr);
// Liste kürzen
liste.remove(z);
z--;
}
}// for z
}// for i
}
}// sortieren()

public Object getValueAt (int rowIndex, int colIndex)
{
return ((String []) rows.get (rowIndex)) [colIndex];
}


public int getColumnCount ()
{
return columnCount;
}

public int getRowCount ()
{
return rows.size ();
}


public boolean isCellEditable (int rowIndex, int colIndex)
{
return true;
}

/**
*/
public void setValueAt (Object value, int rowIndex, int colIndex)
{
((String []) rows.get (rowIndex)) [colIndex] = (String) value;
fireTableCellUpdated (rowIndex, colIndex);
}
} //class TabellenModel

 

Come leggere un file di testo zippato

Una classe che consente di leggere il contenuto di un file all'interno di un archivio zip. Come parametri accetta il nome del file text da leggere ed il nome del file zippato in cui è contenuto il file di testo. La classe legge il file, lo passa ad uno string buffer e restituisce una stringa con il contenuto del file di testo.

import java.io.*;
import java.util.zip.*;
import java.util.*;

public String readZippedFile(String textFilename, String zipFilename) throws Exception
{
StringBuffer buf;
BufferedReader breader;
ZipFile zipFile;
ZipEntry zipEntry;
InputStream iStream;
try
{
zipFile = new ZipFile( zipFilename );
zipEntry = zipFile.getEntry(textFilename);
iStream = zipFile.getInputStream( zipEntry );
breader = new BufferedReader( new InputStreamReader(iStream) );
buf = new StringBuffer();
while (breader.ready())
buf.append( (char)breader.read() );
breader.close();
} //try
catch (Exception e)
{
throw e;
} //catch
return buf.toString();
} //readZippedFile


Come fare la copia profonda di un qualsiasi oggetto

La classe che presentiamo consente di effettuare la copia profonda (deep copy) di un oggetto qualsiasi sia la classe cui appartiene. Il metodo deepCopy accetta come parametro l'oggetto da copiare e, attraverso un processo di serializzazione, restituisce una copia dell'oggetto stesso.
public class ObjectCloner
{

private ObjectCloner(){}

// returns a deep copy of an object
public static Object deepCopy(Object oldObj) throws Exception
{

ObjectOutputStream oos = null;
ObjectInputStream ois = null;

try
{
ByteArrayOutputStream bos =
new ByteArrayOutputStream(); // A
oos = new ObjectOutputStream(bos); // B

// serialize and pass the object
oos.writeObject(oldObj); // C
oos.flush(); // D

ByteArrayInputStream bin =
new ByteArrayInputStream(bos.toByteArray()); // E
ois = new ObjectInputStream(bin); // F

// return the new object
return ois.readObject(); // G

}
catch(Exception e)
{
System.out.println("Eccezione in ObjectCloner = " + e);
throw(e);
}
finally
{
oos.close();
ois.close();
}
}
}


Come realizzare uno sniffer

Un rudimentale port sniffer costruito in poche righe di codice. Sfruttando a fondo le grandi capacità che Java ha nel gestire le operazioni di rete, questo piccolo sniffer può dare grandi soddisfazioni… pronto per essere migliorato e accresciuto con nuove funzionalità.
import java.io.*;
import java.lang.*;
import java.net.*;

public class jps
{

private static void main(String[] args)
{

Socket connect=null;
String host = "localhost";
int numofparams = args.length;
int LOW_RANGE = 1;
int HIGH_RANGE = 1023;

showHeader();

if (numofparams == 1) { //if they only put in a host name
host = args[0];
LOW_RANGE = 1;
HIGH_RANGE = 1024;
System.out.println("No ports specified. Scanning "+host+" on ports 1-1024:");
scanRange(host,LOW_RANGE,HIGH_RANGE,connect);
}
else if (numofparams == 2) { //if they put in a host name and a single port
host = args[0];
LOW_RANGE = Integer.parseInt(args[1]);
HIGH_RANGE = Integer.parseInt(args[1]);
System.out.println("Only one port specified. Scanning "+host+" on port "+LOW_RANGE+":");
scanRange(host,LOW_RANGE,HIGH_RANGE,connect);
}
else if (numofparams == 3) { //if they put in a host name and a port range
host = args[0];
LOW_RANGE = Integer.parseInt(args[1]);
HIGH_RANGE = Integer.parseInt(args[2]);
System.out.println("Scanning "+host+" on ports "+LOW_RANGE+"-"+HIGH_RANGE+":");
scanRange(host,LOW_RANGE,HIGH_RANGE,connect);
}
else { //if they didn't put in anything (because they dont know they can?)
host = "localhost";
LOW_RANGE = 1;
HIGH_RANGE = 1024;
System.out.println("No hostname specified. Scanning "+host+" on ports "+LOW_RANGE+"-"+HIGH_RANGE+":");
scanRange(host,LOW_RANGE,HIGH_RANGE,connect);
}

}

private static void showHeader() {
final String title = "Java Port Scanner";
final String copyright = "CopyRight 2000-2002, J&S Software";
final String version = "v0.41";

System.out.println("");
System.out.println(title + " - " + version);
System.out.println(copyright);
System.out.println("");
System.out.println("USAGE: java jps [hostname] [first/single port] [last port]");
System.out.println("");
}

private static void scanRange(String host, int LOW_RANGE, int HIGH_RANGE, Socket connect) {
for (int iCount = LOW_RANGE; iCount <= HIGH_RANGE; iCount++)
{
try
{
connect = new Socket(host, iCount);
System.out.println("Port "+iCount+" Active.");
}
catch (UnknownHostException e)
{
System.err.println("Could not resolve the Host Name you specified!");
break;
}
catch (IOException e)
{
System.out.println("Port "+iCount+" Timed Out.");
}
finally
{
try
{
connect.close();
}
catch (Exception e) {}
}
}

}
}

 

Come fare calcoli in RPN

Sono passati i tempi in cui Texa Instruments e HP si dividevano il mercato delle calcolatrici programmabili imponendo al mondo due "religioni": HP aveva scelto la Notazione Polacca Inversa e la classe che proponiamo si occupa proprio di effettuare calcoli matematici utilizzando questa logica. Il metodo process accetta come argomento una stringa in cui va indicata l'espressione matematica (a notazione postfissa) che vogliamo sia calcolata in RPN.
import java.io.*;
import java.util.Stack;
import java.util.EmptyStackException;

public class Revpol
{
public int process(String args)
{
int a=0,b=0;
String elements[];

String ans=new String();

Stack numbers;
numbers=new Stack();

elements=words(args.trim());

try{
for(int i=0;i<elements.length;i++)
{
if(elements[i]!=null)
{
if(isNumber(elements[i]))numbers.push(elements[i]);
else{
a=makeNumber((String)numbers.pop());
b=makeNumber((String)numbers.pop());

if(elements[i].equals("+"))numbers.push(String.valueOf(a+b));
if(elements[i].equals("-"))numbers.push(String.valueOf(b-a));
if(elements[i].equals("*"))numbers.push(String.valueOf(a*b));
if(elements[i].equals("/"))numbers.push(String.valueOf(b/a));
}
}
}
ans=(String)numbers.pop();
}catch(EmptyStackException e)
{System.err.println("Error: Empty Stack Exception, probably due to input not being a reverse polish calculation");
}

return makeNumber(ans);
}

String[] words(String line)
{
char lined[]=line.toCharArray();
int s=0,e=0,c=0;
String words[]=new String[lined.length];

for(int i=0;i<line.length();i++)
{
e=i;
if(Character.isWhitespace(lined[i]))
{
words[c]=line.substring(s,e);
s=e+1;
c++;
}
}
words[c]=line.substring(s,line.length());
return words;
}

boolean isNumber(String testdata)
{
int k=1;
char ntestdata[]=testdata.toCharArray();

for(int j=0;j<ntestdata.length;j++)
{
if(!(Character.isDigit(ntestdata[j])))k=0;
}
if(k==1)return true;
else return false;

}

int makeNumber(String testdata)
{
int k=0;
int order=1;
char ntestdata[]=testdata.toCharArray();

for(int j=(ntestdata.length)-1;j>0;j--)
{
k=k+Character.digit(ntestdata[j],10)*order;
order=order*10;
}

if(ntestdata[0]=='-')k=k*-1;
else k=k+Character.digit(ntestdata[0],10)*order;

return k;
}

}




Come cambiare il colore delle scroll-bar di una finestra

Stanchi del solito colore grigio delle barre di scorrimento di Windows? Niente paura ecco due righe di codice, e non si fa per dire, che consentono di personalizzare il colore delle scroll-bar di una qualunque finestra Web:
<html>
<title>Cambiare il colore delle scrool-bar</title>
<style>
body{
scrollbar-base-color: #C0C0C0
}
</style>

<script>
function Cambia_Colore_Scroolbar(C){
if (document.all)
document.body.style.scrollbarBaseColor = C

}
</script>
<a href="javascript:Cambia_Colore_Scroolbar('#FF0000')">Cambia in rosso</a><br>
<a href="javascript:Cambia_Colore_Scroolbar('#FF8000')">Cambia in arancione</a><br>
<a href="javascript:Cambia_Colore_Scroolbar('#FFFF00')">Cambia in giallo</a><br>
<a href="javascript:Cambia_Colore_Scroolbar('#00FF00')">Cambia in verde</a><br>
<a href="javascript:Cambia_Colore_Scroolbar('#4444FF')">Cambia in blue</a><br>

</html>

 

Come richiamare la funzione "Salva con nome" di Internet Explorer

Questo script, attivabile solo in browser Internet Explore 4.0 o superiori, consente di attivare automaticamente la funzione Salva con come presente nel menù File del browser:
<html>
<title>Come richiamare la funzione Salva con nome di Internet Explorer</title>
<script language="JavaScript">
var avviata= false;

function Richiama_SaveAS()
{
if (document.execCommand)
{
if (avviata) {document.execCommand("SaveAs");}
}
else
{
alert('Funzionalità disponibile solo in Internet Exlorer 4.0 e superiori.');
}
}
</script>

<body onload="avviata=true">
<a href="javascript:Richiama_SaveAS()">Clicca questo link per azionare la funzione di SaveAS</a>
</html>



Come ridimensionare un'immagine dinamicamente

Lo script mostra come ridimensionare dinamicamente un'immagine presente in una pagina Web. L'utente potrà ridimensionare l'immagine mediante una semplice operazione di drag & drop. Nell'esempio sono utilizzate due immagini (file immagini: 0.jpg e 1.jpg)
<html>
<head>
<script language="JavaScript">
defaultXsize = 100;
defaultYsize = 100;

minimumXsize = 50;
minimumYsize = 50;

maximumXsize = 250;
maximumYsize = 250;

App_avviata = false;

function Ridimensiona(dragEvent,which)
{
if (App_avviata)
{
posX = eval("document."+which+".offsetLeft");
posY = eval("document."+which+".offsetTop");
newXsize = dragEvent.x;
newYsize = dragEvent.y;
newXsize = newXsize - posX;
newYsize = newYsize - posY;
if (newXsize >= maximumXsize) newXsize = maximumXsize;
if (newYsize >= maximumYsize) newYsize = maximumYsize;
if (newXsize <= minimumXsize) newXsize = minimumXsize;
if (newYsize <= minimumYsize) newYsize = minimumYsize;
eval("document."+which+".width=newXsize");
eval("document."+which+".height=newYsize");
}
}

function Ripristina_Dimensioni(which){
if (App_avviata)
{
eval("document."+which+".width=defaultXsize");
eval("document."+which+".height=defaultYsize");
}
}

</script>

<title>Ridimensionamento dinamico delle immagini</title>
</head>
<body bgcolor="#000000" onload="App_avviata=true;">
<center>
<table>
<tr>
<td>
<font size="2" face="Arial" color="#84A5EF">
- Clicca sull'immagine e trascina per ridimensionare<br>
- Clicca con il tasto destro per ripristinare le dimensioni reali.
</font>
</td>
</tr>
</table>

<img src="0.jpg"
width="100" height="100"
name="Immagine0"
onDrag="Ridimensiona(event,this.name)"
onClick="Ripristina_Dimensioni(this.name)" align="top">

<img src="1.jpg"
width="100" height="100"
name="Immagine1"
onDrag="Ridimensiona(event,this.name)"
onClick="Ripristina_Dimensioni(this.name)" align="top">

</center>
</body>
</html>

 

Come creare un menu riposizionabile nella pagina

Un curioso script che permette di definire un menu e di riposizionarlo dinamicamente all'interno della pagina. Basta selezionare il menu ed effettuare un semplice drag & drop nella pagina.
<html>
<head>
<title>Document Title</title>

<script>
function Test_browser()
{
var x = navigator.appVersion;
y = x.substring(0,4);
if (y>=4)
Setta_variabili();
SpostaOB();
}

function Setta_variabili()
{
if (navigator.appName == "Netscape")
{
h=".left=";v=".top=";dS="document.";sD="";
}
else
{
h=".pixelLeft=";v=".pixelTop=";dS="";sD=".style";
}
objectX="object11"
XX=-70
YY=-70
OB=11
}

function setObject(a)
{
objectX="object"+a
OB=a
XX=eval("xpos"+a)
YY=eval("ypos"+a)
}

function getObject(){
if (isNav)
document.captureEvents(Event.MOUSEMOVE);
}

function releaseObject()
{
if (isNav)
document.releaseEvents(Event.MOUSEMOVE);
check="no"
objectX="object11";
document.close()
}

function SpostaOB()
{
eval(dS + objectX + sD + h + Xpos);
eval(dS + objectX + sD + v + Ypos);
}

var isNav = (navigator.appName.indexOf("Netscape") !=-1)
var isIE = (navigator.appName.indexOf("Microsoft") !=-1)
nsValue=(document.layers)
check="no"

function MoveHandler(e)
{
Xpos = (isIE) ? event.clientX : e.pageX
Ypos = (nsValue) ? e.pageY : event.clientY
if (check=="no")
{
diffX=XX-Xpos
diffY=YY-Ypos
check="yes"
if (objectX=="object11")
check="no"
}
Xpos+=diffX
Ypos+=diffY
if (OB=="1")xpos1=Xpos,ypos1=Ypos
SpostaOB();
}

if (isNav)
{
document.captureEvents(Event.CLICK);
document.captureEvents(Event.DBLCLICK);
}
xpos1=50
ypos1=50
xpos11 = -50;
ypos11 = -50;
Xpos=5
Ypos=5
document.onmousemove = MoveHandler;
document.onclick = getObject;
document.ondblclick = releaseObject;
</script>
</HEAD>

<BODY onload="Test_browser();">
<b><center>Clicca su "Menù riposizionabile" per spostare il menu<br>
Doppio click per riposizionare il menù</b></center>
<br>
<div id="object1" style="position:absolute; visibility:show; left:50px; top:50px; z-index:2">
<table border=1 cellpadding=5><tr><td bgcolor='yellow'>
<a href="javascript:void(0)" onmousedown="setObject(1)">Menù
Riposizionabile</a></td></tr>
<tr><td><br>
<a HREF="javascript:void(0)">Elemento #1</a>
<br><A HREF="javascript:void(0)">Elemento #2</a>
<br><A HREF="javascript:void(0)">Elemento #3</a>
</td></tr>
</table>
</div>
<div id="object11" style="position:absolute; visibility:show; left:70px; top:-70px; z-index:2"></div>
</body>
</html>

 

Come utilizzare i socket

Il namespace System.Net.Sockets comprende due classi fondamentali: TCPListener e TCPClient. Nell'esempio proposto impareremo ad utilizzarle grazie a due file: DateServer e DateClient. DateServer utilizza una classe TCPListener per accettare le richieste provenienti da nuovi client: una volta che un client si è connesso al server, il server gli manderà l'ora e la data corrente provvedendo poi a disconnetterlo per mettersi in attesa di nuovi client. DateClient utilizza invece la classe TCPClient: essa si connette ad una specifica porta del server e invia al server il nome del client. Per testare l'esempio è necessario avviare prima il server e poi il DateClient che si collegherà al server recuperando la data e l'ora corrente.

DateServer.cs

namespace SaurabhNet {
using System;
using System.Net.Sockets;
using System.Net ;
using System.Threading ;
//Import the necessary Namespaces

//Class which shows the implementation of the TCP Date server

public class DateServer
{
private TCPListener myListener ;
private int port = 4554 ;
//The constructor which make the TCPListener start listening on the
//given port.
//It also calls a Thread on the method StartListen().
public DateServer()
{
try{
//start listing on the given port
myListener = new TCPListener(port) ;
myListener.Start();
Console.WriteLine("Server Ready - Listining for new Connections ...") ;
//start the thread which calls the method 'StartListen'
Thread th = new Thread(new ThreadStart(StartListen));
th.Start() ;

}
catch(Exception e)
{
Console.WriteLine("An Exception Occured while Listing :"+e.ToString());
}
}

//main entry point of the class
public static void Main(String[] argv)
{
DateServer dts = new DateServer();
}

//This method Accepts new connection and
//First it receives the welcome massage from the client,
//Then it sends the Current time to the Client.
public void StartListen()
{
while(true)
{
//Accept a new connection
Socket mySocket = myListener.Accept() ;
if(mySocket.Connected)
{
Console.WriteLine("Client Connected!!") ;
//make a byte array and receive data from the client
Byte[] receive = new Byte[64] ;
int i=mySocket.Receive(receive,receive.Length,0) ;
char[] unwanted = {' ',' ',' '};
string rece = System.Text.Encoding.ASCII.GetString(receive);
Console.WriteLine(rece.TrimEnd(unwanted)) ;
//get the current date/time and convert it to string
DateTime now = DateTime.Now;
String strDateLine ="Server: The Date/Time Now is: "+ now.ToShortDateString()
+ " " + now.ToShortTimeString();
// Convert to byte array and send
Byte[] byteDateLine=Text.Encoding.ASCII.GetBytes(strDateLine.ToCharArray());
mySocket.Send(byteDateLine,byteDateLine.Length,0);
}
}
}
}
}


DateClient.cs

namespace SaurabhNet {
using System ;
using System.Net.Sockets ;
using System.Net ;
using System.Threading ;

//Class which shows the implementation of the TCP Date Client
public class DateClient
{
//the needed member fields
private TCPClient tcpc;
private string name ;
private int port=4554 ;
private bool readData=false ;

//Constructor which contains all the code for the client.
//It connects to the server and sends the clients name,
//Then it waits and receives the date from the server
public DateClient(string name)
{
//a label
tryagain :
this.name=name ;
try
{
//connect to the "localhost" at the give port
//if you have some other server name then you can use that
//instead of "localhost"
tcpc =new TCPClient("localhost",port) ;
//get a Network stream from the server
NetworkStream nts = tcpc.GetStream() ;
//if the stream is writiable then write to the server
if(nts.CanWrite)
{
string sender = "Hi Server I am "+name ;
Byte[] sends = System.Text.Encoding.ASCII.GetBytes(sender.ToCharArray());
nts.Write(sends,0,sends.Length) ;
//flush to stream
nts.Flush() ;
}
//make a loop to wait until some data is read from the stream
while(!readData&&nts.CanRead)
{
//if data available then read from the stream
if(nts.DataAvailable)
{
byte[] rcd = new byte[128];
int i=nts.Read( rcd,0,128);
string ree = System.Text.Encoding.ASCII.GetString(rcd);
char[] unwanted = {' ',' ',' '};
Console.WriteLine(ree.TrimEnd(unwanted)) ;
//Exit the loop
readData=true ;
}
}
}
catch(Exception e)
{
Console.WriteLine("Could not Connect to server because "+e.ToString());
//Here an exception can be cause if the client is started before starting
//the server.
//A good way to handle such exceptions and give the client
//a chance to re-try to connect to the server
Console.Write("Do you want to try Again? [y/n]: ") ;
char check = Console.ReadLine().ToChar();
if(check=='y'|| check=='Y')
goto tryagain ;
}
}

//Main Entry point of the client class
public static void Main(string[] argv)
{
//check to see if the user has entered his name
//if not ask him if he wants to enter his name.
if(argv.Length<=0)
{
Console.WriteLine("Usage: DataClient ") ;
Console.Write("Would You like to enter your name now [y/n] ?") ;
char check = Console.ReadLine().ToChar();
if(check=='y'|| check=='Y')
{
Console.Write("Please enter you name :") ;
string newname=Console.ReadLine();
DateClient dc = new DateClient(newname) ;
Console.WriteLine("Disconnected!!") ;
Console.ReadLine() ;
}
}
else
{
DateClient dc = new DateClient(argv[0]) ;
Console.WriteLine("Disconnected!!") ;
Console.ReadLine() ;
}
}
}
}

 

Come implementare una coda

La semplice coda FIFO (First In First Out) realizzata in questo esempio costituisce un ottimo spunto per realizzazioni più complesse. Presenta tutte le funzionalità base e permette di toccare con mano l'efficienza del garbage collector: quando tiriamo fuori un elemento dalla coda, non ci preoccupiamo di distruggerlo… il garbage collector lo farà per noi!

namespace Queue
{
using System;
public class Queue {
private uint count = 0;
private Node front = null;
private Node end = null;
private Node temp = null;

///
/// Verifichiamo che la coda non sia vuota
///
public bool empty {
get {
return(count==0);
}
}
///
/// Numero degli elementi in coda
///
public uint Count {
get {
return count;
}
}
///
/// Effettua l'append alla coda oppure crea il primo nodo
///
public void append(object obj) {
if(count==0){
front = end = new Node(obj, front);
} else {
end.Next = new Node(obj, end.Next);
end = end.Next;
}
count++;
}
///
/// Questa funzione preleva l'elemento dalla testa della coda
/// Da notare che non viene effettuata nessuna deallocazione:
/// il Garbage Collector si occupa della cosa
///
public object serve() {
temp = front;
if(count == 0)
throw new Exception("La coda è vuota: impossibile prelevare!");
front = front.Next;
count--;
return temp.Value;
}
///
/// Questa funzione stampa tutto ciò che è presente nella coda
///
public void printQueue() {
temp = front;
while(temp != null){
Console.WriteLine("{0}", temp.Value.ToString());
temp = temp.Next;
}
}

}
///
/// La classe Node contiene l'oggetto ed il puntatore al prossimo nodo
///
class Node
{
public Node Next;
public object Value;

public Node(object value, Node next)
{
Next = next;
Value = value;
}
}
///
/// Una semplice funzione per testare le funzionalità della coda
///
class QueueTest
{
static void Main() {
Queue Q = new Queue();
object obj;
uint i,j;
UInt16[] numbers = new UInt16[]{10,20,30};
for(i = 0;i < numbers.Length;i++)
Q.append(numbers[i]);
Q.printQueue();
Console.WriteLine("Queue count = {0}", Q.Count);
j = Q.Count;
for(i = 0;i < j;i++){
obj = Q.serve();
Console.WriteLine("serve Queue = {0}", obj.ToString());
}
Console.WriteLine("Queue count = {0}", Q.Count);
}
}

}

 

Come passare ad una funzione un numero variabile di argumenti

Capita di frequente che si renda necessario realizzare delle funzioni che possano accettare un numero non prefissato di argomenti. In C# è possibile risolvere questo problema attraverso la keyword Parami. La sintassi è params tipo_dato[] nome_argomento, ed è da tener presente che deve essere dichiarato come ultimo nella lista degli argomenti di una funzione. Gli argomenti saranno accessibili come un comune array monodimensionale.
class ParamsTest
{
static void Main()
{
System.Console.WriteLine(sum(2,3,4)); // Passiamo tre argomenti
System.Console.WriteLine(sum(10,20,30,40,50,60)); // Oran e passiamo sei
}
static int sum(params int[] num)
{
int tot=0;
foreach(int i in num)
{
tot=tot+i;
}
return tot;
}
}


Come utilizzare la struttura DateTime

L'esempio riportato presenta una completa rassegna delle possibilità offerte dalla struttura DateTime. La funzione dell'applicazione può apparire banale: calcolare l'età di una persona. Ma, seguendolo, toccherete numerosi utili aspetti della gestione delle date disponibile in C#

using System;

class DOB{

private DateTime dtDob;
private DateTime dtNow;
private DateTime dtAge;
private int intDay;
private int intMonth;
private int intYear;
private int intHour;
private int intMinute;
private TimeSpan tsAge;
private int intAgeYear;
private int intAgeMonths;
private int intAgeDays;
private int intAgeHours;
private int intAgeMinutes;


public static void Main (String[] args) {

DOB objDob=new DOB();
objDob.getDob();
objDob.createDateObjects();

Console.WriteLine("La tu età in anni:" + objDob.getAgeInYears());
Console.WriteLine("La tu età in mesi :" + objDob.getAgeInMonths());
Console.WriteLine("La tu età in giorni :" + objDob.getAgeInDays());
Console.WriteLine("La tu età in ore : " + objDob.getAgeInHours());
Console.WriteLine("La tu età in minuti : " + objDob.getAgeInMinutes());
Console.WriteLine("La tu età in precisa è : " + objDob.getAgeInYears() + " anni " +
objDob.getMonthDiff() + " mesi " + objDob.getDayDiff() + " giorni");
}

/* legge la data di nascità */

private void getDob() {

try {

Console.Write("inserisci il giorno incui sei nato : " );
intDay=Console.ReadLine().ToInt32();
Console.Write("il mese : ");
intMonth=Console.ReadLine().ToInt32();;
Console.Write("l'anno (yyyy) : ");
intYear=Console.ReadLine().ToInt32();
Console.Write("l'ora (0-23) : ");
intHour=Console.ReadLine().ToInt32();
Console.Write("il minuto (0-59) : ");
intMinute=Console.ReadLine().ToInt32();
}

catch (Exception e) {
Console.WriteLine(e.StackTrace);
Environment.Exit(0);
}
}


private void createDateObjects() {

dtDob=new DateTime(intYear,intMonth,intDay,intHour,intMinute,0);
dtNow=DateTime.Now;

if (DateTime.Compare(dtNow,dtDob)==1)
tsAge=dtNow.Subtract(dtDob);
else {
Console.WriteLine("La data deve appartenere al passato");
Environment.Exit(0);
}

dtAge=new DateTime(tsAge.Ticks);
Console.WriteLine("Your date of birth :" + dtDob.Format("F",null));

}

/* calcola lìetà in anni */
private int getAgeInYears() {
intAgeYear=dtAge.Year-1;
return intAgeYear;
}

/* calcola lìetà in mesi */
private int getAgeInMonths() {
intAgeMonths=intAgeYear*12;
intAgeMonths=intAgeMonths+(dtAge.Month-1);
return intAgeMonths;
}

/* calcola lìetà in giorni */
private int getAgeInDays() {
if (dtDob.Year==dtNow.Year) {
intAgeDays=dtNow.DayOfYear-dtDob.DayOfYear;
}
else {
if(DateTime.IsLeapYear(dtDob.Year))
intAgeDays=366-dtDob.DayOfYear;
else
intAgeDays=365-dtDob.DayOfYear;

for (int i=dtDob.Year+1;i < dtNow.Year;i++) {
if (DateTime.IsLeapYear(i))
intAgeDays+=366;
else
intAgeDays+=365;
}

intAgeDays+=dtNow.DayOfYear;
}
return intAgeDays;
}

/* calcola lìetà in ore */
private int getAgeInHours() {
intAgeHours=getAgeInDays() * 24;
intAgeHours=intAgeHours+(dtNow.Hour-dtDob.Hour);
return intAgeHours;
}

/* calcola lìetà in minuti */
private int getAgeInMinutes() {
intAgeMinutes=getAgeInHours() * 60;
intAgeMinutes=intAgeMinutes+(dtNow.Minute-dtDob.Minute);
return intAgeMinutes;
}

/* calcola l'età precisa (mesi) */
private int getMonthDiff() {
return getAgeInMonths()%12;
}

/* calcola l'età precisa (giorni) */
private int getDayDiff() {
int intDayTemp1=getAgeInDays();
int intDayTemp2;
int intTempYear;
int intTempMonth;
int intTempDay=intDay;

if (dtNow.Year!=dtDob.Year) {

if (1==dtNow.Month) {
intTempYear=dtNow.Year-1;
intTempMonth=12;
}
else {
if(dtNow.Day < intTempDay)
intTempMonth=dtNow.Month-1;
else {
intTempMonth=dtNow.Month;
intTempDay=1;
}
intTempYear=dtNow.Year;
}
}
else {
if (1==dtNow.Month || dtDob.Month==dtNow.Month)
return getAgeInDays();
else {
if(dtNow.Day < intTempDay)
intTempMonth=dtNow.Month-1;
else {
intTempMonth=dtNow.Month;
intTempDay=1;
}
}
intTempYear=intYear;
}

dtNow=new DateTime(intTempYear,intTempMonth,intDay);

intDayTemp2=getAgeInDays();

return intDayTemp1-intDayTemp2;
}
}




Come manipolare le stringhe in C#

L'esempio allegato illustra numerosi utilizzi della classe String presente in C#. Tra gli esempi troveremo come trasformare una stringa in minuscolo i in maiuscolo, come invertire l'ordine dei caratteri, come scoprire se la stringa è palindroma, come prendere parte di una stringa, come cancellare gli spazi superflui, ed altro ancora. Oltre ad utilizzare metodi della classe String, l'esempio propone delle funzioni aggiuntive, non presenti in C# e che possono tornare utili in molte circostanze.
using System;

class MyString
{
public static void Main()
{
String strData="WeLcOmE tO c#.eNjoy FoLkS";

Console.WriteLine("String Value: {0}",strData);
Console.WriteLine("LowerCase Equivalent: {0}",Lower(strData));
Console.WriteLine("UpperCase Equivalent: {0}",Upper(strData));
Console.WriteLine("PCase Equivalent: {0}",PCase(strData));
Console.WriteLine("Reverse Equivalent: {0}",Reverse(strData));
Console.WriteLine("Is 'rotator' PalinDrome:{0}",IsPalindrome("rotator"));
Console.WriteLine("Is 'visualc#' PalinDrome:{0}",IsPalindrome("visualc#"));
Console.WriteLine("Left(string,5): {0}",Left(strData,5));
Console.WriteLine("Right(String,6): {0}",Right(strData,6));
Console.WriteLine("CharCount(Charcount,c):{0}",CharCount("Charcount","C"));
Console.WriteLine("CharCount(CharCount,c,true):{0}",CharCount("Charcount","C",true));
Console.WriteLine("CharCount(CharCount,d,true):{0}",CharCount("Charcount","d",true));
Console.WriteLine("ToSingleSpace('welcome to C Sharp'): {0}",ToSingleSpace("welcome to C Sharp "));
Console.WriteLine("Replace(aaaaaa,aa,a):{0}",Replace("aaaaaa","aa","a"));
}

// Convert string to LowerCase
public static String Lower(String strParam)
{
return strParam.ToLower();
}

//Convert String to UpperCase
public static String Upper(String strParam)
{
return strParam.ToUpper();
}

//Convert String to ProperCase
public static String PCase(String strParam)
{
String strProper=strParam.Substring(0,1).ToUpper();
strParam=strParam.Substring(1).ToLower();
String strPrev="";

for(int iIndex=0;iIndex < strParam.Length;iIndex++)
{
if(iIndex > 1)
{
strPrev=strParam.Substring(iIndex-1,1);
}
if( strPrev.Equals(" ") ||
strPrev.Equals("\t") ||
strPrev.Equals("\n") ||
strPrev.Equals("."))
{
strProper+=strParam.Substring(iIndex,1).ToUpper();
}
else
{
strProper+=strParam.Substring(iIndex,1);
}
}
return strProper;
}

// Function to Reverse the String
public static String Reverse(String strParam)
{
if(strParam.Length==1)
{
return strParam;
}
else
{
return Reverse(strParam.Substring(1)) + strParam.Substring(0,1);
}
}

// Function to Test for Palindrome
public static bool IsPalindrome(String strParam)
{
int iLength,iHalfLen;
iLength=strParam.Length-1;
iHalfLen=iLength/2;
for(int iIndex=0;iIndex<=iHalfLen;iIndex++)
{
if(strParam.Substring(iIndex,1)!=strParam.Substring(iLength-iIndex,1))
{
return false;
}
}
return true;
}

// Function to get string from beginning.

public static String Left(String strParam,int iLen)
{
if(iLen>0)
return strParam.Substring(0,iLen);
else
return strParam;
}

//Function to get string from end
public static String Right(String strParam,int iLen)
{
if(iLen>0)
return strParam.Substring(strParam.Length-iLen,iLen);
else
return strParam;
}

//Function to count no.of occurences of Substring in Main string
public static int CharCount(String strSource,String strToCount)
{
int iCount=0;
int iPos=strSource.IndexOf(strToCount);
while(iPos!=-1)
{
iCount++;
strSource=strSource.Substring(iPos+1);
iPos=strSource.IndexOf(strToCount);
}
return iCount;
}

//Not available in C#
//Function to count no.of occurences of Substring in Main string
public static int CharCount(String strSource,String strToCount,bool
IgnoreCase)
{
if(IgnoreCase)
{
return CharCount(strSource.ToLower(),strToCount.ToLower());
}
else
{
return CharCount(strSource,strToCount);
}
}

//Useful Function can be used whitespace stripping programs
//Function Trim the string to contain Single between words
public static String ToSingleSpace(String strParam)
{
int iPosition=strParam.IndexOf(" ");
if(iPosition==-1)
{
return strParam;
}
else
{
return ToSingleSpace(strParam.Substring(0,iPosition) +
strParam.Substring(iPosition+1));
}
}

//Function Replace string function.

// Currently Not Available in C#
public static String Replace(String strText,String strFind,String
strReplace)
{
int iPos=strText.IndexOf(strFind);
String strReturn="";
while(iPos!=-1)
{
strReturn+=strText.Substring(0,iPos) + strReplace;
strText=strText.Substring(iPos+strFind.Length);
iPos=strText.IndexOf(strFind);
}
if(strText.Length>0)
strReturn+=strText;
return strReturn;
}
}

 




Come implementare un visualizzatore di immagini

Qualsiasi formato di immagine potrà essere visualizzato grazie a questa piccola applicazione che, oltre a presentarsi come una introduzione alla gestione delle immagini, si dimostra anche un valido mezzo per entrare in contatto con le Winform. Gestione dei menu, gestione dei file, controllo delle dimensioni della finestra: tutti argomenti che saranno chiariti da una attenta lettura del codice riportato.
Per compilare il codice è necessario eseguire dalla riga di comando:

csc /target:winexe /reference:System.dll /reference:System.Winforms.dll 
/reference:System.Drawing.dll /reference:Microsoft.Win32.Interop.dll PictureViewer.cs








namespace myPictViewer
{
using System;
using System.WinForms;
using System.Drawing;
public class PictViewForm : Form
{
protected Bitmap myPicture;
protected bool myPicStyle = true;
protected MenuItem showWindow;
protected MenuItem showNative;
protected MenuItem closePicture;
public PictViewForm()
{
this.Text = "Picture Viewer";
this.ClientSize = new Size(640,480);
MainMenu myMainMenu = new MainMenu();
MenuItem myFileItem = myMainMenu.MenuItems.Add("&File");
MenuItem myHelpItem = myMainMenu.MenuItems.Add("&Help");
//The line below is commented out as it may not work for Beta 1 of .NET
//myFileItem.Popup += new EventHandler (checkMenus);
myFileItem.MenuItems.Add(new MenuItem("&Open" , new EventHandler(OnOpen) , Shortcut.CtrlO));
myFileItem.MenuItems.Add("-");
myFileItem.MenuItems.Add(showWindow = new MenuItem("Show Image - Fit To Window" , new EventHandler(ShowWindow)));
myFileItem.MenuItems.Add(showNative = new MenuItem("Show Image - Native Size" , new EventHandler(ShowNative)));
myFileItem.MenuItems.Add("-");
myFileItem.MenuItems.Add(closePicture = new MenuItem("&Close Picture" , new EventHandler(OnClose) , Shortcut.CtrlH));
myFileItem.MenuItems.Add(new MenuItem("E&xit" , new EventHandler(OnExit) , Shortcut.CtrlE));

myHelpItem.MenuItems.Add(new MenuItem("&About" , new EventHandler(OnAbout) , Shortcut.CtrlA));
closePicture.Enabled = false;
this.Menu = myMainMenu;
this.StartPosition = FormStartPosition.CenterScreen;
}

protected override void OnPaint(PaintEventArgs myArgs)
{
if (myPicture != null)
{
Graphics myGraph = myArgs.Graphics;
if (myPicStyle == true)
{
myGraph.DrawImage(myPicture , AutoScrollPosition.X , AutoScrollPosition.Y , myPicture.Width , myPicture.Height);
}
else
{
myGraph.DrawImage(myPicture , ClientRectangle);
}
}
}

private void OnAbout(Object mySender , EventArgs myArgs)
{
MessageBox.Show("Picture Viewer 1.0 by Jim","About Picture Viewer",MessageBox.OK|MessageBox.IconInformation);
}

private void checkMenus(Object mySender , EventArgs myArgs)
{
if (myPicture != null)
{
if (myPicStyle == true)
{
showNative.Checked = true;
showWindow.Checked = false;
}
else
{
showNative.Checked = false;
showWindow.Checked = true;
}
}
else
{
showNative.Checked = false;
showWindow.Checked = false;
myPicStyle = true;
}
}

private void ShowWindow(Object mySender , EventArgs myArgs)
{
myPicStyle = false;
this.SetStyle (ControlStyles.ResizeRedraw, true);
if (myPicture != null)
{
this.AutoScroll = false;
this.Invalidate();
}
}

private void ShowNative(Object mySender , EventArgs myArgs)
{
myPicStyle = true;
this.SetStyle (ControlStyles.ResizeRedraw, false);
if (myPicture != null)
{
this.AutoScroll = true;
this.AutoScrollMinSize = myPicture.Size;
this.Invalidate();
}
}

private void OnClose(Object mySender , EventArgs myArgs)
{
closePicture.Enabled = false;
myPicture = null;
myPicStyle = false;
this.AutoScroll = false;
this.Invalidate();
}

private void OnExit(Object mySender , EventArgs myArgs)
{
this.Close();
}

private void OnOpen(Object mySender , EventArgs myArgs)
{
if (myPicture != null)
{

}
OpenFileDialog myDialog = new OpenFileDialog();
myDialog.Filter = "Image Files (JPEG,GIF,BMP)|*.jpg;*.jpeg;*.gif;*.bmp|JPEG Files(*.jpg;*.jpeg)|*.jpg;*.jpeg|GIF Files(*.gif)|*.gif|BMP Files(*.bmp)|*.bmp";

if (myDialog.ShowDialog() == DialogResult.OK)
{
String myFileName = myDialog.FileName;
if (myFileName.Length != 0)
{
try
{
closePicture.Enabled = true;
myPicture = new Bitmap(myFileName);
this.Text = "Picture Viewer - " + myFileName;
this.AutoScroll = true;
this.AutoScrollMinSize = myPicture.Size;
this.Invalidate();
}
catch
{
MessageBox.Show(String.Format("{0} is not a valid Image File" , myFileName) , "Picture Viewer" , MessageBox.OK | MessageBox.IconError);
}
}
}
}

public static void Main(string[] args)
{
Application.Run(new PictViewForm());
}





Come utilizzare l'overload

Un interessante e semplice esempio di come utilizzare l'overload degli operatori: creiamo una classe Rectangle ed effettuiamo l'overload sull'operatore di uguaglianza e su quelli di disuguaglianza. Sarà dunque possibile effettuare confronti fra le dimensioni dei rettangoli utilizzando la comune notazione matematica.
using System;

class Rectangle
{
private int iHeight;
private int iWidth;

public Rectangle()
{
Height=0;
Width=0;
}
public Rectangle(int w,int h)
{
Width=w;
Height=h;
}

public int Width
{
get
{
return iWidth;
}
set
{
iWidth=value;
}
}
public int Height
{
get
{
return iHeight;
}
set
{
iHeight=value;
}
}

public int Area
{
get
{
return Height*Width;
}
}

/* OverLoading == */

public static bool operator==(Rectangle a,Rectangle b)
{
return ((a.Height==b.Height)&&(a.Width==b.Width));
}

/* OverLoading != */

public static bool operator!=(Rectangle a,Rectangle b)
{
return !(a==b);
}

/* Overloding > */

public static bool operator>(Rectangle a,Rectangle b)
{
return a.Area>b.Area;
}

/* Overloading < */
public static bool operator < (Rectangle a,Rectangle b)
{
return !(a > b);
}

/* Overloading >= */

public static bool operator >= (Rectangle a,Rectangle b)
{
return (a>b)||(a==b);
}

/* Overloading <= */

public static bool operator <= (Rectangle a,Rectangle b)
{
return (a < b)||(a==b);
}

public override String ToString()
{
return "Height=" + Height + ",Width=" + Width;
}
public static void Main()
{
Rectangle objRect1 =new Rectangle();
Rectangle objRect2 =new Rectangle();
Rectangle objRect3 =new Rectangle(10,15);
objRect1.Height=15;
objRect1.Width=10;
objRect2.Height=25;
objRect2.Width=10;
Console.WriteLine("Rectangle#1 " + objRect1);
Console.WriteLine("Rectangle#2 " + objRect2);
Console.WriteLine("Rectangle#3 " + objRect3);

if(objRect1==objRect2)
{
Console.WriteLine("Rectangle1 & Rectangle2 are Equal.");
}
else
{
if(objRect1 > objRect2)
{
Console.WriteLine("Rectangle1 is greater than Rectangle2");
}
else
{
Console.WriteLine("Rectangle1 is lesser than Rectangle2");
}
}

if(objRect1==objRect3)
{
Console.WriteLine("Rectangle1 & Rectangle3 are Equal.");
}
else
{
Console.WriteLine("Rectangle1 & Rectangle3 are not Equal.");
}
}
}




Come utilizzare gli array

Il codice riportato è un esempio elementare che illustra come creare e un array e come interrogarlo dall'inizio a
Working with Arrays in C#

Open your favorite text editor and type the following C# source code:

using System;

public class ArrayMembers
{
public static void Main(string[] args)
{
Console.WriteLine("\n");

//Iterate through the items of array args using foreach
foreach(string s in args)
{
Console.WriteLine(s);
}

Console.WriteLine("\n\n");

//Declare array strNames
string[] strNames = {"Joe","Mary","Bill","Fred"};

//Iterate through the items of array strNames
for(int i = 0;i < strNames.Length;i++)
{
Console.WriteLine("strNames[{0}] = {1}",i,strNames[i]);
}
}
}



Come manipolare le stringhe in C#

L'esempio allegato illustra numerosi utilizzi della classe String presente in C#. Tra gli esempi troveremo come trasformare una stringa in minuscolo i in maiuscolo, come invertire l'ordine dei caratteri, come scoprire se la stringa è palindroma, come prendere parte di una stringa, come cancellare gli spazi superflui, ed altro ancora. Oltre ad utilizzare metodi della classe String, l'esempio propone delle funzioni aggiuntive, non presenti in C# e che possono tornare utili in molte circostanze.
using System;

class MyString
{
public static void Main()
{
String strData="WeLcOmE tO c#.eNjoy FoLkS";

Console.WriteLine("String Value: {0}",strData);
Console.WriteLine("LowerCase Equivalent: {0}",Lower(strData));
Console.WriteLine("UpperCase Equivalent: {0}",Upper(strData));
Console.WriteLine("PCase Equivalent: {0}",PCase(strData));
Console.WriteLine("Reverse Equivalent: {0}",Reverse(strData));
Console.WriteLine("Is 'rotator' PalinDrome:{0}",IsPalindrome("rotator"));
Console.WriteLine("Is 'visualc#' PalinDrome:{0}",IsPalindrome("visualc#"));
Console.WriteLine("Left(string,5): {0}",Left(strData,5));
Console.WriteLine("Right(String,6): {0}",Right(strData,6));
Console.WriteLine("CharCount(Charcount,c):{0}",CharCount("Charcount","C"));
Console.WriteLine("CharCount(CharCount,c,true):{0}",CharCount("Charcount","C",true));
Console.WriteLine("CharCount(CharCount,d,true):{0}",CharCount("Charcount","d",true));
Console.WriteLine("ToSingleSpace('welcome to C Sharp'): {0}",ToSingleSpace("welcome to C Sharp "));
Console.WriteLine("Replace(aaaaaa,aa,a):{0}",Replace("aaaaaa","aa","a"));
}

// Convert string to LowerCase
public static String Lower(String strParam)
{
return strParam.ToLower();
}

//Convert String to UpperCase
public static String Upper(String strParam)
{
return strParam.ToUpper();
}

//Convert String to ProperCase
public static String PCase(String strParam)
{
String strProper=strParam.Substring(0,1).ToUpper();
strParam=strParam.Substring(1).ToLower();
String strPrev="";

for(int iIndex=0;iIndex < strParam.Length;iIndex++)
{
if(iIndex > 1)
{
strPrev=strParam.Substring(iIndex-1,1);
}
if( strPrev.Equals(" ") ||
strPrev.Equals("\t") ||
strPrev.Equals("\n") ||
strPrev.Equals("."))
{
strProper+=strParam.Substring(iIndex,1).ToUpper();
}
else
{
strProper+=strParam.Substring(iIndex,1);
}
}
return strProper;
}

// Function to Reverse the String
public static String Reverse(String strParam)
{
if(strParam.Length==1)
{
return strParam;
}
else
{
return Reverse(strParam.Substring(1)) + strParam.Substring(0,1);
}
}

// Function to Test for Palindrome
public static bool IsPalindrome(String strParam)
{
int iLength,iHalfLen;
iLength=strParam.Length-1;
iHalfLen=iLength/2;
for(int iIndex=0;iIndex<=iHalfLen;iIndex++)
{
if(strParam.Substring(iIndex,1)!=strParam.Substring(iLength-iIndex,1))
{
return false;
}
}
return true;
}

// Function to get string from beginning.

public static String Left(String strParam,int iLen)
{
if(iLen>0)
return strParam.Substring(0,iLen);
else
return strParam;
}

//Function to get string from end
public static String Right(String strParam,int iLen)
{
if(iLen>0)
return strParam.Substring(strParam.Length-iLen,iLen);
else
return strParam;
}

//Function to count no.of occurences of Substring in Main string
public static int CharCount(String strSource,String strToCount)
{
int iCount=0;
int iPos=strSource.IndexOf(strToCount);
while(iPos!=-1)
{
iCount++;
strSource=strSource.Substring(iPos+1);
iPos=strSource.IndexOf(strToCount);
}
return iCount;
}

//Not available in C#
//Function to count no.of occurences of Substring in Main string
public static int CharCount(String strSource,String strToCount,bool
IgnoreCase)
{
if(IgnoreCase)
{
return CharCount(strSource.ToLower(),strToCount.ToLower());
}
else
{
return CharCount(strSource,strToCount);
}
}

//Useful Function can be used whitespace stripping programs
//Function Trim the string to contain Single between words
public static String ToSingleSpace(String strParam)
{
int iPosition=strParam.IndexOf(" ");
if(iPosition==-1)
{
return strParam;
}
else
{
return ToSingleSpace(strParam.Substring(0,iPosition) +
strParam.Substring(iPosition+1));
}
}

//Function Replace string function.

// Currently Not Available in C#
public static String Replace(String strText,String strFind,String
strReplace)
{
int iPos=strText.IndexOf(strFind);
String strReturn="";
while(iPos!=-1)
{
strReturn+=strText.Substring(0,iPos) + strReplace;
strText=strText.Substring(iPos+strFind.Length);
iPos=strText.IndexOf(strFind);
}
if(strText.Length>0)
strReturn+=strText;
return strReturn;
}
}


Come ottenere l'allineamento a destra

Per realizzare un effetto di giustificato a destra con cout, è necessario chiamare la funzione width con passando come argomento la dimensione dello schermo (espressa come numero di caratteri). Nell'esempio riportato, viene visualizzato un numero allineandolo a destra su un display di 80 caratteri.
#include <iostream>
using namespace std;
int main()
{
int var=15;
cout.width(80);
cout << var << endl; // right-justified display
}


Come emettere un beep

L'emissione di un segnale acustico è spesso utile per segnalare la fine di un ciclo di operazione o in un qualsiasi caso in cui si voglia richiamare l'attenzione dell'utente. La sequenza di escare "\a" corrisponde alla codifica ASCII di un beep. Per far emettere il segnale al nostro programma è dunque sufficiente indirizzare questa sequenza verso lo standard output.
const char BEEP = '\a';
cin<<num;
if(num<1)
{
cout<<BEEP<<"wrong input! Please try again";
}

 

Come calcolare una radice quadrata da record

Il codice riportato permette di calcolare la radice quadrata di un numero in un tempo sensibilmente più breve rispetto alle funzioni standard. Le prestazioni in termini di velocità si pagano un una certa perdita di accuratezza che può essere comunque accettabile nelle applicazioni in cui è la rapidità di esecuzione più che la precisione a fare differenza.
union FastSqrtUnion{  float d;  unsigned long i;};
static unsigned long fast_sqrt_table[0x10000]; // declare table of square roots
void BuildSqrtTable (){ unsigned long i; FastSqrtUnion s;
for (i = 1; i <= 0x7FFF; i++) {
// Build a float with the bit pattern i as mantissa
// and an exponent of 0, stored as 127 s.i = (i << 8) | (0x7F << 23);
s.d = (float)sqrt(s.d);
// Take the square root then strip the first 7 bits of
// the mantissa into the table
fast_sqrt_table[i + 0x8000] = (s.i & 0x7FFFFF);
// Repeat the process, this time with an exponent of 1, // stored as 128
s.i = (i << 8) | (0x80 << 23); s.d = (float)sqrt(s.d);
fast_sqrt_table[i] = (s.i & 0x7FFFFF); } fast_sqrt_table[0] = 0x1f800000;}
float FastSqrt (float n){
*(int*)&n = fast_sqrt_table[(*(int *)&n >> 8) & 0xFFFF] ^ ((((*(int*)&n - 0x3F800000) >> 1) + 0x3F800000) & 0x7F800000);
return n;}

 

Come effettuare le conversioni di temperatura

Una piccolo classe che consente di effettuare tutte le conversioni possible fra gradi Centigradi, Kelvin e Fahrenheit. Una di quelle funzioni da tenere sempre a portata di mouse…
#include <iostream.h>
#include <ctype.h>
#include <stdlib.h>// just for the cls

class TempConversions
{
public:
void f2c(void) { cout << ((temp - 32) / 1.8) << " degrees Celsius" << endl << endl; };
void f2k(void) { cout << ((temp - 32) / 1.8 + 305.15) << " degrees Kelvin" << endl << endl; };

void c2f(void) { cout << (temp * 1.8 + 32) << " degrees Fahrenheit" << endl << endl; };
void c2k(void) { cout << (temp + 273.15) << " degrees Kelvin" << endl << endl; };

void k2f(void) { cout << ((temp - 273.15) * 1.8 + 32) << " degrees Fahrenheit" << endl << endl; };
void k2c(void) { cout << (temp - 273.15) << " degrees Celsius" << endl << endl; };

double temp;
};

int main(void)
{
TempConversions theTemp;

short int choice;
char loop;

system("cls");//clears the screen each time to make it neat
cout << "Temperature Converter 2.3" << endl << endl << endl;

do
{
cout << "Convert from:" << endl;
cout << "1. Fahrenheit to Celsius" << endl;
cout << "2. Fahrenheit to Kelvin" << endl;
cout << "3. Celsius to Fahrenheit" << endl;
cout << "4. Celsius to Kelvin" << endl;
cout << "5. Kelvin to Fahrenheit" << endl;
cout << "6. Kelvin to Celsius" << endl << endl;

do
{
cout << "Please enter your choice: ";
cin >> choice;
} while((choice < 1) || (choice > 6));

cout << "Please enter the temperature: ";
cin >> theTemp.temp;

switch(choice)
{
case 1 : theTemp.f2c();
break;
case 2 : theTemp.f2k();
break;
case 3 : theTemp.c2f();
break;
case 4 : theTemp.c2k();
break;
case 5 : theTemp.k2f();
break;
case 6 : theTemp.k2c();
break;
}

do
{
cout << "Would you like to continue? (y/n) ";
cin >> loop;
loop = toupper(loop);
} while ((loop != 'N') && (loop != 'Y'));

cout << endl;
} while (loop == 'Y');

return 0;
}

 

 

Come trovare numeri primi

Questo interessante codice, ampiamente commentato, si occupa della ricerca di numeri primi: ogni numero trovato è stampato su schermo e trascritto in un file di testo. Ampiamente ottimizzato, offre numerosi spunti per la chi si occupa di programmazione di applicazioni in ambito matematico.
#include <math.h>
#include <iostream>
#include <fstream>
#include <cstdlib> // a C++ version of stdlib.h with everything
// wrapped in the std namespace.
#include <time.h>

using namespace std; // specify that everything in the std namespace
// can be referred to as if it were global.

// Increase this constant and enlarge the factor wheel to speed up testing of
// large numbers. Be warned, the increase in size (which is quite large)
// is probably not worth the small percentage increase in speed).
#define FACTOR_WHEEL_SIZE 48
// The wheel's modulus value. Not sure what this is really called. :)
#define FACTOR_WHEEL_MOD 210

// Used in our wheel factorization
int factorwheel[FACTOR_WHEEL_SIZE] = { 1, 11, 13, 17, 19, 23, 29,
31, 37, 41, 43, 47, 53, 59, 61, 67, 71, 73, 79, 83, 89, 97, 101, 103, 107,
109, 113, 121, 127, 131, 137, 139, 143, 149, 151, 157, 163, 167, 169, 173,
179, 181, 187, 191, 193, 197, 199, 209 };

// isprime()
// =========
// returns true if the number passed into the function is a prime.
// returns false otherwise.
bool isprime(register long int thenumber)
{
//Test < 3 first so for most numbers (>3) we'll only have one
//if instead of 2.
if (thenumber < 3)
{
// the only special case where thenumber < 2 is -1
if ((thenumber == -1) || (thenumber == 2))
return true;
else
return false;
}

// Here we must check the divisors our wheel is based upon. In this case
// it's 2, 3, 5, and 7. We waste a little time if the number is larger
// than 7^2 but that's probably saved by avoiding the square root.
if ((thenumber == 3) || (thenumber == 5) || (thenumber == 7))
return true;

if ((thenumber % 2 == 0) || (thenumber % 3 == 0) || (thenumber % 5 == 0)
|| (thenumber % 7 == 0))
return false;

//If the number is <50 it was covered above, exit it's prime.
if (thenumber < 50)
return true;

// if thenumber has a divisor <= its square root,
// then thenumber is not prime
register long int sqroot = (long int) sqrt(thenumber);
// Loop through using our factor array. Start at position 2
// since we've already tested for 1.
register long int div = 0;
for (register long int mult = 0; div <= sqroot; mult += FACTOR_WHEEL_MOD)
for (register long int loop = (mult > 0 ? 0: 1); loop < FACTOR_WHEEL_SIZE; loop++)
{

if ((div = factorwheel[loop] + mult) > sqroot)
break;

if (thenumber % div == 0)
return false;
}

// if no divisor has been found, it is a prime
return true;
}


// main()
// ======
int main()
{
// get the start and end numbers of the test
register long int startnumber, endnumber, start;
cout << "What number do you want to start the test with? ";
cin >> startnumber;
cout << "What number do you want to end the test with? ";
cin >> endnumber;
cout << endl<< "Primes between the numbers " << startnumber
<< " and " << endnumber << " inclusive:" << endl;

// open the output file
ofstream filesave;
filesave.open("primes.txt");

// for each number between startnumber and endnumber inclusive,
// if it is prime, write it to the screen and the output file.
long int count = 0;

if (startnumber < 4)
start = startnumber;
else
{
start = startnumber % 6;

switch (start)
{
// If startnumber is equal to either a multiple of 6 or +-1 of a
// multiple of six, use startnumber
case 0: //Fall through
case 6: start = startnumber;
break;
// else calculate the next multiple of six
default: start = ((startnumber / 6) + (startnumber < 0)? -1: 1) * 6;
break;
}
}

for (register int smallnumber = start; smallnumber < 4 && smallnumber < endnumber; smallnumber++)
if (isprime(smallnumber))
{
count++;
cout << smallnumber << endl;
filesave << smallnumber << endl;
}

if (start < 6)
start = 6;

for (register long int number = start; number - 1 <= endnumber ; number += 6)
{
if ((number - 1 >= startnumber) && (number - 1 <= endnumber) && isprime(number - 1))
{
count++;
cout << number - 1 << endl;
filesave << number - 1 << endl;
}

if ((number + 1 >= startnumber) && (number + 1 <= endnumber) && isprime(number + 1))
{
count++;
cout << number + 1 << endl;
filesave << number + 1 << endl;
}
}

// close the output file
filesave.close();

// report how many primes
cout << endl << "There are " << count << " primes between "
<< startnumber << " and " << endnumber << " inclusive." << endl;

// end the program
return 0;
}


Come scoprire se una stringa contiene numeri

Una funzione velocissima che si occupa di effettuare il parsing di una stringa con lo scopo di verificare che la stringa stessa sia un numero. Per la serie: la cassetta degli attrezzi del buon programmatore.
// str must be \0-terminated
bool is_a_number( const char* str )
{
if( *str=='-' || *str=='+' ) ++str;
while (*str >= '0' && *str<='9')
++str;
// return true if the first nondigit is the end.
return (*str=='\0');
}

// Using std::string::c_str() is less efficient
bool is_a_number ( std::string const& str )
{
std::string::iterator si = str.begin();
const std::string::iterator end = str.end();

if( *si=='-' || *si=='+' ) ++si;
while ( si != end && (*si>='0' && *si <='9') )
++si;
// return true if the first nondigit is the end.
return ( si == end );
}

 


Come realizzare un token

Una implementazione semplice e funzionale della classe Token che può fare da base per le realizzazioni più complesse. Davvero rimarchevole l'impostazione e la pulizia del codice.
#include <string.h>
#include <stdlib.h>

class cToken
{
char *strToken;
char *strDelimit;
char *strNextToken;
char *strReturnToken;
char* StrDup(char* String=NULL){return String?strdup(string):strdup("");}

public:
cToken(char *Token,char *Delimit){
strToken=Strdup(Token);
strDelimit=StrDup(Delimit);
strNextToken=StrDup(strtok(strToken,strDelimit));
strReturnToken=StrDup();}

char* NextToken(char* NewDelimiter=NULL){
if(NewDelimiter){
free(strDelimit);
strDelimit=strdup(NewDelimiter);}
free(strReturnToken);
strReturnToken=StrDup(strNextToken);
free(strNextToken);
strNextToken=StrDup(strtok(NULL,strDelimit));
return strReturnToken;}

int MoreTokensExists(){return strlen(strNextToken);}

SetNew(char *Token,char *Delimit){
free(strToken);
free(strDelimit);
free(strNextToken);
strToken=StrDup(Token);
strDelimit=StrDup(Delimit);
strNextToken=StrDup(strtok(strToken,strDelimit));
free(strReturnToken);
strReturnToken=StrDup();}

~cToken(){
free(strToken);
free(strDelimit);
free(strNextToken);
free(strReturnToken);}
};

 

Come eliminare gli spazi vuoti in una stringa

Quante volte ci sarà capitato di "compattare" una stringa eliminando gli spazi superflui? Ecco allora pronta una semplice funzione che in pochi passaggi risolve brillantemente il problema.
Private Function Pack(str As String) As String
Dim words As Variant
Dim x As Long
Dim temp As String

words = Split(str, " ")
For x = LBound(words) To UBound(words)
If words(x) <> "" Then
temp = temp & " " & words(x)
End If
Next x
Pack = temp
End Function




Come stampare una pagina Web

Basta invocare una libreria DLL per stampare il contenuto di una pagina Web fornita come parametro. Di seguito le poche righe di codice:
Public Sub StampaWeb(URL As String)
Shell "rundll32.exe c:\windows\system\MSHTML.dll,PrintHTML " & _
URL, vbNormalFocus
End Sub



Come nascondere l'applicazione dai task attivi

Come risaputo, la combinazione dei tasti Ctrl-Alt-Del consente di visualizzare la lista di tutte le applicazioni attualmente avviate sul proprio PC. Il tips proposto consente di rendere "invisibile" la propria applicazione dalla succitata lista.
Public Declare Function GetCurrentProcessId Lib "kernel32" () As Long
Public Declare Function GetCurrentProcess Lib "kernel32" () As Long
Public Declare Function RegisterServiceProcess Lib "kernel32" (ByVal dwProcessID As Long, _
ByVal dwType As Long) As Long

Public Const RSP_SIMPLE_SERVICE = 1
Public Const RSP_UNREGISTER_SERVICE = 0Procedures

' Per nascondere l'applicazione invocare la seguente procedura:

Public Sub MakeMeService()
Dim pid As Long
Dim reserv As Long

pid = GetCurrentProcessId()
regserv = RegisterServiceProcess(pid, RSP_SIMPLE_SERVICE)
End Sub

' Per far riapparire l'applicazione nella lista dei task attivi:

Public UnMakeMeService()
Dim pid As Long
Dim reserv As Long

pid = GetCurrentProcessId()
regserv = RegisterServiceProcess(pid, RSP_UNREGISTER_SERVICE)
End sub



Come reperire la velocità del processore

Bastano poche righe di codice Delphi e qualche "ritocco" assembler per conoscere la velocità (MHZ) del processore che equipaggia il PC.
function GetCPUSpeed: Double; 
const
DelayTime = 500;
var
TimerHi, TimerLo: DWORD;
PriorityClass, Priority: Integer;
begin
PriorityClass := GetPriorityClass(GetCurrentProcess);
Priority := GetThreadPriority(GetCurrentThread);

SetPriorityClass(GetCurrentProcess, REALTIME_PRIORITY_CLASS);
SetThreadPriority(GetCurrentThread, THREAD_PRIORITY_TIME_CRITICAL);

Sleep(10);
asm
dw 310Fh
mov TimerLo, eax
mov TimerHi, edx
end;
Sleep(DelayTime);
asm
dw 310Fh
sub eax, TimerLo
sbb edx, TimerHi
mov TimerLo, eax
mov TimerHi, edx
end;

SetThreadPriority(GetCurrentThread, Priority);
SetPriorityClass(GetCurrentProcess, PriorityClass);

Result := TimerLo / (1000.0 * DelayTime);
end;

// Per utilizzare la funzione:

Caption:=Format('%f MHz', [GetCPUSpeed]);



Come aggiungere un file al menu documenti di Start

Il menu Start di Windows, al suo interno, propone una cartella denominata Documenti; la stessa mantiene la lista degli ultimi documenti utilizzati. La procedura che segue consente di aggiungere automaticamente un documento alla suddetta lista.
uses ShellAPI, ShlOBJ; 

procedure StartDocumentsMenu( FlePath : string );
begin
SHAddToRecentDocs(SHARD_PATH, PChar( FilePath ) );
end;

// Ecco come utilizzare la procedura appena proposta:

StartDocumentsMenu( 'c:\temp\readme.txt' );


Come realizzare uno screen-saver

Realizzare un'applicazione per catturare lo schermo non è mai stato così semplice…provare, ops…digitare per credere!
Procedure TForm1.ScreenShot(x : integer; y : integer; Width : integer; Height : integer; bm : TBitMap);
var
dc: HDC; lpPal : PLOGPALETTE;

begin
if ((Width = 0) OR (Height = 0)) then exit;

bm.Width := Width;
bm.Height := Height;
dc := GetDc(0);
if (dc = 0) then exit;

if (GetDeviceCaps(dc, RASTERCAPS) AND RC_PALETTE = RC_PALETTE) then
begin
GetMem(lpPal, sizeof(TLOGPALETTE) + (255 * sizeof(TPALETTEENTRY)));
FillChar(lpPal^, sizeof(TLOGPALETTE) + (255 * sizeof(TPALETTEENTRY)), #0);
lpPal^.palVersion := $300;
lpPal^.palNumEntries := GetSystemPaletteEntries(dc, 0, 256, lpPal^.palPalEntry);
if (lpPal^.PalNumEntries <> 0) then
begin
bm.Palette := CreatePalette(lpPal^);
end;
FreeMem(lpPal, sizeof(TLOGPALETTE) + (255 * sizeof(TPALETTEENTRY)));
end;



Coma analizzare il contenuto di una cartella

Allo scopo utilizziamo l'oggetto ActiveX Scripting.FileSystemObject. La funzione accetta in ingresso il nome di una cartella, e quindi ne analizza il contenuto restituendo un array di stringhe dove ogni elemento rappresenta il nome di uno dei file contenuti nella cartella.
function Cartella(nomeCartella) {
fso = new ActiveXObject("Scripting.FileSystemObject");
folder = fso.GetFolder(Server.MapPath(nomeCartella));
folderFiles = new Enumerator(folder.files);
var arr = new Array();
var i = 0;
while (!folderFiles.atEnd()) {
temp = fso.GetFile(folderFiles.item());
arr[i++] = temp.Name;
folderFiles.moveNext();
}
return arr;
}

 

Come effettuare lo streaming di un file . mp3

Questo tips mostra come realizzare lo streaming di un file mp3 in una qualunque pagina Web. Basterà includere il nostro file, in questo caso mp3 nella medesima cartella della pagina è richiamarla cosi:
<a href="http://www.xxxx/mp3.asp?play=file.mp3"> Play di un file MP3 </a> 

<%
On Error Resume Next
Dim FileSystemObject, Folder, FileCollection, File
Dim FolderPath, WebDir
If Request.QueryString("play") >"" Then
With Response
.Write("<EMBED src=" & chr(34) & Request.QueryString("play") & chr(34) & vbCrLf)
.Write(" width=350 height=43 controls=console volume=80" & vbCrLf)
.Write(" width=350 loop=false type='audio/mp3'>" & vbCrLf)
.Write("<BR>")
End With
End If
Server.ScriptTimeOut=1
FolderPath= server.MapPath(".") & "\"
WebDir= Request.ServerVariables("PATH_INFO")
Set FileSystemObject = CreateObject("Scripting.FileSystemObject")
Set Folder = FileSystemObject.GetFolder(Folderpath)
Set FileCollection = Folder.Files
For Each File In FileCollection
s = LCase(File.Name)
If File.name="file.mp3" Then
With Response
.Write( "<A href=" & chr(34) & webdir & "?Play=" & File.name & vbCrLf)
.Write("#stream" & chr(34) & "><font size=""2"" face=""Arial"">" & vbCrLf)
.Write("Click per il play del file mp3</font></a> " & vbCrLf)
.Write("(" & File.name & " FileSize=" & File.size & ")<BR>" & vbCrLf)
End With
End If
Next
%>


Come evitare la memorizzazione delle pagine in cache

Come evitare la memorizzazione delle pagine visitate per una successiva visualizzazione più rapida? Semplice basta inserire il codice dello script ASP menzionato, all'inizio della pagina interessata:
<%
Response.ExpiresAbsolute = now()-2
Response.Addheader "pragma","no-cache"
Response.Addheader "cache-control","private"
Response.Cachecontrol="no-cache"
%>