PDA

View Full Version : Licenza C#


kulosia
30-01-2011, 18:02
:D Salve a tutti,

vorrei creare una licenza per un programma.
il programma è un downloader in poche parole.
e vorrei che per avviare questo programma devono avere
una licenza e che tipo dopo 1 mese scade.

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;


namespace FileDownloaderApp
{
#region FileDownloader



















class FileDownloader : System.Object, IDisposable
{

#region Nested Types
public struct FileInfo
{
public string Path;
public string Name;

public FileInfo(String path)
{
this.Path = path;
this.Name = this.Path.Split("/"[0])[this.Path.Split("/"[0]).Length - 1];
}

}

private enum Event
{
CalculationFileSizesStarted,

FileSizesCalculationComplete,
DeletingFilesAfterCancel,

FileDownloadAttempting,
FileDownloadStarted,
FileDownloadStopped,
FileDownloadSucceeded,

ProgressChanged
};

private enum InvokeType
{
EventRaiser,
FileDownloadFailedRaiser,
CalculatingFileNrRaiser
};
#endregion

#region Events
public event EventHandler Started;
public event EventHandler Paused;
public event EventHandler Resumed;
public event EventHandler CancelRequested;
public event EventHandler DeletingFilesAfterCancel;
public event EventHandler Canceled;
public event EventHandler Completed;
public event EventHandler Stopped;

public event EventHandler IsBusyChanged;
public event EventHandler IsPausedChanged;
public event EventHandler StateChanged;

public event EventHandler CalculationFileSizesStarted;
public event CalculatingFileSizeEventHandler CalculatingFileSize;
public event EventHandler FileSizesCalculationComplete;

public event EventHandler FileDownloadAttempting;
public event EventHandler FileDownloadStarted;
public event EventHandler FileDownloadStopped;
public event EventHandler FileDownloadSucceeded;
public event FailEventHandler FileDownloadFailed;
public event EventHandler ProgressChanged;
#endregion

#region Fields
// Default amount of decimals
private const Int32 default_decimals = 2;

// Delegates
public delegate void FailEventHandler(object sender, Exception ex);
public delegate void CalculatingFileSizeEventHandler(object sender, Int32 fileNr);

// The download worker
private BackgroundWorker bgwDownloader = new BackgroundWorker();

// Preferences
private Boolean m_supportsProgress, m_deleteCompletedFiles;
private Int32 m_packageSize, m_stopWatchCycles;

// State
private Boolean m_disposed = false;
private Boolean m_busy, m_paused, m_canceled;
private Int64 m_currentFileProgress, m_totalProgress, m_currentFileSize;
private Int32 m_currentSpeed, m_fileNr;

// Data
private String m_localDirectory;
private List<FileInfo> m_files = new List<FileInfo>();
private Int64 m_totalSize;
private string p;
private int p_2;
private string p_3;
private string p_4;
private string p_5;
private int p_6;
private int p_7;

#endregion

#region Constructors
public FileDownloader()
{
this.initizalize(false);
}

public FileDownloader(Boolean supportsProgress)
{
this.initizalize(supportsProgress);
}

public FileDownloader(string p, int p_2, string p_3, string p_4, string p_5, int p_6, int p_7)
{
// TODO: Complete member initialization
this.p = p;
this.p_2 = p_2;
this.p_3 = p_3;
this.p_4 = p_4;
this.p_5 = p_5;
this.p_6 = p_6;
this.p_7 = p_7;
}

private void initizalize(Boolean supportsProgress)
{
// Set the bgw properties
bgwDownloader.WorkerReportsProgress = true;
bgwDownloader.WorkerSupportsCancellation = true;
bgwDownloader.DoWork += new DoWorkEventHandler(bgwDownloader_DoWork);
bgwDownloader.RunWorkerCompleted += new RunWorkerCompletedEventHandler(bgwDownloader_RunWorkerCompleted);
bgwDownloader.ProgressChanged += new ProgressChangedEventHandler(bgwDownloader_ProgressChanged);

// Set the default class preferences
this.SupportsProgress = supportsProgress;
this.PackageSize = 4096;
this.StopWatchCyclesAmount = 5;
this.DeleteCompletedFilesAfterCancel = true;
}
#endregion

#region Public methods
public void Start() { this.IsBusy = true; }

public void Pause() { this.IsPaused = true; }

public void Resume() { this.IsPaused = false; }

public void Stop() { this.IsBusy = false; }
public void Stop(Boolean deleteCompletedFiles)
{
this.DeleteCompletedFilesAfterCancel = deleteCompletedFiles;
this.Stop();
}

public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}

#region Size formatting functions
public static string FormatSizeBinary(Int64 size)
{
return FileDownloader.FormatSizeBinary(size, default_decimals);
}

public static string FormatSizeBinary(Int64 size, Int32 decimals)
{
// By De Dauw Jeroen - April 2009 - [email protected]
String[] sizes = { "B", "KiB", "MiB", "GiB", "TiB", "PiB", "EiB", "ZiB", "YiB" };
Double formattedSize = size;
Int32 sizeIndex = 0;
while (formattedSize >= 1024 && sizeIndex < sizes.Length)
{
formattedSize /= 1024;
sizeIndex += 1;
}
return Math.Round(formattedSize, decimals) + sizes[sizeIndex];
}

public static string FormatSizeDecimal(Int64 size)
{
return FileDownloader.FormatSizeDecimal(size, default_decimals);
}

public static string FormatSizeDecimal(Int64 size, Int32 decimals)
{
// By De Dauw Jeroen - April 2009 - [email protected]
String[] sizes = { "B", "kB", "MB", "GB", "TB", "PB", "EB", "ZB", "YB" };
Double formattedSize = size;
Int32 sizeIndex = 0;
while (formattedSize >= 1000 && sizeIndex < sizes.Length)
{
formattedSize /= 1000;
sizeIndex += 1;
}
return Math.Round(formattedSize, decimals) + sizes[sizeIndex];
}
#endregion

#endregion

#region Protected methods
protected virtual void Dispose(Boolean disposing)
{
if (!m_disposed)
{
if (disposing)
{
// Free other state (managed objects)
bgwDownloader.Dispose();
}
// Free your own state (unmanaged objects)
// Set large fields to null
this.Files = null;
}
}
#endregion

#region Private methods
private void bgwDownloader_DoWork(object sender, DoWorkEventArgs e)
{
Int32 fileNr = 0;

if (this.SupportsProgress) { calculateFilesSize(); }

if (!Directory.Exists(this.LocalDirectory)) { Directory.CreateDirectory(this.LocalDirectory); }

while (fileNr < this.Files.Count && !bgwDownloader.CancellationPending)
{
m_fileNr = fileNr;
downloadFile(fileNr);

if (bgwDownloader.CancellationPending)
{
fireEventFromBgw(Event.DeletingFilesAfterCancel);
cleanUpFiles(this.DeleteCompletedFilesAfterCancel ? 0 : m_fileNr, this.DeleteCompletedFilesAfterCancel ? m_fileNr + 1 : 1);
}
else
{
fileNr += 1;
}
}
}

private void calculateFilesSize()
{
fireEventFromBgw(Event.CalculationFileSizesStarted);
m_totalSize = 0;

for (Int32 fileNr = 0; fileNr < this.Files.Count; fileNr++)
{
bgwDownloader.ReportProgress((Int32)InvokeType.CalculatingFileNrRaiser, fileNr + 1);
try
{
HttpWebRequest webReq = (HttpWebRequest)WebRequest.Create(this.Files[fileNr].Path);
HttpWebResponse webResp = (HttpWebResponse)webReq.GetResponse();
m_totalSize += webResp.ContentLength;
webResp.Close();
}
catch (Exception) { }
}
fireEventFromBgw(Event.FileSizesCalculationComplete);
}

private void fireEventFromBgw(Event eventName)
{
bgwDownloader.ReportProgress((int)InvokeType.EventRaiser, eventName);
}

private void downloadFile(Int32 fileNr)
{
m_currentFileSize = 0;
fireEventFromBgw(Event.FileDownloadAttempting);

FileInfo file = this.Files[fileNr];
Int64 size = 0;

Byte[] readBytes = new Byte[this.PackageSize];
Int32 currentPackageSize;
System.Diagnostics.Stopwatch speedTimer = new System.Diagnostics.Stopwatch();
Int32 readings = 0;
Exception exc = null;

FileStream writer = new FileStream(this.LocalDirectory + "\\" + file.Name, System.IO.FileMode.Create);

HttpWebRequest webReq;
HttpWebResponse webResp = null;

try
{
webReq = (HttpWebRequest)System.Net.WebRequest.Create(this.Files[fileNr].Path);
webResp = (HttpWebResponse)webReq.GetResponse();

size = webResp.ContentLength;
}
catch (Exception ex) { exc = ex; }

m_currentFileSize = size;
fireEventFromBgw(Event.FileDownloadStarted);

if (exc != null)
{
bgwDownloader.ReportProgress((Int32)InvokeType.FileDownloadFailedRaiser, exc);
}
else
{
m_currentFileProgress = 0;
while (m_currentFileProgress < size && !bgwDownloader.CancellationPending)
{
while (this.IsPaused) { System.Threading.Thread.Sleep(100); }

speedTimer.Start();

currentPackageSize = webResp.GetResponseStream().Read(readBytes, 0, this.PackageSize);

m_currentFileProgress += currentPackageSize;
m_totalProgress += currentPackageSize;
fireEventFromBgw(Event.ProgressChanged);

writer.Write(readBytes, 0, currentPackageSize);
readings += 1;

if (readings >= this.StopWatchCyclesAmount)
{
m_currentSpeed = (Int32)(this.PackageSize * StopWatchCyclesAmount * 1000 / (speedTimer.ElapsedMilliseconds + 1));
speedTimer.Reset();
readings = 0;
}
}

speedTimer.Stop();
writer.Close();
webResp.Close();
if (!bgwDownloader.CancellationPending) { fireEventFromBgw(Event.FileDownloadSucceeded); }
}
fireEventFromBgw(Event.FileDownloadStopped);
}

private void cleanUpFiles(Int32 start, Int32 length)
{
Int32 last = length < 0 ? this.Files.Count -1 : start + length - 1;

for (Int32 fileNr = start; fileNr <= last; fileNr++)
{
String fullPath = this.LocalDirectory + "\\" + this.Files[fileNr].Name;
if (System.IO.File.Exists(fullPath)) { System.IO.File.Delete(fullPath); }
}
}

private void bgwDownloader_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
m_paused = false;
m_busy = false;

if (this.HasBeenCanceled)
{
if (Canceled != null) { this.Canceled(this, new EventArgs()); }
}
else
{
if (Completed != null) { this.Completed(this, new EventArgs()); }
}

if (Stopped != null) { this.Stopped(this, new EventArgs()); }
if (IsBusyChanged != null) { this.IsBusyChanged(this, new EventArgs()); }
if (StateChanged != null) { this.StateChanged(this, new EventArgs()); }
}

