Asp. Net type conversion class of common class code sharing

  • 2021-07-09 07:57:17
  • OfStack

No more nonsense, just post the code for everyone. The specific code is as follows:


 /// <summary>
 ///  Type conversion class 
 ///  Handle the case that the database fetch field is empty 
 /// </summary>
 public static class DBConvert
 {
  #region------------------ToInt32 Type conversion ------------------
  /// <summary>
  ///  Read the string in the database and convert it to Int32
  ///  Returns when empty 0
  /// </summary>
  /// <param name="obj">object Value of type </param>
  /// <returns>Int32 Type </returns>
  public static int ToInt32(object obj)
  {
   int result = 0;
   if (IsInt(Convert.ToString(obj)))
   {
    result = Convert.ToInt32(obj);
   }
   else if (obj != null && obj is Enum) // Dealing with non- null Value type ( Or enumerate )
   {
    result = ((IConvertible)obj).ToInt32(null);
   }
   return result;
  }
  /// <summary>
  ///  Read the string in the database and convert it to Int32
  ///  Returns when empty 0
  /// </summary>
  /// <param name="str">string Value of type </param>
  /// <returns>Int32 Type </returns>
  public static int ToInt32(string str)
  {
   int result = 0;
   if (IsInt(str))
   {
    result = Convert.ToInt32(str);
   }
   return result;
  }
  /// <summary>
  ///  Judge 1 Whether the string belongs to Int Type 
  ///  If yes, return true If it is not returned false
  /// </summary>
  /// <param name="str">string Value of type </param>
  /// <returns>true Yes Int String of ( That is, it can be converted into Int Type ) , false : No Int String of type </returns>
  public static bool IsInt(string str)
  {
   bool result = false;
   if (str != "" && str!=null)
   {
    Regex reg = new Regex("^[0-9]*$");
    if (reg.IsMatch(str))
    {
     result = true;
    }
   }
   return result;
  }
  #endregion
  #region------------------ToString Type conversion ------------------
  /// <summary>
  ///  Read the string in the database and convert it to string
  /// </summary>
  /// <param name="obj">object Value of type </param>
  /// <returns>string Type </returns>
  public static string ToString(object obj)
  {
   string result = "";
   if (obj != null)
   {
    result = Convert.ToString(obj);
   }
   return result;
  }
  #endregion
  #region------------------ToDouble Type conversion ------------------
  /// <summary>
  ///  Judge 1 Whether the string belongs to Double Type ( Including negative floating point type )
  ///  If yes, return true If it is not returned false
  /// </summary>
  /// <param name="str">string Value of type </param>
  /// <returns>true Yes Double String of ( That is, it can be converted into Double Type ) , false : No Double String of type </returns>
  public static bool IsDouble(string str)
  {
   bool result = false;
   if (str != "" && str != null)
   {
    Regex reg = new Regex(@"^(-?\d+)(\.\d+)?$");
    if (reg.IsMatch(str))
    {
     result = true;
    }
   }
   return result;
  }
  /// <summary>
  ///  Read the string in the database and convert it to Int32
  ///  Returns when empty 0
  /// </summary>
  /// <param name="obj">object Value of type </param>
  /// <returns>Int32 Type </returns>
  public static double ToDouble(object obj)
  {
   double result = 0.0;
   if (IsDouble(Convert.ToString(obj)))
   {
    result = Convert.ToDouble(obj);
   }
   else if (obj != null && obj is Enum) // Processing enumeration 
   {
    result = ((IConvertible)obj).ToDouble(null);
   }
   return result;
  }
  /// <summary>
  ///  Read the string in the database and convert it to Int32
  ///  Returns when empty 0
  /// </summary>
  /// <param name="str">string Value of type </param>
  /// <returns>Int32 Type </returns>
  public static double ToDouble(string str)
  {
   double result = 0.0;
   if (IsDouble(str))
   {
    result = Convert.ToDouble(str);
   }
   return result;
  }
  #endregion
  #region------------------ToDateTime Type conversion ------------------
  /// <summary>
  ///  Determining whether the time format is a time type 
  ///  Such as 23:10
  /// </summary>
  /// <param name="str"> String to judge </param>
  /// <returns>true Is a string of type time ( That is, it can be converted to a time type ) , false String not of type time </returns>
  public static bool isDateTime(string str)
  {
   bool result = false;
   if (str != "" && str != null)
   {
    Regex reg = new Regex("(([01]\\d)|(2[0-3])):[0-5]\\d");
    if (reg.IsMatch(str))
    {
     result = true;
    }
   }
   return result;
  }
  #endregion
 }
}
//"^\d+(\.\d+)?$"    // Non-negative floating-point numbers (positive floating-point numbers)  + 0 ) 
//"^(([0-9]+\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\.[0-9]+)|([0-9]*[1-9][0-9]*))$"    // Positive floating point number 
//"^((-\d+(\.\d+)?)|(0+(\.0+)?))$"    // Non-positive floating point number (negative floating point number)  + 0 ) 
//"^(-(([0-9]+\.[0-9]*[1-9][0-9]*)|([0-9]*[1-9][0-9]*\.[0-9]+)|([0-9]*[1-9][0-9]*)))$"    // Negative floating point number 
//"^(-?\d+)(\.\d+)?$"    // Floating point number 

Well, that's the end of the Asp. Net type conversion class (generic class) code sharing.

Let's look at the example code of the ASP. NET page data validation generic class.


public class PageValidate
{
private static Regex RegPhone = new Regex("^[0-9]+[-]?[0-9]+[-]?[0-9]$");
private static Regex RegNumber = new Regex("^[0-9]+$");
private static Regex RegNumberSign = new Regex("^[+-]?[0-9]+$");
private static Regex RegDecimal = new Regex("^[0-9]+[.]?[0-9]+$");
private static Regex RegDecimalSign = new Regex("^[+-]?[0-9]+[.]?[0-9]+$"); // Equivalent to ^[+-]?\d+[.]?\d+$
private static Regex RegEmail = new Regex("^[\\w-]+@[\\w-]+\\.(com|net|org|edu|mil|tv|biz|info)$");//w  A string of English letters or numbers, and  [a-zA-Z0-9]  Grammar 1 Sample 
private static Regex RegCHZN = new Regex("[\u4e00-\u9fa5]");
public PageValidate()
{
}
// Numeric string checking #region  Numeric string checking 
public static bool IsPhone(string inputData)
{
Match m = RegPhone.Match(inputData);
return m.Success;
}
/**//// <summary>
///  Check Request The key value of the query string, whether it is a number, and the maximum length limit 
/// </summary>
/// <param name="req">Request</param>
/// <param name="inputKey">Request Key value of </param>
/// <param name="maxLen"> Maximum length </param>
/// <returns> Return Request Query string </returns>
public static string FetchInputDigit(HttpRequest req, string inputKey, int maxLen)
{
string retVal = string.Empty;
if(inputKey != null && inputKey != string.Empty)
{
retVal = req.QueryString[inputKey];
if(null == retVal)
retVal = req.Form[inputKey];
if(null != retVal)
{
retVal = SqlText(retVal, maxLen);
if(!IsNumber(retVal))
retVal = string.Empty;
}
}
if(retVal == null)
retVal = string.Empty;
return retVal;
}
/**//// <summary>
///  Whether it is a numeric string 
/// </summary>
/// <param name="inputData"> Input string </param>
/// <returns></returns>
public static bool IsNumber(string inputData)
{
Match m = RegNumber.Match(inputData);
return m.Success;
}
/**//// <summary>
///  Whether it is a numeric string   Can be signed 
/// </summary>
/// <param name="inputData"> Input string </param>
/// <returns></returns>
public static bool IsNumberSign(string inputData)
{
Match m = RegNumberSign.Match(inputData);
return m.Success;
}
/**//// <summary>
///  Is it a floating point number 
/// </summary>
/// <param name="inputData"> Input string </param>
/// <returns></returns>
public static bool IsDecimal(string inputData)
{
Match m = RegDecimal.Match(inputData);
return m.Success;
}
/**//// <summary>
///  Is it a floating point number   Can be signed 
/// </summary>
/// <param name="inputData"> Input string </param>
/// <returns></returns>
public static bool IsDecimalSign(string inputData)
{
Match m = RegDecimalSign.Match(inputData);
return m.Success;
}
#endregion
// Chinese detection #region  Chinese detection 
/**//// <summary>
///  Detect whether there are Chinese characters 
/// </summary>
/// <param name="inputData"></param>
/// <returns></returns>
public static bool IsHasCHZN(string inputData)
{
Match m = RegCHZN.Match(inputData);
return m.Success;
}
#endregion
// Mail address #region  Mail address 
/**//// <summary>
///  Is it a floating point number   Can be signed 
/// </summary>
/// <param name="inputData"> Input string </param>
/// <returns></returns>
public static bool IsEmail(string inputData)
{
Match m = RegEmail.Match(inputData);
return m.Success;
}
#endregion
// Others #region  Others 
/**//// <summary>
///  Checks the maximum length of a string and returns a string of the specified length 
/// </summary>
/// <param name="sqlInput"> Input string </param>
/// <param name="maxLength"> Maximum length </param>
/// <returns></returns>
public static string SqlText(string sqlInput, int maxLength)
{
if(sqlInput != null && sqlInput != string.Empty)
{
sqlInput = sqlInput.Trim();
if(sqlInput.Length > maxLength)// Truncating Strings by Maximum Length 
sqlInput = sqlInput.Substring(0, maxLength);
}
return sqlInput;
}
/**//// <summary>
///  String encoding 
/// </summary>
/// <param name="inputData"></param>
/// <returns></returns>
public static string HtmlEncode(string inputData)
{
return HttpUtility.HtmlEncode(inputData);
}
/**//// <summary>
///  Settings Label Display Encode String of 
/// </summary>
/// <param name="lbl"></param>
/// <param name="txtInput"></param>
public static void SetLabel(Label lbl, string txtInput)
{
lbl.Text = HtmlEncode(txtInput);
}
public static void SetLabel(Label lbl, object inputObj)
{
SetLabel(lbl, inputObj.ToString());
}
// String cleaning 
public static string InputText(string inputString, int maxLength)
{
StringBuilder retVal = new StringBuilder();
//  Check whether it is empty 
if ((inputString != null) && (inputString != String.Empty))
{
inputString = inputString.Trim();
// Check length 
if (inputString.Length > maxLength)
inputString = inputString.Substring(0, maxLength);
// Replace dangerous characters 
for (int i = 0; i < inputString.Length; i++)
{
switch (inputString[i])
{
case '"':
retVal.Append("&quot;");
break;
case '<':
retVal.Append("&lt;");
break;
case '>':
retVal.Append("&gt;");
break;
default:
retVal.Append(inputString[i]);
break;
}
}
retVal.Replace("'", " ");//  Replace single quotation marks 
}
return retVal.ToString();
}
/**//// <summary>
///  Convert to  HTML code
/// </summary>
/// <param name="str">string</param>
/// <returns>string</returns>
public static string Encode(string str)
{
str = str.Replace("&","&amp;");
str = str.Replace("'","''");
str = str.Replace("\"","&quot;");
str = str.Replace(" ","&nbsp;");
str = str.Replace("<","&lt;");
str = str.Replace(">","&gt;");
str = str.Replace("\n","<br>");
return str;
}
/**//// <summary>
/// Analyse html Cheng   Ordinary text 
/// </summary>
/// <param name="str">string</param>
/// <returns>string</returns>
public static string Decode(string str)
{
str = str.Replace("<br>","\n");
str = str.Replace("&gt;",">");
str = str.Replace("&lt;","<");
str = str.Replace("&nbsp;"," ");
str = str.Replace("&quot;","\"");
return str;
}
public static string SqlTextClear(string sqlText)
{
if (sqlText == null)
{
return null;
}
if (sqlText == "")
{
return "";
}
sqlText = sqlText.Replace(",", "");// Removal ,
sqlText = sqlText.Replace("<", "");// Removal <
sqlText = sqlText.Replace(">", "");// Removal >
sqlText = sqlText.Replace("--", "");// Removal --
sqlText = sqlText.Replace("'", "");// Removal '
sqlText = sqlText.Replace("\"", "");// Removal "
sqlText = sqlText.Replace("=", "");// Removal =
sqlText = sqlText.Replace("%", "");// Removal %
sqlText = sqlText.Replace(" ", "");// Remove spaces 
return sqlText;
}
#endregion
// Is it composed of specific characters #region  Is it composed of specific characters 
public static bool isContainSameChar(string strInput)
{
string charInput = string.Empty;
if (!string.IsNullOrEmpty(strInput))
{
charInput = strInput.Substring(0, 1);
}
return isContainSameChar(strInput, charInput, strInput.Length);
}
public static bool isContainSameChar(string strInput, string charInput, int lenInput)
{
if (string.IsNullOrEmpty(charInput))
{
return false;
}
else
{
Regex RegNumber = new Regex(string.Format("^([{0}])+$", charInput));
//Regex RegNumber = new Regex(string.Format("^([{0}]{{1}})+$", charInput,lenInput));
Match m = RegNumber.Match(strInput);
return m.Success;
}
}
#endregion
// Check whether the input parameters are some defined special characters: This method is currently used to check the security of password input #region  Check whether the input parameters are some defined special characters: This method is currently used to check the security of password input 
/**//// <summary>
///  Check whether the input parameters are some defined special characters: This method is currently used to check the security of password input 
/// </summary>
public static bool isContainSpecChar(string strInput)
{
string[] list = new string[] { "123456", "654321" };
bool result = new bool();
for (int i = 0; i < list.Length; i++)
{
if (strInput == list[i])
{
result = true;
break;
}
}
return result;
}
#endregion
}

Related articles: