Arquivo

Arquivo da Categoria ‘Uncategorized’

Compartilhando dlls entre várias aplicações usando o GAC

20, agosto, 2010

 

Reusar código é uma boa idéia, então provavelmente seria uma boa idéia reaproveitar códigos em uma dll que forneça serviços por exemplo.Normalmente nós desenvolvedores reusamos uma dll construida com funções básicas. Desde .net 1.1 é possível compartilhar dlls entre aplicações usando o global cache assembly. Este espaço existe em qualquer maquina com o framework instalado, para começar a usar é necessário que o assembly a ser registrado possua um “Nome forte” que entre outras coisas é responsável por identificar de maneira única o assembly.

 

Criando um nome forte para o assembly

SigningAssembly

 

Após a configuração veja que foi gerado um arquivo com extensão .snk

Adicionar assembly na aba referêncy do Visual Studio

Após esta configuração temos um assembly com o nome forte, agora falta registrar o mesmo no GAC.Antes de registrar vamos mover o assembly para a pasta:

%Program Files%\Microsoft Visual Studio 9.0\Common7\IDE\PublicAssemblies

Com o assembly nesta pasta o visual studio reconhece nossa dll como uma dll do .NET, assim fica mais facil adicionar referências.

 

Registrando o assembly

Para registrar o assembly vamos usar o utilitário gacutil. o comando é gacutil /i nomedoassembly.dll

 

Agora já é possível criar aplicativos que possuem como referência um assembly registrado no GAC. Para adicionar a referência basta procurar na aba .NET do visual studio.

 

E quando eu alterar o assembly adicionado no GAC?

Quando um assembly do GAC for alterado será necessário registrar novamente o mesmo e reiniciar o visual studio para que ele atualize a sua referência de desenvolvimento. Como no projeto que surgiu a necessidade de usar o GAC estamos constantemente editando o projeto adicionado nós criamos um script para execução no Build Events do projeto. Se alguem precisar so script pode comentar aqui que eu explico como funciona.

Author: higor.cesar Categories: Arquitetura, Uncategorized, visual Studio Tags:

Resposta:equals é diferente de ==

11, agosto, 2010

Olá Pessoal em resposta aoi post equals é diferente de == a respostá é?!! depende do contexto! No exemplo que postei o segundo caso, usando igual, gera uma exceção durante a comparação pois default(string) é NULL. Nesse caso o resultado é diferente. Eu tive um problema semelhante durante o desenvolvimento e resolvi postar. Então, quem usa object.Equals() tem que ficar esperto.

Author: higor.cesar Categories: Uncategorized Tags:

T4: Acessando o banco de dados

3, fevereiro, 2010

Templates T4 são largamente usados para acessar o banco de dados e gerar código de acordo com os objetos(tabelas e etc). Vamos ver como podemos acessar o SQLServer usando templates tt.Antes de ver o código precisamos baixar ums dlls

1-Importar os assemblies

   1: <#@ assembly name="Microsoft.SqlServer.ConnectionInfo" #>

   2: <#@ assembly name="Microsoft.SqlServer.Smo" #>

   3: <#@ assembly name="Microsoft.SqlServer.Management.Sdk.Sfc" #>

   4: <#@ assembly name="Microsoft.SqlServer.SqlEnum" #>

   5: <#@ import namespace="System.IO" #>

   6: <#@ import namespace="Microsoft.SqlServer.Management.Smo" #>

2-Estabelecer a conexão

   1: <#

   2:     Server server = new Server("NomeDaMaquina\\NomeDaInstancia");

   3:     Database database = new Database(server, "NomeDoDatabase");

   4:     database.Refresh();

   5: #>

3- Gerando uma classe para cada tabela do banco

   1: <#

   2:     foreach (Microsoft.SqlServer.Management.Smo.Table item in database.Tables)

   3:     {

   4: #>

   5:     public class <#=item.Name#>{}

   6:     <# SaveOutput(item.Name+".cs");

   7:     }

   8: #>