private void bgwDownloader_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
switch ((InvokeType)e.ProgressPercentage)
{
case InvokeType.EventRaiser:
switch ((Event)e.UserState)
{
case Event.CalculationFileSizesStarted:
if (CalculationFileSizesStarted != null) { this.CalculationFileSizesStarted(this, new EventArgs()); }
break;
case Event.FileSizesCalculationComplete:
if (FileSizesCalculationComplete != null) { this.FileSizesCalculationComplete(this, new EventArgs()); }
break;
case Event.DeletingFilesAfterCancel:
if (DeletingFilesAfterCancel != null) { this.DeletingFilesAfterCancel(this, new EventArgs()); }
break;

case Event.FileDownloadAttempting:
if (FileDownloadAttempting != null) { this.FileDownloadAttempting(this, new EventArgs()); }
break;
case Event.FileDownloadStarted:
if (FileDownloadStarted != null) { this.FileDownloadStarted(this, new EventArgs()); }
break;
case Event.FileDownloadStopped:
if (FileDownloadStopped != null) { this.FileDownloadStopped(this, new EventArgs()); }
break;
case Event.FileDownloadSucceeded:
if (FileDownloadSucceeded != null) { this.FileDownloadSucceeded(this, new EventArgs()); }
break;
case Event.ProgressChanged:
if (ProgressChanged != null) { this.ProgressChanged(this, new EventArgs()); }
break;
}
break;
case InvokeType.FileDownloadFailedRaiser:
if (FileDownloadFailed != null) { this.FileDownloadFailed(this, (Exception)e.UserState); }
break;
case InvokeType.CalculatingFileNrRaiser:
if (CalculatingFileSize != null) { this.CalculatingFileSize(this, (Int32)e.UserState); }
break;
}
}
#endregion

