Click here to Skip to main content
15,911,789 members
Home / Discussions / ASP.NET
   

ASP.NET

 
AnswerRe: Is Memory Leak happening here. Pin
Abhishek Sur6-May-10 13:58
professionalAbhishek Sur6-May-10 13:58 
Questionchange output format dynamic checkboxlist in asp.net/vb Pin
AsianRogueOne6-May-10 5:41
AsianRogueOne6-May-10 5:41 
AnswerRe: change output format dynamic checkboxlist in asp.net/vb Pin
AsianRogueOne6-May-10 6:03
AsianRogueOne6-May-10 6:03 
QuestionException thrown Pin
MaheshSharma6-May-10 5:04
MaheshSharma6-May-10 5:04 
AnswerRe: Exception thrown Pin
JHizzle6-May-10 5:19
JHizzle6-May-10 5:19 
AnswerRe: Exception thrown Pin
Not Active6-May-10 5:43
mentorNot Active6-May-10 5:43 
AnswerRe: Exception thrown Pin
Sandesh M Patil6-May-10 7:11
Sandesh M Patil6-May-10 7:11 
AnswerRe: Exception thrown Pin
daveyerwin6-May-10 7:18
daveyerwin6-May-10 7:18 
using System;
using System.Configuration;
using System.Web.UI.WebControls;
using System.Security.Principal;
using System.Xml;
using Itools.Encryption;
using System.Web;
using System.Text;
using System.Text.RegularExpressions;

namespace Ashwin.DAL
{
    /// <summary>
    /// Summary description for Util
    /// </summary>
    public class Util
    {
        //Design users
        //adriaanse.a
        //allinsmith.w
        private static readonly string whoami = "ashwin.k";//For testing - for cop ["westring.bd"] 
        private const string encKey = "KFn2oZAwJHWFRbSXoaSlYjl5TADpyyt53rowhbVwH/M=";
        private const string encVector = "nb2dZEGWnzg8R1GZAuUkUQ==";
        private static System.Collections.ICollection appSettings = ConfigurationManager.AppSettings;
        private static System.Configuration.ConnectionStringSettingsCollection connStrings = ConfigurationManager.ConnectionStrings;

        /// <summary>
        /// Returns the username without the domain of the current logged in user. 
        /// </summary>
        /// <param name="User">Current logged in user, example CN\ashwin.k</param>
        /// <returns>Returns the username without the domain of the current logged in user. </returns>
        public static string GetSimpleUsername(IPrincipal User)
        {
            //setup user array to split username into domain and username
#if DEBUG
return whoami;
#endif
            string[] user;

            // define which character is seperating fields
            char[] splitter = { '\\' };

            //perform split
            user = User.Identity.Name.Split(splitter);


            //check to see if no domain exists for user
            if (user.Length < 2)
            {
                return user[0];
            }
            else
            {
                return user[1];

            }
        }

        /// <summary>
        /// Method to make sure that user's inputs are not malicious
        /// </summary>
        /// <param name="text">User's Input</param>
        /// <param name="maxLength">Maximum length of input</param>
        /// <returns>The cleaned up version of the input</returns>
        public static string InputText(string text, int maxLength)
        {
            text = text.Trim();
            if (string.IsNullOrEmpty(text))
                return string.Empty;
            if (text.Length > maxLength)
                text = text.Substring(0, maxLength);
            text = Regex.Replace(text, "[\\s]{2,}", " "); //two or more spaces
            text = Regex.Replace(text, "(<[b|B][r|R]/*>)+|(<[p|P](.|\\n)*?>)", "\n"); //<br>
            text = Regex.Replace(text, "(\\s*&[n|N][b|B][s|S][p|P];\\s*)+", " "); //&nbsp;
            text = Regex.Replace(text, "<(.|\\n)*?>", string.Empty); //any other tags
            text = text.Replace("'", "''");
            return text;
        }

