Se criarem um edmx de Entity Framework 5/6 e depois meterem o Sql Profiler a correr verificam que as queries não estão a correr na base de dados "correcta", elas estão a correr todas a partir da master.
Isto não impede em nada o funcionamento das aplicações (pois todas as queries vêm com as tabelas prefixadas da base de dados correcta) mas se tivermos múltiplas bases de dados torna-se complicado filtrar as queries por base de dados no Sql Profiler ...
Como é que se revolve o "problema"? Simples, basta forçar o atributo MultipleActiveResultSets na connection string a false.
Parece que foi uma decisão de desenho sempre que a conection string tem o MultipleActiveResultSets a true todas as queries que passam por essa conexão usam a base de dados master.
Fonte: SQL Server Profiler showing EF queries against master database?
Wednesday, March 5, 2014
Queries da Entity Framework 5+ a correr na base de dados master
Wednesday, February 26, 2014
Ficheiros de configuração do Log4net por ambiente
Uma boa prática a seguir quando se desenvolvem aplicações é ter os ficheiros de configuração separados por ambiente. Por norma usa-se uma pasta config onde estão os ficheiros de configuração para cada secção do web/app.config por ambiente:
\config\appSettings.local.config
\config\appSettings.staging.config
\config\appSettings.release.config
\config\log4net.local.config
\config\log4net.staging.config
\config\log4net.release.config
Depois no web/app.config através do atributo configSource especifica-se o path para o ficheiro de configuração de cada secção. Desta forma é facil automatizar o processo de build/deploy para apenas alterar o path nos ficheiros web/app.config para a aplicação passar a usar as configurações do ambiente alvo.
O problema surge quando se verifica que o elemento não suporta o atributo configSource ...
No entanto é possivél dar a volta configurando a chave "log4net.Config" na secção appSettings. O log4net quando é inicializado vê se essa chave de configuração existe, e caso exista vai procurar o ficheiro de configuração na path especificada para carregar a sua secção de configuração.
No entanto é possivél dar a volta configurando a chave "log4net.Config" na secção appSettings. O log4net quando é inicializado vê se essa chave de configuração existe, e caso exista vai procurar o ficheiro de configuração na path especificada para carregar a sua secção de configuração.
<appSettings>
...
<add key="log4net.Config" value="config/log4net.local.config" />
...
</appSettings>
Desta forma quando se corre o processo de build/deploy este altera o path para o ficheiro appSettings a usar e depois na chave "log4net.Config" especificamos o path para o ficheiro de configuração do log4net para esse ambiente.
Wednesday, February 19, 2014
Como criar um installer offline para o Visual Studio a partir de um Installer Web
Resumo
Se precisarem do pacote de instalação offline dum visual studio completo ou dum update, para gravar numa network share ou num dvd, e só têm a versão web existe uma forma fácil de "converte-lo". Para isso basta correr o executável a partir da linha de comandos com a opção /layout e ele faz download de todos os ficheiros necessários para a pasta há nossa escolha, depois e só copiar o resultado para onde quisermos.Passo a passo
1) Correr o executável a partir da linha de comandos com o a opção /layout2) Escolher a pasta de destino
3) Esperar até o download acabar e ficamos com os ficheiros necessários para a instalação em modo offline
Fonte: How To: Create an offline installer for Visual Studio from a Web Installer
Friday, February 14, 2014
Usar aplicação nativa da ZXing a partir de uma página web
A ZXing permite que a partir de uma página web chamar a aplicação nativa para fazer a leitura de um código (barras/qr/etc) e devolve-lo por query string de volta para a página.
Só temos de criar um link para a página da ZXing com o endereço de callback em parâmetro:
http://zxing.appspot.com/scan?ret=http%3A%2F%2FENDEREÇO_DE_CALLBACK%2F?result={CODE}
Neste endereço o placeholder {CODE} vai ser substituido pelo resultado da leitura do código e depois na página podemos fazer o que quisermos com ele.
Fica aqui um exemplo (works on my machine/device). Se carregarem no link "TESTAR LEITURA DE CÓDIGO" com um device móvel ele vai abrir a aplicação nativa e depois de lerem um código volta para esta pagina e mostra o resultado dessa leitura.
TESTAR LEITURA DE CÓDIGO
Fonte: ZXing: Scanning From Web Pages
Só temos de criar um link para a página da ZXing com o endereço de callback em parâmetro:
http://zxing.appspot.com/scan?ret=http%3A%2F%2FENDEREÇO_DE_CALLBACK%2F?result={CODE}
Neste endereço o placeholder {CODE} vai ser substituido pelo resultado da leitura do código e depois na página podemos fazer o que quisermos com ele.
Fica aqui um exemplo (works on my machine/device). Se carregarem no link "TESTAR LEITURA DE CÓDIGO" com um device móvel ele vai abrir a aplicação nativa e depois de lerem um código volta para esta pagina e mostra o resultado dessa leitura.
TESTAR LEITURA DE CÓDIGO
CÓDIGO LIDO:
Fonte: ZXing: Scanning From Web Pages
Detetar dispositivo móvel em javascript numa página
Segue aqui um helper em javascript para detetar qual o dispositivo móvel que está a carregar a página:
Fonte: DETECTING MOBILE DEVICES WITH JAVASCRIPT
var isMobile = {
Android: function() {
return navigator.userAgent.match(/Android/i) ? true : false;
},
BlackBerry: function() {
return navigator.userAgent.match(/BlackBerry/i) ? true : false;
},
iOS: function() {
return navigator.userAgent.match(/iPhone|iPad|iPod/i) ? true : false;
},
Windows: function() {
return navigator.userAgent.match(/IEMobile/i) ? true : false;
},
any: function() {
return (isMobile.Android() || isMobile.BlackBerry() || isMobile.iOS() || isMobile.Windows());
}
};
Fonte: DETECTING MOBILE DEVICES WITH JAVASCRIPT
Friday, January 31, 2014
Programação Orientada a Gambiarra
Foi este post que vi no facebook que me fez arrancar com o blog, na altura achei tanta piada que me lembrei de fazer o post com a cheat sheet que usavamos na finsolutia.
E realmente faz todo o sentido também deixar aqui os slides para mais tarde recordar :)
E realmente faz todo o sentido também deixar aqui os slides para mais tarde recordar :)
Monday, January 27, 2014
Cheat Sheet: FAIL - Anti-Patterns and Worst Practices
Fica aqui a cheat sheet que usavamos na finsolutia, muitos destas más praticas/padrões não são usuais ... mas outros são pão nosso de cada dia :)
1) Principles of programming
| Description | Prefer | ||
| FBR | Fast Beats Right | More important to deploy something that appears to work, than to spend time ensuring "correctness" | "Continuous attention to technical excellence and good design enhances agility" - Agile Manifesto |
| FCD | Feeping Creaturitis Driven | Just when the end is in sight, someone adds just one more feature they are desperately in love with | "Deliver working software frequently, from a couple of weeks to a couple of months, with a preference to a shorter timescale." - Agile Manifesto |
| ADP | Assumption Driven Programming | Assume the user will only use your software the way you mean for them to. | Practice defensive coding. Watch how users attempt to use the software. Treat handling the unexpected like any other feature. |
| TP | Telemarketer Principle | The best way to retain control of what your code does is to manage exactly which objects it uses and what calls it makes at all time. | The Dependency Inversion Principle can be used to correct this kind of code. |
2) Anti-Patterns
| Description | Prefer | ||
| SCP | Static Cling Pattern | The easiest way to add functionality or track state is via static/global methods and objects. The Singleton Pattern is also your best friend! | Dependency Inversion Principle. Your code should depend on interfaces, not static calls which cannot be injected. Static methods are death to testable code. |
| VSP | Vestigial Structure Pattern | Don't remove code that's no longer used just in case it's needed later! If you're really brave, comment the code but leave it in there. | VSP is often a symptom of a muddled architecture, where it is difficult to tell where one feature begins and another ends. |
| FOO | Flags Over Objects | Instead of using objects, polymorphism, or delegation, it's much faster to just add a flag to a class and expose it. Who needs inheritance? | Instead of checking a flag before performing and action, tell the object what to do and let it polymorphically do so. |
| TGC | The God Class | Strive to create one class to rule them all, a master class, capable of doing anything and everything your application might require. | Follow the Single Responsibility Principle |
3) Worst Practices
| Description | Prefer | ||
| FOI | Found on Internet | Search engines these days are smart; obviously the first blog post found that appears to solve the issue at hand must be the best approach based on our collective wisdom. Get it to compile and move on. | Write a spike solution to ensure you understand the code. Or be sure to write some tests that confirm the code behaves as you expect. Review other approaches - are you asking the right questions? |
| PO | Premature Optimization | All code written should be optimized for performance, even if the resulting design is less clear or elegant, or if the code is question is nowhere near the critical path for the application. | Define performance requirements. Write tests that validate these requirements are being met. Do not optimize unless these tests fails. Identify bottlenecks don't blindly make "fixes". |
| CPC | Copy-Paste-Compile | The feature you're working on is nearly identical to one already in the system. Just copy, paste, and get the code to compile and you're done! | Keep your application code DRY. Refactor common code into shared modules when it makes sense to do so (avoid introducing excessive coupling). |
| CFV | Copy Folder Versioning | When really big changes are imminent, there's nothing like creating a copy of the current code folder to reassure you that you can always roll back. | Use source control |
| GH | Golden Hammer | Your favorite language, framework, library, or tool can do anything! wield it with confidence, and ignore anybody who tells you another tool might be better suited. | Become familiar with a variety of languages, tools, and frameworks. Keep an open mind as you approach problems. |
| ST | Shiny Toy | Did you hear about the latest beta (tool/language/framework)? I'm sure it will solve all of our application's problems. | Prefer existing and well-known tools and patterns to unproven ones for production use. |
| RTW | Reinvent The Wheel | We can build it better ourselves. No matter what "it" is. We don't trust anything that was Not Invented Here. | Know and use your application framework (e.g. the .NET framework). Share knowledge within your organization. Learn to make reasonable build vs. buy decisions when appropriate. |
4) The Big Ball of Mud / Quagmires
| Description | |||
| BBM | The Big Ball of Mud / Quagmires | Spaghetti code jungle. The overall structure of the system may never have been well defined. Only those who are unconcerned about architecture, and, perhaps, are comfortable with the inertia of the day-to-day chore of patching the holes in these failing dikes, are content to work on such systems. These systems show unmistakable signs of unregulated growth, and repeated, expedient repair | |
| Description | Prefer | ||
| TC | Throwaway Code | Taking the time to write a proper, well thought out, well documented program might take more time that is available to solve a problem, or more time that the problem merits | The real problem with THROWAWAY CODE comes when it isn't thrown away. |
| SUR | Sweeping it Under the Rug | If you can't make a mess go away, ate least you can hide it. | Clean up messy code. There is a limit to how much chaos an individual can tolerate before being overwhelmed. |
| TR | Total Rewrite | Your code has declined to the point where it is beyond repair, or even comprehension. | Therefore, throw it away and start over. Doing a fresh draft is a way to overcome neglect. Issues are revisited. A fresh draft adds vigor. You draw back to leap. The quagmire vanishes. The swamp is drained. |