#region Properties
public List<FileInfo> Files
{
get { return m_files; }
set
{
if (this.IsBusy)
{
throw new InvalidOperationException("You can not change the file list during the download");
}
else
{
if (this.Files != null) m_files = value;
}
}
}

public String LocalDirectory
{
get { return m_localDirectory; }
set
{
if (this.LocalDirectory != value) { m_localDirectory = value; }
}
}

public Boolean SupportsProgress
{
get { return m_supportsProgress; }
set
{
if (this.IsBusy)
{
throw new InvalidOperationException("You can not change the SupportsProgress property during the download");
}
else
{
m_supportsProgress = value;
}
}
}

public Boolean DeleteCompletedFilesAfterCancel
{
get { return m_deleteCompletedFiles; }
set { m_deleteCompletedFiles = value; }
}

public Int32 PackageSize
{
get { return m_packageSize; }
set
{
if (value > 0)
{
m_packageSize = value;
}
else
{
throw new InvalidOperationException("The PackageSize needs to be greather then 0");
}
}
}

public Int32 StopWatchCyclesAmount
{
get { return m_stopWatchCycles; }
set
{
if (value > 0)
{
m_stopWatchCycles = value;
}
else
{
throw new InvalidOperationException("The StopWatchCyclesAmount needs to be greather then 0");
}
}
}