        /// <summary>
        /// Returns true if the user is a member of any role in the list, 
        /// or any group in the list with the User's domain apppended in front of each individual role name. 
        /// If the user it not a member of any role false if returned
        /// </summary>
        /// <param name="usr">User object to check.</param>
        /// <param name="roles">Comma Seperated list of role names</param>
        /// <returns>True if user is a member of any role otherwise return false.</returns>
        public static bool isInAnyRole(IPrincipal usr, string roles)
        {
            //define the splitter
            char[] splitter = { ',' };

            //get user's domain
            string domain = GetUserDomain(usr);

            // create an array of roles
            string[] roleArray = roles.Split(splitter);

            for (int i = 0; i < roleArray.Length; ++i)
            {
                if (usr.IsInRole(roleArray[i]) || usr.IsInRole(domain + '\\' + roleArray[i]))
                {
                    return true;
                }
            }
            return false;

        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="User"></param>
        /// <returns></returns>
        public static string GetUserDomain(IPrincipal User)
        {
            //setup user array to split username into domain and username
            string[] user;

            // define which character is seperating fields
            char[] splitter = { '\\' };

            //perform split
            user = User.Identity.Name.Split(splitter);

            //check to see if no domain exists for user
            if (user.Length < 2)
            {
                return "";
            }
            else return user[0];
        }

        /// <summary>
        /// Get the Server name.
        /// </summary>
        /// <param name="context"></param>
        /// <returns></returns>
        public static string GetServerName(HttpContext context)
        {
            string ret;
            string port = context.Request.ServerVariables["SERVER_PORT"];
            ret = GetConfigValue("ServerName") + ":" + port;
            if (port == "80")
            {
                ret = GetConfigValue("ServerName") + context.Request.ApplicationPath;
            }
            return "http://" + ret;

        }

        /// <summary>
        /// Looks through LDAP groups for a given name and determines if the user is 
        /// in that LDAP group
        /// </summary>
        /// <param name="name"></param>
        /// <param name="GroupName"></param>
        /// <returns></returns>
        public static bool IsUserInLDAPGroup(string name, string GroupName)
        {
            try
            {
                XmlDocument doc = new XmlDocument();
                doc.Load("http://groupservice.internal.pg.com/GDSGroupService.jrun?op=ismember&accountshortname=" +
                name.Replace("-", ".").ToLower() +
                "&groupdn=cn=" + GroupName.ToLower() +
                ",ou=groups,o=world&expand=true");
                return bool.Parse(doc.GetElementsByTagName("ismember")[0].InnerText);
            }
            catch
            {
                return false;
            }

        }

        /// <summary>
        /// Return a value from the web.config file or the app.config file
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public static string GetConfigValue(string name)
        {
            Cryptography crypto = new Cryptography();
            string ret;
            string temp;
            if (AppSettings.GetType().Equals(typeof(System.Configuration.KeyValueConfigurationCollection)))
            {
                temp = ((System.Configuration.KeyValueConfigurationCollection)AppSettings)[name].Value;
            }
            else
            {
                temp = ((System.Collections.Specialized.NameValueCollection)AppSettings)[name];
            }

            //Find out if we need to decrypt the value.
            switch (name)
            {
                case "WebServicePswd":
                case "DBPassword":
                case "ContentMonitorDBPassword":
                    temp = crypto.Decrypt(temp, encKey, encVector);
                    break;
            }

            ret = temp;


            //return the value
            return ret;
        }

        /// <summary>
        /// Return Encrypted value for the specified value 
        /// </summary>
        /// <param name="value"></param>
        /// <returns>returns encrypted value</returns>
        public static string EncryptValue(string value)
        {
            Cryptography crypto = new Cryptography();
            return crypto.Encrypt(value, encKey, encVector);
        }

        /// <summary>
        /// Return Decrypted value for the specified value 
        /// </summary>
        /// <param name="value"></param>
        /// <returns>returns decrypted value</returns>
        public static string DecryptValue(string value)
        {
            Cryptography crypto = new Cryptography();
            return crypto.Decrypt(value, encKey, encVector);
        }

        /// <summary>
        /// Function to return a valid string representing a date
        /// </summary>
        /// <param name="sValue"></param>
        /// <returns></returns>
        public static string GetValidDate(string sValue)
        {
            if (sValue.Length > 0)
            {
                return DateTime.Parse(sValue).ToShortDateString() + " " + DateTime.Parse(sValue).ToShortTimeString();
            }
            else
            {
                return "";
            }

        }

        /// <summary>
        /// Return a valid date as a DateTime object
        /// </summary>
        /// <param name="sValue"></param>
        /// <returns></returns>
        public static DateTime GetValidDateAsDateTime(string sValue)
        {
            if (sValue.Length > 0)
            {
                return DateTime.Parse(sValue);
            }
            else
            {
                return DateTime.Today;
            }

        }

        /// <summary>
        /// Return a valid integer or 0
        /// </summary>
        /// <param name="sValue"></param>
        /// <returns></returns>
        public static int GetValidInt(string sValue)
        {
            if (sValue.Length > 0)
            {
                if (sValue == "True") return 1;
                if (sValue == "False") return 0;
                return Int32.Parse(sValue);
            }
            else
            {
                return 0;
            }
        }

        /// <summary>
        /// Return a valid integer or 0
        /// </summary>
        /// <param name="sValue"></param>
        /// <returns></returns>
        public static decimal GetValidDecimal(string sValue)
        {
            if (sValue.Length > 0)
            {
                return Decimal.Parse(sValue);
            }
            else
            {
                return 0;
            }
        }

        /// <summary>
        /// Returns a valid interger or 0 from a Dropdown list
        /// </summary>
        /// <param name="cbo"></param>
        /// <returns></returns>
        public static int GetValidIntForCombo(DropDownList cbo)
        {
            int ret = 0;
            if (cbo.SelectedIndex > 0)
            {
                ret = GetValidInt(cbo.SelectedValue);
            }
            return ret;
        }

        /// <summary>
        /// Gets item values from a list box and returns them in a string array.
        /// </summary>
        /// <param name="list"></param>
        /// <returns></returns>
        public static string[] GetSelectedItems(ListBox list)
        {
            string items = "";
            foreach (ListItem item in list.Items)
            {
                if (item.Selected)
                {
                    items += (items.Length > 0 ? "|" : "") + item.Value;
                }
            }
            if (items.Length == 0)
            {
                return null;
            }
            return items.Split('|');
        }

        /// <summary>
        /// Gets item values from a list box and returns them in a string of comma sepereated values.
        /// </summary>
        /// <param name="list"></param>
        /// <returns></returns>
        public static string GetSelectedItemsFromList(ListBox list)
        {
            string items = "";
            foreach (int index in list.GetSelectedIndices())
            {
                items += (items.Length > 0 ? "," : "") + list.Items[index].Value;
            }
            if (items.Length == 0)
            {
                return string.Empty;
            }
            return items;
        }

        public static System.Collections.ICollection AppSettings
        {
            get { return appSettings; }
            set { appSettings = value; }
        }

        public static System.Configuration.ConnectionStringSettingsCollection ConnectionStrings
        {
            get { return connStrings; }
            set { connStrings = value; }
        }
        /// <summary>
        /// Returns the exception message + stack trace so it can be logged
        /// </summary>
        /// <param name="ex">exception</param>
        /// <returns>text containing message + stack trace</returns>
        static public string returnExecptionText(System.Exception ex)
        {
            Exception unhandledException = ex;

            StringBuilder error = new StringBuilder();

            while (unhandledException != null)
            {

                error.Append("An unhandled exception occurred: " + unhandledException.Message);
                error.Append(" StackTrace: ");
                error.Append(unhandledException.StackTrace);
                unhandledException = unhandledException.InnerException;
            }

            return error.ToString();
        }

        /// <summary>
        /// Formats the date as 1-JUN-2006
        /// </summary>
        /// <param name="date">The Date to format</param>
        /// <returns></returns>
        public static string DisplayedDate(string date)
        {
            string ret = "";
            try
            {
                ret = DateTime.Parse(date).ToString("dd-MMM-yyyy");
            }
            catch { }
            return ret;

        }

        /// <summary>
        /// converts string array into the integer array
        /// </summary>
        /// <param name="strArray"></param>
        /// <returns></returns>
        public static int[] ConvertStringArrayToIntArray(string[] strArray)
        {
            int[] intArray;
            intArray = Array.ConvertAll<string, int>(strArray, new Converter<string, int>(ConvertStringToInt));
            return intArray;
        }

        /// <summary>
        /// converts integer array into the string array
        /// </summary>
        /// <param name="intArray"></param>
        /// <returns></returns>
        public static string[] ConvertIntArrayToStringArray(int[] intArray)
        {
            string[] strArray;
            strArray = Array.ConvertAll<int, string>(intArray, new Converter<int, string>(ConvertIntToString));
            return strArray;

        }

        /// <summary>
        /// used as predicate to convert the value fron int to string
        /// </summary>
        /// <param name="intParameter"></param>
        /// <returns></returns>
        private static string ConvertIntToString(int intParameter)
        {
            return intParameter.ToString();
        }

        /// <summary>
        /// used as predicate to convert the value fron string to int
        /// </summary>
        /// <param name="strParameter"></param>
        /// <returns></returns>
        private static int ConvertStringToInt(string strParameter)
        {
            return int.Parse(strParameter);
        }
    }
}

GeneralRe: Exception thrown Pin
Not Active6-May-10 8:16
mentorNot Active6-May-10 8:16 
Questionfor each loop for Repeater control Pin
Deb_266-May-10 4:17
Deb_266-May-10 4:17 
AnswerRe: for each loop for Repeater control Pin
Not Active6-May-10 5:46
mentorNot Active6-May-10 5:46 
QuestionAjax Editor control Pin
jitendrafaye5-May-10 23:30
jitendrafaye5-May-10 23:30 
AnswerRe: Ajax Editor control Pin
Peace ON5-May-10 23:49
Peace ON5-May-10 23:49 
GeneralRe: Ajax Editor control Pin
jitendrafaye6-May-10 2:43
jitendrafaye6-May-10 2:43 
AnswerRe: Ajax Editor control Pin
Jamil Hallal6-May-10 1:41
professionalJamil Hallal6-May-10 1:41 
Questionsaving the other information to database if no content is present in file upload control using asp.net with c# Pin
developerit5-May-10 22:03
developerit5-May-10 22:03 
AnswerRe: saving the other information to database if no content is present in file upload control using asp.net with c# Pin
Shahriar Iqbal Chowdhury/Galib5-May-10 22:19
professionalShahriar Iqbal Chowdhury/Galib5-May-10 22:19 
AnswerRe: saving the other information to database if no content is present in file upload control using asp.net with c# Pin
Paramhans Dubey6-May-10 0:02
professionalParamhans Dubey6-May-10 0:02 
Questionsaving the images in database like null value Pin
developerit5-May-10 21:14
developerit5-May-10 21:14 
AnswerRe: saving the images in database like null value Pin
Shahriar Iqbal Chowdhury/Galib5-May-10 21:59
professionalShahriar Iqbal Chowdhury/Galib5-May-10 21:59 
AnswerRe: saving the images in database like null value Pin
Abhishek Sur5-May-10 22:20
professionalAbhishek Sur5-May-10 22:20 
AnswerRe: saving the images in database like null value Pin
AnandDesai196-May-10 2:26
AnandDesai196-May-10 2:26 
AnswerRe: saving the images in database like null value Pin
T M Gray6-May-10 9:27
T M Gray6-May-10 9:27 
QuestionSearch bar needed Pin
reogeo20085-May-10 20:06
reogeo20085-May-10 20:06 
AnswerRe: Search bar needed Pin
Ankur\m/5-May-10 21:02
professionalAnkur\m/5-May-10 21:02 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.