ATOUTFOX
COMMUNAUTÉ FRANCOPHONE DES PROFESSIONNELS FOXPRO
Visual FoxPro : le développement durable

StrTran en C#   



L'auteur

Gregory Adam
Belgique Belgique
Membre Actif (personne physique)
# 0000001121
enregistré le 04/06/2006

Fiche personnelle


Note des membres
20/20
1 vote


Contributions > 80 dotnet > 01 C#

StrTran en C#
# 0000000751
ajouté le 06/04/2010 11:58:40 et modifié le 07/04/2010
consulté 10761 fois
Niveau débutant


Le téléchargement des pièces jointes est limité aux membres
Veuillez vous identifier ou vous inscrire si vous n'avez pas encore de compte ...
Description

Deux methodes d'extension de Strtran - avec

  • Une qui utilise IndexOf()
  • Une qui utilise RegEx
Code source :
// exemple de celle qui utilise Regex
using System;

using GregoryAdam.Base.ExtensionMethods;

namespace BaseTest
{
  class test3
  {

    //______________________________________________________________________
    static void Main()
    {
      string[,] test =
      {
        { "hello""o""123""hell123"},
        { "+1+2""+""-""-1-2" },
        { "$1$2""$""-""-1-2" },
        { "{1+{2""{""-""-1+-2" },
        { "{1+{2""{""$""$1+$2" },
        { "hello""O""$$""hell$$"},
        { "hello""H", @"$1\$2", @"$1\$2ello"},
        { "hello""H"null, @"ello"}
      };

      for (int i = 0; i <= test.GetUpperBound(0); i++)
      {
        string input = test[i, 0];
        string from = test[i, 1];
        string to = test[i, 2];
        string expect = test[i, 3];

        string got = input.Replace(fromto, true);

        Console.WriteLine("input: {0}, expect: {1}, got: {2}, result: {3}"input, expect, got, expect == got);
      }
      Console.ReadLine();
    }

  }
}


// source des deux methodes
using System;
using System.Text;
using System.Text.RegularExpressions;

using GregoryAdam.Base.Constants;

namespace GregoryAdam.Base.ExtensionMethods
{
  public static partial class ExtensionMethods_String
  {

    //______________________________________________________________________
    /// <summary>
    /// Replaces every occurrence of oldValue with newValue
    /// </summary>
    /// <param name="s"></param>
    /// <param name="oldValue">The string to be replaced</param>
    /// <param name="newValue">The string that replaces all occurrences of oldValue
    /// <para>May be null or the empty string</para></param>
    /// <param name="stringComparison"></param>
    /// <returns></returns>
    public static string Replace(
        this string s,
        string oldValue,
        string newValue,
        StringComparison stringComparison
      )
    {
      if (string.IsNullOrEmpty(s) || string.IsNullOrEmpty(oldValue))
        return s;

      int offset = 0;
      int n = s.IndexOf(oldValue, offset, stringComparison);

      if (n < 0 )
        return s;

      int oldLength = oldValue.Length;
      bool isNewValueNullOrEmpty = string.IsNullOrEmpty(newValue);

      StringBuilder sb = new StringBuilder();

      do
      {
        if (n - offset > 0)
          sb.Append(s, offset, n - offset);

        if( !isNewValueNullOrEmpty )
          sb.Append(newValue);

        offset = n + oldLength;
      }
      while ((n = s.IndexOf(oldValue, offset, stringComparison)) >= 0);

      if (offset < s.Length)
        sb.Append(s, offset, s.Length - offset);

      return sb.ToString();

    }
    //______________________________________________________________________
    /// <summary>
    /// Replaces every occurrence of oldValue with newValue using Regex
    /// </summary>
    /// <param name="s"></param>
    /// <param name="oldValue">The string to be replaced</param>
    /// <param name="newValue">The string that replaces all occurrences of oldValue
    /// <para>May be null or the empty string</para></param>
    /// </param>
    /// <param name="ignoreCase"></param>
    /// <returns></returns>
    public static string Replace(
        this string s,
        string oldValue,
        string newValue,
        bool ignoreCase
      )
    {
      if (string.IsNullOrEmpty(s) || string.IsNullOrEmpty(oldValue))
        return s;

      // oldValuePattern
      string oldValuePattern = Regex.Replace(
                  oldValue,
                  RegexConstants.SpecialPatternCharsPattern,
                  RegexConstants.SpecialPatternCharsPatternReplace
                  );

      string newValuePattern;
      if (string.IsNullOrEmpty(newValue))
        newValuePattern = "";
      else
        newValuePattern = Regex.Replace(
                  newValue,
                  RegexConstants.SpecialReplaceCharsPattern,
                  RegexConstants.SpecialReplaceCharsPatternReplace
                  );


      RegexOptions regexOptions = !ignoreCase ?
            RegexOptions.None
          : RegexOptions.CultureInvariant | RegexOptions.IgnoreCase;

      return Regex.Replace(s, oldValuePattern, newValuePattern, regexOptions);

    }
    //______________________________________________________________________
  }
}

