Obter valor do ENUM C#

Para retornar todos os valores do ENUM em C#

Enum.GetValues(typeof(EnumClass)).Cast(EnumClass);

Pode ser definida uma classe

public class EnumUtil
    {
        /// <summary>
        /// Retorna lista com todos as propriedades e valores do ENUM
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public static List<SimpleEnumResponse> GetPropertyValues<T>()
        {
            List<SimpleEnumResponse> lstRetorno = new List<SimpleEnumResponse>();
            SimpleEnumResponse model = null;
            foreach (int i in Enum.GetValues​​(typeof(T)))
            {
                model = new SimpleEnumResponse();
                model.Id = i;
                model.Name = Enum.GetName(typeof(T), i);
                lstRetorno.Add(model);
            }
            return lstRetorno;
        }

        /// <summary>
        /// Retorna somente a lista de valores de um ENUM
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <returns></returns>
        public static IEnumerable<T> GetValues<T>()
        {
            return Enum.GetValues(typeof(T)).Cast<T>();
        }
    }

    public class SimpleEnumResponse
    {
        public int Id { get; set; }
        public string Name { get; set; }
    }

Forma de USO:

var listFoo = EnumUtil.GetPropertyValues<Foo>();

<span class="entry-utility-prep entry-utility-prep-cat-links">Posted in</span> .NET | <span class="entry-utility-prep entry-utility-prep-tag-links">Tagged</span> , | Leave a comment

Foreach em CheckBox com JQuery

De maneira rápida é possível fazer um foreach em todos os checkbox da página

$('input[type=checkbox]').each(function () {
    
});

Dessa forma você pode acessar todas as propriedades do input utilizando, exemplo:

this.id

Até a próxima

<span class="entry-utility-prep entry-utility-prep-cat-links">Posted in</span> JavaScript, JQuery | <span class="entry-utility-prep entry-utility-prep-tag-links">Tagged</span> , | Leave a comment

Autenticação em Pasta da Rede C#

Autenticação em pasta de rede com C#

Para utilizar o código da classe abaixo faça da seguinte maneira:

public string networkPath = @"\\IP\Shared";  
NetworkCredential credentials = new NetworkCredential(@"USUÁRIO", "SENHA");  

Exemplo de Uso:

using (new NetworkConnection(networkPath, credentials))
    {
			using (StreamWriter writer = new StreamWriter(networkPath "\teste.txt", true))
            {
                writer.WriteLine("[" + DateTime.Now.ToString() + "]" + texto);
            }
	}
