Tuesday, March 20, 2012

How to get Value from an Enum Item in asp.net?

Here i am showing how to get value from an Enum Item

/// <summary>
        /// GetDescriptionFromEnumValue is returns the name or value for an Enum Item
        /// </summary>
        /// <param name="value">Enum Value</param>
        /// <returns>Description For Enum</returns>
        public static int GetValueFromEnum(Enum value)
        {
            FieldInfo fi = value.GetType().GetField(value.ToString());
            int val = (int)fi.GetValue(value);

            return val;
        }
Use this method
-----------------
 objtblLog.LogType = EnumUtility.GetValueFromEnum((Logtype)Session.ErrorLogtype);

Where Session.ErrorLogtype is an integer value

Thanks to my Project manager , who guide me lot to know these things and how to handle a project to get better performance ... "Thank you Sir"

How to get the Key from an Enum in asp.net?

This method will return the Key or Description from an Enum Item

 /// <summary>
        /// GetDescriptionFromEnumValue is returns the name  for an Enum Item
        /// </summary>
        /// <param name="value">Enum Value</param>
        /// <returns>Description For Enum</returns>
        public static string GetDescriptionFromEnumItem(Enum value)
        {
            DescriptionAttribute attribute = value.GetType()
                .GetField(value.ToString())
                .GetCustomAttributes(typeof(DescriptionAttribute), false)
                .SingleOrDefault() as DescriptionAttribute;
            return attribute == null ? value.ToString() : attribute.Description;
        }

Here how to use this function from other class
-----------------------------------------------
 /// Function Name: GetComTypes
        /// Bishnu Tewary
        /// 05-03-2012
        /// <summary>
        /// GetTitleNameByValue function return the Name of an enum item for its value
        /// </summary>
        /// <param name="value"> value of the enumitem</param>
        /// <returns>name of the value</returns>
        public string GetTitleNameByValue(int value)
        {
            TitleTypes enumItem = (TitleTypes)Enum.Parse(typeof(TitleTypes), Convert.ToString(value));
            return EnumUtility.GetDescriptionFromEnumItem(enumItem);
        }

How to use Description with an Enum Key in asp.net?

What happened if we have to bind a dropdownlist from Enum which holds Titles like Mr and Mrs but we have to show the textvaluefield like "Mr." and "Mrs."? Ok for this type of requirement we can use description attribute with the Key of a particular Enum, Here I am showing how to do that.

/// <summary>
        /// Enumeration TitleTypes use for getting the Titles
        /// Here I use DescriptionAttribute for holding the "Mr." Because "." is not supported in variable declaration
        /// </summary>
        public enum TitleTypes
        {
            /// <summary>
            /// Title As Mr and DescriptionAttribute set to Mr.
            /// </summary>
            [DescriptionAttribute("Mr.")]
            Mr = 1,

            /// <summary>
            /// Title As Mrs and DescriptionAttribute set to Mrs.
            /// </summary>
            [DescriptionAttribute("Mrs.")]
            Mrs = 2
        }

Cheers!

How to bind a dropdownlist from Enum in MVC3?

This post will help you to bind a dropdownlist from an Enum in MVC 3 application. Here i create a methode which will return an IQueryable<SelectListItem> list from a given enum.
the methode is like bellow
public static IQueryable<SelectListItem> BindDropdownListFromEnum<T>()
        {
            List<SelectListItem> lstEnum = new List<SelectListItem>();
            var lsttype = from t in lstEnum select t;
            try
            {
                T objType = Activator.CreateInstance<T>();
                foreach (T enumValue in Enum.GetValues(typeof(T)))
                {
                    FieldInfo fi = typeof(T).GetField(enumValue.ToString());
                    DescriptionAttribute da = (DescriptionAttribute)Attribute.GetCustomAttribute(fi, typeof(DescriptionAttribute));
                    SelectListItem lstItem = new SelectListItem();
                    int val = (int)fi.GetValue(enumValue);
                    if (da != null)
                    {
                        lstItem = new SelectListItem { Text = da.Description, Value = Convert.ToString(val) };
                    }
                    else
                    {
                        lstItem = new SelectListItem { Text = fi.Name, Value = Convert.ToString(val) };
                    }

                    if (!lstEnum.Contains(lstItem))
                    {
                        lstEnum.Add(lstItem);
                    }
                }

                lsttype = from t in lstEnum select t;
            }
            catch (Exception ex)
            {
                throw ex;
            }

            return ((IEnumerable<SelectListItem>)lsttype).Select(x => x).AsQueryable();
        }

Here if the enum has description for its Key then it will return the Key as Description and the Value will be the enum value. as a list of IEnumerable<SelectListItem> where SelectListItem's key and value will be the enum types key and value respectively.

In controller
-----------------
 IEnumerable<SelectListItem> lstUsertypes = EnumUtility.BindDropdownListFromEnum<UserType>();
 ViewBag.UserType = lstUsertypes;

In view
----------
Usertype :  @Html.DropDownList("UserType", "-- Select All --")

Enum
-----------
 /// <summary>
    /// Enumeration UserType use for Get User Type
    /// </summary>
    public enum UserType
    {
        /// <summary>
        /// For Private Value is 1
        /// </summary>
        Private = 1,

        /// <summary>
        /// For Company Value is 2
        /// </summary>
        Company = 2,

        /// <summary>
        /// For Organisation Value is 3
        /// </summary>
        Organisation = 3
    }

How to get client IP Address in MVC3?

Before implementing this I did so many things but not succeed like this to get the client Ip address means from where the browser open. In one of my project i have to save the client IP address, browser name  and browser version. Its a MVC 3 razor application.
  So here i am showing you how to get these

        public static string GetIPAddress(HttpRequestBase request)
        {
            string ip = string.Empty;
            try
            {
                ip = request.ServerVariables["HTTP_X_FORWARDED_FOR"];
                if (!string.IsNullOrEmpty(ip))
                {
                    if (ip.IndexOf(",") > 0)
                    {
                        string[] allIps = ip.Split(',');
                        int le = allIps.Length - 1;
                        ip = allIps[le];
                    }
                }
                else
                {
                    ip = request.UserHostAddress;
                }      
            }
            catch (Exception ex)
            {
                throw ex;
            }

            return ip;
        }

         public static string GetBrowserType(HttpRequestBase request)
        {
            try
            {
                HttpContext.Current.Session["BrowserType"] = request.Browser.Browser;
              
                return HttpContext.Current.Session["BrowserType"].ToString();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

         public static string GetBrowserVesrsion(HttpRequestBase request)
        {
            try
            {
                HttpContext.Current.Session["BrowserVesrsion"] = request.Browser.MajorVersion;

                return HttpContext.Current.Session["BrowserVesrsion"].ToString();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }