Utilities.cs :  » Database » SQL-Power-Injector » SQLPowerInjector » 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 » Database » SQL Power Injector 
SQL Power Injector » SQLPowerInjector » Utilities.cs
//*********************************************************************
//                                   //
//  SQL Power Injector 1.2 Copyright (c) 2006-2007 Francois Larouche //
//                                   //
//  Author  : francois.larouche@sqlpowerinjector.com         //
//  Web Site: www.sqlpowerinjector.com                 //
//                                   //
//*******************************************************************//
using System;
using System.Windows.Forms;
using System.Reflection;
using System.IO;
using System.Text;
using System.Drawing;
using System.Collections;
using System.Xml;
using System.Xml.XPath;
using System.Xml.Serialization;
using System.Diagnostics;
using System.Text.RegularExpressions;

namespace SQLPowerInjector{
  /// <summary>
  /// Summary description for Utilities.
  /// </summary>
  public class Utilities
  {
    #region Constants
    public const int ENCODE_ERROR_CODE = -111111;
    private const int XML_ERROR_FORMAT = -2146233079;
    private const string USER_AGENTS_FILE = "userAgents.xml";
    private const string USER_AGENT_NAME = "name";
    private const string USER_AGENT_ID = "id";
    #endregion

    #region Public Enums
    public enum RichTextboxTypeSearch
    {
      New      = 1,
      Next    = 2,
      Previous  = 3
    }

    public enum enumSQLServerOptions 
    {
      DISABLE_DEF_CNST_CHK = 1,
      IMPLICIT_TRANSACTIONS = 2,
      CURSOR_CLOSE_ON_COMMIT = 4,
      ANSI_WARNINGS = 8,
      ANSI_PADDING = 16,
      ANSI_NULLS = 32,
      ARITHABORT = 64,
      ARITHIGNORE = 128,
      QUOTED_IDENTIFIER = 256,
      NOCOUNT = 512,
      ANSI_NULL_DFLT_ON = 1024,
      ANSI_NULL_DFLT_OFF = 2048,
      CONCAT_NULL_YIELDS_NULL = 4096,
      NUMERIC_ROUNDABORT = 8192,
      XACT_ABORT = 16384
    };
    #endregion

    #region Constructor
    public Utilities() {}
    #endregion

    public static string EncodeURL(string stringToEncode)
    {
      if(stringToEncode != null)
      {
        stringToEncode = stringToEncode.Replace("%", "%25");
        stringToEncode = stringToEncode.Replace("#", "%23");
        stringToEncode = stringToEncode.Replace("+", "%2B");
        stringToEncode = stringToEncode.Replace(" ", "+");
        stringToEncode = stringToEncode.Replace("'", "%27");
        stringToEncode = stringToEncode.Replace("=", "%3D");
        stringToEncode = stringToEncode.Replace("(", "%28");
        stringToEncode = stringToEncode.Replace(")", "%29");
        stringToEncode = stringToEncode.Replace("&", "%26");
      }

      return stringToEncode;
    }

    public static string EncodeCookie(string stringToEncode, bool encodeEqualSign) 
    { 
      if(stringToEncode != null) 
      { 
        stringToEncode = stringToEncode.Replace("%", "%25");
        stringToEncode = stringToEncode.Replace("#", "%23");
        stringToEncode = stringToEncode.Replace("+", "%2B");
        stringToEncode = stringToEncode.Replace(" ", "+");
        stringToEncode = stringToEncode.Replace("'", "%27");
        if(encodeEqualSign)
          stringToEncode = stringToEncode.Replace("=", "%3D");
        stringToEncode = stringToEncode.Replace("(", "%28");
        stringToEncode = stringToEncode.Replace(")", "%29");
        stringToEncode = stringToEncode.Replace(";", "%3b"); 
      } 

      return stringToEncode; 
    } 