public class NetworkConnection : IDisposable
    {
        string _networkName;

        public NetworkConnection(string networkName,
            NetworkCredential credentials)
        {
            _networkName = networkName;

            var netResource = new NetResource()
            {
                Scope = ResourceScope.GlobalNetwork,
                ResourceType = ResourceType.Disk,
                DisplayType = ResourceDisplaytype.Share,
                RemoteName = networkName
            };

            var userName = string.IsNullOrEmpty(credentials.Domain)
                ? credentials.UserName
                : string.Format(@"{0}\{1}", credentials.Domain, credentials.UserName);

            var result = WNetAddConnection2(
                netResource,
                credentials.Password,
                userName,
                0);

            if (result != 0)
            {
                throw new Win32Exception(result);
            }
        }

        ~NetworkConnection()
        {
            Dispose(false);
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        protected virtual void Dispose(bool disposing)
        {
            WNetCancelConnection2(_networkName, 0, true);
        }

        [DllImport("mpr.dll")]
        private static extern int WNetAddConnection2(NetResource netResource,
            string password, string username, int flags);

        [DllImport("mpr.dll")]
        private static extern int WNetCancelConnection2(string name, int flags,
            bool force);
    }

    [StructLayout(LayoutKind.Sequential)]
    public class NetResource
    {
        public ResourceScope Scope;
        public ResourceType ResourceType;
        public ResourceDisplaytype DisplayType;
        public int Usage;
        public string LocalName;
        public string RemoteName;
        public string Comment;
        public string Provider;
    }

    public enum ResourceScope : int
    {
        Connected = 1,
        GlobalNetwork,
        Remembered,
        Recent,
        Context
    };

    public enum ResourceType : int
    {
        Any = 0,
        Disk = 1,
        Print = 2,
        Reserved = 8,
    }

    public enum ResourceDisplaytype : int
    {
        Generic = 0x0,
        Domain = 0x01,
        Server = 0x02,
        Share = 0x03,
        File = 0x04,
        Group = 0x05,
        Network = 0x06,
        Root = 0x07,
        Shareadmin = 0x08,
        Directory = 0x09,
        Tree = 0x0a,
        Ndscontainer = 0x0b
    }

<span class="entry-utility-prep entry-utility-prep-cat-links">Posted in</span> .NET, Windows | <span class="entry-utility-prep entry-utility-prep-tag-links">Tagged</span> , , | Leave a comment

Criar dropdown com jQuery (select option)

De forma simples e rápida é possível criar um input select utilizando o jQuery.

Pode ser feito da seguinte maneira…

$(‘#id-input-select-option’).empty();
$(‘#id-input-select-option’).append(‘‘);
jQuery.each(driverList, function () {
$(‘

Até a próxima!

Para aprender um pouco mais sobre jQuery recomendo o curso https://bit.ly/2WOPXSW

<span class="entry-utility-prep entry-utility-prep-cat-links">Posted in</span> JavaScript, JQuery | <span class="entry-utility-prep entry-utility-prep-tag-links">Tagged</span> | Leave a comment

Upload de Multiplos Arquivos HTML e jQuery

Informação básica de como fazer upload de vários arquivos utilizando de forma rápida o HTML e jQuery



Script

É só isso!

Obrigado e até mais!

<span class="entry-utility-prep entry-utility-prep-cat-links">Posted in</span> JavaScript, JQuery | <span class="entry-utility-prep entry-utility-prep-tag-links">Tagged</span> , | Leave a comment

Como retornar versão no Entity Framework Migration C# (Roolback)

A forma de retornar versão do Migration, seja por falha, estrutura criada de forma equivocada ou outros motivos. Seria da seguinte maneira:

Update-Database -TargetMigration:"ArquivoMigrationQueDesejaRetornar"

Exemplo: Digamos que você executou a Migration AddStatusProduto, porém o campo Status produto que não pode aceitar null, está aceitando. Você terá que retornar para o último Migration executado, que poderia ser o AddCategoriaProduto.

Neste caso seria digitado o comando Update-Database -TargetMigration “AddCategoriaProduto”

Obrigado!

<span class="entry-utility-prep entry-utility-prep-cat-links">Posted in</span> .NET | <span class="entry-utility-prep entry-utility-prep-tag-links">Tagged</span> , , | Leave a comment

jQuery Obter elemento ou valor pelo data-id

Como obter um elemento pelo data-id ou outra propriedade através do jQuery?

Digamos que tenha um input e queira obter o seu valor pelo data-item-id. Neste caso você irá obter fazendo…

<input class="whatever" data-item-id="stand-out">
$('[data-item-id="stand-out"]').val();

Caso queira tratar o elemento completo remova o .val() e atribua a uma variável, ficaria:

var elemento = $('[data-item-id="stand-out"]').val();

Até a próxima!

<span class="entry-utility-prep entry-utility-prep-cat-links">Posted in</span> JavaScript, JQuery | <span class="entry-utility-prep entry-utility-prep-tag-links">Tagged</span> , | Leave a comment

Converter input em Label

Como converter um campo input em um label?

Suponhamos que necessitamos ter uma mesma tela para edição/inclusão e queremos deixar essa tela também para visualização sem os inputs readonly.

Podemos através do jQuery alterar nossos inputs para campo label com o trecho abaixo:

 

Aprenda mais sobre javascript do básico ao avançado utilizando algum curso, além dos blogs, para melhorar a sua capacitação.

Leia sobre este curso

$('#id-do-campo').replaceWith(function(){
     return $('', {
     'class': this.className,
     text: this.value
    })
});
<span class="entry-utility-prep entry-utility-prep-cat-links">Posted in</span> JavaScript, JQuery | <span class="entry-utility-prep entry-utility-prep-tag-links">Tagged</span> , , | Leave a comment

Abrir Modal BootStrap JQuery

[html]
$(‘#myModal’).modal(‘toggle’);
$(‘#myModal’).modal(‘show’);
$(‘#myModal’).modal(‘hide’);
[/html]

<span class="entry-utility-prep entry-utility-prep-cat-links">Posted in</span> JQuery | Leave a comment

Validar CNPJ via JavaScript

Método rápido de validação de CNPJ através do JavaScript.

[html]function isCNPJValid(cnpj) {
cnpj = cnpj.replace(/[^\d]+/g, ”);
if (cnpj == ”) return false;
if (cnpj.length != 14)
return false;
// Elimina CNPJs invalidos conhecidos
if (cnpj == “00000000000000” ||
cnpj == “11111111111111” ||
cnpj == “22222222222222” ||
cnpj == “33333333333333” ||
cnpj == “44444444444444” ||
cnpj == “55555555555555” ||
cnpj == “66666666666666” ||
cnpj == “77777777777777” ||
cnpj == “88888888888888” ||
cnpj == “99999999999999”)
return false;

// Valida DVs
tamanho = cnpj.length – 2
numeros = cnpj.substring(0, tamanho);
digitos = cnpj.substring(tamanho);
soma = 0;
pos = tamanho – 7;
for (i = tamanho; i >= 1; i–) {
soma += numeros.charAt(tamanho – i) * pos–;
if (pos < 2) pos = 9; } resultado = soma % 11 < 2 ? 0 : 11 – soma % 11; if (resultado != digitos.charAt(0)) return false; tamanho = tamanho + 1; numeros = cnpj.substring(0, tamanho); soma = 0; pos = tamanho – 7; for (i = tamanho; i >= 1; i–) {
soma += numeros.charAt(tamanho – i) * pos–;
if (pos < 2) pos = 9; } resultado = soma % 11 < 2 ? 0 : 11 – soma % 11; if (resultado != digitos.charAt(1)) return false; return true; } [/html]

<span class="entry-utility-prep entry-utility-prep-cat-links">Posted in</span> JavaScript, JQuery | Leave a comment