Non molto tempo fà ho dovuto sviluppare un'applicazione che integrasse un filmato Flash e interagisse con esso. Vediamo come realizzare un'applicazione del genere:

Per prima cosa dobbiamo aggiungere nella toolbox (casella degli strumenti) di Visual Studio i controlli Shockwave ActiveX, quindi tasto destro sulla toolbox -> Aggiungi Scheda e assegnargli un nome.

Ora bisogna generare un InterOp Asembly che vi permetterà di usare il controllo ActiveX nel vostro Form. Per fare questo, tasto destro sulla nuova scheda creata nella toolbox -> Scegli elementi -> Componenti COM e aggiungere 'Shockwave Flash Object'.

Prima di fare il drag di questo nuovo controllo sul vostro form bisogna sapere che VS2008 così come il suo predecessore VS2005 non aggiunge automaticamente i riferimenti COM necessari per l' OLE Automation quindi per rimediare a questa situazione bisogna aggiungere il riferimento a OLE Automation COM nel vostro progetto.
Per fare questo, da Esplora Soluzioni espandere il vostro progetto in questione, tasto destro su Riferimenti -> Aggiungi riferimento e nella scheda COM selezionare 'OLE Automation' e fare OK.
Ora draggando il controllo sul form noterete che Visual Studio aggiungerà alcuni nuovi riferimenti al vostro progetto. Questi sono gli InterOp Assembly per il controllo ActiveX Shockwave Flash Object Player.
Create una funzione e caricate il filmato flash in questo modo:

string path = System.Environment.CurrentDirectory;
path += @"\prova.swf";
axShockwaveFlash1.LoadMovie(0,path);
axShockwaveFlash1.Play();


Ricordate di aggiungere l'.swf nella vostra directory di Debug prima di testare.
Spostiamoci ora in Macromedia Flash e vediamo come far interagire il vostro .swf. Per mandare dati da un filmato Flash verso la vostra applicazione c'è bisogno di una chiamata alla funzione FSCommand. Questa funzione richiede 2 parametri opzionali: comando e parametri.








Per fare un esempio ho creato in Flash 3 bottoni (non mi dilungo a spiegare come perchè questo non è un tutorial su Flash):

Nell'evento on (press) dell'action script del primo bottone ci ho inserito:

on (press) {
    fscommand("Bottone","uno");
}

Adesso abbiamo bisogno di raccogliere i dati inviati dal filmato Flash.
Per fare questo incominciamo nell'aggiungere un nuovo gestore di eventi in questo modo:

this.axShockwaveFlash1.FSCommand += new AxShockwaveFlashObjects._IShockwaveFlashEvents_FSCommandEventHandler(this.axShockwaveFlash1_FSCommand);

e la sua relativa funzione:

private void axShockwaveFlash1_FSCommand(object sender, AxShockwaveFlashObjects._IShockwaveFlashEvents_FSCommandEvent e)
{
label1.Text = "E' stato premuto: " + e.command.ToString() + " " + e.args.ToString();
}


Eseguiamo la nostra applicazione:

Continua a leggere!

C#: Form con effetto Fadein e Fadeout

Molti software utilizzano questo effetto, soprattutto nel loro avvio iniziale (loading screen). Ecco una classe per realizzarlo:

public class WindowAnimator
{
Form window;
float Step;
Timer time;

public WindowAnimator(Form FormToAnimate)
{
window = FormToAnimate;
}

public void WindowFadeIn(int interval, float steps)
{
//Salva steps
Step = steps;
//Crea il Timer
time = new Timer();
time.Interval = interval;
time.Tick += new EventHandler(Timer_TickIn);
time.Start();
}
private void Timer_TickIn(object sender, EventArgs e)
{
//Controlla l'opacità del form
if (window.Opacity != 1.0)
{
//Se è inferiore di 1 incrementa l'opacità
window.Opacity += Step;
}
else
{
//Finito, stoppa il timer.
time.Stop();
}
}

public void WindowFadeOut(int interval, float steps)
{
Step = steps;
time = new Timer();
time.Interval = interval;
time.Tick += new EventHandler(Timer_TickOut);
time.Start();
}

private void Timer_TickOut(object sender, EventArgs e)
{
if (window.Opacity != 0.1)
{
window.Opacity -= Step;
}
else
{
time.Stop();
}
}
}

Continua a leggere!

C#: Salvare e caricare contenuti Textbox con xml