4- Usamos um método SaveOutput que está em outro tt que foi incluido no início do arquivo

   1: <#@ include file="SaveOutput.tt" #>

5- Código do SaveOutput.tt

   1: <#@ template language="C#" hostspecific="true" #>

   2: <#@ import namespace="System.IO" #>

   3: <#+

   4:   void SaveOutput(string outputFileName)

   5:   {

   6:       string templateDirectory = Path.GetDirectoryName(Host.TemplateFile);

   7:       string outputFilePath = Path.Combine(templateDirectory, outputFileName);

   8:       File.WriteAllText(outputFilePath, this.GenerationEnvironment.ToString());

   9:

  10:       this.GenerationEnvironment.Remove(0, this.GenerationEnvironment.Length);

  11:   }

  12: #>

Download do código fonte

Author: higor.cesar Categories: Agile, SQLServer, T4, Uncategorized Tags:

Entity Framework 4: CodeOnly e POCO

22, dezembro, 2009

Fala galera, este post é resultado do meu estudo sobre as features do EFv4. A idéia deste post é mostrar o básico do CodeOnly e uso de POCOs no EF, este post foi baseado no exemplo feito pelo time do ADO.NET. Para rodar o código é necessário instalar o CTP2 que pode ser baixado aqui.

1-Inicialmente vamos criar uma solution vazia no visual studio.

2-Adicionar uma projeto(classLibrary) chamado Classes, neste projeto vamos colocar nossos POCOs

3- No projeto Classes adicionar uma classe chamada pessoa com o código abaixo

   1: public class Person

   2:    {

   3:        public int PersonID { get; set; }

   4:        public String Name { get; set; }

   5:        public int Age { get; set; }

   6:        public String Email { get; set; }

   7:    }

4- Agora vamos criar um novo projeto(classLibrary) chamado Model, neste projeto vamos colocar as configurações do EF

5- Vamos adicionar nestr projeto referências para a dll  Microsoft.Data.Entity.ctp e System.Data.Entity

6- Agora vamos adicionar uma classe chamada PersonConfiguration, esta classe será responsável pelo mapeamento do nosso POCO para o banco de dados.

   1: public class PersonConfiguration : EntityConfiguration<Person>

   2: {

   3:     public PersonConfiguration()

   4:     {

   5:         //Estamos indicando que PersoID é Identity

   6:         Property(p => p.PersonID).IsIdentity();

   7:

   8:         //Estamos indicando que o nome é NOT NULL

   9:         Property(p => p.Name).IsRequired();

  10:     }

  11: }

este arquivo vai existir para cada classe POCO do projeto.

7-Vamos criar uma classe chamada Model, esta classe será o nosso DataContext.

   1: public class SimpleCodeOnlyExampleModel : ObjectContext

   2:     {

   3:         public SimpleCodeOnlyExampleModel(EntityConnection entityConnection)

   4:             : base(entityConnection)

   5:         {

   6:             DefaultContainerName = "SimpleCodeOnlyExampleModel";

   7:         }

   8:

   9:         //IObject é uma interface que que possui os métodos necessários para o CRUD

  10:         public IObjectSet<Person> People

  11:         {

  12:             get { return base.CreateObjectSet<Person>(); }

  13:         }

  14:     }

8- Agora vamos criar uma factory para encapsular a criação do DataContext e tudo pronto

   1: public class DataContext

   2: {

   3:

   4:     public static SimpleCodeOnlyExampleModel FactoryDataContext()

   5:     {

   6:         String connection = @"Data Source=.\SQLEXPRESS;Initial Catalog=SimpleCodeOnlyExampleModel;Integrated Security=SSPI;";

   7:         var builder = new ContextBuilder<SimpleCodeOnlyExampleModel>();

   8:

   9:         //Adicionamos todas as configurações

  10:         builder.Configurations.Add(new PersonConfiguration());

  11:         return builder.Create(new SqlConnection(connection));

  12:     }

  13:

  14:     /// <summary>

  15:     /// Este método cria o database de acordo com o mapeamento realizado nas classes

  16:     /// de configuração do POCO

  17:     /// </summary>

  18:     public static void CreateDataBase()

  19:     {

  20:         var ctx = FactoryDataContext();

  21:         if (!ctx.DatabaseExists())

  22:             ctx.CreateDatabase();

  23:     }

  24: }

