4 de julho de 2011

Asp.Net - MVC 3 Html Helpers

Usando: VS2010, Asp.net Mvc 3.0 e C#


1 - Crie um novo projeto File | New | Project | Web | Asp.net Mvc 3 Web Application 
2 - De nome MyHtmlHelper 

























 3 - Crie um novo Folder: Helpers























4 - Crie um nova Classe no folder Helpers chamada : HtmlHelpers.cs


5 - Adicione o código abaixo :


using System.Web.Mvc;

namespace MyHtmlHelper.Helpers
{
    public static class HtmlHelpers
    {
        public static string Truncate(this HtmlHelper helper, string input, int length)
        {
            if (input.Length <= length)
            {
                return input;
            }
            else
            {
                return input.Substring(0, length) + "...";
            }
        }
    }
}

6 - Vamos adicionar a referencia no web.config para que todas as paginas desse projeto possa ter acesso.


    <pages>
      <namespaces>
        <add namespace="System.Web.Helpers" />
        <add namespace="System.Web.Mvc" />
        <add namespace="System.Web.Mvc.Ajax" />
        <add namespace="System.Web.Mvc.Html" />
        <add namespace="System.Web.Routing" />
        <add namespace="System.Web.WebPages"/>
        <add namespace="MyHtmlHelper.Helpers" />
      </namespaces>
    </pages>



7 - Abra abra a Views | Home | index.aspx do seu projeto e modifique o codigo abaixo :


<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
    Home Page
</asp:Content>

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">
    <h2><%: Html.Truncate((string)ViewBag.Message,10) %></h2>
    <p>
        To learn more about ASP.NET MVC visit <a href="http://asp.net/mvc" title="ASP.NET MVC Website">http://asp.net/mvc</a>.
    </p>
</asp:Content>

8 - O resultado, foi criado um html helper no qual trunca sua string.

1 de julho de 2011

GAC - adicionar e remover Assembly

Utilizando C# e Framework 3.5

Adicionando e removendo um assembly do GAC:


  internal static class GAC
    {
        /// <summary>
        /// Add strong-named assembly to GAC. DLL must be in current directory.
        /// </summary>
        /// <param name="assemblyName">name of assembly (without .dll extension).</param>
        internal void Register ( String assemblyName )
        {
            ProcessStartInfo processStartInfo = new ProcessStartInfo("gacutil.exe"string.Format("/i {0}.dll", assemblyName));
            processStartInfo.UseShellExecute = false;
            Process process = Process.Start(processStartInfo);
            process.WaitForExit;
        }
        /// <summary>
        /// Remove assembly from GAC.
        /// </summary>
        /// <param name="assemblyName">name of assembly (without .dll extension).</param>
        internal void Unregister ( String assemblyName )
        {
            ProcessStartInfo processStartInfo = new ProcessStartInfo("gacutil.exe"string.Format("/u {0}.dll",             assemblyName));
            processStartInfo.UseShellExecute = false;
            Process process = Process.Start(processStartInfo);
            process.WaitForExit;
        }
    }

Obs: GACUTIL deve ter permissão de administrador.


Fonte: http://social.msdn.microsoft.com/Forums/en-US/csharpgeneral/thread/7d3165cf-ca3b-43cc-8f77-a46dbf38f13d/#a34173da-e511-4e56-a452-11afd827269c

Asp.Net - Criando HTML Snippet

Utilizando: Visual Studio 2010, C#, FrameWork 4.0 e Asp.Net Webforms


1 - Crie um novo projeto C# | Web | ASP.NET Empty Web Application
2 - Crie um novo arquivo XML New | File | General | Xml File
3 - Insira o código abaixo no arquivo XML :



<CodeSnippet Format="1.0.0" xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
  <Header>
    <Title>Address Block</Title>
    <Author>author</Author>
    <Shortcut>AddrBlock</Shortcut>
    <Description>XML Snippet to create a quick address block.</Description>
    <SnippetTypes>
      <SnippetType>Expansion</SnippetType>
    </SnippetTypes>
  </Header>
  <Snippet>
    <Code Language="html">
      <![CDATA[
   <label for="CustomerType">Customer Type:</label>
   <select>
   <option>Federal</option>
   <option>State</option>
   <option>Corporate</option>
   <option>Residential</option>
   </select> 
   <br />


    <label>Name: </label>
    <input id="name" name="name"/><br />


    <label >Address Line 1: </label>
    <input id="AddressLine1" name="AddressLine1"/><br />


    <label>Address Line 2: </label>
    <input id ="AddressLine2" name="AddressLine2"/><br />


    <label>City </label> <input id="City" name="City"/><br />


    <label>State </label><input id="State" name="State"/><br />


    <label >Zip Code </label>   <input id="zip" name="zip"/><br /><br />


      $end$]]>
    </Code>
  </Snippet>
</CodeSnippet>


4 - Salve o Arquivo XML em  C:\Users\<Username>\Documents\Visual Studio 10\Code Snippets\Visual Web Developer\My HTML Snippets\ , com o nome de Address Block como a extensão *.snippet 




























5 - Clique com botão direito na sua WebApplication abaixo da solução | Add | New | Item | Web Form,  abra o arquivo criado, clique entre as tag <div> e pressione CTRL + K E CTRL + X