    public static string DecodeURL(string stringToDecode)
    {
      if(stringToDecode != null)
      {
        stringToDecode = stringToDecode.Replace("%26", "&");
        stringToDecode = stringToDecode.Replace("%29", ")");
        stringToDecode = stringToDecode.Replace("%28", "(");
        stringToDecode = stringToDecode.Replace("%3D", "=");
        stringToDecode = stringToDecode.Replace("%3d", "=");
        stringToDecode = stringToDecode.Replace("%27", "'");
        stringToDecode = stringToDecode.Replace("%2B", "+");
        stringToDecode = stringToDecode.Replace("%23", "#");
        stringToDecode = stringToDecode.Replace("%2D", "-");
        stringToDecode = stringToDecode.Replace("%2d", "-");
        stringToDecode = stringToDecode.Replace("%3C", "<");
        stringToDecode = stringToDecode.Replace("%3c", "<");
        stringToDecode = stringToDecode.Replace("%3E", ">");
        stringToDecode = stringToDecode.Replace("%3e", ">");
        stringToDecode = stringToDecode.Replace("%22", ".");
        stringToDecode = stringToDecode.Replace("%3C", "<");
        stringToDecode = stringToDecode.Replace("%3c", "<");
        stringToDecode = stringToDecode.Replace("%7B", "{");
        stringToDecode = stringToDecode.Replace("%7b", "{");
        stringToDecode = stringToDecode.Replace("%7D", "}");
        stringToDecode = stringToDecode.Replace("%7d", "}");
        stringToDecode = stringToDecode.Replace("%7C", "|");
        stringToDecode = stringToDecode.Replace("%7c", "|");
        stringToDecode = stringToDecode.Replace("%5C", "\\");
        stringToDecode = stringToDecode.Replace("%5c", "\\");
        stringToDecode = stringToDecode.Replace("%5E", "^");
        stringToDecode = stringToDecode.Replace("%5e", "^");
        stringToDecode = stringToDecode.Replace("%7E", "~");
        stringToDecode = stringToDecode.Replace("%7e", "~");
        stringToDecode = stringToDecode.Replace("%5B", "[");
        stringToDecode = stringToDecode.Replace("%5b", "[");
        stringToDecode = stringToDecode.Replace("%5D", "]");
        stringToDecode = stringToDecode.Replace("%5d", "]");
        stringToDecode = stringToDecode.Replace("%60", "`");
        stringToDecode = stringToDecode.Replace("%2F", "/");
        stringToDecode = stringToDecode.Replace("%2f", "/");
        stringToDecode = stringToDecode.Replace("%3F", "?");
        stringToDecode = stringToDecode.Replace("%3f", "?");
        stringToDecode = stringToDecode.Replace("%25", "%");
      }

      return stringToDecode;
    }

    public static string Char(int asciiCode)
    {
      return ((char)(asciiCode)).ToString();
    }

    public static string GetStreamHTMLData(Stream currentStream, string charSet, bool supportSeek)
    {
      StringBuilder sb = new StringBuilder();
      string tempString = null;
      int count = 0;
            
      // used on each read operation
      byte[] buf = new byte[8192];
      
      if(supportSeek) // Restart it at the beginning
        currentStream.Position = 0;

      try
      {
        do
        {
          // fill the buffer with data
          count = currentStream.Read(buf, 0, buf.Length);

          // make sure we read some data
          if(count != 0)
          {
            if(charSet != null)
            {
              if(charSet.Trim() != "")
              {
                try
                {
                  tempString = Encoding.GetEncoding(charSet).GetString(buf, 0, count);
                }
                catch(ArgumentException ex)
                {
                  ex.Source += "\nInside the method: " + MethodInfo.GetCurrentMethod().Name;
                  throw new ArgumentException(Convert.ToString(ENCODE_ERROR_CODE), ex);
                }
              }
              else
                tempString = Encoding.ASCII.GetString(buf, 0, count);
            }
            else // translate from bytes to ASCII text
              tempString = Encoding.ASCII.GetString(buf, 0, count);

            // continue building the string
            sb.Append(tempString);
          }
        }
        while (count > 0); // any more data to read?

        // Clean up
        if(currentStream != null)
          currentStream.Close();

        return sb.ToString();
      }
      catch(Exception ex1)
      {
        ex1.Source += "\nInside the method: " + MethodInfo.GetCurrentMethod().Name;
        throw(ex1);
      }
    }

    public static void CopyStream(Stream sourceStream, Stream destinationStream)
    {
      byte[] buf = new byte[4096];
      
      try
      {
        while(true)
        {
          int bytesRead = sourceStream.Read(buf, 0, buf.Length);

          // Read returns 0 or -1 when it reaches end of stream.
          if (bytesRead <= 0)
            break;
          else
            destinationStream.Write(buf, 0, bytesRead);
        }
      }
      catch(Exception ex)
      {
        ex.Source += "\nInside the method: " + MethodInfo.GetCurrentMethod().Name;
        throw(ex);
      }
    }

    public static string GetNewGETUrl(string newQuery, string currentUri)
    {
      Uri queryUri = new Uri(currentUri);

      return queryUri.GetLeftPart(UriPartial.Path) + "?" + newQuery;  
    }

    public static bool IsNumeric(string valueToCheck)
    {
      try
      {
        Int32.Parse(valueToCheck);
      }
      catch 
      {
        return false;
      }
      return true;
    }

    public static string GetCurrentVersion()
    {
      XPathDocument myXPathDocument = null;
      XPathNavigator myXPathNavigator = null;
      XPathNodeIterator myXPathNodeIterator = null;
      string uriVersion = "http://www.sqlpowerinjector.com/Common/CurrentSQLPinjVersionInfo.xml";
      string currentVersionNumber = Application.ProductVersion;

      try
      {
        myXPathDocument = new XPathDocument(uriVersion);
        myXPathNavigator = myXPathDocument.CreateNavigator();

        // Get the current version
        myXPathNodeIterator = myXPathNavigator.Select("SQL_Power_Injector_Version_Info/CurrentVersionNumber");

        while(myXPathNodeIterator.MoveNext())
        {
          currentVersionNumber = myXPathNodeIterator.Current.Value;
          break;
        }

        return currentVersionNumber;
      }
      catch(Exception)
      {
        return currentVersionNumber;
      }
    }

    public static bool IsCurrentVersionNewer(string currentVersionNumber, string productVersion)
    {
      bool isCurVerNewer = false;
      string[] arrCurVerNumber = currentVersionNumber.Split('.');
      string[] arrProductVersion = productVersion.Split('.');

      if(arrCurVerNumber.Length >= 3 && arrProductVersion.Length >= 3)
      {
        // Verify first if all the parts are numeric, if not there is a error and we go out
        for(int i=0;i<arrCurVerNumber.Length;i++)
        {
          if(!IsNumeric(arrCurVerNumber[i]))
            return false;
        }

        // If the actual working version is higher than the deployed one it will always say that there's
        // a new version when in fact it's not true. I don't care because it will never happen since that
        // XML file will be always updated when the working version becomes the official one
        if(Convert.ToInt32(arrCurVerNumber[0]) > Convert.ToInt32(arrProductVersion[0]))
          isCurVerNewer = true;
        else if(Convert.ToInt32(arrCurVerNumber[1]) > Convert.ToInt32(arrProductVersion[1]))
          isCurVerNewer = true;
        else if(Convert.ToInt32(arrCurVerNumber[2]) > Convert.ToInt32(arrProductVersion[2]))
          isCurVerNewer = true;
      }

      return isCurVerNewer;
    }

    public static int FindTextInRichTextBox(RichTextBox curRichTextBox, RichTextboxTypeSearch searchType, string stringToFind, int startPos, bool wholeWord, bool doesMatchCase)
    {
      int returnFoundPos = -1;
      bool reverseSearch = false;

      if(searchType == RichTextboxTypeSearch.New)
        startPos = 0;
      if(searchType == RichTextboxTypeSearch.Next)
        startPos += 1;
      else if(searchType == RichTextboxTypeSearch.Previous)
      {
        reverseSearch = true;
        startPos -= 1;
        if(startPos == -1) startPos = 0;
      }
      
      // Make sure that a search string has been specified with a valid start point
      if (stringToFind.Length > 0 && startPos >= 0)
      {
        if(startPos <= curRichTextBox.Text.Length && startPos >= 0)
        {
          if(reverseSearch)
          {
            if(wholeWord && doesMatchCase)
              returnFoundPos = curRichTextBox.Find(stringToFind, 0, startPos, RichTextBoxFinds.Reverse | RichTextBoxFinds.WholeWord | RichTextBoxFinds.MatchCase);
            else if(wholeWord)
              returnFoundPos = curRichTextBox.Find(stringToFind, 0, startPos, RichTextBoxFinds.Reverse | RichTextBoxFinds.WholeWord);
            else if(doesMatchCase)
              returnFoundPos = curRichTextBox.Find(stringToFind, 0, startPos, RichTextBoxFinds.Reverse | RichTextBoxFinds.MatchCase);
            else
              returnFoundPos = curRichTextBox.Find(stringToFind, 0, startPos, RichTextBoxFinds.Reverse);
          }
          else
          {
            if(wholeWord && doesMatchCase)
              returnFoundPos = curRichTextBox.Find(stringToFind, startPos, RichTextBoxFinds.WholeWord | RichTextBoxFinds.MatchCase);
            else if(wholeWord)
              returnFoundPos = curRichTextBox.Find(stringToFind, startPos, RichTextBoxFinds.WholeWord);
            else if(doesMatchCase)
              returnFoundPos = curRichTextBox.Find(stringToFind, startPos, RichTextBoxFinds.MatchCase);
            else
              returnFoundPos = curRichTextBox.Find(stringToFind, startPos, RichTextBoxFinds.None);
          }
        }
      }

      if(searchType != RichTextboxTypeSearch.New && returnFoundPos == -1 && startPos >= 0)
      {
        if(searchType == RichTextboxTypeSearch.Next)
          startPos = -1;
        else if(searchType == RichTextboxTypeSearch.Previous)
          startPos = curRichTextBox.Text.Length+1;

        returnFoundPos = FindTextInRichTextBox(curRichTextBox, searchType, stringToFind, startPos, wholeWord, doesMatchCase);
      }

      return returnFoundPos;
    }

