ParseHelper.cs :  » Persistence-Frameworks » ORM.NET » OrmLib » C# / CSharp Open Source

Home
C# / CSharp Open Source
1.2.6.4 mono .net core
2.2.6.4 mono core
3.Aspect Oriented Frameworks
4.Bloggers
5.Build Systems
6.Business Application
7.Charting Reporting Tools
8.Chat Servers
9.Code Coverage Tools
10.Content Management Systems CMS
11.CRM ERP
12.Database
13.Development
14.Email
15.Forum
16.Game
17.GIS
18.GUI
19.IDEs
20.Installers Generators
21.Inversion of Control Dependency Injection
22.Issue Tracking
23.Logging Tools
24.Message
25.Mobile
26.Network Clients
27.Network Servers
28.Office
29.PDF
30.Persistence Frameworks
31.Portals
32.Profilers
33.Project Management
34.RSS RDF
35.Rule Engines
36.Script
37.Search Engines
38.Sound Audio
39.Source Control
40.SQL Clients
41.Template Engines
42.Testing
43.UML
44.Web Frameworks
45.Web Service
46.Web Testing
47.Wiki Engines
48.Windows Presentation Foundation
49.Workflows
50.XML Parsers
C# / C Sharp
C# / C Sharp by API
C# / CSharp Tutorial
C# / CSharp Open Source » Persistence Frameworks » ORM.NET 
ORM.NET » OrmLib » ParseHelper.cs
//This file is part of ORM.NET.
//
//ORM.NET is free software; you can redistribute it and/or
//modify it under the terms of the GNU Lesser General Public
//License as published by the Free Software Foundation; either
//version 2.1 of the License, or (at your option) any later version.
//
//ORM.NET is distributed in the hope that it will be useful,
//but WITHOUT ANY WARRANTY; without even the implied warranty of
//MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
//Lesser General Public License for more details.
//
//You should have received a copy of the GNU Lesser General Public
//License along with ORM.NET; if not, write to the Free Software
//Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA


using System;
using System.Text.RegularExpressions;
using System.Diagnostics;
using System.Collections;
using System.Collections.Specialized;
using System.IO;
using System.ComponentModel;

namespace OrmLib{
  /// <summary>
  /// Wrapper class to handle emails.
  /// </summary>
  [EditorBrowsable(EditorBrowsableState.Never)]
  public class Email
  {
    private string _NamePart;
    private string _DomainPart;