6 - Selecione My HTML Snippets e depois Address Block








































7 - Veja o resultado final :


















Fonte : Microsoft Training Kit VS2010

30 de junho de 2011

Asp.Net - WebForms JQuery exemplo simples

Utilizando: Visual Studio 2010, C#, FrameWork 4.0 e Asp.Net Webforms

1 - Crie um novo projeto C# | Web | ASP.NET Web Application
2 - Como nome do projeto de NewWebApplicationTemplate 

































3 - Abra Default.apsx e insira o código em destaque abaixo abaixo :


<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
    <h2>
        Welcome to ASP.NET!
    </h2>
    <p>
        To learn more about ASP.NET visit <a href="http://www.asp.net" title="ASP.NET Website">www.asp.net</a>.
    </p>
    <p>
        You can also find <a href="http://go.microsoft.com/fwlink/?LinkID=152368&amp;clcid=0x409"
            title="MSDN ASP.NET Docs">documentation on ASP.NET at MSDN</a>.
    </p>
    <input type="button" id="btnChangeTitleStyle" value="Change Title Style" />
</asp:Content>


4 - Para usar o jQuery, você deve adicionar uma referência à biblioteca jQuery. Para fazer isso, adicione o  seguinte elemento script, que faz referência ao arquivo de origem jQuery, dentro da tag HeaderContent.



<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
    <script type="text/javascript" src="Scripts/jquery-1.4.1.js"></script>
</asp:Content>



5 - Abaixo da tag script adicionada acima insira o bloco de codigo abaixo :


    <script type="text/javascript">
        $(document).ready(function () {
            $("#btnChangeTitleStyle").click(function () {
                $("h2").css("color", "red");
            });
        });
    </script>


6 - F5 para executar o projeto e veja como ficou




















Fonte : Microsoft Training Kit VS2010

Office Application - Criando Business Entities e inserindo em uma planilha Excel

Utilizando: Visual Studio 2010, Framework 4.0, C# e Office 2007.

1 - Crie um novo projeto windows | console application.
2 - Defina o nome do projeto como OfficeApplication
3 - Adicione duas referencias: Microsoft.Office.Interop.Excel Microsoft.Office.Interop.Word



















Obs : certifique-se que a versão selecionada é 12.0.0.0

4 - Adicione uma nova classe chamada Account.cs
5 - Adicione as propriedades abaixo:


    public class Account
    {
        public int ID { get; set; }
        public double Balance { get; set; }
        public string AccountHolder { get; set; }
    }

6 - Crie um novo método chamado CreateAccountList na classe Program.cs

        private static List<Account> CreateAccountList()
        {
            var checkAccounts = new List<Account> {
            new Account{
                ID = 1,
                Balance = 285.93,
                AccountHolder = "John Doe"
            },
            new Account {
                ID = 2,
                Balance = 2349.23,
                AccountHolder = "Richard Roe"
            },
            new Account {
                ID = 3,
                Balance = -39.46,
                AccountHolder = "I Dunoe"
            }
                };
            return checkAccounts;
        }

7 - No método Main da classe Program.cs adicione o código abaixo :

static void Main(string[] args)
        {
            var checkAccounts = CreateAccountList();
        }


8 - Na classe Programa.cs adicione os namespace :


using Microsoft.Office.Interop;
using Excel = Microsoft.Office.Interop.Excel;
using Word = Microsoft.Office.Interop.Word;


9 - Abaixo do método Main insira o bloco de código abaixo que cria um nova planilha :


        static void DisplayInExcel(this IEnumerable<Account> accounts,
                          Action<Account, Excel.Range> DisplayFunc)
        {
            var x1 = new Excel.Application();

            //veja as Células abaixo criando o cabeçalho
            x1.Workbooks.Add();
            x1.Visible = true;
            x1.get_Range("A1").Value2 = "ID";
            x1.get_Range("B1").Value2 = "Balance";
            x1.get_Range("C1").Value2 = "Account Holder";
            x1.get_Range("A2").Select();

            foreach (var ac in accounts)
            {
                DisplayFunc(ac, x1.ActiveCell);
                x1.ActiveCell.get_Offset(1, 0).Select();
            }

            ((Excel.Range)x1.Columns[1]).AutoFit();
            ((Excel.Range)x1.Columns[2]).AutoFit();
            ((Excel.Range)x1.Columns[3]).AutoFit();
        }


Obs: É necessário a alterar a classe Program.cs  para static como exemplo abaixo:


    static class Program
    { ...


10 - Adicione no seu método Main da classe Program.cs o bloco de código abaixo :


            checkAccounts.DisplayInExcel((account, cell) =>
            {
                cell.Value2 = account.ID;
                cell.get_Offset(0, 1).Value2 = account.Balance;
                cell.get_Offset(0, 2).Value2 = account.AccountHolder;

                if (account.Balance < 0)
                {
                    cell.Interior.Color = 255;
                    cell.get_Offset(0, 1).Interior.Color = 255;
                    cell.get_Offset(0, 2).Interior.Color = 255;
                }
            });

11  - Aperte F5 para executar o projeto e veja como ficou.

















Fonte : Microsoft Training Kit VS2010