    public static XmlDocument LoadXMLFile(string pathFile)
    {
      XmlTextReader reader = null;
      XmlDocument xmlDoc = new XmlDocument();

      try
      {
        reader = new XmlTextReader(pathFile);
        reader.WhitespaceHandling = WhitespaceHandling.None;

        xmlDoc.Load(reader);
      }
      catch(MyException ex1)
      {
        if(ex1.MyHref == XML_ERROR_FORMAT)
          MessageBox.Show("The xml file you have loaded doesn't have the right formatting!\n\n" +
            "It could be because it has been modified and it is no more valid\n" +
            "or it is not a xml from SQL Power Injector", "Bad XML file formatting",
            MessageBoxButtons.OK, MessageBoxIcon.Error);
        else
          MessageBox.Show(ex1.Message + "\n\nMethod name: " + MethodInfo.GetCurrentMethod().Name +
            "\nSource: " + ex1.Source +
            "\n\nPlease send me an email with this message at bugs@sqlpowerinjector.com", "Error message", 
            MessageBoxButtons.OK, MessageBoxIcon.Error);
        return null;
      }
      catch(XmlException ex11)
      {
        MessageBox.Show(ex11 + "\nThe xml file you have loaded doesn't have the right formatting!\n\n" +
          "It could be because it has been modified and it is no more valid\n" +
          "or it is not a xml file from SQL Power Injector", "Bad XML file formatting",
          MessageBoxButtons.OK, MessageBoxIcon.Error);
        return null;
      }
      catch(Exception ex3)
      {
        MessageBox.Show(ex3.Message + "\n\nMethod name: " + MethodInfo.GetCurrentMethod().Name +
          "\nSource: " + ex3.Source +
          "\n\nPlease send me an email with this message at bugs@sqlpowerinjector.com", "Error message", 
          MessageBoxButtons.OK, MessageBoxIcon.Error);
        return null;
      }
      finally
      {
        if (reader != null)
          reader.Close();
      }

      return xmlDoc;
    }

    public static bool SerializeXML(object objectToSave, string XMLFileName)
    {
      TextWriter textWriter = null;
      bool success = false;
      
      try
      {
        // Create serializer object using the type name of the Object to serialize.
        XmlSerializer xmlSerializer = new XmlSerializer(objectToSave.GetType());

        textWriter = new StreamWriter(XMLFileName);

        xmlSerializer.Serialize(textWriter, objectToSave);

        success = true;
      }
      catch(Exception ex)
      {
        throw(ex);
      }
      finally
      {
        if (textWriter != null)
          textWriter.Close();                
      }

      return success;
    }

