Copier coller un répertoire en C# (Copy-Paste folder)

 01/01/2019 |   Admin |  C#


Copier le contenu d'un répertoire en utilisant la récursivité :

private static void CopyAll(DirectoryInfo source, DirectoryInfo target)
{
   // Check if the target directory exists, if not, create it.
   if (Directory.Exists(target.FullName) == false)
   {
       Directory.CreateDirectory(target.FullName);
   }
   // Copy each file into the new directory.
   foreach (FileInfo fi in source.GetFiles())
   {
fi.CopyTo(Path.Combine(target.ToString(), fi.Name), true);
   }
   // Copy each subdirectory using recursion.
   foreach (DirectoryInfo diSourceSubDir in source.GetDirectories())
   {
       DirectoryInfo nextTargetSubDir = target.CreateSubdirectory(diSourceSubDir.Name);
       CopyAll(diSourceSubDir, nextTargetSubDir);
   }
}

Lire >>

Changer la connection string d'une autre application avec XML

 01/01/2019 |   Admin |  C#


Comment changer la conenction string d'une autre application avec XML.

A utiliser SEULEMENT pour ce cas, sinon utiliser les méthodes habituelles avec configuration manager.

 

private bool ChangeConnectionString(string connStringName, string newValue, string path)
{
try
{
//CreateXDocument and load configuration file
XDocument doc = XDocument.Load(path + "/web.config");
//Find all connection strings
var query1 = from p in doc.Descendants("connectionStrings").Descendants()
                             select p;
 
//Go throught each connection string elements find atribute specified by argument and replace its value with newVAlue
foreach (var child in query1)
{
foreach (var atr in child.Attributes())
{
if (atr.Name.LocalName == "name" && atr.Value == connStringName)
 
 if (atr.NextAttribute != null && atr.NextAttribute.Name == "connectionString")
 
atr.NextAttribute.Value = newValue;
}
}

doc.Save(path + "/web.config");
return true;
}
catch (Exception ex)
{
lblError.Text += "Error to change the web.config with this value " + newValue + " and this path " + path + "<br/> " + ex.Message;
return false;
       }
}

Lire >>

Trier une liste en c# (avec delegate et sort)

 01/01/2019 |   Admin |  C#


List<TheType> theList = new List<TheType>();
theList.Sort(delegate(TheType t1, TheType t2)
{  return t1.PropertyToOrder.CompareTo(t2.PropertyToOrder);
});

Lire >>

Utiliser les fuseaux horaires (TimeZone) avec ASP.NET

 01/01/2019 |   Admin |  C#


Je travaille actuellement dans une entreprise londonienne, Vestibule-solutions : http://www.vestibule-solutions.com/.

Afin de pouvoir commercialiser ses produits à l'international, la gestion des fuseaux horaires devenait une urgence. Les serveurs sont situés au Royaume Unis, donc si l'on utilise par exemple la fonction DateTime.Now pour un client en Chine, la date retournée sera la date du serveur. Ce qui peut etre étrange pour le client.

Pour moi, le meilleur moyen d'utiliser la gestion des fuseaux horaires est :

  • d'ajouter une classe qui implémentera les méthodes de la classe TimeZoneInfo (Qui a été ajoutée dans le framework 4). Il est préférable d'ajouter une classe pour la flexibilité. Si vous voulez implémenter ou modifier le moyen d'utiliser les fuseaux horaires, seulement cette classe aura besoin d'etre modifiée. 
  • De stocker les dates et heures en base de données au format du serveur. Beaucoup plus simple pour la maintenance. Et si un client venait a changer de pays, il suffit de changer seulement une valeur dans le fichier de configuration.
  • Et bien sur d'afficher toutes les dates sur l'interface utilisateur au format "Local". Toutes les manipulation des dates internes au programme doivent rester au format serveur. 

1- Créer la classe MyDateTime

//-----------------------------------------------------------------------
// <copyright file="MyDateTime.cs" company="Vestibule Solutions">
//     Copyright (c) Vestibule Solutions. All rights reserved.
// </copyright>
// <author>Pierre-Henri Nogues</author>
// <date>17/01/2012</date>
//-----------------------------------------------------------------------
 
namespace Exact.Hospitality.Core.Utility
{
    #region IMPORTS
 
    using System;
    using System.Collections.Generic;
    using System.Configuration;
    using System.Text;
    using Exact.Hospitality.Core.BusinessLogic;
 
    #endregion
 
    ///<summary>
    /// Class MyDateTime to use the TimeZone functions
    ///</summary>
    public class MyDateTime
    {
        #region Properties
 
        ///<summary>
        /// Gets the time zone name of the customer
        ///</summary>
        public static string TimeZoneName
        {
            get
            {
                string timeZone = ConfigurationManager.AppSettings[Constants.AppConfig.TIMEZONE];
 
                if (string.IsNullOrEmpty(timeZone))
                {
                    timeZone = TimeZoneInfo.Local.Id;
                }
 
                return timeZone;
            }
        }
 
        #endregion
 
        #region NOW
 
        ///<summary>
        /// Gets the dateNow of the customer timeZone
        ///</summary>
        public static DateTime Now
        {
            get
            {
                return ConvertToTimeZone(DateTime.Now);
            }
        }
 
        #endregion
 
        #region ConvertTo
 
        ///<summary>
        /// Convert the dateTime to the timeZone dateTime
        ///</summary>
        ///<param name="dt">The dateTime to convert</param>
        ///<returns>Return the dateTime of the time zone</returns>
        public static DateTime ConvertToTimeZone(DateTime dt)
        {
            return TimeZoneInfo.ConvertTimeBySystemTimeZoneId(dt, TimeZoneName);
        }
 
        ///<summary>
        /// Convert the dateTime to the timeZone dateTime
        ///</summary>
        ///<param name="dateString">The dateTime to convert</param>
        ///<returns>Return the dateTime of the time zone</returns>
        public static string ConvertToTimeZone(string dateString)
        {
            try
            {
                if (!string.IsNullOrEmpty(dateString))
                {
                    return TimeZoneInfo.ConvertTimeBySystemTimeZoneId(Convert.ToDateTime(dateString), TimeZoneName).ToString();
                }
                else
                {
                    return string.Empty;
                }
            }
            catch (FormatException fEx)
            {
                // Your logger here ** (Log4Net for example)
 
                return string.Empty;
            }
        }
 
        ///<summary>
        /// Convert the dateTime to the local time
        ///</summary>
        ///<param name="dt">The dateTime to convert</param>
        ///<returns>The local time of this time zone dateTime</returns>
        public static DateTime ConvertToLocal(DateTime dt)
        {
            return TimeZoneInfo.ConvertTime(dt, TimeZoneInfo.FindSystemTimeZoneById(TimeZoneName), TimeZoneInfo.Local);
        }
 
        ///<summary>
        /// Convert a date string to the datetime local time
        ///</summary>
        ///<param name="dateTimeString">The dateTime string to convert</param>
        ///<returns>The local time of this time zone dateTime</returns>
        public static DateTime ConvertToLocal(string dateTimeString)
        {
             return TimeZoneInfo.ConvertTime(Convert.ToDateTime(dateTimeString), TimeZoneInfo.FindSystemTimeZoneById(TimeZoneName), TimeZoneInfo.Local);
        }

        #endregion
 
        #region GetTimeZones
 
        ///<summary>
        /// Get all the time zones
        ///</summary>
        ///<returns>The time zone list</returns>
        public static IList<TimeZoneInfo> GetTimeZones()
        {
            return TimeZoneInfo.GetSystemTimeZones();
        }
 
        #endregion
    }
}

2 - Comment utiliser cette classe :

Du serveur au navigateur :

Utiliser "Now" comme avant mais non plus avec "DateTime.Now" mais "MyDateTime.Now"

Exemple :

txtDate.Text = MyDateTime.Now.ToShortDateString();
Du navigateur au serveur (ou base de données) :

Au lieu d'utiliser "Convert.ToDatetime", utiliser "MyDateTime.ConvertToLocale"

Exemple :

DateTime theDate = MyDateTime.ConvertToLocale(txtDate.Text);

