2025-06-03 15:11:16 +02:00

1772 lines
56 KiB
C#

using System;
using System.Data;
using System.Data.OracleClient;
using System.Data.Common;
using System.Collections.Generic;
using Microsoft.Practices.EnterpriseLibrary.Data;
using Microsoft.Practices.EnterpriseLibrary.Data.Oracle;
using Microsoft.Practices.EnterpriseLibrary.Data.Sql;
using System.Data.SqlClient;
using NLog;
using DataAccessLayer;
using System.Globalization;
using System.Linq;
using System.Collections.Concurrent;
using System.Configuration;
using System.IO;
using System.Net;
using System.Dynamic;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Diagnostics;
using System.Threading;
using System.Drawing.Imaging;
using System.Drawing;
using System.Text;
using System.Security.Cryptography;
using ceTe.DynamicPDF.PageElements;
using System.ComponentModel;
namespace NLog
{
#pragma warning disable CS0168
public static class NLogEx
{
public static void WriteToConsole(this Logger logger, string msg)
{
try
{
if (msg != null && msg.Trim() != string.Empty)
Console.WriteLine(msg);
}
catch (Exception ex2)
{
}
}
public static void Infos(this Logger logger, string msg)
{
if (!CACHE.OnlyError)
{
try
{
//var s = Pre();
if (msg != null && msg.Trim() != string.Empty)
{
//if (CACHE.LANCIO != "") msg = CACHE.LANCIO + "|" + msg;
logger.Info(msg);
}
}
catch (Exception ex1)
{
}
}
}
public static void Errors(this Logger logger, Exception ex)
{
try
{
//var s = Pre();
if (ex != null)
{
//string msg = ex.Message;
//if (CACHE.LANCIO != "") msg = CACHE.LANCIO + "|" + msg;
logger.Error(ex.Message + "|" + ex.StackTrace);
}
}
catch (Exception ex1)
{
}
}
public static void Errors(this Logger logger, string msg)
{
try
{
//var s = Pre();
if (msg != null && msg.Trim().Length > 0)
{
//if (CACHE.LANCIO != "") msg = CACHE.LANCIO + "|" + msg;
logger.Error(msg);
}
}
catch (Exception ex1)
{
}
}
public static void Debugs(this Logger logger, string msg)
{
if (!CACHE.OnlyError)
{
try
{
//var s = Pre();
if (msg != null && msg.Trim() != string.Empty)
{
//if (CACHE.LANCIO != "") msg = CACHE.LANCIO + "|" + msg;
logger.Debug(msg);
}
}
catch (Exception ex1)
{
}
}
}
public static void Traces(this Logger logger, string msg)
{
if (!CACHE.OnlyError)
{
try
{
//var s = Pre();
if (msg != null && msg.Trim() != string.Empty)
{
//if (CACHE.LANCIO != "") msg = CACHE.LANCIO + "|" + msg;
logger.Trace(msg);
}
}
catch (Exception ex1)
{
}
}
}
private static string Pre()
{
string ret = string.Empty;
//var a1 = Assembly.GetCallingAssembly();
//var a2 = Assembly.GetExecutingAssembly();
var a3 = Assembly.GetEntryAssembly();
//ret += a3.GetName().Name;
var expt = a3.GetExportedTypes();
if (expt != null && expt.Length > 0)
{
var st1 = expt[0].FullName;
ret += st1;
StackTrace st = new StackTrace(true);
var st2 = st.GetFrames();
int l = (st2!=null ? st2.Length : 0);
StackFrame mx = null;
if (l>0)
{
mx = st.GetFrame(l - 1);
MethodBase ml = mx.GetMethod();
ret += "." + ml.Name;
ret += "(" + mx.GetFileLineNumber() + ")";
}
//MethodBase m = st.GetFrame(1).GetMethod();
//var clc = m.DeclaringType.FullName;
}
return ret;
}
}
}
namespace System
{
#pragma warning disable CS0168
public struct StructColor
{
private Int16 _red;
private Int16 _blue;
private Int16 _green;
private string _tipo;
private string _codice;
private string _descrizione;
// Red
public Int16 Red
{
get { return _red; }
set { _red = value; }
}
// Green
public Int16 Green
{
get { return _green; }
set { _green = value; }
}
// Blue
public Int16 Blue
{
get { return _blue; }
set { _blue = value; }
}
// Tipo
public string Tipo
{
get { return _tipo; }
set { _tipo = value; }
}
// Codice
public string Codice
{
get { return _codice; }
set { _codice = value; }
}
// Descrizione
public string Descrizione
{
get { return _descrizione; }
set { _descrizione = value; }
}
}
public enum TipoContratto:Int32
{
[Category("Sei")]
[Description("Old")]
Old = 0,
[Category("Sei")]
[Description("Affluent")]
Affluent = 1,
[Category("Sei")]
[Description("Private")]
Private = 2,
[Category("DA")]
[Description("Dadvisory")]
Dadvisory = 3
}
/// <summary>
/// Enumeratore del tipo di Report.
/// </summary>
public enum TipologiaReport
{
DIAGNOSI,
PROPOSTA,
PIANIFICAZIONE,
MONITORAGGIO
}
public class ReportTipo
{
#region private member
private int _idReport;
private int _idModello;
private string _descrizione;
private TipologiaReport _tipoReport;
#endregion
#region public member
public int IdReport
{
get { return _idReport; }
set { _idReport = value; }
}
public int IdModello
{
get { return _idModello; }
set { _idModello = value; }
}
public string Descrizione
{
get { return _descrizione; }
set { _descrizione = value; }
}
public TipologiaReport TipoReport
{
get { return _tipoReport; }
set { _tipoReport = value; }
}
#endregion
public ReportTipo(int idReport, int idModello, string descrizione, TipologiaReport tipoReport)
{
_idReport = idReport;
_idModello = idModello;
_descrizione = descrizione;
_tipoReport = tipoReport;
}
public ReportTipo()
: this(-1, -1, "", TipologiaReport.DIAGNOSI)
{
}
}
public class DataThreadModel : ICloneable
{
#region private members
private string _rete;
private string _nomeRete;
private string _agente;
private string _cognomeAgente;
private string _nomeAgente;
private string _indirizzoAgente;
private string _capAgente;
private string _cittaAgente;
private string _telefonoAgente;
private string _codiceFiscale;
private string _cognomeCliente;
private string _nomeCliente;
private string _tipoReport;
private string _dataLotto;
private bool _profiloIsAct;
private string _intermediario;
private string _area;
private string _areaestesa;
private string _progetto;
private int _idReportPDFDiagnosi;
private int _idReportPDFMonitoraggio;
private decimal _patrimoniocomplessivototalectv;
private decimal _patrimoniofinanziarioctv;
private decimal _patrimoniobancafideuramctv;
private decimal _patrimoniobancafideuramctvalnettocontocorrente;
private decimal _patrimonioterzictv;
private decimal _patrimonioterzicontocorrente;
private decimal _patrimonioterzictvalnettocontocorrente;
private decimal _patrimonioimmobiliarectv;
private decimal _patrimonioaltroctv;
private decimal _contoCorrente;
private decimal _partiteviaggiantiinvestimento;
private decimal _partiteviaggiantidisinvestimento;
private decimal _patrimonioNonRappresentabileAI;
private decimal _patrimonioNonRappresentabileCompl;
private decimal _patrimonioNonRappresentabileFI;
private decimal _patrimonioNonRappresentabile;
private decimal _risorseNonAssociate;
private int _numeroIntermediari;
private bool adesioneSuccessivaAvanzato;
private bool generaDiagnosi;
private decimal _totaleS6;
private decimal _totaleS57;
private bool periodico;
private string _CodiceContratto;
private decimal _varrisorsenonassociate;
private decimal _coperturarisorsenonassociate;
private decimal _vartotalerisorsefinanziarie;
private decimal _coperturatotalerisorsefinanziarie;
private string _flgprof;
private decimal _totalNegativeCurrentAccountValue;
private decimal _totalSelfNegCurrentAccountValue;
private decimal _GPEligoFondi;
private decimal _GPEligoTitoli;
private decimal _GradoCoperturaMacroAssetInterno;
private decimal _GradoCoperturaMacroAssetTotale;
private decimal _GradoCoperturaMacroAssetAltri;
private string _codice;
private bool _HasProdottiAltaComplessita;
private DateTime _datafinetrimestrecorrente;
private DateTime _dataFineTrimestreCorrente_LetteraAccompagnamento;
//private List<Tuple<string, string, decimal>> _selfNegativeValue;
private string _ultimaSezioneStampata;
#endregion
public DataThreadModel()
{
Agente = "";
Area = "";
AreaEstesa = "";
CapAgente = "";
CittaAgente = "";
CodiceFiscale = "";
CognomeAgente = "";
CognomeCliente = "";
IndirizzoAgente = "";
Intermediario = "";
NomeAgente = "";
NomeCliente = "";
NomeRete = "";
Rete = "";
TelefonoAgente = "";
TipoReport = "";
VaRRisorseNonAssociate = 0;
CoperturaRisorseNonAssociate = 0;
PatrimonioTerziContoCorrente = 0;
IsAdequatezza = null;
IsSavingMap = false;
IsAPC103 = false;
}
#region public members
public int NumeroIntermediari
{
get { return _numeroIntermediari; }
set { _numeroIntermediari = value; }
}
/// <summary>
/// Imposta o recupera il controvalore totale delle risorse non associate.
/// </summary>
public decimal RisorseNonAssociate
{
get { return _risorseNonAssociate; }
set { _risorseNonAssociate = value; }
}
public decimal TotaleS57
{
get { return _totaleS57; }
set { _totaleS57 = value; }
}
public decimal TotaleS6
{
get { return _totaleS6; }
set { _totaleS6 = value; }
}
public bool HasProdottiAltaComplessita
{
get { return _HasProdottiAltaComplessita; }
set { _HasProdottiAltaComplessita = value; }
}
/// <summary>
/// Imposta o recupera un indicatore booleano che indica se va generato anche il report di DIAGNOSI per la fase2.
/// </summary>
public bool GeneraDiagnosi
{
get { return generaDiagnosi; }
set { generaDiagnosi = value; }
}
public string Flgprof
{
get { return _flgprof; }
set { _flgprof = value; }
}
/// <summary>
/// Imposta o recupera il nome del progetto d'investimento.
/// </summary>
public String Progetto
{
get { return _progetto; }
set { _progetto = value; }
}
public bool ProfiloIsAct
{
get { return _profiloIsAct; }
set { _profiloIsAct = value; }
}
/// <summary>
/// Imposta o recupera il controvalore del PatrimonioNonRappresentabile
/// </summary>
public decimal PatrimonioNonRappresentabileAI
{
get { return _patrimonioNonRappresentabileAI; }
set { _patrimonioNonRappresentabileAI = value; }
}
public decimal PatrimonioNonRappresentabileCompl
{
get { return _patrimonioNonRappresentabileCompl; }
set { _patrimonioNonRappresentabileCompl = value; }
}
public decimal PatrimonioNonRappresentabileFI
{
get { return _patrimonioNonRappresentabileFI; }
set { _patrimonioNonRappresentabileFI = value; }
}
/// <summary>
/// Imposta o recupera la somma delle Partite Viaggianti in investimento.
/// </summary>
public decimal PartiteViaggiantiInvestimento
{
get { return _partiteviaggiantiinvestimento; }
set { _partiteviaggiantiinvestimento = value; }
}
/// <summary>
/// Imposta o recupera la somma delle Partite Viaggianti in disinvestimento.
/// </summary>
public decimal PartiteViaggiantiDisinvestimento
{
get { return _partiteviaggiantidisinvestimento; }
set { _partiteviaggiantidisinvestimento = value; }
}
/// <summary>
/// Imposta o recupera il controvalore del Conto corrente.
/// </summary>
public decimal ContoCorrente
{
get { return _contoCorrente; }
set { _contoCorrente = value; }
}
public decimal Patrimonioaltroctv
{
get { return _patrimonioaltroctv; }
set { _patrimonioaltroctv = value; }
}
/// <summary>
/// Imposta o recupera il controvalore immobiliare totale.
/// </summary>
public decimal Patrimonioimmobiliarectv
{
get { return _patrimonioimmobiliarectv; }
set { _patrimonioimmobiliarectv = value; }
}
/// <summary>
/// Patrimonio terzi al netto del CC
/// </summary>
public decimal PatrimonioterzictvAlNettoContoCorrente
{
get { return _patrimonioterzictvalnettocontocorrente; }
set { _patrimonioterzictvalnettocontocorrente = value; }
}
/// <summary>
/// Imposta o recupera il controvalore totale detenuto presso istituti terzi.
/// </summary>
public decimal Patrimonioterzictv
{
get { return _patrimonioterzictv; }
set { _patrimonioterzictv = value; }
}
/// <summary>
/// Contocorrente altri istituti.
/// </summary>
public decimal PatrimonioTerziContoCorrente
{
get { return _patrimonioterzicontocorrente; }
set { _patrimonioterzicontocorrente = value; }
}
public bool AdesioneSuccessivaAvanzato
{
get { return adesioneSuccessivaAvanzato; }
set { adesioneSuccessivaAvanzato = value; }
}
/// <summary>
/// Imposta o recupera il controvalore totale del patrimonio detenuto presso BF o SPI
/// </summary>
public decimal Patrimoniobancafideuramctv
{
get { return _patrimoniobancafideuramctv; }
set { _patrimoniobancafideuramctv = value; }
}
/// <summary>
/// Patrimonio BF al netto del CC
/// </summary>
public decimal PatrimonioBancaFideuramCtvAlNettoContoCorrente
{
get { return _patrimoniobancafideuramctvalnettocontocorrente; }
set { _patrimoniobancafideuramctvalnettocontocorrente = value; }
}
/// <summary>
/// Imposta o recupera il controvalore del patrimonio finanziario
/// </summary>
public decimal Patrimoniofinanziarioctv
{
get { return _patrimoniofinanziarioctv; }
set { _patrimoniofinanziarioctv = value; }
}
/// <summary>
/// Imposta o recupera il controvalore del patrimonio complessivo
/// </summary>
public decimal Patrimoniocomplessivototalectv
{
get { return _patrimoniocomplessivototalectv; }
set { _patrimoniocomplessivototalectv = value; }
}
/// <summary>
/// Imposta o recupera la descrizione estesa dell'area di bisogno
/// </summary>
public string AreaEstesa
{
get { return _areaestesa; }
set { _areaestesa = value; }
}
/// <summary>
/// Imposta o recupera il codice di area di bisogno
/// </summary>
public string Area
{
get { return _area; }
set { _area = value; }
}
/// <summary>
/// Imposta o recupera il codice della rete
/// </summary>
public string Rete
{
get { return _rete; }
set { _rete = value; }
}
/// <summary>
/// Imposta o recupera la descrizione estesa della rete
/// </summary>
public string NomeRete
{
get { return _nomeRete; }
set { _nomeRete = value; }
}
/// <summary>
/// Imposta o recupera l'agente
/// </summary>
public string Agente
{
get { return _agente; }
set { _agente = value; }
}
public string Flagnqp { get; set; }
public string Flagprlrde { get; set; }
public int Flagpg { get; set; }
public int RiskArea { get; set; }
/// <summary>
/// Imposta o recupera il cognome dell'agente
/// </summary>
public string CognomeAgente
{
get { return _cognomeAgente; }
set { _cognomeAgente = value; }
}
/// <summary>
/// Imposta o recupera il nome dell'agente
/// </summary>
public string NomeAgente
{
get { return _nomeAgente; }
set { _nomeAgente = value; }
}
/// <summary>
/// Imposta o recupera l'indirizzo dell'agente
/// </summary>
public string IndirizzoAgente
{
get { return _indirizzoAgente; }
set { _indirizzoAgente = value; }
}
/// <summary>
/// Imposta o recupera il cap dell'agente
/// </summary>
public string CapAgente
{
get { return _capAgente; }
set { _capAgente = value; }
}
/// <summary>
/// Imposta o recupera la città dell'agente
/// </summary>
public string CittaAgente
{
get { return _cittaAgente; }
set { _cittaAgente = value; }
}
/// <summary>
/// Imposta o recupera la il telefono dell'agente
/// </summary>
public string TelefonoAgente
{
get { return _telefonoAgente; }
set { _telefonoAgente = value; }
}
public string CodiceFiscale
{
get { return _codiceFiscale; }
set { _codiceFiscale = value; }
}
/// <summary>
/// IdReport di Diagnosi del PdF generato su ReportManager
/// </summary>
public int IdReportPDFDiagnosi
{
get { return _idReportPDFDiagnosi; }
set { _idReportPDFDiagnosi = value; }
}
/// <summary>
/// IdReport di Monitoraggio del PdF generato su ReportManager
/// </summary>
public int IdReportPDFMonitoraggio
{
get { return _idReportPDFMonitoraggio; }
set { _idReportPDFMonitoraggio = value; }
}
/// <summary>
/// Imposta o recupera il cognome del cliente
/// </summary>
public string CognomeCliente
{
get { return _cognomeCliente; }
set { _cognomeCliente = value; }
}
/// <summary>
/// Imposta o recupera il nome del cliente
/// </summary>
public string NomeCliente
{
get { return _nomeCliente; }
set { _nomeCliente = value; }
}
/// <summary>
/// Imposta o recupera il tipo di report.
/// Attualemente si produzcono solo report per DIAGNOSI e MONITORAGGIO
/// </summary>
public string TipoReport
{
get { return _tipoReport; }
set { _tipoReport = value; }
}
//public TipoContratto _tipoContratto;
//public TipoContratto TipoContratto
//{
// get { return _tipoContratto; }
// set { _tipoContratto = value; }
//}
private bool _contrattoOld;
public bool ContrattoOld
{
get { return _contrattoOld; }
set { _contrattoOld = value; }
}
private bool _noMonitoraggio;
public bool NoMonitoraggio
{
get { return _noMonitoraggio; }
set { _noMonitoraggio = value; }
}
public string Intermediario
{
get { return _intermediario; }
set { _intermediario = value; }
}
public string CodiceContratto
{
get { return _CodiceContratto; }
set { _CodiceContratto = value; }
}
public bool Periodico
{
get { return periodico; }
set { periodico = value; }
}
public string NomeFilePdf
{
get
{
return TipoReport + "_" + CodiceFiscale + "_" + Rete;
}
}
public string NomeFileReport
{
get
{
DateTime data = DateTime.Now;
return String.Concat(CodiceContratto, "_", data.ToString("yyyyMMdd", CultureInfo.InvariantCulture));
}
}
public string DataLotto
{
set { _dataLotto = value; }
get
{
if (_dataLotto == string.Empty)
_dataLotto = DateTime.Now.ToString("yyyyMMdd", CultureInfo.InvariantCulture);
return _dataLotto;
}
}
public bool SavedMap { get; set; } = false;
public decimal VaRRisorseNonAssociate
{
get { return _varrisorsenonassociate; }
set { _varrisorsenonassociate = value; }
}
public decimal CoperturaRisorseNonAssociate
{
get { return _coperturarisorsenonassociate; }
set { _coperturarisorsenonassociate = value; }
}
public decimal VaRTotaleRisorseFinanziarie
{
get { return _vartotalerisorsefinanziarie; }
set { _vartotalerisorsefinanziarie = value; }
}
public decimal CoperturaTotaleRisorseFinanziarie
{
get { return _coperturatotalerisorsefinanziarie; }
set { _coperturatotalerisorsefinanziarie = value; }
}
public DateTime DataFineTrimestreCorrente
{
get { return _datafinetrimestrecorrente; }
set { _datafinetrimestrecorrente = value; }
}
public DateTime DataFineTrimestreCorrente_LetteraAccompagnamento
{
get { return _dataFineTrimestreCorrente_LetteraAccompagnamento; }
set { _dataFineTrimestreCorrente_LetteraAccompagnamento = value; }
}
public decimal TotalNegativeCurrentAccountValue
{
get { return _totalNegativeCurrentAccountValue; }
set { _totalNegativeCurrentAccountValue = value; }
}
public decimal TotalSelfNegCurrentAccountValue
{
get { return _totalSelfNegCurrentAccountValue; }
set { _totalSelfNegCurrentAccountValue = value; }
}
public string UltimaSezioneStampata
{
get { return _ultimaSezioneStampata; }
set { _ultimaSezioneStampata = value; }
}
public decimal GPEligoFondi
{
get { return _GPEligoFondi; }
set { _GPEligoFondi = value; }
}
public decimal GPEligoTitoli
{
get { return _GPEligoTitoli; }
set { _GPEligoTitoli = value; }
}
public decimal GradoCoperturaMacroAssetTotale
{
get { return _GradoCoperturaMacroAssetTotale; }
set { _GradoCoperturaMacroAssetTotale = value; }
}
public decimal GradoCoperturaMacroAssetAltri
{
get { return _GradoCoperturaMacroAssetAltri; }
set { _GradoCoperturaMacroAssetAltri = value; }
}
public decimal GradoCoperturaMacroAssetInterno
{
get { return _GradoCoperturaMacroAssetInterno; }
set { _GradoCoperturaMacroAssetInterno = value; }
}
public string codice
{
get { return _codice; }
set { _codice = value; }
}
public bool IsCompleted { get; set; } = false;
public DataTable DtDSS6Intermediari { get; set; }
public bool? IsAdequatezza { get; set; }
public bool IsSavingMap { get; set; }
public bool IsAPC103 { get; set; }
public int Scaduto { get; set; }
public int TotalePagine { get; set; }
public byte[] Stream { get; set; }
#endregion
#region ICloneable Members
public object Clone()
{
return this.MemberwiseClone();
}
public decimal PatrimonioNonRappresentabile { get => _patrimonioNonRappresentabile; set => _patrimonioNonRappresentabile = value; }
public bool IsProfessionalClient
{
get
{
try
{
return (this.Flgprof == "S");
}
catch
{
return false;
}
}
}
#endregion
}
public class DataTemplate
{
public string rete { get; set; }
public int contracttype { get; set; }
public int reporttypefontcolor_r { get; set; }
public int reporttypefontcolor_g { get; set; }
public int reporttypefontcolor_b { get; set; }
public int chapterbackground_r { get; set; }
public int chapterbackground_g { get; set; }
public int chapterbackground_b { get; set; }
public int chapterfontcolor_r { get; set; }
public int chapterfontcolor_g { get; set; }
public int chapterfontcolor_b { get; set; }
public int tableheaderfontcolor_r { get; set; }
public int tableheaderfontcolor_g { get; set; }
public int tableheaderfontcolor_b { get; set; }
public string templatereportpath { get; set; }
public string templatecopertinapath { get; set; }
public string templateglossariopath { get; set; }
public string templatewelcomeletterpath { get; set; }
}
public class MinimalTrack
{
public string codicefiscale { get; set; }
public string rete { get; set; }
public string tipocontratto { get; set; }
public string SeiDa { get; set; }
}
public class RecuperoPDF
{
public string CodiceContratto { get; set; }
public string Rete { get; set; }
public string CodiceFiscale { get; set; }
public string NomeCliente { get; set; }
public string CognomeCliente { get; set; }
public string CodicePB { get; set; }
public string NomePB { get; set; }
public string CognomePB { get; set; }
public int numeroPagine { get; set; }
public byte[] Bytes { get; set; }
}
public static class SystemEx
{
public static List<T> ConvertToList<T>(this DataTable dt)
{
if (dt == null) return null;
const BindingFlags flags = BindingFlags.Public | BindingFlags.Instance;
var columnNames = dt.Columns.Cast<DataColumn>()
.Select(c => c.ColumnName)
.ToList();
var objectProperties = typeof(T).GetProperties(flags);
var listrows = dt.Rows.Cast<DataRow>();
var targetList = listrows.Select(dataRow =>
{
var instanceOfT = Activator.CreateInstance<T>();
foreach (var properties in objectProperties.Where(properties => columnNames.Contains(properties.Name) && dataRow[properties.Name] != DBNull.Value))
{
properties.SetValue(instanceOfT, dataRow[properties.Name], null);
}
return instanceOfT;
}).ToList();
return targetList;
}
[DllImport("Kernel32", EntryPoint = "GetCurrentThreadId", ExactSpelling = true)]
public static extern Int32 GetCurrentWin32ThreadId();
public static void SetThreadProcessorAffinity(this object th, int mId, int core, int cores) // params int[] cpus)
{
//https://www.codeproject.com/Articles/35679/Parallel-computing-and-processor-affinity-Never-un
if (mId > 0 && core < cores)
{
// Supports up to 64 processors
//double cpuMask = Math.Pow(2, logicalcpu);
//core = core ^ (1 << core);
long cpuMask = 0;
cpuMask |= 1L << core;
// Ensure managed thread is linked to OS thread; does nothing on default host in current .Net versions
Thread.BeginThreadAffinity();
// Find the ProcessThread for this thread.
var threads = Process.GetCurrentProcess().Threads.Cast<ProcessThread>();
ProcessThread thread = threads.Where(t => t.Id == mId).FirstOrDefault();
if (thread != null)
{
thread.ProcessorAffinity = new IntPtr(Convert.ToInt64(cpuMask));
thread.IdealProcessor = core;
}
Thread.EndThreadAffinity();
// Set the thread's processor affinity
}
}
public static int PageCount(this int elementscount, int pagesize)
{
return (int)Math.Ceiling((double)elementscount / pagesize);
}
public static string ToDBString(this object o)
{
if (!(o is System.DBNull) && (o != null))
return o.ToString();
else
return string.Empty;
}
public static uint ToUInt32(this object o, UInt32 defaultvalue = 0)
{
if (o == null) o = (object)defaultvalue;
try
{
Int32 io = Convert.ToInt32(o);
return (UInt32)(Math.Abs(io));
}
catch
{
return defaultvalue;
}
}
public static ulong ToUInt64(this object o, UInt64 defaultvalue = 0)
{
if (o == null) o = (object)defaultvalue;
try
{
Int64 io = Convert.ToInt64(o);
return (UInt64)(Math.Abs(io));
}
catch
{
return defaultvalue;
}
}
public static int ToInt32(this object o, int defaultvalue = 0)
{
if (o == null) o = (object)defaultvalue;
try
{
return Convert.ToInt32(o);
}
catch
{
return defaultvalue;
}
}
public static int ToByte(this object o, int defaultvalue = 0)
{
if (o == null) o = (object)defaultvalue;
try
{
return (Byte)(Convert.ToInt32(o) / 255);
}
catch
{
return defaultvalue;
}
}
public static int ToInt32(this string s, int defaultvalue = 0)
{
int ret = defaultvalue;
int.TryParse(s, out ret);
return ret;
}
public static double ToDouble(this string s, double defaultvalue = 0)
{
double ret = defaultvalue;
double.TryParse(s, out ret);
return ret;
}
public static string FilterNumericString(this string s, char[] ce)
{
string ret = string.Empty;
foreach (char c in s.ToCharArray())
{
int code = Convert.ToInt32(c);
if (code > 47 && code < 58)
ret += c;
foreach (char x in ce)
if ((char)code == x)
ret += (char)code;
}
return ret;
}
public static string FilterNumericString(this string s)
{
string ret = string.Empty;
foreach (char c in s.ToCharArray())
{
int code = Convert.ToInt32(c);
if (code > 47 && code < 58)
ret += c;
}
return ret;
}
public static int ToInt32b(this string s)
{
return s.FilterNumericString().ToInt32();
}
public static Int64 ToInt64b(this string s)
{
return s.FilterNumericString().ToInt64();
}
public static int uInt(this bool b)
{
if (b)
return 1;
else
return 0;
}
public static bool ToBool(this object o, bool defaultvalue = false)
{
bool ret = defaultvalue;
if (o != null)
try
{
ret = Convert.ToBoolean(o);
}
catch
{
ret = defaultvalue;
}
return ret;
}
public static Int64 ToInt64(this object o)
{
if (o == null) o = (object)0;
try
{
return Convert.ToInt64(o);
}
catch
{
return 0;
}
}
public static string TOString(this object o)
{
if (o == null) return "";
return o.ToString();
}
public static double ToDouble(this object o, double defaultvalue = 0)
{
if (o == null) o = (object)0;
try
{
return Convert.ToDouble(o);
}
catch
{
return defaultvalue;
}
}
public static decimal ToDecimal(this object o, decimal defaultvalue = 0)
{
if (o == null) o = (object)0;
try
{
return Convert.ToDecimal(o);
}
catch
{
return defaultvalue;
}
}
public static decimal ToDecimal(this double o)
{
return Convert.ToDecimal(o);
}
public static string LeftStr(this string value, int maxLength)
{
if (string.IsNullOrEmpty(value)) return value;
maxLength = Math.Abs(maxLength);
return (value.Length <= maxLength
? value
: value.Substring(0, maxLength)
);
}
public static string RightStr(this string value, int maxLength)
{
if (string.IsNullOrEmpty(value)) return value;
maxLength = Math.Abs(maxLength);
return (value.Length <= maxLength
? value
: value.Substring(value.Length - maxLength, maxLength)
);
}
public static string Serialize(this DataThreadModel model)
{
if (model == null) return string.Empty;
StringBuilder sb = new StringBuilder();
sb.Append("Agente" + "=" + model.Agente.TOString() + ";");
sb.Append("NomeAgente" + "=" + model.NomeAgente.TOString() + ";");
sb.Append("CognomeAgente" + "=" + model.CognomeAgente.TOString() + ";");
sb.Append("IndirizzoAgente" + "=" + model.IndirizzoAgente.TOString() + ";");
sb.Append("CittaAgente" + "=" + model.CittaAgente.TOString() + ";");
sb.Append("CapAgente" + "=" + model.CapAgente.TOString() + ";");
sb.Append("TelefonoAgente" + "=" + model.TelefonoAgente.TOString() + ";");
sb.Append("NomeCliente" + "=" + model.NomeCliente.TOString() + ";");
sb.Append("CognomeCliente" + "=" + model.CognomeCliente.TOString() + ";");
sb.Append("CodiceFiscale" + "=" + model.CodiceFiscale.TOString() + ";");
sb.Append("Rete" + "=" + model.Rete.TOString() + ";");
sb.Append("TipoReport" + "=" + model.TipoReport.TOString() + ";");
sb.Append("NomeRete" + "=" + model.NomeRete.TOString() + ";");
sb.Append("NomeFilePdf" + "=" + model.NomeFilePdf.TOString() + ";");
sb.Append("NomeFileReport" + "=" + model.NomeFileReport.TOString() + ";");
sb.Append("DataLotto" + "=" + model.DataLotto.TOString() + ";");
sb.Append("Intermediario" + "=" + model.Intermediario.TOString() + ";");
sb.Append("Scaduto" + "=" + model.Scaduto.TOString() + ";");
sb.Append("TotalePagine" + "=" + model.TotalePagine.TOString() + ";");
string ch = sb.ToString();
sb = null;
return ((new XDS(CACHE.PASSKEY)).Encrypt(ch));
}
public static IEnumerable<dynamic> ConvertToListT(this DataTable table)
{
if (table == null)
{
yield break;
}
foreach (DataRow row in table.Rows)
{
IDictionary<string, object> dRow = new ExpandoObject();
foreach (DataColumn column in table.Columns)
{
var value = row[column.ColumnName];
dRow[column.ColumnName] = Convert.IsDBNull(value) ? null : value;
}
yield return dRow;
}
}
public static string InCommand(this string[] args, string command)
{
string ret = string.Empty;
if (args != null && args.Length > 0)
{
foreach (var arg in args)
{
if (arg.Contains("="))
{
var valori = arg.Split('=');
if (valori.Length == 2)
{
if (valori[0].ToLower() == command.ToLower())
{
ret = valori[1];
break;
}
}
}
}
}
return ret;
}
public static List<T> GetPage<T>(this List<T> list, int page, int pagesize)
{
return list.Skip(page * pagesize).Take(pagesize).ToList();
}
public static string ChangeExtension(this string s, string newExtension)
{
if (newExtension.Length > 0)
{
return System.IO.Path.GetDirectoryName(s) + "\\" + System.IO.Path.GetFileNameWithoutExtension(s) + (newExtension.StartsWith(".") ? newExtension : (newExtension.Length > 0 ? "." : "") + newExtension);
}
else
{
return s;
}
}
public static class EnumHelper<T>
{
public static string GetEnumDescription(int valore)
{
// string levelexp = EnumHelper<LoggerLevel>.GetEnumDescription(l.ToInt32()).ToUpper();
Type type = typeof(T);
string value = Enum.GetName(type, valore);
var name = Enum.GetNames(type).Where(f => f.Equals(value, StringComparison.CurrentCultureIgnoreCase)).Select(d => d).FirstOrDefault();
if (name == null)
{
return string.Empty;
}
var field = type.GetField(name);
var customAttribute = field.GetCustomAttributes(typeof(DescriptionAttribute), false);
return customAttribute.Length > 0 ? ((DescriptionAttribute)customAttribute[0]).Description : name;
}
public static string GetEnumCategory(int valore)
{
// string levelexp = EnumHelper<LoggerLevel>.GetEnumCategory(l.ToInt32()).ToUpper();
Type type = typeof(T);
string value = Enum.GetName(type, valore);
var name = Enum.GetNames(type).Where(f => f.Equals(value, StringComparison.CurrentCultureIgnoreCase)).Select(d => d).FirstOrDefault();
if (name == null)
{
return string.Empty;
}
var field = type.GetField(name);
var customAttribute = field.GetCustomAttributes(typeof(CategoryAttribute), false);
return customAttribute.Length > 0 ? ((CategoryAttribute)customAttribute[0]).Category : name;
}
}
}
public class KeyValue
{
public string key { get; set; }
public string value { get; set; }
public KeyValue()
{
}
public KeyValue(string Key, string Value)
{
key = Key;
value = Value;
}
}
public class dIMAGES
{
public const string IMAGESFILE = "IMAGES";
private Dictionary<string, System.IO.Stream> images = null;// new Dictionary<string, System.IO.Stream>();
public string FileImages { get; set; }
private string _defaultpath = System.IO.Path.Combine(Environment.CurrentDirectory, IMAGESFILE);
public dIMAGES()
{
if (File.Exists(_defaultpath))
{
FileImages = _defaultpath;
Read();
}
}
private void Read()
{
images = FileImages.ConvertToDictionary();
}
public System.IO.Stream Get(string key)
{
key = key.ToLower();
//key = key.Replace(".png", "");
try
{
return images[key];
}
catch (Exception ex)
{
return null;
}
}
}
public static class UtilityManager
{
public static string getAppSetting(string chiave)
{
if (ConfigurationManager.AppSettings[chiave] != null)
return ConfigurationManager.AppSettings[chiave];
return String.Empty;
}
}
}
namespace System.Drawing
{
public static class ImageExtender
{
public static string ImagePathToBase64(this string path, System.Drawing.Imaging.ImageFormat format)
{
var imagedata = File.ReadAllBytes(path);
var ms = new MemoryStream(imagedata);
System.Drawing.Image image = Image.FromStream(ms);
return image.ImageToBase64(format);
}
public static string ImageToBase64(this Image image, System.Drawing.Imaging.ImageFormat format)
{//Questo è il sistema corretto per trasformare una image passando da bitmap altrimenti si ha l'errore GDI+
using (var ms = new MemoryStream())
{
Bitmap bmp = new Bitmap(image);
bmp.Save(ms, format);
string base64String = Convert.ToBase64String(ms.ToArray());
return base64String;
}
}
public static Stream ImageToStream(this Image img, System.Drawing.Imaging.ImageFormat format)
{
var ms = new MemoryStream();
img.Save(ms, format);
return ms;
}
public static string Base64ToString(this string base64EncodedData)
{
var base64EncodedBytes = System.Convert.FromBase64String(base64EncodedData);
return System.Text.Encoding.UTF8.GetString(base64EncodedBytes);
}
public static string StringToBase64(this string plainText)
{
var plainTextBytes = System.Text.Encoding.UTF8.GetBytes(plainText);
return System.Convert.ToBase64String(plainTextBytes);
}
public static Image Base64ToImage(this string base64String)
{
try
{
byte[] imageBytes = Convert.FromBase64String(base64String);
// Convert byte[] to Image
using (var ms = new MemoryStream(imageBytes, 0, imageBytes.Length))
{
Image image = Image.FromStream(ms, true);
return image;
}
}
catch //(Exception ex)
{
return null;
}
}
public static string Image64(this object obj)
{
try
{
System.Drawing.Image bImg = obj as System.Drawing.Image;
System.Drawing.ImageConverter converter = new System.Drawing.ImageConverter();
return "data:image/png;base64, " + Convert.ToBase64String((byte[])converter.ConvertTo(bImg, typeof(byte[])));
}
catch //(Exception ex)
{
return string.Empty;
}
}
public static Dictionary<string, System.IO.Stream> ConvertToDictionary(this string filename)
{
Func<string, Imaging.ImageFormat> ifmt = f =>
{
Imaging.ImageFormat retf = Imaging.ImageFormat.Gif;
string extension = System.IO.Path.GetExtension(f);
switch (extension.ToLower())
{
case ".jpg":
case ".jpeg":
retf = Imaging.ImageFormat.Jpeg;
break;
case ".bmp":
retf = Imaging.ImageFormat.Bmp;
break;
case ".png":
retf = Imaging.ImageFormat.Png;
break;
default:
break;
}
return retf;
};
var list = File.ReadAllLines(filename).ToList().OrderBy(y => y);
var ret = list.Distinct().Select((a) => new { a }).ToDictionary(x => x.a.Split(';')[0], x => x.a.Split(';')[1].Base64ToImage().ImageToStream(ifmt(x.a.Split(';')[0])));
return ret;
}
}
}
namespace System.Security.Cryptography
{
/// <summary>
/// USO string c = (new XDS("passkey")).Encrypt("testo");
/// </summary>
public class XDS : IDisposable
{
#region IDisposable Support
private bool disposedValue = false; // To detect redundant calls
protected virtual void Dispose(bool disposing)
{
if (!disposedValue)
{
if (disposing)
{
// dispose managed state (managed objects).
}
// free unmanaged resources (unmanaged objects) and override a finalizer below.
// set large fields to null.
disposedValue = true;
}
}
// override a finalizer only if Dispose(bool disposing) above has code to free unmanaged resources.
// ~Xds() {
// // Do not change this code. Put cleanup code in Dispose(bool disposing) above.
// Dispose(false);
// }
// This code added to correctly implement the disposable pattern.
public void Dispose()
{
// Do not change this code. Put cleanup code in Dispose(bool disposing) above.
Dispose(true);
// uncomment the following line if the finalizer is overridden above.
// GC.SuppressFinalize(this);
}
#endregion
public XDS(string keY)
{
key = keY;
}
public string key { get; set; }
public string Encrypt(string toEncrypt, bool useHashing = true)
{
byte[] keyArray;
byte[] toEncryptArray = UTF8Encoding.UTF8.GetBytes(toEncrypt);
//System.Configuration.AppSettingsReader settingsReader =
// new AppSettingsReader();
// Get the key from config file
//string key = (string)settingsReader.GetValue("SecurityKey",
// typeof(String));
//System.Windows.Forms.MessageBox.Show(key);
//If hashing use get hashcode regards to your key
if (useHashing)
{
MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider();
keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(key));
//Always release the resources and flush data
// of the Cryptographic service provide. Best Practice
hashmd5.Clear();
}
else
keyArray = UTF8Encoding.UTF8.GetBytes(key);
TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();
//set the secret key for the tripleDES algorithm
tdes.Key = keyArray;
//mode of operation. there are other 4 modes.
//We choose ECB(Electronic code Book)
tdes.Mode = CipherMode.ECB;
//padding mode(if any extra byte added)
tdes.Padding = PaddingMode.PKCS7;
ICryptoTransform cTransform = tdes.CreateEncryptor();
//transform the specified region of bytes array to resultArray
byte[] resultArray =
cTransform.TransformFinalBlock(toEncryptArray, 0,
toEncryptArray.Length);
//Release resources held by TripleDes Encryptor
tdes.Clear();
//Return the encrypted data into unreadable string format
return Convert.ToBase64String(resultArray, 0, resultArray.Length);
}
public string Decrypt(string cipherString, bool useHashing = true)
{
byte[] toEncryptArray = Convert.FromBase64String(cipherString);
return InternalDecrypt(toEncryptArray, useHashing);
}
public string InternalDecrypt(byte[] toEncryptArray, bool useHashing = true)
{
byte[] keyArray;
if (useHashing)
{
//if hashing was used get the hash code with regards to your key
MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider();
keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(key));
//release any resource held by the MD5CryptoServiceProvider
hashmd5.Clear();
}
else
{
//if hashing was not implemented get the byte code of the key
keyArray = UTF8Encoding.UTF8.GetBytes(key);
}
TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();
//set the secret key for the tripleDES algorithm
tdes.Key = keyArray;
//mode of operation. there are other 4 modes.
//We choose ECB(Electronic code Book)
tdes.Mode = CipherMode.ECB;
//padding mode(if any extra byte added)
tdes.Padding = PaddingMode.PKCS7;
ICryptoTransform cTransform = tdes.CreateDecryptor();
byte[] resultArray = cTransform.TransformFinalBlock(
toEncryptArray, 0, toEncryptArray.Length);
//Release resources held by TripleDes Encryptor
tdes.Clear();
//return the Clear decrypted TEXT
return UTF8Encoding.UTF8.GetString(resultArray);
}
public void EncryptBitmap(string inputfile, string outputfile, bool useHashing = true)
{
byte[] toEncryptArray = File.ReadAllBytes(inputfile);
byte[] keyArray;
if (useHashing)
{
MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider();
keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(key));
hashmd5.Clear();
}
else
keyArray = UTF8Encoding.UTF8.GetBytes(key);
TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();
tdes.Key = keyArray;
tdes.Mode = CipherMode.ECB;
tdes.Padding = PaddingMode.PKCS7;
ICryptoTransform cTransform = tdes.CreateEncryptor();
byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
tdes.Clear();
File.WriteAllBytes(outputfile, resultArray);
}
private Bitmap ByteArrayToBitmap(byte[] source)
{
using (var ms = new MemoryStream(source))
{
return new Bitmap(ms);
}
}
public Bitmap DecryptBitmap(string inputfile, bool useHashing = true)
{
byte[] toEncryptArray = File.ReadAllBytes(inputfile);
byte[] keyArray;
if (useHashing)
{
MD5CryptoServiceProvider hashmd5 = new MD5CryptoServiceProvider();
keyArray = hashmd5.ComputeHash(UTF8Encoding.UTF8.GetBytes(key));
hashmd5.Clear();
}
else
keyArray = UTF8Encoding.UTF8.GetBytes(key);
TripleDESCryptoServiceProvider tdes = new TripleDESCryptoServiceProvider();
tdes.Key = keyArray;
tdes.Mode = CipherMode.ECB;
tdes.Padding = PaddingMode.PKCS7;
ICryptoTransform cTransform = tdes.CreateDecryptor();
byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
tdes.Clear();
return ByteArrayToBitmap(resultArray);
}
//private static readonly RNGCryptoServiceProvider _generator = new RNGCryptoServiceProvider();
public static int Random(int minimumValue, int maximumValue)
{
RNGCryptoServiceProvider _generator = new RNGCryptoServiceProvider();
byte[] randomNumber = new byte[1];
_generator.GetBytes(randomNumber);
double asciiValueOfRandomCharacter = Convert.ToDouble(randomNumber[0]);
// We are using Math.Max, and substracting 0.00000000001,
// to ensure "multiplier" will always be between 0.0 and .99999999999
// Otherwise, it's possible for it to be "1", which causes problems in our rounding.
double multiplier = Math.Max(0, (asciiValueOfRandomCharacter / 255d) - 0.00000000001d);
// We need to add one to the range, to allow for the rounding done with Math.Floor
int range = maximumValue - minimumValue + 1;
double randomValueInRange = Math.Floor(multiplier * range);
return (int)(minimumValue + randomValueInRange);
}
}
}