// Constants for method that uses Regex
using System.Text;

namespace GregoryAdam.Base.Constants
{
  public static class RegexConstants
  {
    //______________________________________________________________________
    /// <summary>
    /// Characters that need to be escaped in a pattern
    /// </summary>
    public static readonly char[] SpecialPatternChars =
    {  '\\''^''$''.',
      '['']',
      '('')''|',
      '{''}',
      '*''+''?'
    };
    //______________________________________________________________________
    public static readonly string SpecialPatternCharsPattern =
        Build_SpecialPatternCharsPattern(SpecialPatternChars);
    //______________________________________________________________________
    public static string SpecialPatternCharsPatternReplace = @"\$1";
    //______________________________________________________________________
    /// <summary>
    /// chars that have to be escaped with $ in the replacement pattern
    /// </summary>
    public static readonly char[] SpecialReplaceChars =
      {  '$' };
    //______________________________________________________________________
    public static readonly string SpecialReplaceCharsPattern =
      Build_SpecialPatternCharsPattern(SpecialReplaceChars);
    //______________________________________________________________________
    public static readonly string SpecialReplaceCharsPatternReplace = @"$$$1";
    //______________________________________________________________________
    private static string Build_SpecialPatternCharsPattern(char[] chars)
    {
      // a b c   becomes
      // (\a|\b|\c)
      // length * 3 + 1 + 1 - 1
      StringBuilder sb = new StringBuilder(chars.Length * 3 + 1);
      sb.Append('(');

      foreach (char c in chars)
      {
        sb.AppendFormat(@"\{0}|", c);
      }

      sb[sb.Length-1] = ')';

      return sb.ToString();
    }
    //______________________________________________________________________
  }
}

Commentaires
le 29/05/2015, Olivier Hamou a écrit :
Salut Greg,

Tu aurais une routine qui peut crypter et décrypter un varchar(30) ?

le 29/05/2015, Gregory Adam a écrit :

(1) Sache que crypter/décrypter en .net se fait sur des bytes
Donc il faut convertir les char ( ou la chaine) en un byte[] d'abord

(2) Si c'est pour un mot de passé, utilise un hash ( eg MD5)

(3) Dans les autres cas regarde AES/Rijndael qui fait du block cypher
La longueur du resultat crypté sere un multiple du block size, donc impossible de connaitre la longueur de la chaine originale

Utilise PKCS7 ou ANSIX923 ou ISO10126 padding et Key + IV


Publicité

Les pubs en cours :

www.atoutfox.org - Site de la Communauté Francophone des Professionnels FoxPro - v3.4.0 - © 2004-2024.
Cette page est générée par un composant COM+ développé en Visual FoxPro 9.0-SP2-HF3