3 - Ajouter la constante dans votre fichier Constants.cs (Ou le creer si vous ne l'utiliser pas)

public class Constants
{
///<summary>
/// Constants for the key of the app.config file
///</summary>
public class AppConfig
{
public const string TIMEZONE = "TimeZone";
}
}

4 - Utiliser app.config pour stocker l'identifiant de la "TimeZone"

<?xmlversion="1.0"encoding="utf-8" ?>
<appSettings>
    <addkey="TimeZone"value="Kamchatka Standard Time" />
</appSettings>

 

Il s'agit d'un exemple avec un client web qui

  • liste tous les fuseaux horaires
  • Change le fuseaux horaire de l'application
  • Affiche l'heure avec le fuseau utilisé
  • Read et Write dans le fichier app.config, l'identifiant de la TimeZone a utiliser

N'hésitez à laisse vos commentaires pour discuter de cette article.

Lire >>

Transformer un fichier CSV en XML

 01/01/2019 |   Admin |  C#


public class ConvertCSVToXML
{
// conversion du fichier CSV téléchargé en fichier xml
private const string _root = "Articles";
private const string _node = "Article";
private const char _separator = ';';
 
public static DataSet convert(string pathSource, string pathDestination)
{
        // remplacement du caractère " " par rien ("")
        StreamReader stream = null;
        string[] saEntetes = null;
        string sLigne = string.Empty;
 
        // Initialisation des DataSet et DataTable
        DataSet csvDataSet = null;
        DataTable csvDataTable = null;
        try
          {
            csvDataSet = new DataSet(_root);
            csvDataTable = new DataTable(_node);
 
            // Lecture du fichier CSV ligne par ligne
            stream = new StreamReader(pathSource);
            sLigne = stream.ReadLine();
 
            // En tenant compte du séparateur
            saEntetes = sLigne.Split(_separator);
 
            for (int i = 0; i < saEntetes.Length; i++)
            {
                // formatage des éléments du fichier XML
                csvDataTable.Columns.Add(saEntetes[i].ToString());
            }
            int ii = 0;
 
            while (sLigne != null)
            {
                if (ii != 0)
             
...

Lire >>

Accéder aux ressources depuis le code behind

 01/01/2019 |   Admin |  C#


label.Text = Resources.NomDuFichier.NomDeLaRessource;

Lire >>

Langue dans laquelle le client utilise son navigateur

 01/01/2019 |   Admin |  C#


using System.Globalization;

 

CultureInfo ci = new CultureInfo(Request.UserLanguages[0]);

string langue = ci.ToString();


[0] -> ordre de préférence du client

Lire >>

Utiliser un rating control dans une GridView

 01/01/2019 |   Admin |  C#


Partie cliente, page aspx

<asp:GridView runat="server"
ID="theGridView"
AutoGenerateColumns="false" >
<Columns>
<asp:TemplateField>
<ItemTemplate>
<table>
<tr>
<td colspan="2">
<%# Eval("texte") %>
</td>
</tr>
<tr>
<td>
<act:Rating
ID="RatingBlague"
runat="server"
MaxRating="6"
CssClass="ratingStar"
StarCssClass="ratingItem"
WaitingStarCssClass="Saved"
FilledStarCssClass="Filled"
EmptyStarCssClass="Empty"
BorderStyle="None"
CurrentRating='<%# Eval("Rang") %>'
Tag='<%# Eval("Id")  %>'
OnChanged="RatingBlague_Changed">
</act:Rating>
</td>
</tr>
</table>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>

CSS

/*RATING*/
 
.ratingStar
{
       white-space: nowrap;
       margin: 1em;
       height: 14px;
       border-style:none;
       border-color:transparent;
}
 
.ratingStar .ratingItem
{
       font-size: 0pt;
       width: 25px;
       height: 25px;
       margin: 0px;
       padding: 0px;
       display: block;
       background-repeat: no-repeat;
       cursor: pointer;
}
 
.ratingStar .Filled
{
       background-image: url(images/ratingStarFilled2.png);
}
 
.ratingStar .Empty
{
       background-image: url(images/ratingStarEmpty2.png);
}
 
.ratingStar .Saved
{
       background-image:
...

Lire >>