    public static int[] ToIntArray(ArrayList arraylistToConvert)
    {
      // First we need to check how many data in the array list is really an int
      int[] arraylistIntArray;
      int numberIntInArray = 0;
      int curArrayListIntIndex = 0;

      for(int curIndex=0; curIndex<arraylistToConvert.Count; curIndex++)
      {
        if(IsNumeric(Convert.ToString(arraylistToConvert[curIndex])))
          numberIntInArray++;
      }

      // Now we know for sure how many int there are in the arraylist we can resize it
      arraylistIntArray = new int[numberIntInArray];

      // We create the int array if not a int we discard it
      for(int curIntIndex=0; curIntIndex<arraylistToConvert.Count;curIntIndex++)
      {
        if(IsNumeric(Convert.ToString(arraylistToConvert[curIntIndex])))
        {
          arraylistIntArray[curArrayListIntIndex] = (int)arraylistToConvert[curIntIndex];
          curArrayListIntIndex++;
        }
      }

      return arraylistIntArray;
    }

    /// <summary>
    /// This is a special comparison function, we don't need all the nice features that some algo would have.
    /// In our case we just want to see what's more in the positive HTML source code to get our positive answer
    /// string. Also, once we found that list of statements we will compare it again to the negative text to
    /// see if it's somewhere else in the text, if not we will get false positive. The goal in a nutshell is
    /// finally to get strings that are not present at all in the negative text.
    /// </summary>
    /// <param name="textPositiveHTMLSourceCode">Positive HTML Source code to compare with the negative HTML source text</param>
    /// <param name="textNegativeHTMLSourceCode">Negative HTML Source code to compare with the positive HTML source text</param>
    /// <param name="isCaseSensitive">In case it is not case sensitive we need to disregard the case during the comparison</param>
    /// <param name="doesRemoveSpecialChars">Remove all specials chars like /t, /n, /r </param>
    /// <returns>ArrayList of all the strings that were in addition in comparison of the negative text</returns>
    public static ArrayList ComparePositiveAndNegativeHTMLSourceCode(string textPositiveHTMLSourceCode, string textNegativeHTMLSourceCode, bool isCaseSensitive, bool doesRemoveSpecialChars)
    {
      ArrayList arrDiffStringInPositiveAns = new ArrayList();
      ArrayList arrFinalDiffStringInPositiveAns = new ArrayList();
      string tmpString = "";
      int curNegativeCharIndex = 0;
      char[] positiveTextChars;
      char[] originalPositiveTextChars;
      char[] negativeTextChars;

      if(doesRemoveSpecialChars)
      {
        textPositiveHTMLSourceCode = textPositiveHTMLSourceCode.Replace("\r", "");
        textPositiveHTMLSourceCode = textPositiveHTMLSourceCode.Replace("\n", "");
        textPositiveHTMLSourceCode = textPositiveHTMLSourceCode.Replace("\t", "");
        textNegativeHTMLSourceCode = textNegativeHTMLSourceCode.Replace("\r", "");
        textNegativeHTMLSourceCode = textNegativeHTMLSourceCode.Replace("\n", "");
        textNegativeHTMLSourceCode = textNegativeHTMLSourceCode.Replace("\t", "");
      }

      // First we check if there is a difference before to go thru the whole process for nothing
      if(textPositiveHTMLSourceCode.CompareTo(textNegativeHTMLSourceCode) != 0)
      {
        MessageBox.Show("there is a difference!");

        if(isCaseSensitive)
        {
          positiveTextChars = textPositiveHTMLSourceCode.ToCharArray();
          originalPositiveTextChars = textPositiveHTMLSourceCode.ToCharArray();
          negativeTextChars = textNegativeHTMLSourceCode.ToCharArray();
        }
        else
        {
          positiveTextChars = textPositiveHTMLSourceCode.ToUpper().ToCharArray();
          originalPositiveTextChars = textPositiveHTMLSourceCode.ToCharArray();
          negativeTextChars = textNegativeHTMLSourceCode.ToUpper().ToCharArray();
        }

        for(int curPositiveCharIndex = 0; (curPositiveCharIndex < positiveTextChars.Length && curNegativeCharIndex < negativeTextChars.Length); curPositiveCharIndex++)
        {
          if(positiveTextChars[curPositiveCharIndex] != negativeTextChars[curNegativeCharIndex])
          {
            // We are only interested in the positive answer extra strings
            tmpString = "";
            while(curPositiveCharIndex < positiveTextChars.Length && positiveTextChars[curPositiveCharIndex] != negativeTextChars[curNegativeCharIndex])
            {
              tmpString += originalPositiveTextChars[curPositiveCharIndex];
              curPositiveCharIndex++;
            }
            arrDiffStringInPositiveAns.Add(tmpString);
          }

          curNegativeCharIndex++;
        }

        // Now that we have our list we need to check if each string found can be found in the negative text
        foreach(string curfoundString in arrDiffStringInPositiveAns)
        {
          // We accept the fact that it's case sensitive...
          if(textNegativeHTMLSourceCode.IndexOf(curfoundString) == -1)
            arrFinalDiffStringInPositiveAns.Add(curfoundString);
        }
      }
      else
        MessageBox.Show("there is no difference!");
  
      return arrFinalDiffStringInPositiveAns;
    }

