Login Login
MORE

WIDGETS

Widgets

Wanted articles
Who is online?
Article tools

Difference between revisions of "CSharp:Soluzioni varie"

From Aino Wiki

Jump to: navigation, search
(Esempio)
 
(No difference)

Latest revision as of 16:27, 30 September 2024

Contents

Clonare, copiare un oggetto

Duplica una Entità creando cioè una nuova copia della prima ma che ha una vita diversa. Il 'this' nel contratto del metodo serve a creare una estensione della classe da clonare.
Infine occorre aggiungere la Reference a "System.Runtime.Serialization".

        /// <summary>
        ///     Entities.Product product = ProductDAO.SelectByID(idProduct);
        ///     Entities.ProductproductOld = Clone(Entities.Product>(product);
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="source"></param>
        /// <returns></returns>
        public static T Clone<T>(this T source)
        {
            var dcs = new System.Runtime.Serialization.DataContractSerializer(typeof(T));
            using (var ms = new System.IO.MemoryStream())
            {
                dcs.WriteObject(ms, source);
                ms.Seek(0, System.IO.SeekOrigin.Begin);
                return (T)dcs.ReadObject(ms);
            }
        }

Operazioni dinamiche

Ottenere dinamicamente il metodo chiamato

using System.Diagnostics;
// Get call stack
StackTrace stackTrace = new StackTrace();
 
// Get calling method name
Console.WriteLine(stackTrace.GetFrame(1).GetMethod().Name);

Ottenere dinamicamente metodo chiamato da Exception

private static string GetCallerMethod(Exception ex)
{
    string methodName = string.Empty;
 
    try
    {
        StackTrace s = new StackTrace(ex);
        Assembly thisAssembly = Assembly.GetExecutingAssembly();
        methodName = s.GetFrames().Select(f => f.GetMethod()).First(m => m.Module.Assembly == thisAssembly).Name;
        methodName = string.Format("[{0}]", methodName);
    }
    catch 
    {
    }
    return methodName;
}

Ottenere dinamicamente proprietà di un oggetto

Metodo 1

Si ottiene prima l'elenco delle properties e dopo si potrà assegnare opportunamente i valori, da stackoverflow:
Type myType = myObject.GetType();
IList<PropertyInfo> props = new List<PropertyInfo>(myType.GetProperties());
 
foreach (PropertyInfo prop in props)
{
    object propValue = prop.GetValue(myObject, null);
 
    // Do something with propValue
}

Metodo 2

Da codeproject
Type myObjectType = typeof(MyObject);
 
System.Reflection.FieldInfo[] fieldInfo = myObjectType.GetFields();
 
foreach (System.Reflection.FieldInfo info in fieldInfo)
   Console.WriteLine(info.Name);

Soluzione 1, automatizzare popolamento oggetto

Caricamento di una entità\oggetto usando 2 dizionari, uno per i valori ed un'altro di mapping tra origine e destinazione.

       /// <summary>
        /// Riempie "automaticamente" un oggetto\entità con i valori usando un dizionario 
        /// per il mapping nome proprietà attributo dal server MDE (OPC UA)
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="dictMappingPropertyIndex">Dizionario (chiave, valore) contenente il mapping tra il nome della 
        /// Property dell'entità da restituire in output e il dizionario con i valori</param>
        /// <returns></returns>
        private static T FillOutputEntity<T>(Dictionary<string, string> dictMappingPropertyIndex,
                                             Dictionary<string, ObjectValueInfo> dictEntityProperties)
        {
            Type entityType = typeof(T);
            T entity = (T)entityType.Assembly.CreateInstance(entityType.FullName);
            string strPropertyType = string.Empty;
            string propertyIndex = string.Empty;
            string sourceIndex = string.Empty;
 
            IList<FieldInfo> lstProperties = new List<FieldInfo>(entityType.GetFields());
            try
            {
                foreach (FieldInfo property in lstProperties)
                {
                    strPropertyType = property.FieldType.FullName.ToString();
                    propertyIndex = property.Name;
                    if (!dictMappingPropertyIndex.ContainsKey(propertyIndex))
                    {
                        // Non essendoci mapping si vuole l'assegnazione di default, quindi si continua all'elemento successivo
                        continue; 
                    }
 
                    sourceIndex = dictMappingPropertyIndex[propertyIndex];
 
                    // Esempio:  (int)(dictEntityProperties[property.GetType().Name].ValueObject);
                    switch (strPropertyType)
                    {
                        case "System.Int32" :  
                        case "System.Int" :                        
                            //Assegnazione condizionata affinchè rimanga il valore di Default nel caso il valore da inserire sia nullo 
                            if (dictEntityProperties[sourceIndex].ValueObject != DBNull.Value)
                            {
                                entityType.GetField(propertyIndex, BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase)
                                                    .SetValue(entity, (int)(dictEntityProperties[sourceIndex].ValueObject));                        
                            }
                            break;
                        case "System.Double":
                            entityType.GetField(propertyIndex, BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase)
                                                                .SetValue(entity, (double)(dictEntityProperties[sourceIndex].ValueObject));
                            break;
                        case "System.String":
                            entityType.GetField(propertyIndex, BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase)
                                                                .SetValue(entity, (dictEntityProperties[sourceIndex].ValueObject).ToString());
                            break;
                        case "System.DateTime":
                            entityType.GetField(propertyIndex, BindingFlags.Public | BindingFlags.Instance | BindingFlags.IgnoreCase)
                                                                .SetValue(entity, (DateTime)(dictEntityProperties[sourceIndex].ValueObject));
                            break;
                        default :
                            m_logger.Warn(string.Format("FillOutputEntity() type '{0}' of property '{1}' not managed (source property '{2}').",
                                            strPropertyType, propertyIndex, sourceIndex));
                            break;
                    }
                }
            }
            catch (Exception ex)
            {
                throw new Exception(string.Format("{0}\r\nFor: '{1}' of property '{2}' not managed (source property '{3}').",
                                    ex.Message, strPropertyType, propertyIndex, sourceIndex));
            }
            return entity;
        }

Eseguire dinamicamente un metodo da assembly

Segue metodo che carica un assembly e ne esegue il metodo pubblico indicato con parametri in ingresso ed uscita. Classe con metodo eseguito dinamicamente caricandone la DLL:

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace VF_Digitalk_WebSrv_PMSME
{
    public class TOL_PMSME
    {
        // Pretend to be a method checking if a number is a Fibonacci  
        // but which actually attempts to read a file.  
        public static bool IsEvenNumber(int number)
        {
            //File.ReadAllText("D:\\Tmp\\TestFile.txt");
            int remainder = number % 2;
 
            return remainder == 0;
        }
    }
}

Classe e metodo che caricherà la DLL di sopra:

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
 
namespace VF_Common
{
    public class AssemblyRun
    {
        public static object Process(string assemblyFullPath
                                    , string className
                                    , string methodName
                                    , object[] inParams)
        {
            object returnObject = null;
            MethodInfo mi = null;
            ConstructorInfo ci = null;
            object responder = null;
            Type type = null;
            System.Type[] objectTypes;
            int count = 0;
            try
            {
                string assemblyName = Path.GetFileNameWithoutExtension(assemblyFullPath);
 
                //Load the assembly and get it's information
                type = Assembly.LoadFrom(assemblyFullPath)
                               .GetType(assemblyName + "." + className);
                //Get the Passed parameter types to find the method type
                objectTypes = new System.Type[inParams.GetUpperBound(0) + 1];
                foreach (object objectParameter in inParams)
                {
                    if (objectParameter != null)
                        objectTypes[count] = objectParameter.GetType();
                    count++;
                }
 
                //Get the reference of the method
                mi = type.GetMethod(methodName, objectTypes);
                ci = type.GetConstructor(Type.EmptyTypes);
                responder = ci.Invoke(null);
                //Invoke the method
                returnObject = mi.Invoke(responder, inParams);
            }
            catch (Exception)
            {
                throw;
            }
            finally
            {
                mi = null;
                ci = null;
                responder = null;
                type = null;
                objectTypes = null;
            }
            //Return the value as a generic object
            return returnObject;
        }
    }
}

Consumato così:

private void BtnTestExecAssembly_Click(object sender, EventArgs e)
{
	string fileSelected = string.Empty;
	string className = string.Empty;
	string methodName = string.Empty;
	try
	{
		Cursor.Current = Cursors.WaitCursor;
		fileSelected = TxtAssemblyFullPath.Text.Trim();
		className = TxtAssemblyClassName.Text;
		methodName = TxtAssemblyMethod.Text;
		object[] inParams = new object[] { 22 };
 
		object o = AssemblyRun.Process(fileSelected, className, methodName, inParams);
		RcTxt_Log.Text += string.Format("{0},", o.ToString());
 
		Cursor.Current = Cursors.Default;
	}
	catch (Exception ex)
	{
		Cursor.Current = Cursors.Default;
		m_logger.Error(ex);
		RcTxt_Log.Text += string.Format("Error: {0}\r\n", ex.Message);
		MessageBox.Show(ex.Message, "Test_Wcf_App"
						, MessageBoxButtons.OK, MessageBoxIcon.Error);
	}
}

Eredità di classi

Copia dell'oggetto Base nell'oggetto derivato, estensione

Es. 1

        /// <summary>
        /// es: ProductEntityExt productOldExt = Entity.Utility.BaseToDerived[Entities.Product, ProductEntityExt>(productOld);
        /// </summary>
        /// <typeparam name="TSource"></typeparam>
        /// <typeparam name="TDestination"></typeparam>
        /// <param name="objectToClone"></param>
        /// <returns></returns>
        public static TDestination BaseToDerived<TSource, TDestination>(TSource objectToClone)
        {
            Type sourceType = typeof(TSource);
            Type destinationType = typeof(TDestination);
 
 
            TSource source = objectToClone; //CloneSerializable<TSource>(objectToClone);
            TDestination destination = (TDestination)destinationType.Assembly.CreateInstance(destinationType.FullName);
 
 
            PropertyInfo[] props = sourceType.GetProperties();
            foreach (var item in props)
            {
                object val = item.GetValue(source, null);
                item.SetValue(destination, val, null);
            }
            return destination;
        }

Es. 2, dopo lettura da DB

Nel caso si legga dal DB e si voglia riempire una classe derivata oltre alla base, a seconda dei casi, il metodo\tecnica migliore ovvero più efficiente è la seguente:

Entity del Model:

public class ClasseBase
{
	public int ID  { get; set; }
 
	public string ProprietaBase1 { get; set; }
 
	public string ProprietaBase2 { get; set; }
}
 
public class EspensioneBase : ClasseBase
{
	public string ProprietaEstensione1 { get; set; }
 
	public string ProprietaEstensione2 { get; set; }
}

Classe del DAO:

public List<ClasseBase> Get(int id)
{
	List<ClasseBase> objOut = new List<ClasseBase>();
	DataTable dt = null;
	//...Codice di popolamento del DataTable 'dt'
	foreach (DataRow dr in dt.Rows)
	{
		ClasseBase b = new ClasseBase();
		objOut.Add(FillBaseObject(dr, b));
	}
	return objOut;
}
 