Tudo pronto! agora vamos ao nosso exemplo. Podemos criar um projeto chamado ConsoleApp(Console Application) para rodar nosso exemplo.

   1: public static void Main()

   2: {

   3:     //este método cria um database

   4:     DataContext.CreateDataBase();

   5:

   6:     //Cadastradando uma pessoa

   7:     Person p = new Person();

   8:     p.Name = "Higor";

   9:     p.Age = 20;

  10:     p.Email = "higor.crr@gmail.com";

  11:     var ctx = DataContext.FactoryDataContext();

  12:

  13:     ctx.People.AddObject(p);

  14:     ctx.SaveChanges();

  15:

  16:     //lendo todas as pessoas

  17:     var people = ctx.People.ToList();

  18:

  19:

  20: }

Após rodar o código podemos observar que um database foi criado no SQLServerExpress e que temos dados e tudo.

Estou achando o trabalho do pessoal muito bom, e vocês? vou abordar questões mais complexas nos próximos posts. Vou adiantar que o proximo assunto será lazyLoading e tipos de dados complexos.

fonte:http://higorcesar.com.br/Download/SimpleCodeOnlySample.rar

Author: higor.cesar Categories: Uncategorized Tags:

Would you like to study at IST-RIO?

23, junho, 2009

Hello folks, Today I’ve you good news. If you want to join us and study at IST-Rio you can fill the application form here.

IST-Rio is the technology college of FAETEC. I have been studying at IST-Rio since 2007, I really like this place! There you can breathe science computer, you can join a research project or doing some special classes such as multi-modeling language If you want there are others colleges such as ISERJ.

Resources

http://201.20.19.254/Faetec_2009.2/

http://www.faetec.rj.gov.br/

http://www.faetec.rj.gov.br/ist-rio/app/index.php

http://www.rafaelbiriba.com/2009/06/18/ist-rio-inscricoes-abertas-vestibular-2009-2%C2%BA-semestre.html

Author: higor.cesar Categories: Uncategorized Tags:

Hello world!

16, junho, 2009

Welcome to WordPress. This is your first post. Edit or delete it, then start blogging!

Author: higor.cesar Categories: Uncategorized Tags:

Problems with Entity Reference in LINQTOSQL

14, abril, 2009

Hi fellows, Today I’ll talk about a boring problem that was occurring. The problem is about entity reference properties in entities generated By LINQTOSQL, So look this table for relationship for instance:

When you have a property which is an entity it is called EntityReference(EntityRef), you have to pay attention when you are setting this kind of properties because you can do it in two different s ways, the first way is set the ID property , for example:

employee.DepartmentID = department.DepartmentID;

The other way is setting the entity, for example:

employee.Department = new Department();

So, I have never noticed the strong difference between these codes. I have noticed this difference with some erros when I was submitting changes such as an insert or update.

Insert

when I’m inserting or attaching a new object in a context I can’t set the reference object in the property ‘cause this object can exists in the current context, and how the object that will be attached this properties will too so the DataContext will Attach an entity that already exists. In this case is better set the PropID because there is no chance to attach a existent object.Look this code:

set

{

if ((this._DepartmentID != value))

{

if (this._Department.HasLoadedOrAssignedValue)

{

throw new System.Data.Linq.ForeignKeyReferenceAlreadyHasValueException();

}

this.OnDepartmentIDChanging(value);

this.SendPropertyChanging();

this._DepartmentID = value;

this.SendPropertyChanged(“DepartmentID”);

this.OnDepartmentIDChanged();

}

}

Update

Different from insert, when you are updating an object you are submitting changes in one attached object , so how this object is attached this properties are attached to. So in this case you can’t change the a property that defines the entity of an reference object so you can’t change the ID you have to change the entity reference and the set method of a entity reference set the id, look this code:

set

