quinta-feira, 23 de julho de 2015

ExtensionMethods

using System;
using System.Collections.Generic;
using System.Web.UI.WebControls;
using System.Web.SessionState;
using System.Web;
using Lapuinka.Entities;


namespace Lapuinka.Web
{
   
    public static class ExtensionMethods
    {

        public static bool IsAjaxRequest(this System.Web.HttpRequest request)
        {
            return request.QueryString["ajax"] == "true" || request["ajax_request"] == "true";
        }

        public static void SetSelected(this DropDownList drop, string text, bool byValue = false)
        {
            drop.ClearSelection();
            ListItem item = byValue ? drop.Items.FindByValue(text) : drop.Items.FindByText(text);
            if (item != null)
                item.Selected = true;
        }

        public static string SelectedText(this DropDownList drop, bool emptyIsNull = false)
        {
            return drop.SelectedItem != null ? drop.SelectedItem.Text.Trim() : (emptyIsNull) ? null : "";
        }

        public static bool HasValidSelection(this DropDownList drop)
        {
            return drop.SelectedItem != null && drop.SelectedItem.Text != "";
        }
       
        public static string ToFormatedDate(this string str, bool emptyIsNull = false)
        {
            DateTime dt;
            return DateTime.TryParse(str, out dt) ? dt.ToString("dd/MM/yyyy") : (emptyIsNull) ? null : "";
        }

        public static bool IsCpf(this string str)
        {
            return str.Length == 14;
        }

        public static bool IsCnpj(this string str)
        {
            return str.Length > 14;
        }

        public static string EmptyAsNull(this string str)
        {
            string st = str.Trim();
            return st == "" ? null : st;
        }

        public static int ToInt(this string str)
        {
            int out_int;
            return int.TryParse(str, out out_int) ? out_int : 0;
        }

        public static double ToDouble(this string str)
        {
            double out_int;
            return double.TryParse(str, out out_int) ? out_int : 0;
        }

        public static string ToMoney(this double dt)
        {
            return String.Format("{0:N2}", dt);
        }

        public static string ToPercent(this double dt)
        {
            return String.Format("{0:N2}", dt);
        }
    }

}
Postar um comentário