public List<EspensioneBase> GetExtension(int id)
{
	List<EspensioneBase> objOut = new List<EspensioneBase>();
	DataTable dt = null;
	//...Codice di popolamento del DataTable 'dt'
	foreach (DataRow dr in dt.Rows)
	{
		EspensioneBase e = new EspensioneBase();
		objOut.Add(FillBaseObject(dr, e));
		objOut.Add(FillDerivedObject(dr, e));
	}
	return objOut;
}
 
#region Metodi PRIVATI
private void FillBaseObject(DataRow dr, ClasseBase b)
{
	//b potrà essere di tipo ClasseBae o EspensioneBase, 
	//non si genereranno eccezioni ma il cast sarà implicito
	b.ID = (int)dr["ID"];
	if (dr["ProprietaBase1"] != DBNull.value) {
		b.ProprietaBase1 = dr["ProprietaBase1"].ToString();
	}
	if (dr["ProprietaBase1"] != DBNull.value) {
		b.ProprietaBase2 = dr["ProprietaBase2"].ToString();
	}	
}
 
private void FillDerivedObject(DataRow dr, EspensioneBase e)
{
	//b potrà essere di tipo ClasseBae o EspensioneBase, 
	//non si genereranno eccezioni ma il cast sarà implicito
	if (dr["ProprietaEstensione1"] != DBNull.value) {
		e.ProprietaEstensione1 = dr["ProprietaEstensione1"].ToString();
	}
	if (dr["ProprietaEstensione2"] != DBNull.value) {
		e.ProprietaEstensione2 = dr["ProprietaEstensione2"].ToString();
	}	
}
#endregion

Collezioni dati

Definizione e assegnazione di una List (lista, collezione) di oggetti:
Cat cat = new Cat { Age = 10, Name = "Fluffy" };
 
        List cats = new List
        {
            new Cat(){ Name = "Sylvester", Age=8 },
            new Cat(){ Name = "Whiskers", Age=2 },
            new Cat(){ Name = "Sasha", Age=14 }
        };

Automatizzare la verifica di valori nulli per collezione di dati

Il seguente metodo, dato un tipo generico ed il parametro di tipo object, verifica la collezione in input restituendo vero, se tutti gli items in collezione (List) hanno attributi NON NULLI, falso altrimenti, il tutto in automatico:
        /// <summary>
        /// Data una struttura dati di tipo lista di oggetti, verifica che almeno un elemento abbia una property 
        /// non NULLA o diverso dal valore di default.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="objLstToCheck">Lista di tipo List(T)></param>
        /// <param name="strExceptionCSVPropertyName">DEVE ESSERE nella seguente forma es: |SourceName|Altro|</param>
        /// <returns></returns>
        private static bool CheckListValueNotNull<T>(object objLstToCheck, string strExceptionCSVPropertyName)
        {
            Type entityType = typeof(T);
            IList<FieldInfo> lstProperties = new List<FieldInfo>(entityType.GetFields());
            string strPropertyType = string.Empty;
            string strValue = string.Empty;
 
            foreach (T item in (List<T>)objLstToCheck)
            {
                // Ciclo per ogni proprietà prevista in item
                foreach (FieldInfo property in lstProperties)
                {
                    // Salta le eccezioni
                    if (strExceptionCSVPropertyName.IndexOf("|" + property.Name + "|", StringComparison.CurrentCultureIgnoreCase) >= 0) 
                    {
                        continue;
                    }
                    object objValue = property.GetValue(item);
                    strPropertyType = property.FieldType.FullName.ToString();
                    strValue = string.Empty;
                    if (objValue != null)
                    { 
                        switch (strPropertyType)
                        {
                            case "System.Int32":
                            case "System.Int":
                            case "System.Double":
                                strValue = objValue.ToString();
                                // Stò supponendo valori != -1 per esser validi
                                if (double.Parse(strValue) != -1)
                                {
                                    return true;
                                }
                                break;
                            case "System.String":
                                if (!string.IsNullOrEmpty(objValue.ToString()))
                                {
                                    return true;
                                }
                                break;
                            case "System.DateTime":
                                DateTime dt = new DateTime();
                                strValue = objValue.ToString();
                                if (!string.IsNullOrEmpty(strValue)
                                    && strValue.IndexOf("0001") < 0)
                                {
                                    dt = DateTime.ParseExact(strValue, "dd/MM/yyyy HH:mm:ss", System.Globalization.CultureInfo.InvariantCulture);
                                    if (dt != DateTime.MinValue)
                                    {
                                        return true;
                                    }
                                }
                                break;
                            default:
                                // Se è un tipo che non conose ignora la valutazione
                                break;
                        }
                    }
                } // FINE per ogni proprietà dell'entità corrente
            } // FINE per ogni Entità in Lista
            return false;
        }

Rimozione elemento

Per rimuover un elemento da una lista (List) ci sono due modi:
AisData a = (from x in ShipData.Instance.lstAIVDM
			  where x.mmsi == mmsi
			  select x).FirstOrDefault();
ShipData.Instance.lstAIVDM.Remove(a);
Invece con una scansione diretta (da stackoverflow):
var list = new List<int>(Enumerable.Range(1, 10));

for (int i = list.Count - 1; i >= 0; i--) {

   if (list[i] > 5)
   	list.RemoveAt(i);

}

list.ForEach(i => Console.WriteLine(i));

Ordinare liste

Come ordinare una lista usando LinQ, supponendo di ordinare per Data:
List<Order> listaGrezza = new List<Order> ();
List<Order> ListaOrdinata = listaGrezza.OrderBy(o=>o.DataOrdine).ToList();
Ecco come effettuare l'ordinamento multiplo:
public class Leg

{

   public int Day { get; set; }
   public int Hour { get; set; }
   public int Min { get; set; }

}   //... List<Leg> legs = GetLegs()

               .OrderBy(o=>o.Day)
               .ThenBy(o=>o.Hour)
.ThenBy(o=>o.Min).ToList();
Altro metodo che include la comparazione di elementi in liste da Microsoft:
using System;

using System.Collections.Generic; // Simple business object. A PartId is used to identify the type of part // but the part name can change. public class Part : IEquatable<Part> , IComparable<Part> {

   public string PartName { get; set; }

 

   public int PartId { get; set; }

 

   public override string ToString()
   {
       return "ID: " + PartId + "   Name: " + PartName;
   }
   public override bool Equals(object obj)
   {
       if (obj == null) return false;
       Part objAsPart = obj as Part;
       if (objAsPart == null) return false;
       else return Equals(objAsPart);
   }
   public int SortByNameAscending(string name1, string name2)
   {

 

       return name1.CompareTo(name2);
   }

 

   // Default comparer for Part type. 
   public int CompareTo(Part comparePart)
   {
         // A null value means that this object is greater. 
       if (comparePart == null)
           return 1;

 

       else 
           return this.PartId.CompareTo(comparePart.PartId);
   }
   public override int GetHashCode()
   {
       return PartId;
   }
   public bool Equals(Part other)
   {
       if (other == null) return false;
       return (this.PartId.Equals(other.PartId));
   }
   // Should also override == and != operators.

  } public class Example {

   public static void Main()
   {
       // Create a list of parts.
       List<Part> parts = new List<Part>();

 

       // Add parts to the list.
       parts.Add(new Part() { PartName = "regular seat", PartId = 1434 });
       parts.Add(new Part() { PartName= "crank arm", PartId = 1234 });
       parts.Add(new Part() { PartName = "shift lever", PartId = 1634 }); ;
       // Name intentionally left null.
       parts.Add(new Part() {  PartId = 1334 });
       parts.Add(new Part() { PartName = "banana seat", PartId = 1444 });
       parts.Add(new Part() { PartName = "cassette", PartId = 1534 });

   

       // Write out the parts in the list. This will call the overridden  
       // ToString method in the Part class.
       Console.WriteLine("\nBefore sort:");
       foreach (Part aPart in parts)
       {
           Console.WriteLine(aPart);
       }

   

       // Call Sort on the list. This will use the  
       // default comparer, which is the Compare method  
       // implemented on Part.
       parts.Sort();

   

       Console.WriteLine("\nAfter sort by part number:");
       foreach (Part aPart in parts)
       {
           Console.WriteLine(aPart);
       }

 

       // This shows calling the Sort(Comparison(T) overload using  
       // an anonymous method for the Comparison delegate.  
       // This method treats null as the lesser of two values.
       parts.Sort(delegate(Part x, Part y)
       {
           if (x.PartName == null && y.PartName == null) return 0;
           else if (x.PartName == null) return -1;
           else if (y.PartName == null) return 1;
           else return x.PartName.CompareTo(y.PartName);
       });

 

       Console.WriteLine("\nAfter sort by name:");
       foreach (Part aPart in parts)
       {
           Console.WriteLine(aPart);
       }

 

       /*

 

           Before sort:

ID: 1434 Name: regular seat ID: 1234 Name: crank arm ID: 1634 Name: shift lever ID: 1334 Name: ID: 1444 Name: banana seat ID: 1534 Name: cassette   After sort by part number: ID: 1234 Name: crank arm ID: 1334 Name: ID: 1434 Name: regular seat ID: 1444 Name: banana seat ID: 1534 Name: cassette ID: 1634 Name: shift lever   After sort by name: ID: 1334 Name: ID: 1444 Name: banana seat ID: 1534 Name: cassette ID: 1234 Name: crank arm ID: 1434 Name: regular seat ID: 1634 Name: shift lever  

        */

 

   }
}
Esempio con ricerca binaria:
using System;
using System.Collections.Generic;
 
public class Example
{
    public static void Main()
    {
        List<string> dinosaurs = new List<string>();
 
        dinosaurs.Add("Pachycephalosaurus");
        dinosaurs.Add("Amargasaurus");
        dinosaurs.Add("Mamenchisaurus");
        dinosaurs.Add("Deinonychus");
 
        Console.WriteLine();
        foreach(string dinosaur in dinosaurs)
        {
            Console.WriteLine(dinosaur);
        }
 
        Console.WriteLine("\nSort");
        dinosaurs.Sort();
 
        Console.WriteLine();
        foreach(string dinosaur in dinosaurs)
        {
            Console.WriteLine(dinosaur);
        }
 
        Console.WriteLine("\nBinarySearch and Insert \"Coelophysis\":");
        int index = dinosaurs.BinarySearch("Coelophysis");
        if (index < 0)
        {
            dinosaurs.Insert(~index, "Coelophysis");
        }
 
        Console.WriteLine();
        foreach(string dinosaur in dinosaurs)
        {
            Console.WriteLine(dinosaur);
        }
 
        Console.WriteLine("\nBinarySearch and Insert \"Tyrannosaurus\":");
        index = dinosaurs.BinarySearch("Tyrannosaurus");
        if (index < 0)
        {
            dinosaurs.Insert(~index, "Tyrannosaurus");
        }
 
        Console.WriteLine();
        foreach(string dinosaur in dinosaurs)
        {
            Console.WriteLine(dinosaur);
        }
    }
}

Enumerativi

Conversioni

Da stringa a Enumerativo

/// <summary>
        /// Trasforma una stringa nel valore enumerativo del tipo indicato.
        /// Es: StatusEnum MyStatus = EnumUtil.ParseEnum(StatusEnum>("Active"); // (-- La prima parentesi tonda è in realtà angolare !!!
        /// In alternativa direttamente scrivere: (AvailabilitiesEnum)Enum.Parse(typeof(AvailabilitiesEnum), DDLAvailabilityType.SelectedValue);
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="value"></param>
        /// <returns></returns>
        public static T ParseEnum<T>( string value )
        {
            return (T) Enum.Parse( typeof( T ), value, true );
        }


Seguono 2 metodi che creano un dizionario chiave valore da un enumerativo, utile per popolare una DropDownList.
/// <summary>
       /// Dato un valore di un enumerativo, restituisce un dizionario chiave (nome dell'enumerativo) Valore Descrizione
       /// </summary>
       /// <param name="value">Va dato un item enumerativo a caso (per ottenerne automaticamente il tipo)</param>
       /// <param name="noEmptyValues">Se consentire l'inserimento di un Item senza valore</param>
       /// <returns>Dizionario stringa stringa ovvero chiave valore</returns>
       public static Dictionary<string, string> GetEnumDictionary(Enum value, bool noEmptyValues)
       {
           Dictionary<string, string> dict = new Dictionary<string, string>();

 

           FieldInfo[] arrFI = value.GetType().GetFields();

 

           bool inherit = false;
           foreach (FieldInfo fi in arrFI)
           {
               DescriptionAttribute[] attributes = (DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), inherit);

 

               if (attributes != null
                   && attributes.Length > 0)
               {
                   if (noEmptyValues && string.IsNullOrEmpty(fi.Name))
                   {
                       continue;
                   }
                   dict.Add(fi.Name, attributes[0].Description);//attributes[0].Description);
               }
               else
               {
                   if (!noEmptyValues)
                   {
                       dict.Add(string.Empty, string.Empty); 
                   }
               }                
           }
           return dict;
       }

 

       /// <summary>
       /// Dato un valore di un enumerativo, restituisce un dizionario chiave (nome dell'enumerativo) Valore Descrizione.
       /// Inserisce un Item VUOTO.
       /// </summary>
       /// <param name="value">Va dato un item enumerativo a caso (per ottenerne automaticamente il tipo)</param>
       /// <returns>Dizionario stringa stringa ovvero chiave valore</returns>
       public static Dictionary<string, string> GetEnumDictionary(Enum value)
       {
           bool noEmptyValues = false;
           return GetEnumDictionary(value, noEmptyValues);
}

Ottenimento info

Quando si associano degli attributi agli enumerativi, ad es per la descrizione da visualizzare eventualmente in un form:

        public static string GetEnumDescription(Enum value)
        {
            FieldInfo fi = value.GetType().GetField(value.ToString());
 
            bool inherit = false;
            DescriptionAttribute[] attributes = (DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), inherit);
 
            if (attributes != null &&
                attributes.Length > 0)
                return attributes[0].Description;
            else
                return value.ToString();
        }

Quindi si applica in questi casi usando l'attributo 'Description', è necessario aggiungere la USING 'System.ComponentModel':

        public enum SearchModeEnum
        {
            [Description("%")]
            LIKE = 0,
            [Description("=")]
            EQUAL = 1
        }
 
        public enum SortDirectionEnum
        {
            [Description("Ascendente")]
            ASC = 0,
            [Description("Discendente")]
            DESC = 1
        }

Segue come ottenere una stringa dell'attributo dell'enumerativo 'descrizione', l'esempio si riferisce all'attributo dell'enumerativo indicato sopra:

string strDisplay = GetEnumDescription(SearchModeEnum.EQUAL); // strDisplay conterrà "="

Files

File ASCII

Caricamento di un file ASCII da file system

Caricamento in unica soluzione

Da C# Example
using System.IO;
 
StreamReader streamReader = new StreamReader(filePath);
string text = streamReader.ReadToEnd();
streamReader.Close();

Caricamento e scansione per linea

Soluzione 1
int counter = 0;  
string line;  
 
// Read the file and display it line by line.  
System.IO.StreamReader file =   
    new System.IO.StreamReader(@"c:\test.txt");  
while((line = file.ReadLine()) != null)  
{  
    System.Console.WriteLine (line);  
    counter++;  
}  
 
file.Close();  
System.Console.WriteLine("There were {0} lines.", counter);
Soluzione 2
string text = System.IO.File.ReadAllText(@"C:\Users\Public\TestFolder\WriteText.txt");
 
// Read each line of the file into a string array. Each element
// of the array is one line of the file.
string[] arrLines = System.IO.File.ReadAllLines(@"C:\Users\Public\TestFolder\WriteLines2.txt");
 
// Line scanning
foreach (string line in arrLines)
{
	Console.WriteLine("\t" + line);
}

Ottenere l'ultima riga di un file

Da http://stackoverflow.com/questions/11625595/read-last-line-of-text-file StackOverflow]
Soluzione semplice:

var lastLine = File.ReadLines("file.txt").Last();

Soluzione efficiente ma complicata da stackoverflow

Sostituzione di marcatori da un template