public Boolean IsBusy
{
get { return m_busy; }
set
{
if (this.IsBusy != value)
{
m_busy = value;
m_canceled = !value;
if (this.IsBusy)
{
m_totalProgress = 0;
bgwDownloader.RunWorkerAsync();

if (Started != null) { this.Started(this, new EventArgs()); }
if (IsBusyChanged != null) { this.IsBusyChanged(this, new EventArgs()); }
if (StateChanged != null) { this.StateChanged(this, new EventArgs()); }
}
else
{
m_paused = false;
bgwDownloader.CancelAsync();
if (CancelRequested != null) { this.CancelRequested(this, new EventArgs()); }
if (StateChanged != null) { this.StateChanged(this, new EventArgs()); }
}
}
}
}

public Boolean IsPaused
{
get { return m_paused; }
set
{
if (this.IsBusy)
{
if (this.IsPaused != value)
{
m_paused = value;
if (this.IsPaused)
{
if (Paused != null) { this.Paused(this, new EventArgs()); }
}
else
{
if (Resumed != null) { this.Resumed(this, new EventArgs()); }
}
if (IsPausedChanged != null) { this.IsPausedChanged(this, new EventArgs()); }
if (StateChanged != null) { this.StateChanged(this, new EventArgs()); }
}
}
else
{
throw new InvalidOperationException("You can not change the IsPaused property when the FileDownloader is not busy");
}
}
}

public Boolean CanStart
{
get { return !this.IsBusy; }
}

public Boolean CanPause
{
get { return this.IsBusy && !this.IsPaused && !bgwDownloader.CancellationPending; }
}

public Boolean CanResume
{
get { return this.IsBusy && this.IsPaused && !bgwDownloader.CancellationPending; }
}

/// <summary>Gets if the FileDownloader can stop</summary>
public Boolean CanStop
{
get { return this.IsBusy && !bgwDownloader.CancellationPending; }
}

/// <summary>Gets the total size of all files together. Only avaible when the FileDownloader suports progress</summary>
public Int64 TotalSize
{
get
{
if (this.SupportsProgress)
{
return m_totalSize;
}
else
{
throw new InvalidOperationException("This FileDownloader that it doesn't support progress. Modify SupportsProgress to state that it does support progress to get the total size.");
}
}
}

/// <summary>Gets the total amount of bytes downloaded</summary>
public Int64 TotalProgress
{
get { return m_totalProgress; }
}

/// <summary>Gets the amount of bytes downloaded of the current file</summary>
public Int64 CurrentFileProgress
{
get { return m_currentFileProgress; }
}

/// <summary>Gets the total download percentage. Only avaible when the FileDownloader suports progress</summary>
public Double TotalPercentage()
{
return this.TotalPercentage(default_decimals);
}

/// <summary>Gets the total download percentage. Only avaible when the FileDownloader suports progress</summary>
public Double TotalPercentage(Int32 decimals)
{
if (this.SupportsProgress)
{
return Math.Round((Double)this.TotalProgress / this.TotalSize * 100, decimals);
}
else
{
throw new InvalidOperationException("This FileDownloader that it doesn't support progress. Modify SupportsProgress to state that it does support progress.");
}
}

/// <summary>Gets the percentage of the current file progress</summary>
public Double CurrentFilePercentage()
{
return this.CurrentFilePercentage(default_decimals);
}

/// <summary>Gets the percentage of the current file progress</summary>
public Double CurrentFilePercentage(Int32 decimals)
{
return Math.Round((Double)this.CurrentFileProgress / this.CurrentFileSize * 100, decimals);
}

/// <summary>Gets the current download speed in bytes</summary>
public Int32 DownloadSpeed
{
get { return m_currentSpeed; }
}

/// <summary>Gets the FileInfo object representing the current file</summary>
public FileInfo CurrentFile
{
get { return this.Files[m_fileNr]; }
}

/// <summary>Gets the size of the current file in bytes</summary>
public Int64 CurrentFileSize
{
get { return m_currentFileSize; }
}

/// <summary>Gets if the last download was canceled by the user</summary>
public Boolean HasBeenCanceled
{
get { return m_canceled; }
}
#endregion

}
}
#endregion

questo è il sorgente del downloader e questo file è chiamato FileDownloader.cs
e qui all'interno di questo file dovrei aggiungere anche la licenza ma non ho idea di come.
avevo pensato di fare una cosa del genere prendendo il sorgente da un'altro programma ma ci sono alcuni problemi.

register.php per la connessione

//registro l'utente
$nomehost = "127.0.0.1";
$nomeuser = "root";
$password = "TUAPASSWORDDATABASE";
$dbname="TUODATABASE";



database per registrare un utente

-- phpMyAdmin SQL Dump
-- version 3.1.3.1
-- http://www.phpmyadmin.net
--
-- Host: localhost
-- Generato il: 02 mag, 2010 at 12:20 PM
-- Versione MySQL: 5.1.33
-- Versione PHP: 5.2.9

SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO";

--
-- Database: `holo_37`
--

-- --------------------------------------------------------

--
-- Struttura della tabella `licenza`
--

CREATE TABLE IF NOT EXISTS `licenza` (
`username` varchar(100) NOT NULL,
`nome_hotel` varchar(200) NOT NULL,
`email` varchar(200) NOT NULL,
`password` varchar(200) NOT NULL,
`licenza` varchar(200) NOT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

--
-- Dump dei dati per la tabella `licenza`
--




public static void Writelicenza(string logText)
{
wait();
bwait = true;
Console.ForegroundColor = ConsoleColor.Cyan ;
Console.Write("- ");
Console.WriteLine(logText);
bwait = false;
}



public static DatabaseManager dblicenza;
private static string _hotel;
private static string __email;
private static string _licenza;


private static bool check()
{

string iniLocation = IO.workingDirectory + @"\Config\Account.ini";
if (!File.Exists(iniLocation ))
{
Out.WriteError("Il file Acccount.ini non è presente in " + iniLocation );
Shutdown();
}
string str2 = IO.readINI("account", "nomeutente", iniLocation);
string str3 = IO.readINI("account", "password", iniLocation);
Out.Writelicenza("Licenza Created By Max090");
Out.Writelicenza ("Avvio controllo per " + str2 + " con la seguente password " + str3);
dblicenza = new DatabaseManager("TUOHOST", 3306, "TUOUSER", "TUAPASSWORD", "TUODATABASE", 1, 100);
Out.Writelicenza("Connessione al database... in attesa di autenticazione...");
dblicenza.SetClientAmount(dbMaxConnections);
DatabaseClient client = Eucalypt.dblicenza.GetClient();

bool query = client.findsResult("Select * from licenza where username = '" + str2 + "' and password = '" + str3 + "'");

if (query)
{
Out.Writelicenza("Carico le informazzioni....");
_hotel = client.getString ("Select nome_hotel from licenza where username = '" + str2+"'") ;
Out.Writelicenza("");
Out.Writelicenza("");
Out.Writelicenza("");
Out.Writelicenza ("Nome Hotel " + _hotel );
Out.Writelicenza("");
Out.Writelicenza("");
Out.Writelicenza("");
__email = client.getString("Select email from licenza where username = '" + str2 + "'");
Out.Writelicenza("");
Out.Writelicenza("");
Out.Writelicenza("");
Out.Writelicenza("Email Utilizzata " + __email);
Out.Writelicenza("");
Out.Writelicenza("");
Out.Writelicenza("");
_licenza = client.getString("Select licenza from licenza where username = '" + str2 + "'");
Out.Writelicenza ("");
Out.Writelicenza("");
Out.Writelicenza("");
Out.Writelicenza("LA TUA LICENZA E' " + _licenza );
Out.Writelicenza("");
Out.Writelicenza("");
Out.Writelicenza("");
Out.Writelicenza("Nome utente e licenza autenticati con successo");
Out.Writelicenza("BENVENUTO " + str2);
return true;

}
else

return false;

}


se avete altre idee o cosa c'è di sbagliato in questi sorgenti che non mi va fatemi sapere grazie :D

kulosia
01-02-2011, 12:25
up.

kulosia
02-02-2011, 23:09
up.

kulosia
03-02-2011, 18:35
up.

kulosia
04-02-2011, 23:39
un aiutino per favore