Ancora oggi, purtroppo, durante lo sviluppo di un'applicazione vengono utilizzati file .ini, metodo ormai obsoleto. Vediamo come salvare il testo contenuto nelle TextBox di un Form in un file .xml e successivamente ricaricare i dati nei rispettivi TextBox.

  • Esempio file app.config

  • <?xml version="1.0" encoding="utf-8"?>
    <configuration>
    <appSettings>
    <app key="Nome" value="Mario Rossi" />
    <app key="Email" value="mariorossi@blabla.it" />
    </appSettings>
    </configuration>


  • Scrittura del file app.config

  • string ConfigFile = "app.config";
    FileStream fs = new FileStream(ConfigFile, FileMode.Create);
    XmlTextWriter w = new XmlTextWriter(fs, Encoding.UTF8);

    w.WriteStartDocument();
    w.WriteStartElement("configuration");
    w.WriteStartElement("appSettings");
    w.WriteStartElement("app");
    w.WriteAttributeString("key", "Nome");
    w.WriteAttributeString("value", textBoxUser.Text);
    w.WriteEndElement();
    w.WriteStartElement("app");
    w.WriteAttributeString("key", "Email");
    w.WriteAttributeString("value", textBoxEmail.Text);
    w.WriteEndElement();
    w.Flush();
    fs.Close();
  • Lettura del file app.config

  • string ConfigFile = "app.config";
    FileStream fs = new FileStream(ConfigFile, FileMode.Create);
    XmlTextWriter w = new XmlTextWriter(fs, Encoding.UTF8);

    w.WriteStartDocument();
    w.WriteStartElement("configuration");
    w.WriteStartElement("appSettings");
    w.WriteStartElement("app");
    w.WriteAttributeString("key", "Nome");
    w.WriteAttributeString("value", textBoxUser.Text);
    w.WriteEndElement();
    w.WriteStartElement("app");
    w.WriteAttributeString("key", "Email");
    w.WriteAttributeString("value", textBoxEmail.Text);
    w.WriteEndElement();
    w.Flush();
    fs.Close();

  • Lettura del file app.config

  • public static NameValueCollection AppSettings;

    private void load_Config()
    {
    try
    {
    if (File.Exists(ConfigFile))
    {
    XmlDocument oXml = new XmlDocument();
    oXml.Load(ConfigFile);
    XmlNodeList appList = oXml.GetElementsByTagName("appSettings");
    AppSettings = new NameValueCollection();
    foreach (XmlNode aNode in appList)
    {
    foreach (XmlNode aKey in aNode.ChildNodes)
    {
    AppSettings.Add(aKey.Attributes["key"].Value, aKey.Attributes["value"].Value);
    }
    }
    textBoxUser.Text = AppSettings["Nome"];
    textBoxEmail.Text = AppSettings["Email"];
    }
    }
    catch
    {
    MessageBox.Show("Errore lettura file di configurazione.");
    }
    }


    Non dimenticare ovviamente di aggiungere i namespace System.Xml, System.Collections.Specialized e System.IO.

Continua a leggere!

InputBox di Visual Basic 6.0 in C#

Sfortunatamente in C# non esiste una funzione InputBox() come in Visual Basic 6.0/.NET ma si può risolvere il problema aggiungendo il riferimento a 'Microsoft.VisualBasic.dll'.
In Visual Studio 2005/2008 andare in Esplora Soluzioni, tasto destro su Riferimenti -> Aggiungi Riferimento. Nel tab .NET selezionare Microsoft.VisualBasic e fare OK.

Ecco un esempio di una InputBox dove inserire un valore:


private void show_InputBox()
{
String Prompt = "Inserisci valore";
String Title = "Valore richiesto";
String Default = "";
Int32 XPos = ((SystemInformation.WorkingArea.Width / 2) - 200);
Int32 YPos = ((SystemInformation.WorkingArea.Height / 2) - 100);

String Result = Microsoft.VisualBasic.Interaction.InputBox(Prompt, Title, Default, XPos, YPos);

if (Result != "")
{
//Codice per valore inserito. Esempio:
MessageBox.Show("Valore inserito: " + Result);
}
else
{
//Codice per valore non inserito. Esempio:
MessageBox.Show("Valore non inserito");
}
}

Continua a leggere!

Un esempio su come cryptare e decryptare con una password, tramite l'algoritmo DES, un file di testo.

- Il parametro sInputFilename specifica il file da cryptare.
- Il parametro sOutputFilename specifica il file da decryptare.
- Il parametro sKey specifica la password da utilizzare.

Utilizzare i seguenti Namespace:

using System;
using System.IO;
using System.Security;
using System.Security.Cryptography;
using System.Text;


I metodi mostrati di seguito utilizzano il componente CryptoStream.

public static void EncryptFile(string sInputFilename, string sOutputFilename, string sKey)
{
FileStream fsEncrypted = new FileStream(sInputFilename, FileMode.Create, FileAccess.ReadWrite);

DESCryptoServiceProvider DES = new DESCryptoServiceProvider();
DES.Key = ASCIIEncoding.ASCII.GetBytes(sKey);
DES.IV = ASCIIEncoding.ASCII.GetBytes(sKey);
ICryptoTransform desencrypt = DES.CreateEncryptor();
CryptoStream cryptostream = new CryptoStream(fsEncrypted, desencrypt, CryptoStreamMode.Write);

byte[] bytearrayinput = new byte[fsEncrypted.Length];
fsEncrypted.Read(bytearrayinput, 0, bytearrayinput.Length);
cryptostream.Write(bytearrayinput, 0, bytearrayinput.Length);
cryptostream.Close();
fsEncrypted.Close();
}