Frequente è il caso di disporre dei template HTML e di sostituire dei segnaposto \ marcatori \ token con i valori presenti nel DB o altro. E' anche il caso di quando su vuol fare mailmerging (mail marging). Ecco una soluzione che adotta una regular expression per selezionare tutti i marcatori e metterli in un array, un successivo ciclo sostituirà i marcatori con il dato definitivo.
internal static string ReplaceTokens(string textToReplace, MailInfoToSend mailConfig)
        { 
            // Crea lista dei segnaposto\Token da sostituire, per ogniuno si fa opportuna e puntuale sostituzione
            MatchCollection regxCollectionToken = Regex.Matches(textToReplace, Config.TokenRegExp);
            string currStrToken = string.Empty;
 
            // Sostituzione puntuale di ciascun token
            foreach (Match match in regxCollectionToken)
            {
                currStrToken = match.ToString();
 
                switch (currStrToken)
                {
                    case "#DateTimeNow#":
                        textToReplace = textToReplace.Replace(currStrToken, DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss.fff"));
                        break;
                    case "#MailTo#":
                        textToReplace = textToReplace.Replace(currStrToken, mailConfig.MailTo);
                        break;
                    case "#TriggerDateUTC#":
                        textToReplace = textToReplace.Replace(currStrToken, mailConfig.TriggerDateUTC.ToString("dd/MM/yyyy HH:mm:ss.fff"));
                        break;
                    case "#AlertType#":
                        textToReplace = textToReplace.Replace(currStrToken, mailConfig.AlertTypeEnum.ToString());
                        break;
                    case "#AlertId#":
                        textToReplace = textToReplace.Replace(currStrToken, mailConfig.AlertId.ToString());
                        break;
                    case "#AlertShipCode#":
                        textToReplace = textToReplace.Replace(currStrToken, mailConfig.AlertShipCode);
                        break;
                    case "#AlertCompanyCode#":
                        textToReplace = textToReplace.Replace(currStrToken, mailConfig.AlertCompanyCode);
                        break;
                    case "#CompanyName#":
                        textToReplace = textToReplace.Replace(currStrToken, mailConfig.AlertCompanyCode); // ToDo a regime dovrebbe essere altro campo
                        break;
                    case "#ShipName#":
                        textToReplace = textToReplace.Replace(currStrToken, mailConfig.AlertShipCode); // ToDo a regime dovrebbe essere altro campo
                        break;
                    case "#EntityName#":
                        textToReplace = textToReplace.Replace(currStrToken, mailConfig.EntityName);
                        break;
                    case "#GroupName#":
                        textToReplace = textToReplace.Replace(currStrToken, mailConfig.GroupName);
                        break;
                    case "#OtherGroupMembers#":
                        textToReplace = textToReplace.Replace(currStrToken, mailConfig.OtherGroupMembers);
                        break;
                    case "#CustomHTMLTextSection#":
                        textToReplace = textToReplace.Replace(currStrToken, mailConfig.CustomHTMLTextSection);
                        break;
                    case "#ServerName#":
                        textToReplace = textToReplace.Replace(currStrToken, Environment.MachineName);
                        break;
                    case "#RunningPath#":
                        textToReplace = textToReplace.Replace(currStrToken, AppDomain.CurrentDomain.BaseDirectory);
                        break;
                    default:
                        // Si ripulisce e STOP, magari perché previsto ma non ancora gestito qs token
                        textToReplace = textToReplace.Replace(currStrToken, string.Empty);
                        break;
                }
            }
            return textToReplace;
        }

Scrivere testo in file

Seguono due soluzioni prese ed adattate da esempi su Microsoft MSDN.
public static bool WriteToTextFile(string fullPath, string text, out string strMsgError)
{
	bool ok = true;
	strMsgError = string.Empty;
 
	try
	{
		File.WriteAllText(fullPath, text);
	}
	catch (Exception ex)
	{
		ok = false;
		strMsgError = string.Format("[{0}]\r\nfullPath='{1}'\r\n\r\n{2}\r\n",
						"MultiPrepareKTUpdater.Helper.WriteToTextFile()", fullPath, ex.Message);
	}
	return ok;
}
 
public static bool AppendToTextFile(string fullPath, string text, out string strMsgError)
{
	bool ok = true;
	strMsgError = string.Empty;
 
	try
	{
		if (!File.Exists(fullPath))
		{
			throw new Exception(string.Format("The file to update '{0}' doesn't exists.", fullPath));
		}
 
		using (System.IO.StreamWriter file = new System.IO.StreamWriter(fullPath, true))
		{
			file.WriteLine(text);
		}
	}
	catch (Exception ex)
	{
		ok = false;
		strMsgError = string.Format("[{0}]\r\nfullPath='{1}'\r\n\r\n{2}\r\n",
						"MultiPrepareKTUpdater.Helper.AppendToTextFile()", fullPath, ex.Message);
	}
	return ok;
}

Scrivere esplicitamente n linee come da array di stringhe:

string[] lines = { "First line", "Second line", "Third line" };
 
// WriteAllLines creates a file, writes a collection of strings to the file, 
// and then closes the file.
System.IO.File.WriteAllLines(@"C:\Users\Public\TestFolder\WriteLines.txt", lines);

Usando stream writer

TextWriter tw = new StreamWriter("date.txt");
 
// write a line of text to the file
tw.WriteLine(DateTime.Now);
 
// close the stream
tw.Close();

File Excel

Leggere la seguente sezione interna dove son presentati esempi d'uso di diverse librerie diverse da quella standard di Microsoft: Accesso ai files, Excel.
Elenco:

Networking

TCP-UDP, socket

Soluzione di test UDP funzinante al ink interno: Multithreading Windows Form UDP TCP Tester
(Da stackoverflow) Essenzialmente:

  • UDP è più veloce del TCP perché i pacchetti sono inviati senza garantire la consegna;
  • TCP è sicuro perché ogni pacchetto ha la conferma e l'ordine.

Utili:

Esempio

Codice Server
E' un estratto da applicazione console che parte e scrive in output ogni chiamata da un client, l'applicazione gira sinché non è esplicitamente chiusa, IP e porta sono ottenute da un file configurazione.

private static Logger m_logger = LogManager.GetCurrentClassLogger();
 
private static string m_GitGwCmd_IPSrv
{
	get
	{
		string value = "127.0.0.1";
		if (ConfigurationManager.AppSettings["GitGwCmd_IPSrv"] != null)
		{
			value = ConfigurationManager.AppSettings["GitGwCmd_IPSrv"].ToString();
		}
		return value;
	}
}
 
private static int m_GitGwCmd_Port
{
	get
	{
		int value = 9999;
		if (ConfigurationManager.AppSettings["GitGwCmd_Port"] != null)
		{
			value = int.Parse(ConfigurationManager.AppSettings["GitGwCmd_Port"].ToString());
		}
		return value;
	}
}
 
static void Main(string[] args)
{
	string execOutput = string.Empty;
	string execFile = string.Empty;
	string strCommand = string.Empty;
	string workingDirectory = string.Empty;
	string userName = string.Empty;
	string password = string.Empty;
	string domain = string.Empty;
	bool isException = false;
 
	int bytesReaded = 0;
	IPAddress ipAddress = IPAddress.Parse(m_GitGwCmd_IPSrv);
	TcpListener tcpListener = new TcpListener(ipAddress, m_GitGwCmd_Port);
 
	/* **************************** SERVER IN ASCOLTO **************************** */
 
	try
	{
		string strMsgFROMClient = string.Empty;
		m_logger.Debug("Inizio"); Console.WriteLine("Inizio");
 
		tcpListener.Start();  // this will start the server
		while (true)   //we wait for a connection
		{
			Console.WriteLine("Attesa connessione con un client");
			TcpClient handler = tcpListener.AcceptTcpClient();  //if a connection exists, the server will accept it
 
			NetworkStream netStream = handler.GetStream(); //networkstream is used to send/receive messages
 
			//NOTA il messaggio che il server restituisce al Client può essere costruito anticipatamente o
			//      posticipatamente alla lettura, funge comunque da hack solo che nell'ultimo caso
			//      potrebbe anche essere usato come output di una funzione di elaborazione
			if (handler.Connected)  //(ex while) the client is connected, we look for incoming messages
			{
				byte[] arrtMsgFROMClien = new byte[handler.ReceiveBufferSize];     //the messages arrive as byte array
				bytesReaded = netStream.Read(arrtMsgFROMClien, 0, handler.ReceiveBufferSize);   //the same networkstream reads the message sent by the client
 
				strMsgFROMClient = Encoding.UTF8.GetString(arrtMsgFROMClien, 0, bytesReaded);
				Console.WriteLine(string.Format("Ricevuto messaggio:\r\n\t\"{0}\"\r\n", strMsgFROMClient)); //now , we write the message as string
				m_logger.Debug(strMsgFROMClient);
 
 
				// ELABORAZIONE
				/* execOutput = VerifyGitCOMMAND(strMsgFROMClient, out strCommand, out workingDirectory);
				if (string.IsNullOrEmpty(execOutput))
				{
					execOutput = DoGitCOMMAND(strCommand, workingDirectory);
				}*/
			}
 
			execOutput = "xxxx"; // <-------------------- OUTCOME 
 
			byte[] arrHOutcome = Encoding.UTF8.GetBytes(execOutput);  //conversion string => byte array
			Console.WriteLine("Invio Outcome msg:\r\n\t\"{0}\"", execOutput);
			netStream.Write(arrHOutcome, 0, arrHOutcome.Length);     //sending the message
 
			handler.Close();
			handler.Dispose();
		}
 
		m_logger.Debug(execOutput); Console.WriteLine(execOutput);
	}
	catch (Exception ex)
	{
		Console.WriteLine(ex.Message);
	}
	finally
	{
		tcpListener.Stop();                
	}
	m_logger.Debug("Fine"); Console.WriteLine("Fine");
}

Codice Client E' un estratto da una desktop application di test.

private void button1_Click(object sender, EventArgs e)
{
	string stringFROMServer = string.Empty;
	int maxLenLenServerMsg = 1024;
	try
	{
		TcpClient tcpClient = new TcpClient();                
		m_logger.Debug("Connecting.....");
		RTX_Log.Text += "Connecting.....";
 
		IPAddress ipAd = IPAddress.Parse("127.0.0.1");
		var ipEndPoint = new IPEndPoint(ipAd, 9999);
		tcpClient.Connect(ipEndPoint); // use the ipaddress as in the server program
 
		m_logger.Debug("Connected");
		RTX_Log.Text += "Connected";
 
		string stringTOServer = TxtStringToMessageToSend.Text;
 
		NetworkStream netStream = tcpClient.GetStream();
		UTF8Encoding byteEncoder = new UTF8Encoding();
		//ASCIIEncoding byteEncoder = new ASCIIEncoding();
		//UnicodeEncoding byteEncoder = new UnicodeEncoding();
 
		byte[] byteArray_TOServer = byteEncoder.GetBytes(stringTOServer);
 
		m_logger.Debug("Trasmettendo:\r\n\t\"{0}\"", stringTOServer);
		RTX_Log.Text += string.Format("Trasmettendo:\r\n\"{0}\"", stringTOServer);
		// INVIO !!!!!!!!!!!!!
		netStream.Write(byteArray_TOServer, 0, byteArray_TOServer.Length);
		//streamToFromClient.Write(BitConverter.GetBytes((int)byteArray_TOServer.Length), 0, 4);
		//streamToFromClient.Write(byteArray_TOServer, 0, (int)byteArray_TOServer.Length);
 
		m_logger.Debug("Leggo eventuale risposta\\hack dal server...");
		RTX_Log.Text += "Leggo eventuale risposta\\hack dal server...";
 
		// LETTURA !!!!!!!!!!!
		byte[] byteArray_FROMServer = new byte[tcpClient.ReceiveBufferSize];
		int bytesReaded = netStream.Read(byteArray_FROMServer, 0, tcpClient.ReceiveBufferSize);   //the same networkstream reads the message sent by the client
		stringFROMServer = Encoding.UTF8.GetString(byteArray_FROMServer, 0, bytesReaded);
 
 
		stringFROMServer += "\r\n";
		netStream.Flush();
 
		m_logger.Debug("Il server ha risposto con:\r\n\t\"{0}\"", stringFROMServer);
		RTX_Log.Text += string.Format("Il server ha risposto con:\r\n\"{0}\"", stringFROMServer);
 
		tcpClient.Close();
		tcpClient.Dispose();
	}
	catch (Exception ex)
	{
		m_logger.Debug(ex);
		RTX_Log.Text += string.Format("\r\n{0}", ex.Message);
	}
	m_logger.Debug("Fine lavoro dal client TCP!");
}

WEB

Browser HTML

Ottenere l'HTML di una pagina WEB ad un determinato URL. Segue esempio preso da stackoverflow.com che riporto sotto.

private void BtnTest3_Click(object sender, EventArgs e)
{
	string urlAddress = TxtURLTest3.Text;
	string userName = string.Empty;
 
	StreamReader readStream = null;
	HttpWebResponse response = null;
	try
	{
		HttpWebRequest request = (HttpWebRequest)WebRequest.Create(urlAddress);
		TxtLog.Text += string.Format("{0}\t", urlAddress);
 
		if (ChkToAuthenticate.Checked)
		{
			userName = TxtUser.Text.Trim();
			SecureString passWord = new SecureString();
			foreach (char c in TxtPassword.Text.ToCharArray())
			{
				passWord.AppendChar(c);
			}
			request.AllowAutoRedirect = true;
			request.Credentials = new NetworkCredential(userName, passWord);
		}
 
		response = (HttpWebResponse)request.GetResponse();
		if (response.StatusCode == HttpStatusCode.OK)
		{
			Stream receiveStream = response.GetResponseStream();
 
			if (String.IsNullOrWhiteSpace(response.CharacterSet))
				readStream = new StreamReader(receiveStream);
			else
				readStream = new StreamReader(receiveStream, Encoding.GetEncoding(response.CharacterSet));
 
			string data = readStream.ReadToEnd();
		}
	}
	catch (Exception ex)
	{
		string strError = string.Format("\r\n\t\t{0} - [{1}]", "ERROR: BtnTest3_Click", ex.Message);
		TxtLog.Text += string.Format("{0}\r\n", strError);
		MessageBox.Show(ex.Message, "ERROR BtnTest3_Click", MessageBoxButtons.OK, MessageBoxIcon.Error);
	}
	finally
	{ 
		if (readStream != null)
			readStream.Close();
		if (readStream != null)
			readStream.Close();
	}
}

Nel caso l'applicazione restituisca il seguente errore allora sarà necessaria l'autenticazione:

The remote server returned an error: (403) Forbidden.

Aggiungere:

request.UseDefaultCredentials = true;
// oppure:
request.Proxy.Credentials = System.Net.CredentialCache.DefaultCredentials;

Query String

Ecco come ottenere la queryString usando LinQ:
//Dictionary<string, string>
var qs = Request.GetQueryNameValuePairs().ToDictionary(k => k.Key,
					k => k.Value,
					StringComparer.OrdinalIgnoreCase);
// Verifica parametri obbligatori
if (!qs.ContainsKey("ships"))
{
	throw new Exception(string.Format("Mandatory parameter '{0}' NOT supplied.", "ships"));
}
Invece col metodo tradizionale, verificando prima se il parametro è stato fornito:
this.SynchronizationId = Request.QueryString["SynchId"] == null 
                                        ? string.Empty 
                                        : Request.QueryString["SynchId"].ToString();

Client FTP

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
 
namespace CommonLib
{
    public class FTP_Hlp
    {
        /// <summary>
        /// The hostname or IP address of the FTP server
        /// es:     ftp://aino.mobi/
        /// </summary>
        private string _remoteHost;
 
        // The remote username
        private string _remoteUser;
 
        // Password for the remote user
        private string _remotePass;
 
        public FTP_Hlp(string remoteHost, string remoteUser, string remotePassword, bool debug = false)
        {
            _remoteHost = remoteHost;
            _remoteUser = remoteUser;
            _remotePass = remotePassword;
        }
 
        #region Directories
        public bool DirectoryExists(string startDirectory, string drirectoryToFound)
        {
            bool exists = false;
            string currentDirrectory = string.Empty;
 
            FtpWebRequest request = (FtpWebRequest)WebRequest.Create(_remoteHost + startDirectory);
            request.Method = WebRequestMethods.Ftp.ListDirectory;
            request.Credentials = new NetworkCredential(_remoteUser, _remotePass);
            FtpWebResponse response = (FtpWebResponse)request.GetResponse();
            Stream responseStream = response.GetResponseStream();
            StreamReader reader = new StreamReader(responseStream);
 
 
            while (!reader.EndOfStream)
            {
                currentDirrectory = reader.ReadLine();
                if (currentDirrectory == drirectoryToFound.Trim())
                {
                    exists = true;
                    break;
                }
            }
            reader.Close();
            response.Close();
 
            return exists;
        }
 
        public bool CreateDirectory(string drirectoryToFound)
        {
            WebRequest request = WebRequest.Create(_remoteHost + drirectoryToFound);
            request.Method = WebRequestMethods.Ftp.MakeDirectory;
            request.Credentials = new NetworkCredential(_remoteUser, _remotePass);
 
            FtpWebResponse response = (FtpWebResponse)request.GetResponse();
            string strStatusCode = response.StatusCode.ToString(); //PathnameCreated
            return strStatusCode.IndexOf("PathnameCreated") >= 0;
        }
 
        public bool DeleteDirectory(string drirectoryToDelete) //La cartella deve essere prima completamente vuota
        {
            string uriString = _remoteHost + drirectoryToDelete;
 
            Uri severUri = new Uri(uriString);
            if (severUri.Scheme != Uri.UriSchemeFtp)
                return false;
 
            FtpWebRequest request = (FtpWebRequest)WebRequest.Create(severUri);
            request.Method = WebRequestMethods.Ftp.DeleteFile;
            request.Credentials = new NetworkCredential(_remoteUser, _remotePass);
 
            string result = string.Empty;
            FtpWebResponse response = (FtpWebResponse)request.GetResponse();
            long size = response.ContentLength;
            Stream datastream = response.GetResponseStream();
            StreamReader sr = new StreamReader(datastream);
            result = sr.ReadToEnd();
            sr.Close();
            datastream.Close();
            response.Close();
 
            string strStatusCode = response.StatusCode.ToString(); //
            return strStatusCode.IndexOf("PathnameCreated") >= 0;
        }
 
        public void DeleteDirectoryFull(string parent, string path) //ex delete_ftp_directory
        {
            //string path_segment = get_next_path_segment(path); /* first valid segment before a separator / or \ */
            //string path = advance_path_segment(path); /* update path variable to point to the next segment if any */
 
            //if (ftp_directory_has_files(Path.Combine(parent, path_segment)))
            //{
            //    /* has files delete them all. */
            //    DeleteDirectoryFull(parent, path);
            //}
 
            ///* Now delete the directory itself */
            //DeleteDirectory(Path.Combine(parent, path_segment));
        }
        #endregion
 
        #region Files
        /// <summary>
        /// Get a list of files and folders on the FTP server
        /// </summary>
        /// <returns></returns>
        public List<string> ListDirectoryFiles()
        {
            string fileExtFilter = string.Empty;
            return ListDirectoryFiles(string.Empty, fileExtFilter);
        }
 
        /// <summary>
        /// List files and folders in a given folder on the server
        /// </summary>
        /// <param name="folder"></param>
        /// <returns></returns>
        public List<string> ListDirectoryFiles(string folder, string fileExtFilter = "")
        {
            FtpWebRequest request = (FtpWebRequest)WebRequest.Create(_remoteHost + folder);
            request.Method = WebRequestMethods.Ftp.ListDirectory;
            request.Credentials = new NetworkCredential(_remoteUser, _remotePass);
            FtpWebResponse response = (FtpWebResponse)request.GetResponse();
            Stream responseStream = response.GetResponseStream();
            StreamReader reader = new StreamReader(responseStream);
 
            List<string> lstDirecrory = new List<string>();
            string line = string.Empty;
 
            while (!reader.EndOfStream)
            {
                line = reader.ReadLine();
                if (!string.IsNullOrEmpty(fileExtFilter))
                {
                    if (Path.GetExtension(line) == fileExtFilter)
                    {
                        lstDirecrory.Add(line);
                    }
                }
                else
                {
                    lstDirecrory.Add(line);
                }                
            }
 
            reader.Close();
            response.Close();
            return lstDirecrory;
        }
 
 
        /// <summary>
        /// Remove a file from the server.
        /// </summary>
        /// <param name="filename">filename and path to the file, e.g. public_html/test.zip</param>
        public void DeleteFile(string filename)
        {
            FtpWebRequest request = (FtpWebRequest)WebRequest.Create(_remoteHost + filename);
            request.Method = WebRequestMethods.Ftp.DeleteFile;
            request.Credentials = new NetworkCredential(_remoteUser, _remotePass);
            FtpWebResponse response = (FtpWebResponse)request.GetResponse();
            response.Close();
        }
        #endregion
 
        /// <summary>
        /// Download a file from the FTP server to the destination
        /// </summary>
        /// <param name="filename">filename and path to the file, e.g. public_html/test.zip</param>
        /// <param name="destination">The location to save the file, e.g. c:test.zip</param>
        public void DownloadFile(string filename, string destination)
        {
            FtpWebRequest request = (FtpWebRequest)WebRequest.Create(_remoteHost + filename);
            request.Method = WebRequestMethods.Ftp.DownloadFile;
            request.Credentials = new NetworkCredential(_remoteUser, _remotePass);
            FtpWebResponse response = (FtpWebResponse)request.GetResponse();
            Stream responseStream = response.GetResponseStream();
            StreamReader reader = new StreamReader(responseStream);
 
            StreamWriter writer = new StreamWriter(destination);
            writer.Write(reader.ReadToEnd());
 
            writer.Close();
            reader.Close();
            response.Close();
        }
 
        /// <summary>
        /// Upload a file to the server
        /// </summary>
        /// <param name="srcLocalFullPath">Full path to the source file e.g. c:test.zip</param>
        /// <param name="remoteRelFullPath">destination folder and filename e.g. public_html/test.zip</param>
        public bool UploadFile(string srcLocalFullPath, string remoteRelFullPath)
        {
            string uriString = _remoteHost + remoteRelFullPath;
 
            Uri severUri = new Uri(uriString);
            if (severUri.Scheme != Uri.UriSchemeFtp)
                return false;
 
            FtpWebRequest request = (FtpWebRequest)WebRequest.Create(severUri);
            request.Method = WebRequestMethods.Ftp.UploadFile;
            request.UseBinary = true;       // !
            //request.UsePassive = true;      // !
            //request.KeepAlive = false;      // !
            //request.Proxy = null;
            //request.Timeout = System.Threading.Timeout.Infinite;    // ?
            //request.AuthenticationLevel = System.Net.Security.AuthenticationLevel.None;
            request.Credentials = new NetworkCredential(_remoteUser, _remotePass);
 
            // --StreamReader sourceStream = new StreamReader(srcLocalFullPath);            //Non ha funzionato
            // --byte[] fileContents = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd());    //Non ha funzionato
            byte[] fileContents = File.ReadAllBytes(srcLocalFullPath);
            // --sourceStream.Close();                                                      //Non ha funzionato
            request.ContentLength = fileContents.Length;
 
            Stream requestStream = request.GetRequestStream();
            requestStream.Write(fileContents, 0, fileContents.Length);
            requestStream.Close();
            requestStream.Dispose();
 
            FtpWebResponse response = (FtpWebResponse)request.GetResponse();
            response.Close();
            response.Dispose();
 
            string strOutcome = response.StatusDescription; //226 Transfer complete
            return (fileContents.Length > 0) || strOutcome.IndexOf("Transfer complete") > 0;
        }
 
        //------------------------------------ ok --------------------
        public bool UploadFile(string password, string userName
                             , string originFile, string destinationFile //Es: ftp://aino.mobi/pizzarrone.bp
                             , ref string strMsgError)
        {
            try
            {
                strMsgError = string.Empty;
                //
                Uri severUri = new Uri(destinationFile);
                //
                if (severUri.Scheme != Uri.UriSchemeFtp)
                    return false;
                //
                FtpWebRequest request = (FtpWebRequest)WebRequest.Create(severUri);
                request.Method = WebRequestMethods.Ftp.UploadFile;
                request.UseBinary = true;
                request.UsePassive = true;//true;
                request.KeepAlive = false;
                request.Timeout = System.Threading.Timeout.Infinite;
                request.AuthenticationLevel = System.Net.Security.AuthenticationLevel.None;
                request.Credentials = new NetworkCredential(userName, password);
 
                StreamReader sourceStream = new StreamReader(originFile);
                byte[] fileContents = Encoding.UTF8.GetBytes(sourceStream.ReadToEnd());
                sourceStream.Close();
                request.ContentLength = fileContents.Length;
                //
                Stream requestStream = request.GetRequestStream();
                requestStream.Write(fileContents, 0, fileContents.Length);
                requestStream.Close();
                requestStream.Dispose();
 
                //
                FtpWebResponse response = (FtpWebResponse)request.GetResponse();
                //
                response.Close();
                response.Dispose();
 
                //
                return true;
            }
            catch (Exception ex)
            {
                strMsgError = ex.Message;
                return (false);
            }
        }
    }
}

Validazioni

Uso di Regular Expression

Vedere guida interna: Regular expression in C#

Indirizzo e-mail

Esempio 1 su indirizzi email, questa usa sia la funzione della libreria .Net che una regular expression in quanto la libreria standard di .Net comunque fa passare dei casi "dubbi".

//..
using System.Net.Mail;
using System.Text.RegularExpressions;
//..
 
 
public static bool IsValid_Email(string emailaddress)
{
	try
	{
		MailAddress m = new MailAddress(emailaddress);
		//Ulteriore verifica !!!
		// Perché altrimenti alcune passerebbero comunque, es.: 
		//      polpot.a zz@gmail.com , polpot.azz'o@gmail.com
		Regex regex = new Regex(@"^([\w\.\-]+)@([\w\-]+)((\.(\w){2,3})+)$");
		Match match = regex.Match(emailaddress);
		if (match.Success)
			return true;
		else
			return false;
	}
	catch (FormatException)
	{
		return false;
	}
}

Sulle stringhe

Doppie virgole

Ecco come usare gli apici doppi in una stringa:

string str = @"""nota la chiocciola, nel esempio che segue non c'è e si usa altro sistema""";
// oppure
string str = "\"Si usa un carattere speciale\"";

Contare le occorrenze in una stringa

Per contare le occorrenze di un carattere in una stringa occorrono dei trucchi
Usando LinQ
int count = stringaDiRicerca.Count(s => s == '*');
Sfruttando gli array e lo Split ma di un solo carattere pattern
int count = stringaDiRicerca.Split('x').Length - 1;

Per le stringhe:

using System.Text.RegularExpressions;
...
if (Regex.Matches(strOut, imoNumber).Count == 2)
{
     // Esegui azioni
}

Ricerche

Ottenere il primo carattere

Usando un metodo di verifica StartsWith:

HandleUpdateAIS(lstDraftInfo.Where(x => x.ID.StartsWith("M", StringComparison.InvariantCultureIgnoreCase)).ToList(), 
                                    ShipData.Instance.lstAIVDM);

Ricerca di un valore in un insieme

La stessa cosa poteva esser fatta ricercando in una stringa CSV ma il seguente esempio è migliore in quanto adattabile a diversi altri tipi di dati:
List<int> aisbasictypes = new List<int>() { 1, 2, 3, };
List<int> aisextendedtypes = new List<int>() { 5 };
 
//..
AisData basicdata = (from AisData a in lstAIVDO
					 where aisbasictypes.Contains(a.type)
					 select a
					).FirstOrDefault();
AisData extdata = (from AisData a in lstAIVDO
                                           where aisextendedtypes.Contains(a.type)
                                           select a
                                          ).FirstOrDefault();

Elaborazioni

Incrementare il numero di versione dopo l'ultimo punto

Il seguente metodo prende l'elenco di cartelle nel file system e determinando l'ultima in ordine alfabetico (senza punti) ne aumenta di 1 il numero dopo l'ultimo punto. Serve nel calcolo della versione successiva di un software, il pattern del versioning è:

1.0.0         che passerà a    --> 1.0.1
1.0.0.1       scartato, quindi --> 1.0.0.1
ciccio.c.3    che passerà a    --> ciccio.c.0.3
Ecco il codice:
/// <summary>
/// Calcola in automatico la prossima versione del servizio per una determinata nave, lo fa interrogando il fileSystem ed incrementando
/// il numero dietro l'ultimo punto più a destra e conservando la stringa a sinistra di questo punto.
/// ATTENZIONE il percorso\path DEVE finire col nome del servizio, es.: 
///         D:\KT\KT.Install.Repository\Aida\VT\KTUnifiedDataCollector
/// </summary>
/// <param name="shipBasePath">Percorso associato alla nave della compagnia e al servizio da aggiornare.</param>
/// <returns></returns>
private string GetAutoNextVersion(string shipBasePath)
{
	string strNextVersion = string.Empty;
	string strMsgError = string.Empty;
	IEnumerable<string> shipVersions = null;
 
	try
	{
		if (Directory.Exists(shipBasePath))
		{
			//memorizzo il nome di tutte le cartelle versionate
			shipVersions = Directory.EnumerateDirectories(shipBasePath, "*", SearchOption.TopDirectoryOnly).Select(r => Path.GetFileName(r));
 
			//eliminio le cartelle che non hanno una versione valida come nome
			shipVersions = shipVersions.Where(r => Regex.IsMatch(r, "^[0-9]{1}[.]{1}[0-9]{1,}[.]{1}[0-9]{1,}$"));
		}
		else
		{
			m_loggerForm.Warn("The directory '{0}', doesnt'exist we suppose is a new installation!", shipBasePath);
		}
 
		if (shipVersions == null || shipVersions.Count() == 0)
		{
			//se non ce ne sono parto dal valore minimo
			strNextVersion = "1.0.0";
		}
		else
		{
			//prendo la versione attualmente più alta
			string[] maxVersionSplit = shipVersions.OrderByDescending(r => int.Parse(r.Replace(".", ""))).First().Split('.');
 
			//prendo l'ultimo valore dopo il punto e lo incremento di uno
			string lastVersionIncrement = maxVersionSplit[2];
			int newVersion = int.Parse(lastVersionIncrement);
			newVersion++;
 
			//creo la nuova versione: i primi due valori rimangono uguali, mentre l'ultimo è incrementato di uno
			string newVersionPadded = string.Format("000000{0}", newVersion);
			strNextVersion = string.Format("{0}.{1}.{2}", maxVersionSplit[0], maxVersionSplit[1], newVersionPadded.Substring(newVersionPadded.Length - lastVersionIncrement.Length));
		}
		m_loggerForm.Info("Computed next version '{0}'.", strNextVersion);
	}
	catch (Exception ex)
	{
		strMsgError = string.Format("On path '{0}', error: {1}", shipBasePath, ex.Message);
		m_loggerForm.Error("{0}\r\n\r\n{1}", strMsgError, ex.StackTrace);
	}
	return strNextVersion;
}

Sistema Operativo

File System

Lista di directory

string[] arrDirectoryList = Directory.GetDirectories("C:\\cartellaRoot", "*", SearchOption.AllDirectories);
foreach (string dirPath in arrDirectoryList)
{
	// Operazioni su ciascuna cartella

Soluzione scansione cartella fileSystem per pulizia vecchi files

La seguente funzione cancella i file più vecchi di n minuti, usa l'attributo CreationDate di ogni files nella cartella corrente.

private int PuliziaVecchiFile(string pathToScan, string extToManage, int maxMinutesOld)
{
	int nrFilesInCaertella = 0;
	int nrFilesCancellati = 0;
	string ultimoNomeFileCoinvolto = string.Empty;
 
	if (maxMinutesOld == 0)
	{
		log.WarnFormat("FUNZIONE DI CANCELLAZIONE '{0}' VECCHI DISABILITATA.", extToManage);
		return 0;
	}
 
	try
	{
 
		if (Directory.Exists(pathToScan))
		{
			DirectoryInfo di = new DirectoryInfo(pathToScan);
			FileInfo[] filesInfo = di.GetFiles(string.Format("*.{0}", extToManage));
			nrFilesInCaertella = filesInfo.Length;
			foreach (FileInfo fi in filesInfo)
			{
				if (DateTime.Now.Subtract(fi.CreationTime).TotalMinutes > maxMinutesOld)
				{
					ultimoNomeFileCoinvolto = fi.FullName;
					log.DebugFormat("Si cancella il file '{0}', più vecchio di {1} minuti.", ultimoNomeFileCoinvolto, maxMinutesOld);
					fi.Delete();
					if (!File.Exists(fi.FullName))
					{
						nrFilesCancellati++;
						log.DebugFormat("'{0}' corettamente cancelalto.", ultimoNomeFileCoinvolto);
					}
					else
					{
						log.ErrorFormat("Tentativo di cancellazionefile '{0}' NON RIUSCITO!", ultimoNomeFileCoinvolto);
					}
				}
			}
			/*
			string[] fileEntries = Directory.GetFiles(pathToScan);
			foreach (string fileName in fileEntries)
			{
			}
			*/
		}
		else
		{
			log.ErrorFormat("Il path '{0}' NON ESISTE. La pulizia dei vecchi files NON FUNZIONERA'!", pathToScan);
		}
	}
	catch (Exception e)
	{
		log.ErrorFormat("Files '{0}' presenti in cartella {1}: {2}. Cancellati {3}. Ultimo file coinvolto '{4}'. Errore generico {5}, {6}",
						extToManage, pathToScan, nrFilesInCaertella, nrFilesCancellati, ultimoNomeFileCoinvolto, e.HResult, e.Message);
	}
	return nrFilesCancellati;
}

Lista ordinata di directory

Da esempio: stackoverflow
Attenzione ai parametri della SearchOption si usa TopDirectoryOnly ovvero si cerca solo la prima lista di cartelle e non tutte comprese le annidate.
private void button1_Click(object sender, EventArgs e) 
{
		DirectoryInfo di = new DirectoryInfo(@"C:\Windows");
		DirectoryInfo[] dirs = di.GetDirectories("*", SearchOption.TopDirectoryOnly);
 
	Array.Sort<DirectoryInfo>(dirs, new Comparison<DirectoryInfo>(CompareDirs));
}
 
// Comparazione sull'orario di creazione
private int CompareDirs(DirectoryInfo a, DirectoryInfo b) 
{
	return a.CreationTime.CompareTo(b.CreationTime);
}
Prestare attenzione alla soluzione di ordinamento che usa Array.Sort

Comprimere e Decomprimere

Come da documentazione Microsot
Aggiungere la reference alla libreria System.IO.Compression.FileSystem. Come creare un file ZIP (zippare) e UnZipparlo.

using System;
using System.IO;
using System.IO.Compression;
 
namespace ConsoleApplication
{
    class Program
    {
        static void Main(string[] args)
        {
            string startPath = @"c:\example\start";
            string zipPath = @"c:\example\result.zip";
            string extractPath = @"c:\example\extract";
 
            ZipFile.CreateFromDirectory(startPath, zipPath, CompressionLevel.Fastest, true);
 
            ZipFile.ExtractToDirectory(zipPath, extractPath);
        }
    }
}

Estratto di un mio esempio reale

using System.IO.Compression;
//...
private void Btn_Deploy_ZipTheFolderSource_Click(object sender, EventArgs e)
{
    Cursor previousCursor = Cursor.Current;
    try
    {
        Cursor.Current = Cursors.WaitCursor;
        SSStatus.Text = "Working";
 
        string sourceFoldetToZip = ConfigurationManager.AppSettings["DevPathDeploySurce"];
        string zipFileName = ConfigurationManager.AppSettings["DevZipFileNameSurce"];
        string fullPathFileZip = ConfigurationManager.AppSettings["DevDeployFolder"] + "\\" + zipFileName;
 
        if (File.Exists(fullPathFileZip))
        {
            File.Delete(fullPathFileZip);
        }
 
        ZipFile.CreateFromDirectory(sourceFoldetToZip, fullPathFileZip, CompressionLevel.Fastest, true);
 
        SSStatus.Text = "Ready";
    }
    catch (Exception ex)
    {
        SSStatus.Text = "Error";
        MessageBox.Show(string.Format("{0}", ex.Message),
            "[Btn_Deploy_ExploreLogFolder_Click] Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
    }
    finally
    {
        Cursor.Current = previousCursor;
    }
}

Copia di una intera directory

Copia di una intera directory in un'altra. Da StackOverflow:

//Now Create all of the directories
foreach (string dirPath in Directory.GetDirectories(SourcePath, "*", SearchOption.AllDirectories))
{
    Directory.CreateDirectory(dirPath.Replace(SourcePath, DestinationPath));
}
 
//Copy all the files & Replaces any files with the same name
foreach (string newPath in Directory.GetFiles(SourcePath, "*.*", SearchOption.AllDirectories))
{
    File.Copy(newPath, newPath.Replace(SourcePath, DestinationPath), true);
}

Clonazione directory e sottodirectories

Da stackoverflow.com

class Program
{
    static void Main(string[] args)
    {
        CloneDirectory(@"C:\SomeRoot", @"C:\SomeOtherRoot");
    }
 
    private static void CloneDirectory(string root, string dest)
    {
        foreach (var directory in Directory.GetDirectories(root))
        {
            //Get the path of the new directory
            var newDirectory = Path.Combine(dest, Path.GetFileName(directory));
            //Create the directory if it doesn't already exist
            Directory.CreateDirectory(newDirectory);
            //Recursively clone the directory
            CloneDirectory(directory, newDirectory);
        }
 
        foreach (var file in Directory.GetFiles(root))
        {
            File.Copy(file, Path.Combine(dest, Path.GetFileName(file)));
        }
    }
}

Rimozione directory e sottodirectories

public static void RemoveDirectory(string dirToRemove)
{
	DirectoryInfo di = new DirectoryInfo(dirToRemove);
 
	DeleteFolderRecursive(di);
}
 
private static void DeleteFolderRecursive(DirectoryInfo baseDir)
{
	baseDir.Attributes = FileAttributes.Normal;
	foreach (var childDir in baseDir.GetDirectories())
		DeleteFolderRecursive(childDir);
 
	foreach (var file in baseDir.GetFiles())
		file.IsReadOnly = false;
 
	baseDir.Delete(true);
}

Scelta file

La classe è 'OpenFileDialog'.

using System.Windows.Forms;
 
// etc
 
OpenFileDialog ofd = new OpenFileDialog(); // <----
ofd.InitialDirectory = _JsonFilePath;
if (ofd.ShowDialog() == DialogResult.OK)
{
	FileStream fs = new FileStream(ofd.FileName, FileMode.Open);
	StreamReader sr = new StreamReader(fs);
	textOfFile = sr.ReadToEnd();
	model = JsonConvert.DeserializeObject<ItemMasterServiceReference.ItemMasterData>(textOfFile);
	sr.Close();
	fs.Close();
	RTxt_InputJSON.Text = textOfFile;
}
else
{
	return;
}

Scelta directory

La classe è 'FolderBrowserDialog'.

using System.Windows.Forms;
using System.IO;
 
// etc
 
using(var fbd = new FolderBrowserDialog())
{
    fbd.SelectedPath = _JsonFilePath; // Custom folder to stat from
    DialogResult result = fbd.ShowDialog();
    if (result == DialogResult.OK 
        && !string.IsNullOrWhiteSpace(fbd.SelectedPath))
    {
        string[] files = Directory.GetFiles(fbd.SelectedPath);
        System.Windows.Forms.MessageBox.Show("Files found: " + files.Length.ToString(), "Message");
    }
}

Scelta directory per salvare un file

SaveFileDialog savefile = new SaveFileDialog(); 
// set a default file name
savefile.FileName = "unknown.txt";
// set filters - this can be done in properties as well
savefile.Filter = "Text files (*.txt)|*.txt|All files (*.*)|*.*";
 
if (savefile.ShowDialog() == DialogResult.OK)
{
    using (StreamWriter sw = new StreamWriter(savefile.FileName))
        sw.WriteLine ("Hello World!");
}

Esempio realistico

private void Btn_SaveJsonInINPUT_Click(object sender, EventArgs e)
{
	Cursor previousCursor = Cursor.Current;
	try
	{
		RTxtLogOutDescriptions.Text = string.Empty;
		SSStatus.Text = "Selecting";
 
		SaveFileDialog savefile = new SaveFileDialog();
		savefile.FileName = "IN_OUT_.json";
		savefile.Filter = "JSON files (*.json)|*.json|All files (*.*)|*.*";
		savefile.DefaultExt = "json";
		savefile.InitialDirectory = _JsonFilePath;
 
		if (savefile.ShowDialog() == DialogResult.OK)
		{
			using (StreamWriter sw = new StreamWriter(savefile.FileName))
			{
				sw.WriteLine(RTxt_InputJSON.Text);
			}
		}
		Cursor.Current = Cursors.WaitCursor;
		SSStatus.Text = "Ready";
	}
	catch (Exception ex)
	{
		SSStatus.Text = "Error";
		MessageBox.Show(string.Format("{0}", ex.Message),
			"[Btn_SaveJsonInINPUT_Click] Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
	}
	finally
	{
		Cursor.Current = previousCursor;
	}
}

Utenze Windows

WikiAino: Sistemi di autenticazione
Materiale:

Per utenze non in dominio

Soluzione di creazione di un'utenza su Windows7 e Windows 2008 Server.
La seguente soluzione viene da support.microsoft.com, occorre aggiungere una reference alla libreria System.DirectoryServices ed usare l'omonima classe:

using System.DirectoryServices; 
 
//...
 
private void AddUser(string userName, string password, string userFullName, 
					string machineName, string userDescription, string groupName)
{
	machineName = string.IsNullOrEmpty(machineName)
					? Environment.MachineName
					: machineName;
 
	DirectoryEntry AD = new DirectoryEntry(string.Format("WinNT://{0},computer", machineName));
	DirectoryEntry newUser = AD.Children.Add(userName, "user");
	if (!string.IsNullOrWhiteSpace(userFullName))
	{
		newUser.Properties["FullName"].Add(userFullName);
	}
	newUser.Invoke("SetPassword", new object[] { password });
	newUser.Invoke("Put", new object[] {"Description", userDescription });
	newUser.CommitChanges();
	DirectoryEntry grp;
 
	grp = AD.Children.Find(groupName, "group");
	if (grp != null)
	{
		grp.Invoke("Add", new object[] {newUser.Path});
	}
}

La prova è che avviando: Strumenti di amministrazione, gestione computer si ha quanto segue:

WinUserCreation01.png

L'utente creato appartiene al gruppo 'Guests', ecco l'elenco di esempio dei gruppi sul mio PC:

WinUserCreation02.png

Utenze in dominio

La seguente è una soluzione (presa da anyrest, autore Raymund) NON testata, segue la classe con le operazioni comuni:

using System;
using System.Collections;
using System.DirectoryServices.AccountManagement;
 
namespace WFA_WindUserTests
{
    /* author: Raymund
     * page: https://anyrest.wordpress.com/2010/06/28/active-directory-c/
     */
    public class ADMethodsAccountManagement
    {
        #region Variables with default value
        private string m_Domain = "test.com";
        private string m_DefaultOU = "OU=Test Users,OU=Test,DC=test,DC=com";
        private string m_DefaultRootOU = "DC=test,DC=com";
        private string m_ServiceUser = @"ServiceUser";
        private string m_ServicePassword = "ServicePassword";
        #endregion
 
        #region Constructor
        public ADMethodsAccountManagement()
        {
            m_Domain = null;
            m_DefaultOU = null;
            m_DefaultRootOU = null;
            m_ServiceUser = null;
            m_ServicePassword = null;
        }
 
        public ADMethodsAccountManagement(string domain) : this()
        {
            m_Domain = domain;
        }
 
        public ADMethodsAccountManagement(string domain, string defaultOU) 
            : this(domain)
        {
            m_DefaultOU = defaultOU;
        }
 
        public ADMethodsAccountManagement(string domain, string defaultOU, string defaultRootOU) 
            : this(domain, defaultOU)
        {
            m_DefaultRootOU = defaultRootOU;
        }
        #endregion
 
        #region Validate Methods
        /// <summary>
        /// Validates the username and password of a given user
        /// </summary>
        /// <param name="sUserName">The username to validate</param>
        /// <param name="sPassword">The password of the username to validate</param>
        /// <returns>Returns True of user is valid</returns>
        public bool ValidateCredentials(string sUserName, string sPassword)
        {
            PrincipalContext oPrincipalContext = GetPrincipalContext();
            return oPrincipalContext.ValidateCredentials(sUserName, sPassword);
 
        }
 
        /// <summary>
        /// Checks if the User Account is Expired
        /// </summary>
        /// <param name="sUserName">The username to check</param>
        /// <returns>Returns true if Expired</returns>
        public bool IsUserExpired(string sUserName)
        {
            UserPrincipal oUserPrincipal = GetUser(sUserName);
            if (oUserPrincipal.AccountExpirationDate != null)
            {
                return false;
            }
            else
            {
                return true;
            }
        }
 
        /// <summary>
        /// Checks if user exsists on AD
        /// </summary>
        /// <param name="sUserName">The username to check</param>
        /// <returns>Returns true if username Exists</returns>
        public bool IsUserExisiting(string sUserName)
        {
            if (GetUser(sUserName) == null)
            {
                return false;
            }
            else
            {
                return true;
            }
        }
 
        /// <summary>
        /// Checks if user accoung is locked
        /// </summary>
        /// <param name="sUserName">The username to check</param>
        /// <returns>Retruns true of Account is locked</returns>
        public bool IsAccountLocked(string sUserName)
        {
            UserPrincipal oUserPrincipal = GetUser(sUserName);
            return oUserPrincipal.IsAccountLockedOut();
        }
        #endregion
 
        #region Search Methods
 
        /// <summary>
        /// Gets a certain user on Active Directory
        /// </summary>
        /// <param name="sUserName">The username to get</param>
        /// <returns>Returns the UserPrincipal Object</returns>
        public UserPrincipal GetUser(string sUserName)
        {
            PrincipalContext oPrincipalContext = GetPrincipalContext();
 
            UserPrincipal oUserPrincipal = UserPrincipal.FindByIdentity(oPrincipalContext, sUserName);
            return oUserPrincipal;
        }
 
        /// <summary>
        /// Gets a certain group on Active Directory
        /// </summary>
        /// <param name="sGroupName">The group to get</param>
        /// <returns>Returns the GroupPrincipal Object</returns>
        public GroupPrincipal GetGroup(string sGroupName)
        {
            PrincipalContext oPrincipalContext = GetPrincipalContext();
 
            GroupPrincipal oGroupPrincipal = GroupPrincipal.FindByIdentity(oPrincipalContext, sGroupName);
            return oGroupPrincipal;
        }
 
        #endregion
 
        #region User Account Methods
 
        /// <summary>
        /// Sets the user password
        /// </summary>
        /// <param name="sUserName">The username to set</param>
        /// <param name="sNewPassword">The new password to use</param>
        /// <param name="sMessage">Any output messages</param>
        public void SetUserPassword(string sUserName, string sNewPassword, out string sMessage)
        {
            try
            {
                UserPrincipal oUserPrincipal = GetUser(sUserName);
                oUserPrincipal.SetPassword(sNewPassword);
                sMessage = "";
            }
            catch (Exception ex)
            {
                sMessage = ex.Message;
            }
 
        }
 
        /// <summary>
        /// Enables a disabled user account
        /// </summary>
        /// <param name="sUserName">The username to enable</param>
        public void EnableUserAccount(string sUserName)
        {
            UserPrincipal oUserPrincipal = GetUser(sUserName);
            oUserPrincipal.Enabled = true;
            oUserPrincipal.Save();
        }
 
        /// <summary>
        /// Force disbaling of a user account
        /// </summary>
        /// <param name="sUserName">The username to disable</param>
        public void DisableUserAccount(string sUserName)
        {
            UserPrincipal oUserPrincipal = GetUser(sUserName);
            oUserPrincipal.Enabled = false;
            oUserPrincipal.Save();
        }
 
        /// <summary>
        /// Force expire password of a user
        /// </summary>
        /// <param name="sUserName">The username to expire the password</param>
        public void ExpireUserPassword(string sUserName)
        {
            UserPrincipal oUserPrincipal = GetUser(sUserName);
            oUserPrincipal.ExpirePasswordNow();
            oUserPrincipal.Save();
 
        }
 
        /// <summary>
        /// Unlocks a locked user account
        /// </summary>
        /// <param name="sUserName">The username to unlock</param>
        public void UnlockUserAccount(string sUserName)
        {
            UserPrincipal oUserPrincipal = GetUser(sUserName);
            oUserPrincipal.UnlockAccount();
            oUserPrincipal.Save();
        }
 
        /// <summary>
        /// Creates a new user on Active Directory
        /// </summary>
        /// <param name="sOU">The OU location you want to save your user</param>
        /// <param name="sUserName">The username of the new user</param>
        /// <param name="sPassword">The password of the new user</param>
        /// <param name="sGivenName">The given name of the new user</param>
        /// <param name="sSurname">The surname of the new user</param>
        /// <returns>returns the UserPrincipal object</returns>
        public UserPrincipal CreateNewUser(string sOU, string sUserName, string sPassword, string sGivenName, string sSurname)
        {
            if (!IsUserExisiting(sUserName))
            {
                PrincipalContext oPrincipalContext = GetPrincipalContext(sOU);
 
                UserPrincipal oUserPrincipal = new UserPrincipal(oPrincipalContext, sUserName, sPassword, true /*Enabled or not*/);
 
                //User Log on Name
                oUserPrincipal.UserPrincipalName = sUserName;
                oUserPrincipal.GivenName = sGivenName;
                oUserPrincipal.Surname = sSurname;
                oUserPrincipal.Save();
 
                return oUserPrincipal;
            }
            else
            {
                return GetUser(sUserName);
            }
        }
 
        /// <summary>
        /// Deletes a user in Active Directory
        /// </summary>
        /// <param name="sUserName">The username you want to delete</param>
        /// <returns>Returns true if successfully deleted</returns>
        public bool DeleteUser(string sUserName)
        {
            try
            {
                UserPrincipal oUserPrincipal = GetUser(sUserName);
 
                oUserPrincipal.Delete();
                return true;
            }
            catch
            {
                return false;
            }
        }
 
        #endregion
 
        #region Group Methods
 
        /// <summary>
        /// Creates a new group in Active Directory
        /// </summary>
        /// <param name="sOU">The OU location you want to save your new Group</param>
        /// <param name="sGroupName">The name of the new group</param>
        /// <param name="sDescription">The description of the new group</param>
        /// <param name="oGroupScope">The scope of the new group</param>
        /// <param name="bSecurityGroup">True is you want this group to be a security group, false if you want this as a distribution group</param>
        /// <returns>Retruns the GroupPrincipal object</returns>
        public GroupPrincipal CreateNewGroup(string sOU, string sGroupName, string sDescription, GroupScope oGroupScope, bool bSecurityGroup)
        {
            PrincipalContext oPrincipalContext = GetPrincipalContext(sOU);
 
            GroupPrincipal oGroupPrincipal = new GroupPrincipal(oPrincipalContext, sGroupName);
            oGroupPrincipal.Description = sDescription;
            oGroupPrincipal.GroupScope = oGroupScope;
            oGroupPrincipal.IsSecurityGroup = bSecurityGroup;
            oGroupPrincipal.Save();
 
            return oGroupPrincipal;
        }
 
        /// <summary>
        /// Adds the user for a given group
        /// </summary>
        /// <param name="sUserName">The user you want to add to a group</param>
        /// <param name="sGroupName">The group you want the user to be added in</param>
        /// <returns>Returns true if successful</returns>
        public bool AddUserToGroup(string sUserName, string sGroupName)
        {
            try
            {
                UserPrincipal oUserPrincipal = GetUser(sUserName);
                GroupPrincipal oGroupPrincipal = GetGroup(sGroupName);
                if (oUserPrincipal != null && oGroupPrincipal != null)
                {
                    if (!IsUserGroupMember(sUserName, sGroupName))
                    {
                        oGroupPrincipal.Members.Add(oUserPrincipal);
                        oGroupPrincipal.Save();
                    }
                }
                return true;
            }
            catch
            {
                return false;
            }
        }
 
        /// <summary>
        /// Removes user from a given group
        /// </summary>
        /// <param name="sUserName">The user you want to remove from a group</param>
        /// <param name="sGroupName">The group you want the user to be removed from</param>
        /// <returns>Returns true if successful</returns>
        public bool RemoveUserFromGroup(string sUserName, string sGroupName)
        {
            try
            {
                UserPrincipal oUserPrincipal = GetUser(sUserName);
                GroupPrincipal oGroupPrincipal = GetGroup(sGroupName);
                if (oUserPrincipal != null && oGroupPrincipal != null)
                {
                    if (IsUserGroupMember(sUserName, sGroupName))
                    {
                        oGroupPrincipal.Members.Remove(oUserPrincipal);
                        oGroupPrincipal.Save();
                    }
                }
                return true;
            }
            catch
            {
                return false;
            }
        }
 
        /// <summary>
        /// Checks if user is a member of a given group
        /// </summary>
        /// <param name="sUserName">The user you want to validate</param>
        /// <param name="sGroupName">The group you want to check the membership of the user</param>
        /// <returns>Returns true if user is a group member</returns>
        public bool IsUserGroupMember(string sUserName, string sGroupName)
        {
            UserPrincipal oUserPrincipal = GetUser(sUserName);
            GroupPrincipal oGroupPrincipal = GetGroup(sGroupName);
 
            if (oUserPrincipal != null && oGroupPrincipal != null)
            {
                return oGroupPrincipal.Members.Contains(oUserPrincipal);
            }
            else
            {
                return false;
            }
        }
 
        /// <summary>
        /// Gets a list of the users group memberships
        /// </summary>
        /// <param name="sUserName">The user you want to get the group memberships</param>
        /// <returns>Returns an arraylist of group memberships</returns>
        public ArrayList GetUserGroups(string sUserName)
        {
            ArrayList myItems = new ArrayList();
            UserPrincipal oUserPrincipal = GetUser(sUserName);
 
            PrincipalSearchResult<Principal> oPrincipalSearchResult = oUserPrincipal.GetGroups();
 
            foreach (Principal oResult in oPrincipalSearchResult)
            {
                myItems.Add(oResult.Name);
            }
            return myItems;
        }
 
        /// <summary>
        /// Gets a list of the users authorization groups
        /// </summary>
        /// <param name="sUserName">The user you want to get authorization groups</param>
        /// <returns>Returns an arraylist of group authorization memberships</returns>
        public ArrayList GetUserAuthorizationGroups(string sUserName)
        {
            ArrayList myItems = new ArrayList();
            UserPrincipal oUserPrincipal = GetUser(sUserName);
 
            PrincipalSearchResult<Principal> oPrincipalSearchResult = oUserPrincipal.GetAuthorizationGroups();
 
            foreach (Principal oResult in oPrincipalSearchResult)
            {
                myItems.Add(oResult.Name);
            }
            return myItems;
        }
 
        #endregion
 
        #region Helper Methods
 
        /// <summary>
        /// Gets the base principal context
        /// </summary>
        /// <returns>Retruns the PrincipalContext object</returns>
        public PrincipalContext GetPrincipalContext()
        {
            /*
            //SPXMIW2869    SPXMIW2869\giuseppe.aino
            //WORKGROUP
            string name = "SPXMIW2869"; //sDomain
            string container = "WORKGROUP";  //DefaultOU
            string userName = "giuseppe.aino"; //ServiceUser
            string password = "P0lpetta71"; //ServicePassword
             */
            PrincipalContext oPrincipalContext;
            if (string.IsNullOrWhiteSpace(m_Domain))
            {
                oPrincipalContext = new PrincipalContext(ContextType.Domain, null); // Default domain
            }
            else
            {
                oPrincipalContext = new PrincipalContext(ContextType.Domain,
                    m_Domain,
                    m_DefaultOU,
                    ContextOptions.SimpleBind,
                    m_ServiceUser,
                    m_ServicePassword);
 
            }
            return oPrincipalContext;
        }
 
        /// <summary>
        /// Gets the principal context on specified OU
        /// </summary>
        /// <param name="sOU">The OU you want your Principal Context to run on</param>
        /// <returns>Retruns the PrincipalContext object</returns>
        public PrincipalContext GetPrincipalContext(string sOU)
        {
            PrincipalContext oPrincipalContext = new PrincipalContext(ContextType.Domain, 
                                            m_Domain, 
                                            sOU, 
                                            ContextOptions.SimpleBind, 
                                            m_ServiceUser, 
                                            m_ServicePassword);
            return oPrincipalContext;
        }
 
        #endregion
    }
}

Esempio d'uso:

ADMethodsAccountManagement ADMethods = new ADMethodsAccountManagement();
 
UserPrincipal myUser = ADMethods.GetUser("Test");
myUser.GivenName = "Given Name";
myUser.Surname = "Surname";
myUser.MiddleName = "Middle Name";
myUser.EmailAddress = "Email Address";
myUser.EmployeeId = "Employee ID";
myUser.Save();

Utenze Impersonificazione

Per eseguire delle operazioni con utente specifico, link interno: [CSharp:Sicurezza Impersonificazione | Impersonificazione]]

Processi

Comando Sleep

Esempio di applicazione console, differenza di date con DateTimeOffset:

using System;
using System.Threading;
 
public class Program
{
    public static void Main()
    {
        DateTime ora = DateTime.UtcNow;
        Thread.Sleep(30000);
        DateTimeOffset oraDopo = DateTime.UtcNow;
        double differenza = oraDopo.Subtract(ora).TotalMinutes; // Risultato positivo > 0 ovvero 0.50000
 
 
        Console.WriteLine(string.Format("Ora {0}, dopo {1}\r\nDifferenza {2}", ora.ToString(), oraDopo, differenza));
        Console.ReadLine();
    }
}

Appunti Soluzioni da elaborare

Accedere al FileSystem in rete con credenziali

"Open/browse a password protected mapped network drive""Connect to network drive with user name and password"
Ho trovato qs:

JSON

Caricare un file JSON

Caricamento in oggetto tipizzato

Esempio prelevato da StackOverflow [1]

public void LoadJson()
{
    using (StreamReader r = new StreamReader("file.json"))
    {
        string json = r.ReadToEnd();
        List<Item> items = JsonConvert.DeserializeObject<List<Item>>(json);
    }
}
 
public class Item
{
    public int millis;
    public string stamp;
    public DateTime datetime;
    public string light;
    public float temp;
    public float vcc;
}

Caricamento in oggetto dinamico

dynamic array = JsonConvert.DeserializeObject(json);
foreach(var item in array)
{
    Console.WriteLine("{0} {1}", item.temp, item.vcc);
}

C'è una via più interessante qui [2] Lo riporto

JObject o1 = JObject.Parse(File.ReadAllText(@"c:\videogames.json"));
 
// read JSON directly from a file
using (StreamReader file = File.OpenText(@"c:\videogames.json"))
using (JsonTextReader reader = new JsonTextReader(file))
{
  JObject o2 = (JObject) JToken.ReadFrom(reader);
}

Date Giorni Settimane Mesi

Ottenere Lunedì e Martedì

Metodo di Helper

/// <summary>
/// Data in input una data, restituisce il Lunedì della settimana di appartenenza in formato DateTime!
/// Se ECCEZIONE restituisce la data di oggi
/// </summary>
/// <param name="sData">Data di riferimento nel formato dd/MM/yyyy</param>
/// <returns>Lunedì della settimana, in CASO DI ECCEZIONE restituisce la data odierna!</returns>
public static DateTime GetMonday(string sData)
{
	try
	{
		DateTime currentTime = sData.ConvertStringDateToDateTime();
		DateTime mondayDate = currentTime;
		int deltaDays;
 
		if (currentTime.DayOfWeek != DayOfWeek.Monday)
		{
			if (currentTime.DayOfWeek == DayOfWeek.Sunday)
				deltaDays = 6;
			else
				deltaDays = currentTime.DayOfWeek - DayOfWeek.Monday;
			TimeSpan ts = new TimeSpan(deltaDays, 0, 0, 0);
			mondayDate -= ts;
		}
		return mondayDate;
	}
	catch (Exception e)
	{
		return DateTime.Now;
	}
}

Uso

DateTime dtDataDa = FBHelper.GetMonday(lstCuCe.giorno);
TimeSpan ts = new TimeSpan(6, 0, 0, 0);
TimeSpan delta = new TimeSpan(1, 0, 0, 0);
DateTime dtDataA = dtDataDa + ts;

Mappa e Links


C# | Tips programmazione


Helper DB | WindowsForm Soluzioni varie | dotnetfiddle