{

Department previousValue = this._Department.Entity;

if (((previousValue != value)

|| (this._Department.HasLoadedOrAssignedValue == false)))

{

this.SendPropertyChanging();

if ((previousValue != null))

{

this._Department.Entity = null;

previousValue.Employees.Remove(this);

}

this._Department.Entity = value;

if ((value != null))

{

value.Employees.Add(this);

this._DepartmentID = value.DepartmentID;

}

else

{

this._DepartmentID = default(int);

}

this.SendPropertyChanged(“Department”);

}

}

I solved my problem using these concepts, So when I am working with an attached entity I set the EntityRef object otherwise set just the ID. I wish it could help you. C ya

Author: higor.cesar Categories: Uncategorized Tags:

Learning about unit test

4, fevereiro, 2009

Hi people, today my team began to use automated unit tests. we are using some tools such as selenium, xpathchecker and NUnit. I’ve already said in other post that we’re using selenium to test the web user interface. We are using the selenium IDE, its provides an action recorder that saves clicks and behavior so is very simple generate User interface tests. I’ve looked for information about how to write good unit tests, unfortunately i didn’t find it. I found some things about good practices but I think that just good practices don’t make me write good tests. i will look for more information and any news I tell you.

Author: higor.cesar Categories: Uncategorized Tags:

Thinking about data layer

17, dezembro, 2008

    Hi Folks, I was searching some information about patterns to persist & retrieve Data. The first thing that I did was search about DAO patterns and its applications. Basically the benefit of apply this patterns is create a independent data layer and separate it from business layer . You can se more information about DAO at end of this post.

  I’ll use Entity framework in my project. Entity framework(EF) is a object-relational-mapping tool. This  toll provide objects and methods to work with Data Stores. You can see more information about it here. Who already worked with LINQ(Language Integrated Query) will have more facilities with EF. So I was thinking is use DAO Pattern but I saw that EF/LINQ provides some facilities of this pattern. I’ll describe the same point of these approaches.

1 – Working with different data store technologies

DAO – provides an interface to work with Data store, so isn’t necessary know if data is saved in txt files, relational databases or xml files. DAO provides its using a interface that defines all methods of an entity. Each class that implements a different way to store data must implements the defined interface.

EF/LINQ – The EF provides some ways to store data too. With LINQ is possible use XML,MSSQL and others. Using EF will be possible work with many Data store tool as Oracle,MSSQL and MySQL.

2- Hide real implementation

 

DAO -  When you work with DAO you use an interface, so your client code will use methods defined in a interface. Its mean that you don’t need worry about implementation of methods.

EF/LINQ -  EF provides all methods necessaries to work with data Stores as DAO you don’t need worry about these methods they are created automatically.

 

    In other words, EF/LINQ has some benefits of DAO pattern but  EF is more powerful because many others features as Validation in compilation time, a powerful language and less code. Well, I am still thinking how I’ll implement the connection between Data store and business code.

 

ps: Sorry for my poor English, I was reading and I decided to write about my doubts..

LINKS:

DAO

http://java.sun.com/blueprints/corej2eepatterns/Patterns/DataAccessObject.html

http://www.urubatan.com.br/dao-generico-um-exemplo-a-pedidos/

Author: higor.cesar Categories: Uncategorized Tags:

Navegadores

10, setembro, 2008

Fala galera, como já mencionei aqui trabalho em uma empresa de Desenvolvimento web, logo conversas sobre navegadores ocorrem a todo momento. Sendo eu um jovem ‘amante’ de software livre e open Source estava defendendo o Google Chrome e o Mozilla. Até ai tudo bem.. Estava virado trabalhando na minha estação de trabalho quando um dos membros da equipe disse:

        “Bom mesmo é o safári. Até o branco no safári é mais branco!”

Bem, não estou preocupado em defender qualquer navegador que seja neste post, apenas o redigi, pois achei muito inusitada a frase do meu amigo Marvin …rsrs e ai alguém ai acha que o branco do safári é mais branco?

Abraços..

Author: higor.cesar Categories: Uncategorized Tags: