Archive

Posts Tagged ‘C#’

c#: Gestire un file di testo come risorsa

August 14th, 2010 Nicola No comments

Ecco un esempio di come creare in fase di sviluppo e di come leggere in fase di esecuzione un file di testo come risorsa all’interno dello stesso assembly.

Creare il Resources File:

- Creare un progetto di test con Visual Studio

- Impostare il nome dell’assembly ed il nome del namespace di default.

Assembly e Namespace di default

- Aggiungere al progetto un oggetto di tipo “Resources File”. Nel mio caso si chiama “license”

Oggetto di tipo Resources File

- Aggiungere al nuovo contenitore di risorse creato un nuovo file di testo. Nel mio esempio GPLlicense.txt

Text file in Resources File

Nel solution explorer compare il nuovo file (ed anche su filesystem).

New file in Solution Explorer

Leggere il file di testo dal Resources File a runtime

private void GetResourceFile(string nomeFile)
{
   try
   {
      System.Reflection.Assembly assembly;
      assembly = this.GetType().Assembly;
 
      ResourceManager resourceManager = 
                              new ResourceManager("Nicola.TestResources.license",
                                                              assembly);
 
      String s = resourceManager.GetString(nomeFile);
      Console.WriteLine(s.ToString());
   }
   catch (Exception e)
   {
      Console.WriteLine(e.Message);
   }
}

Il risultato:

Console output

Categories: C#, Programmazione Tags: ,

C# e Sql Server: sp_help_job, monitorare i job.

January 29th, 2010 Nicola No comments

In questo link mamma microsoft ci parla della store procedure sp_hel_job, utile per monitorare i job di sql server:

http://technet.microsoft.com/it-it/library/ms186722(SQL.90).aspx

Il metodo di esempio DammiElencoJob riportato sotto non fa altro che eseguire la query:

"exec [msdb].dbo.sp_help_job @enabled = 1"

per avere l’elenco di tutti i job attivi.


private String DammiElencoJob()
{

StringBuilder _sb = new StringBuilder();
DataTable _ds;

_ds = QueryDB.getRecordSQL(, ,, , "exec [msdb].dbo.sp_help_job @enabled = 1");

if (_ds.Rows.Count == 0)

{
_sb.Append("Errore: nessun job trovato.").Append(Environment.NewLine);
}
else
{
_sb.Append("NOME                                                               + "
" |ULTIMA    |ESITO").Append(Environment.NewLine);
foreach (DataRow r in _ds.Rows)
{
string _name =  ((string)r["name"]).PadRight(90);
_sb.Append(_name).Append("|");
DateTime dt = new DateTime((int)r["last_run_date"]);
string _last_run_date = ("" + dt.ToString("dd/MM/yyyy")).PadRight(10);
_sb.Append(_last_run_date).Append("|");
int _last_run_outcome = (int)r["last_run_outcome"];
switch (_last_run_outcome)
{
case 0:
_sb.Append("Non completato");
break;
case 1:
_sb.Append("Completato");
break;
case 3:
_sb.Append("Annullato");
break;
case 5:
_sb.Append("Stato sconosciuto");
break;
default:
_sb.Append("Stato sconosciuto");
break;
}
_sb.Append(Environment.NewLine);
}
}
_sb.Append(Environment.NewLine);
return _sb.ToString();

}


public static DataTable getRecordSQL(String datasource,String user, String password, String database, String sql)

{

String connStr;
OleDbConnection conn;
OleDbDataAdapter adattatore;
DataTable ds = new DataTable();

connStr = @"Provider = SQLOLEDB.1;Password=" + password + ";User ID=" + user + ";Initial Catalog=" + database + ";Data Source=" + datasource;

conn = new OleDbConnection(connStr);
adattatore = new OleDbDataAdapter();
adattatore.SelectCommand = new OleDbCommand(sql, conn);

try

{
adattatore.Fill(ds);
adattatore.Dispose();
conn.Dispose();
return ds;
}
catch (SqlException se)
{
return null;
}
catch (Exception ex)
{
return null;
}

}

Categories: C#, SQL Server Tags: , , ,

Dot Net: Naming Conventions

January 26th, 2010 Nicola 2 comments

Direttamente da mamma Microsoft: http://msdn.microsoft.com/en-us/library/ms229045.aspx, di cui questa pagina è una maccheronica traduzione:

I Nomi

  • Scegliete nomi di facile lettura. No, gli acronimi non sono di facile lettura.
  • Date preferenza alla leggibilità sulla brevità. Dalla versione 3.5 di .net mamma Microsoft non fa più pagare un tot a carattere.
  • Non usate “_”, “-” o altri caratteri non alfanumerici. Non andate sempre a complicare le cose, su.
  • Non usare la notazione Ungherese (es. txtApri, lblTitolo, ecc…). Non state mica programmando in Visual Basic 6, diamine.
  • Evitate di usare nomi che vanno in conflitto con le parole chiave del linguaggio che state usando. Tanto non ve lo fa fare.

Abbreviazioni e Acronimi

  • Non usare abbreviazioni o contrazioni delle parole. Non state scrivendo un sms.
  • Non usare acronimi a meno che questi non siano largamente riconosciuti (es. Xml, Http ecc…). Si, lo so che non volete che nessuno capisca il vostro codice come lo capite voi… vi capisco…

Nomi specifici di linguaggio

  • Se dovete riferirvi ad un tipo, utilizzate il suo common language runtime (CLR), e non la denominazione in un determinato linguaggio. Ad esempio, Int16 è int in c#, Integer in VB ecc… ma se un metodo si riferisce un Int16, metteteci Int16 nel nome, e non int o Integer.
  • Utilizzate nomi comuni (come “value” o “item”) dove non ci sia la necessità di dare un significato all’identificatore o il tipo nel parametro non sia importante (es. Il “value” utilizzato nei metodi Get e Set). Non so se Pippo o Pluto possano considerarsi nomi comuni però…

A dire la verità, cercavo un’altra cosa stasera, ma sono incappato in questa pagina…

Categories: Programmazione Tags: ,

c#: monitorare la Memoria di sistema

December 11th, 2009 Nicola No comments

Instanziamo la classe: System.Diagnostics.PerformanceCounterCategory sulla categoria “Memory”:

System.Diagnostics.PerformanceCounterCategory memoria = new

System.Diagnostics.PerformanceCounterCategory("Memory");

Questa categoria non contiene istanze in realtime da monitorare, quindi l’array restituito da

momeria.GetInstanceNames();

non contiene elementi.

Per avere l’elenco di tutti i counters appartenenti alla categoria è sufficiente il ciclo:

System.Diagnostics.PerformanceCounter[] counters = memoria.GetCounters();

for (int i = 0; i < counters.Length;i++)
{
Console.WriteLine("Performance counter: {0} = {1}", counters[i].CounterName, counters[i].NextValue());
}

Un esempio del risultato:

Performance counter: Page Faults/sec = 0
Performance counter: Available Bytes = 8,281293E+07
Performance counter: Committed Bytes = 7,408845E+08
Performance counter: Commit Limit = 1,716732E+09
Performance counter: Write Copies/sec = 0
Performance counter: Transition Faults/sec = 0
Performance counter: Cache Faults/sec = 0
Performance counter: Demand Zero Faults/sec = 0
Performance counter: Pages/sec = 0
Performance counter: Pages Input/sec = 0
Performance counter: Page Reads/sec = 0
Performance counter: Pages Output/sec = 0
Performance counter: Pool Paged Bytes = 8,963277E+07
Performance counter: Pool Nonpaged Bytes = 1,693696E+07
Performance counter: Page Writes/sec = 0
Performance counter: Pool Paged Allocs = 74229
Performance counter: Pool Nonpaged Allocs = 55166
Performance counter: Free System Page Table Entries = 185494
Performance counter: Cache Bytes = 3,138232E+08
Performance counter: Cache Bytes Peak = 3,642819E+08
Performance counter: Pool Paged Resident Bytes = 8,944026E+07
Performance counter: System Code Total Bytes = 1114112
Performance counter: System Code Resident Bytes = 1990656
Performance counter: System Driver Total Bytes = 8232960
Performance counter: System Driver Resident Bytes = 1163264
Performance counter: System Cache Resident Bytes = 2,212291E+08
Performance counter: % Committed Bytes In Use = 43,19485
Performance counter: Available KBytes = 80004
Performance counter: Available MBytes = 78

Se si vuole il valore di un unico counter si può utilizzare un’altro costruttore di PerformanceCounter (http://physicus.blogspot.com/2006/12/real-time-ram-usage-with-c.html):

PerformanceCounter pc = new PerformanceCounter("Memory", "Available Bytes");

Console.WriteLine("{0:0} Bytes available ({1:0} kB \t {2:0} MB)", byteCount, byteCount / 1024, byteCount / (1024 *

1024));

c# – Classe FileSystemWatcher

November 18th, 2009 Nicola No comments

Ecco un esempio di utilizzo. Talmente semplice che non necessita di grandi spiegazioni:


using System;
using System.IO;

namespace IlMioBelNamespace
{
/// <summary>
/// La mia bella classe che monitora quello che succede in una directory
/// </summary>
public class LaMiaBellaClasse
{
FileSystemWatcher watcher;

public void start()
{

/// Creo il nuovo oggetto FileSystemWatcher.
watcher = new FileSystemWatcher();

/// Posso filtrare dal nome del file o dalla sua estensione.
watcher.Filter = "*.txt";

/// Sottoscrivo l'evento Created
watcher.Created += new  FileSystemEventHandler(watcher_FileCreated);

/// Sottoscrivo l'evento Changed
watcher.Changed += new  FileSystemEventHandler(watcher_FileChanged);

/// Sottoscrivo l'evento Deleted
watcher.Deleted += new  FileSystemEventHandler(watcher_FileDelete);

/// Sottoscrivo l'evento Renamed
watcher.Renamed += new System.IO.RenamedEventHandler(watcher_FileRenamed);

/// Imposto il Path
watcher.Path = @"c:\incoming"

/// Si parte!
watcher.EnableRaisingEvents = true;

}

void watcher_FileCreated(object sender, FileSystemEventArgs e)
{

/// e' stato creato un file

}

void watcher_FileChanged(object sender, FileSystemEventArgs e)
{

/// è stato modificato un file

}

void watcher_FileDelete(object sender, FileSystemEventArgs e)
{

/// è stato cancellato un file

}

void watcher_FileRenamed(object sender, System.IO.RenamedEventArgs e)
{
/// è stato rinominato un file
}

}
}
}

Categories: C# Tags: ,