public static void DecryptFile(string sInputFilename, string sOutputFilename, string sKey)
{
DESCryptoServiceProvider DES = new DESCryptoServiceProvider();
DES.Key = ASCIIEncoding.ASCII.GetBytes(sKey);
DES.IV = ASCIIEncoding.ASCII.GetBytes(sKey);

FileStream fsread = new FileStream(sInputFilename, FileMode.Open, FileAccess.Read);
ICryptoTransform desdecrypt = DES.CreateDecryptor();

CryptoStream cryptostreamDecr = new CryptoStream(fsread, desdecrypt, CryptoStreamMode.Read);
StreamWriter fsDecrypted = new StreamWriter(sOutputFilename);
fsDecrypted.Write(new StreamReader(cryptostreamDecr).ReadToEnd());
fsDecrypted.Flush();
fsDecrypted.Close();
}

Continua a leggere!

Un esempio su come estrarre il nome del dominio da un indirizzo web.

- Il parametro Url specifica l'URL della pagina web.

public static string ExtractDomainNameFromURL(string Url)
{
if (!Url.Contains("://"))
Url = "http://" + Url;

return new Uri(Url).Host;
}



Anche se è un metodo più lento, mostro come fare la stessa cosa utilizzando le espressioni regolari:

public static string ExtractDomainNameFromURL(string Url)
{
return System.Text.RegularExpressions.Regex.Replace(
Url,
@"^([a-zA-Z]+:\/\/)?([^\/]+)\/.*?$",
"$2"
);
}

Continua a leggere!

Questo è un esempio su come salvare il contenuto di una pagina web in una stringa.

- Il parametro Url specifica l'URL della pagina web.

public string DownloadWebPage(string Url)
{
// Apre la connessione
HttpWebRequest WebRequestObject = (HttpWebRequest)HttpWebRequest.Create(Url);

// Si possono specificare i valori di un header aggiuntivo
// come l'user agent o il referer:
WebRequestObject.UserAgent = ".NET Framework/2.0";
WebRequestObject.Referer = "http://www.example.com/";

// Risposta della richiesta:
WebResponse Response = WebRequestObject.GetResponse();

// Apre lo stream:
Stream WebStream = Response.GetResponseStream();

// Crea un oggetto per la lettura:
StreamReader Reader = new StreamReader(WebStream);

// Legge l'intero contenuto dello stream:
string PageContent = Reader.ReadToEnd();

// Pulisce
Reader.Close();
WebStream.Close();
Response.Close();

return PageContent;
}

Continua a leggere!

Un semplice metodo per generare un hash MD5 da una stringa utilizzando un metodo di Encoding.

- Il parametro Input è la stringa data in input.
- Il parametro UseEncoding è il metodo di Encoding.

public static string CalculateMD5(string Input, Encoding UseEncoding)
{
System.Security.Cryptography.MD5CryptoServiceProvider CryptoService;
CryptoService = new System.Security.Cryptography.MD5CryptoServiceProvider();

byte[] InputBytes = UseEncoding.GetBytes(Input);
InputBytes = CryptoService.ComputeHash(InputBytes);
return BitConverter.ToString(InputBytes).Replace("-", "");
}


Un semplice metodo per generare un hash MD5 da una stringa utilizzando un encoding di default.

- Il parametro Input è la stringa data in input.

public static string CalculateMD5(string Input)
{
return CalculateMD5(Input, System.Text.Encoding.Default);
}

Continua a leggere!

Generazione di una stringa random di una determinata lunghezza.

- Il parametro size determina la dimensione della stringa.
- Il parametro lowerCase se true, genera una stringa in minuscolo.


public static string RandomString(int size, bool lowerCase)
{
StringBuilder RandStr = new StringBuilder(size);

// Ascii posizione iniziale (65 = A / 97 = a)
int Start = (lowerCase) ? 97 : 65;

// Aggiunge caratteri random
for (int i = 0; i < size; i++)
RandStr.Append((char)(26 * randomSeed.NextDouble() + Start));

return RandStr.ToString();
}


Generazione di un numero random.

- Il parametro Minimal determina il risultato minimo di numeri.
- Il parametro Maximal determina il risultato massimo di numeri.

public static int RandomNumber(int Minimal, int Maximal)
{
return randomSeed.Next(Minimal, Maximal);
}

Continua a leggere!

Per cancellare il testo di tutte le TextBox di un form, è possibile utilizzare questo codice:

private void clear_tBox()
{
foreach (Control c in this.Controls)
if (c is TextBox)
(c as TextBox).Clear();
}


Ovviamente se il TextBox è contenuto in un Panel, GroupBox, etc. è necessario specificare dove localizzare i controlli, quindi:

...
foreach (Control c in panel1.Controls)
...

Continua a leggere!


static void wLog(string msg)
{
try
{
if(!EventLog.SourceExists("Setup"))
{
EventLog.CreateEventSource("Setup", "DevEnne");
}
EventLog myLog = new EventLog();
myLog.Source = "Setup";

myLog.WriteEntry(msg, EventLogEntryType.Information);
}
catch
{
// gestione errori
}
}

Continua a leggere!