    /// <summary>
    /// Default Constructor.
    /// </summary>
    public Email()
    {
      _NamePart = "";
      _DomainPart = "";
    }
    /// <summary>
    /// Initailizes fully populated.
    /// </summary>
    /// <param name="email">The underlying email string.</param>
    public Email(string email)
    {
      _NamePart = email.Split('@')[0];
      _DomainPart = email.Split('@')[1];
    }
    /// <summary>
    /// The alias of the email.
    /// </summary>
    /// <value>The alias of the email.</value>
    public string NamePart { get { return _NamePart; } set { _NamePart = value; } }
    /// <summary>
    /// The full domain part of the email.
    /// </summary>
    /// <value>The full domain part of the email.</value>
    public string DomainPart { get { return _DomainPart; } set { _DomainPart = value; } }
    /// <summary>
    /// The alias with an '@' at the end.
    /// </summary>
    /// <value>The alias with an '@' at the end.</value>
    public string FilePart { get { return _NamePart + "@"; } }
    /// <summary>
    /// A path for the domain, in the format tld\domain(\sld)
    /// </summary>
    /// <value>A path for the domain, in the format tld\domain(\sld)</value>
    public string PathPart
    {
      get 
      {
        string result = "";

        result = _DomainPart;
        string[] pathElements = result.Split( '.');
      
        int topPos = pathElements.Length - 1;

        result = "";
        for (int i = topPos; i >= 0; i--)
        {
          result += pathElements[i] + "\\";
        }
        result = result.TrimEnd('\\');
        return result;
      }
    }
    /// <summary>
    /// Gets and sets the full email address.
    /// </summary>
    /// <value>Full email address</value>
    public string EmailAddress
    {
      get
      {
        if (_NamePart == "") return "";

        return _NamePart + "@" + _DomainPart;
      }
      set
      {
        _NamePart = value.Split('@')[0];
        _DomainPart = value.Split('@')[1];
      }
    }
    /// <summary>
    /// Strictly validates the supplied email, returning true if it is valid.
    /// </summary>
    /// <param name="email">The email to validate.</param>
    /// <returns>Whether the email was valid.</returns>
    public static bool ValidateEmail( string email)
    {
      //Regex regexEmail = new Regex( @"\w+([-+._]\w+)*@\w+([-._]\w+)*\.\w+([-.]\w+)*", RegexOptions.IgnoreCase);
      Regex regexEmail = new Regex( @"[a-z]{1}[\w\-+._]{0,63}@([a-z]{1,64}\.){0,1}[a-z0-9]{1,64}\.[a-z]{2,4}", RegexOptions.IgnoreCase);
      Match m = regexEmail.Match( email );
      
      if ((m.Length == email.Length) && (email.Length != 0)) return true;
      else return false;
    }
    /// <summary>
    /// Loosely validates the supplied email, returning true if it is valid.
    /// </summary>
    /// <param name="email">The email to validate.</param>
    /// <returns>Whether the email was valid.</returns>
    public static bool ValidateEmailLenient( string email )
    {
      //if we were to just match by position/occurrence then maybe use these
      //char dot = '.';
      //char at = '@';

      Regex regexEmail = new Regex(@"[\w\d\-_\.]+@[\w\d\-_\.]+\.[\w]+", RegexOptions.IgnoreCase);
      Match m = regexEmail.Match( email );
      
      if ((m.Length == email.Length) && (email.Length != 0)) return true;
      else return false;
    }
    /// <summary>
    /// Loosely validates the supplied emails, returning them in an array format.
    /// </summary>
    /// <param name="emailList">The emails to validate.</param>
    /// <returns>An array of emails, or null if any failed.</returns>
    public static string[] ValidateMultipleEmails( string emailList)
    {
      char[] delims = { ';', ':', ' ', '\t', '\n','\r' };
      string[] email = emailList.Split(delims) ;
      string[] validEmails = null;
      int pos = 0;

      foreach(string s in email)
        if (s != "" && !ValidateEmailLenient(s))
          return null;
        else
          validEmails[pos++] = s;

      return validEmails;
    }
    /// <summary>
    /// Loosely validates the supplied emails, returning all valid ones in a new array.
    /// </summary>
    /// <param name="emailList">The emails to validate.</param>
    /// <returns>An array of valid emails.</returns>
    public static string[] ValidateArrayOfEmails( string[] emailList)
    {
      ArrayList InvalidEmails = new ArrayList();

      foreach(string s in emailList)
        if (s != "" && !ValidateEmailLenient(s)) 
          InvalidEmails.Add(s);  

      return (string[]) InvalidEmails.ToArray(typeof(System.String));
    }
    /// <summary>
    /// Gets the full email address.
    /// </summary>
    /// <returns>Email address.</returns>
    public string ToEmailFormat()
    {
      if (_NamePart == "") return "";

      return _NamePart + "@" + _DomainPart;
    }
    /// <summary>
    /// Gets the web site format, ie. me@domain.com -> me.domin.com
    /// </summary>
    /// <returns>FQDN.</returns>
    public string ToWebFormat()
    {
      if (_NamePart == "") return "";

      return _NamePart + "." + _DomainPart;
    }
  }

  /// <summary>
  /// Helper functions for <seealso cref="Email">Emails</seealso> and strings.
  /// </summary>
  [EditorBrowsable(EditorBrowsableState.Never)]
  public class ParseHelper
  {
    private ParseHelper(){}

    public static Email ParseEmail( string email)
    {
      return new Email(email);
    }

    public static string ToEmail( string accountName, string domainName)
    {
      return accountName + "@" + domainName;
    }

    public static string FormatDateString( DateTime d)
    {
      return d.ToShortDateString() + " " + d.ToLongTimeString();
    }

    public static string ExtractTextBetween( string source, string startTag, string endTag, bool includeStartEndTags)
    {
      
      /*
       * Regex r;

      if (!includeStartEndTags)
        //r = new Regex( startTag + @"(?<content>.*)" + endTag, RegexOptions.IgnoreCase);
        r = new Regex("<body>(?<content>.*)</body>", RegexOptions.IgnoreCase);
      else
        r = new Regex( @"(" + startTag + "?<content>.*" + endTag + ")", RegexOptions.IgnoreCase);

      Match m = r.Match( source );
      if (m.Length > 0) return m.Groups["content"].ToString();
      
      return ""; */

      
      if (source == null || source.Length <= 0) return "";

      int beginPos = source.IndexOf(startTag);
      if (beginPos >= 0)
      {
        //Debug.WriteLine("Found start tag");
        if (!includeStartEndTags) beginPos += startTag.Length;
  
        int endPos = source.IndexOf(endTag, beginPos);
        if (endPos >= 0)
        {
          //Debug.WriteLine("Found end tag");
          if (includeStartEndTags) endPos += endTag.Length;
        }

        string result = source.Substring( beginPos, (endPos - beginPos));
        //Debug.WriteLine("Returning " + result);
        return result;
      }
      return source;
    }

    static public StringDictionary ParseQueryString( string command)
    {
      
      string sKey = "", sValue = "";        
      if ( command.IndexOf('&') == 0 ) command += "&";

      // chop up the query into name value pairs
      StringDictionary sd = new StringDictionary();
      foreach ( string s in command.Split('&') )
      {
        if ( s.IndexOf('=') > 0 )
        {
          sKey = s.Split( '=' )[0];
          sValue = s.Split( '=' )[1];
        }
        else if ( s.Length > 0 )
        {
          sKey = s;
          sValue = "";
        }
        if ( sKey == null ) sKey = "";
        if ( sValue == null ) sValue = "";
          
          
        if (!sd.ContainsKey(sKey)) sd.Add( sKey, sValue );

      }
      return sd;
    }

  }

  /// <summary>
  /// Provides static functions for rendering various objects as strings.
  /// </summary>
  [EditorBrowsable(EditorBrowsableState.Never)]
  public class Formatter
  {
    private Formatter(){}
    /// <summary>
    /// Formats currency into a string
    /// </summary>
    /// <param name="amount">currency amount</param>
    /// <returns>string representation of the currency amount</returns>
    public static string FormatCurrency(decimal amount)
    {
      System.Globalization.NumberFormatInfo n = new System.Globalization.NumberFormatInfo();
      return amount.ToString( "c",  (IFormatProvider) n.GetFormat( n.GetType() ));
    }
    /// <summary>
    /// Formats currency into a string
    /// </summary>
    /// <param name="amount">currency amount</param>
    /// <returns>string representation of the currency amount</returns>
    public static string FormatCurrencyNoDollar(decimal amount)
    {
      return FormatCurrency(amount).TrimStart('$');
    }
    /// <summary>
    /// Useless method
    /// </summary>
    /// <param name="d">Date to format</param>
    /// <returns>string representation of date</returns>
    public static string FormatShortDate( DateTime d)
    {
      return d.ToShortDateString();
    }
    /// <summary>
    /// Converts datetime into an sql compliant string
    /// </summary>
    /// <param name="d">Date to format</param>
    /// <returns>string representation of date</returns>
    public static string FormatShortDateTime( DateTime d)
    {
      return d.ToShortDateString() + " " + d.ToLongTimeString();
    }

    public static string ToHex(byte[] bytes)
    {
      System.Text.StringBuilder sb = new System.Text.StringBuilder(bytes.Length * 2);

      foreach ( byte b in bytes )
      {
        sb.Append(Uri.HexEscape((char)b).Substring(1,2));
      }

      return sb.ToString();
    }
  }

  /// <summary>
  /// Provides static functions for validating standard input types.
  /// </summary>
  public class Validator
  {
    private static Regex r = new Regex( @"\d{13,16}" );
    private static Regex regexPassword = new Regex(@"[\*\-_\w!]{6,30}", RegexOptions.IgnoreCase);

    /// <summary>
    /// Determines if a valid cretitcard number was passed in
    /// </summary>
    /// <param name="cardNumber">The number to check</param>
    /// <returns>whether it was valid</returns>
    public static bool ValidateCreditCard( string cardNumber)
    {
      if ((cardNumber == null) || (cardNumber == "")) return false;
      cardNumber = cardNumber.Replace( " ", "");
      cardNumber = cardNumber.Replace( "-", "");

      if (r.Match( cardNumber).Length > 0) return true;
      return false;
    }
    /// <summary>
    /// This is an internal method and should not be used.
    /// </summary>
    /// <param name="password"></param>
    /// <param name="retypePassword"></param>
    /// <param name="currentLang"></param>
    /// <returns></returns>
    public static ArrayList IsValidPassword(string password, string retypePassword, StringDictionary currentLang)
    {
      //usage: messages.Add IsValidPassword();
      ArrayList messages = new ArrayList();
      Match mPassword = regexPassword.Match(password);

      if (password.Trim() == "") messages.Add(currentLang["Error.SelectPassword"]);
      if (mPassword.Length < password.Length)
        messages.Add (currentLang["Error.InvalidPassword"]);

      if (retypePassword.Trim() == "") messages.Add(currentLang["Error.SelectSecondPassword"]);
      if (password != retypePassword) messages.Add(currentLang["Error.SelectPasswordsNotMatch"]);

      return messages;
    }
    /// <summary>
    /// Checks if the string can be parsed into a double
    /// </summary>
    /// <param name="input">The string to parse</param>
    /// <returns>whether the string could be parsed</returns>
    public static bool IsNumeric( string input)
    {
      try
      {
        //int x = int.Parse( input );
        double.Parse( input );;
      }
      catch(Exception)
      {
        return false;
      }

      return true;
    }
    /// <summary>
    /// Checks if the string can be parsed into a DateTime value
    /// </summary>
    /// <param name="date">The string to parse</param>
    /// <returns>whether the string could be parsed</returns>
    public static bool IsDate( string date)
    {
      try
      {
        DateTime d = DateTime.Parse( date);
      }
      catch(Exception)
      {
        return false;
      }
      return true;
    }
    /// <summary>
    /// 
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    public static bool IsAlphaOnly( string input )
    {
      if ( input == null ) return false;

      Regex r = new Regex("[^a-z]+", RegexOptions.IgnoreCase);

      if ( r.IsMatch(input) ) return false;

      return true;
    }
  }

  /// <summary>
  /// Random string generator.
  /// </summary>
  [EditorBrowsable(EditorBrowsableState.Never)]
  public class Generator
  {
    private Generator(){}

    /// <summary>
    /// Generates a random string.
    /// </summary>
    /// <returns>A random string.</returns>
    public static string GenerateRandomString()
    {
      string result = "";
      char[] letters = {'1','b','c','d','2','f','g','h','3','j','k','l','m','n','4','p','q','r','s','t','5','v','w','x','y','z' };
      System.Random r = new System.Random();
      
      for(int i = 0; i < 8; i++)
      {
        int j = r.Next( 26);
        char c = letters[j];
        result += c;
      }
      return result;      
    }
  }

  
}
www.java2v.com | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.