    public static void AddCookieToArrayList(ref ArrayList arrCookies)
    {
      string newCookieNameValue = "";

      InputBox.Title = "Cookie insertion";
      InputBox.Question = "Please insert the name-value pair of your cookie\n\nExample:\n                   ASP.NET_SessionId=iax0xj55koqxvcm4hpthg5ix";
      InputBox.LabelHeight = 56;
      newCookieNameValue = InputBox.ShowInputBox();

      if(InputBox.IsOk)
      {
        if(newCookieNameValue.Trim() != "" && newCookieNameValue.Trim().Length > 2)
        {
          if(newCookieNameValue.IndexOf("=", 1) != -1) // If it's the first position we don't care, it's not valid
          {
            Regex rxgCookie = new Regex(@"^(?<name>[^=\r\n]+)?\s*=\s*(?<value>[^\r\n]*)", RegexOptions.IgnoreCase);
            Match rxgMatch = rxgCookie.Match(newCookieNameValue.Trim());
            string cookieName = rxgCookie.Match(newCookieNameValue.Trim()).Result("${name}");
            if(cookieName.Length > 0)
            {
              string cookieValue = rxgCookie.Match(newCookieNameValue.Trim()).Result("${value}");
              bool cookieNameAlreadyExists = false;
        
              if(arrCookies == null)
                arrCookies = new ArrayList();

              foreach(CLoadPageCookie lpCookie in arrCookies)
              {
                if(cookieName == lpCookie.LoadPageCookieName)
                {
                  if(MessageBox.Show("The name " + cookieName + " already exists inside the Load Page cookie collection!\n\n" +
                    "Do you want to overwrite its value?\n\nIf you don't overwrite it you will lose the new value...",
                    "Cookie name already exists", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                  {
                    lpCookie.LoadPageCookieValue = cookieValue;
                  }
                  cookieNameAlreadyExists = true;
                  break;
                }
              }
              if(!cookieNameAlreadyExists)
              {
                CLoadPageCookie item = new CLoadPageCookie(cookieName, cookieValue);
                arrCookies.Add(item);
              }
            }
          }
        }
      }
    }

    public static ArrayList GetUserAgentList()
    {
      string pathAndFileName = "\\Settings\\" + USER_AGENTS_FILE;

      #if DEBUG
        pathAndFileName = @"\..\..\" + pathAndFileName;
      #endif

      pathAndFileName = Application.StartupPath + pathAndFileName;
      XmlDocument xmlDocToParse = Utilities.LoadXMLFile(pathAndFileName);
      XmlElement curXMLEle = null;
      UserAgent curUserAgent = null;
      ArrayList curUserAgentArray = new ArrayList();
      XmlNodeList xmlNodeList = xmlDocToParse.SelectNodes("descendant::UserAgents/UserAgent");

      IEnumerator nodeList = xmlNodeList.GetEnumerator();
      while(nodeList.MoveNext())
      {
        curUserAgent = new UserAgent();
        curXMLEle = (XmlElement)nodeList.Current;

        // If the current user agent is not valid we don't care to get it
        if(curXMLEle.Attributes[USER_AGENT_ID].Value != null && IsNumeric(curXMLEle.Attributes[USER_AGENT_ID].Value))
        {
          if(curXMLEle.Attributes[USER_AGENT_NAME].Value != null)
          {
            curUserAgent.UserAgentID = Convert.ToInt32(curXMLEle.Attributes[USER_AGENT_ID].Value);
            curUserAgent.UserAgentName = curXMLEle.Attributes[USER_AGENT_NAME].Value;
            curUserAgent.UserAgentValue =  curXMLEle.InnerText;

            curUserAgentArray.Add(curUserAgent);
          }
        }
      }

      return curUserAgentArray;
    }

    public static bool IsIpAddressValid(string ipAddress)
    {
      string ipAddressRegEx = @"\b(?:\d{1,3}\.){3}\d{1,3}\b";
      Regex rxgIpAddress = new Regex(ipAddressRegEx, RegexOptions.None);
      Match rxgMatch = rxgIpAddress.Match(ipAddress);

      return rxgMatch.Success;
    }

    public static string GetMSSQLOptionsValues(int optionsReturnInt)
    {
      string optionsValues = "";
      int nbrOptions = 0;

      if ((optionsReturnInt & (int)enumSQLServerOptions.DISABLE_DEF_CNST_CHK) > 0)
      {
        nbrOptions++;
        optionsValues = "DISABLE_DEF_CNST_CHK\n";
      }
      if ((optionsReturnInt & (int)enumSQLServerOptions.IMPLICIT_TRANSACTIONS) > 0)
      {
        nbrOptions++;
        optionsValues += "IMPLICIT_TRANSACTIONS\n";
      }
      if ((optionsReturnInt & (int)enumSQLServerOptions.CURSOR_CLOSE_ON_COMMIT) > 0) 
      {
        nbrOptions++;
        optionsValues += "CURSOR_CLOSE_ON_COMMIT\n";
      }
      if ((optionsReturnInt & (int)enumSQLServerOptions.ANSI_WARNINGS) > 0) 
      {
        nbrOptions++;
        optionsValues += "ANSI_WARNINGS\n";
      }
      if ((optionsReturnInt & (int)enumSQLServerOptions.ANSI_PADDING) > 0) 
      {
        nbrOptions++;
        optionsValues += "ANSI_PADDING\n";
      }
      if ((optionsReturnInt & (int)enumSQLServerOptions.ANSI_NULLS) > 0) 
      {
        nbrOptions++;
        optionsValues += "ANSI_NULLS\n";
      }
      if ((optionsReturnInt & (int)enumSQLServerOptions.ARITHABORT) > 0) 
      {
        nbrOptions++;
        optionsValues += "ARITHABORT\n";
      }
      if ((optionsReturnInt & (int)enumSQLServerOptions.ARITHIGNORE) > 0) 
      {
        nbrOptions++;
        optionsValues += "ARITHIGNORE\n";
      }
      if ((optionsReturnInt & (int)enumSQLServerOptions.QUOTED_IDENTIFIER) > 0) 
      {
        nbrOptions++;
        optionsValues += "QUOTED_IDENTIFIER\n";
      }
      if ((optionsReturnInt & (int)enumSQLServerOptions.NOCOUNT) > 0)
      {
        nbrOptions++;
        optionsValues += "NOCOUNT\n";
      }
      if ((optionsReturnInt & (int)enumSQLServerOptions.ANSI_NULL_DFLT_ON) > 0) 
      {
        nbrOptions++;
        optionsValues += "ANSI_NULL_DFLT_ON\n";
      }
      if ((optionsReturnInt & (int)enumSQLServerOptions.ANSI_NULL_DFLT_OFF) > 0) 
      {
        nbrOptions++;
        optionsValues += "ANSI_NULL_DFLT_OFF\n";
      }
      if ((optionsReturnInt & (int)enumSQLServerOptions.CONCAT_NULL_YIELDS_NULL) > 0) 
      {
        nbrOptions++;
        optionsValues += "CONCAT_NULL_YIELDS_NULL\n";
      }
      if ((optionsReturnInt & (int)enumSQLServerOptions.NUMERIC_ROUNDABORT) > 0) 
      {
        nbrOptions++;
        optionsValues += "NUMERIC_ROUNDABORT\n";
      }
      if ((optionsReturnInt & (int)enumSQLServerOptions.XACT_ABORT) > 0) 
      {
        nbrOptions++;
        optionsValues += "XACT_ABORT";
      }

      if(nbrOptions > 0)
      {
        if(nbrOptions == 1)
          optionsValues = "This option is turned on:                \n\n" + optionsValues;
        else
          optionsValues = "These options are turned on:            \n\n" + optionsValues;
      }
      else
        optionsValues = "There is no values for the provided @@OPTIONS!";
  
      return optionsValues;
    }
  }
}
www.java2v.com | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.