Monday, November 29, 2010

New and Improved Adobe Acrobat X

Adobe Acrobat remains one of the best kept secrets in the software industry. While many users, use the ubiquitous Adobe Acrobat Reader to open, print and display files on the web- many are unaware of the engine that makes this all happen. I have been fortunate enough to be provided with a Reviewer Copy of Adobe Acrobat X Pro which was recently released into the marketplace. As a long time user of Adobe Acrobat I was looking forward to working with the latest version of Acrobat to see what new and innovative features were build into this version. Adobe Acrobat X is now available for both Windows and Macintosh computers and builds on the long tradition of Acrobat as easy to use tool to create and publish PDF files.

The most significant change that you will see when you start up Adobe Acrobat X is in the interface. If you have used any of Adobe's newer applications you will feel right at home. Adobe has really done their homework and analyzed how users are most likely to use Acrobat and reconfigured the menus. You will notice on the right had side of the screen three different tabs, Tools, Comments, and Share. Clicking on any of these items will reveal a Pane with the associated tools and features. Being a long time user of Acrobat it was always a challenge to find where I might find the tool that I was looking for. Having the new interface now makes it a cinch to know exactly where to find something. The new interface is very intuitive and makes it easy for you to be as efficient as possible when you are looking for the right tool. The simplicity of the interface is going to be a hallmark of this version and one that I know I will enjoy using.

Creating PDF files is a lot easier to create with the new version of Adobe Acrobat X. Simply select the Create button from the menu and you have your choice of how you would like to create your PDF. One of the areas that has been vastly improved is creating a PDF from Scanner. I found that Adobe Acrobat X was much faster at creating the PDF and the finished PDF file size was much smaller than in the past. There were significant improvements in the Optical Character Recognition Engine which would account for better recognition of scanned material. Having a fully search-able PDF document with a small footprint really foots the bill for me.

One of my favorite features which was introduced in version 9 of Acrobat is the concept of a PDF Portfolio. This is an extremely powerful tool  and one that I feel has the potential to take this product far both in business and education sectors. As the term would implies a PDF Portfolio is a way for you to include a range of different types of  files and media formats and wrap it up in a PDF envelope. With a PDF Portfolio one could include a Word, Excel, Audio, Video, PDF documents and convert it into one single PDF file that can be delivered to your client or student. When they receive the PDF Portfolio you can package it and brand it with your company's colors or logo. Your recipient then receive I highly stylized PDF portfolio with easy to use navigation that can be opened with the free Adobe Acrobat Reader (version 9 or X) and presented with the files in the order that you wold like to present them in. Perfect for a business or educational portfolio which displays a range of different content and media. Adding video and Flash content is easier than ever and allows you to bring your documents to life with video playing inside your PDF portfolios.

Sending your PDF documents just got a lot easier with the advent of the new Adobe Service called Adobe SendNow Online. Adobe SendNow Online. is now integrated within Adobe Acrobat X and can be accessed from the Share tab. Adobe SendNow Online, as you can tell from the name, stores your files in the cloud and provides a link to your PDF that you can email to your recipients right within Adobe Acrobat X. If you have ever had the problem of sharing large PDF files via email, then you will really like how Adobe handles this new feature. Simply enter the recipients email address and they will receive a link to download the file. It is really that simple and you can control how much time they have before the link expires and receive delivery receipts when it is downloaded. The integration of Adobe SendNow Online with Adobe Acrobat X is really seamless and you will be asking yourself how did you ever live without it.

Working with Adobe Acrobat as much as I do, I am extremely pleased with this upgrade and the thought that went into making this easier and more intuitive to use. Right out of the box you will find Adobe Acrobat X a pleasure to work with. With a little time you will find that Adobe Acrobat X is one of thiose must have applications that you will turn to for all of your creative needs.

PS: Look for another post on the Action Wizard and Forms coming soon

Sunday, November 28, 2010

Mobile Broadband Telkomsel di Linux Fedora Core 13 dan Huawei E220 3G

Awalnya cukup ragu akan ada driver Huawei E220 di linux fedora core 13, namun setelah mampir dan sedikit mencuri ilmu di gramedia (tanpa membeli bukunya), ternyata ada caranya..

mungkin dengan gambar gambar berikut ini dapat menggambarkan bagaimana kita dapat melakukan koneksi Mobile Broadband Telkomsel di Linux Fedora Core 13. Internetan dengan modem 3G di Linux sama saja dengan di Windows, hanya saja kita tidak perlu melakukan instalasi modem disini.



Mobile Broadband Telkomsel di Linux Fedora Core 13 dan Huawei E220 3G

Mobile Broadband Telkomsel di Linux Fedora Core 13 dan Huawei E220 3G

Mobile Broadband Telkomsel di Linux Fedora Core 13 dan Huawei E220 3G


Mobile Broadband Telkomsel di Linux Fedora Core 13 dan Huawei E220 3G

Mobile Broadband Telkomsel di Linux Fedora Core 13 dan Huawei E220 3G

Saturday, November 27, 2010

Panther: Extending extents / Estendendo os extents

This article is written in English and Portuguese
Este artigo está escrito em Inglês e Português

English version:

Back to Panther... Although I'm not in the video on the right, I do love Informix. That doesn't mean I ignore some issues it has (or had in this particular case). One thing that always worries an Informix DBA is the number of extents in his tables. Why? Because it used to have a maximum amount, and because that maximum was pretty low (if compared with other databases). But what is an extent? In short an extent is a sequence of contiguous pages (or blocks) that belong to a specific table or table partition. A partition (a table has one or more partitions) has one or more extents.
Before I go on, and to give you some comparison I'd like to tell you about some feedback I had over the years from a DBA (mostly Oracle, but who also managed an Informix instance):
  • A few years ago he spent lots of time running processes to reduce the number of extents in a competitor database that had reach an incredible number of extents (around hundreds of thousands). This was caused by real large tables and real badly defined storage allocation
  • Recently I informed the same customer that Informix was eliminating the extent limits and the same guy told me that he was afraid that it could lead to situations as above. He added, and I quote, "I've always admired the way Informix deals with extents"
So, if a customer DBA is telling that he admires the way we used to handle extents, and he's afraid of this latest change, why am I complaining about the past? As in many other situations, things aren't exactly black and white... Let's see what Informix have done well since ever:

  1. After 16 allocations of new extents Informix automatically doubles the size of the next extent for the table. This decreases the number of times it will try to allocate a new extent. So, using only this rule (which is not correct as we shall see) if you create a table with a next size of 16K, you would reach 4GB with around 225 extents.
  2. If Informix can allocate a new extent contiguous to an already existing one (from the same table of course) than it will not create a new one, but instead it will extend the one that already exists (so it does not increase the number of extents). This is one reason why rule number one may not be seen in practice. In other words, it's more than probable that you can reach 4GB with less than 225 extents.
  3. In version 11.50 if I'm correct, a fix was implemented to prevent excessive extent doubling (rule 1). If the next extent size is X and the dbspace only has a maximum of Y (Y < X) informix will allocate Y and will not raise any error.
    If this happens many times, we could end up having a number of allocated pages relatively small, but a next extent size too big. There's a real problem in this: If in these circumstances we create another chunk in the same dbspace, and after that our table requires another extent, the engine could reserve a large part of the new (and possibly still empty) chunk to our table. This can be much more than the size already allocated to the table. To avoid this, extent doubling will only happen when there is a reasonable relation between the new calculated next extent size and the space effectively allocated to the table.
  4. Extent description in Informix have never been stored in the database catalog. This leads to simpler and efficient space management. Compared to other databases that used to do the management in the catalog, they tend to hit issues in the SQL layer and at the same time these were slower. One of our competitors changed that in their later versions, and DBAs have seen improvement with that (but they had to convert). Informix always worked the better way...
So, these are the good points. Again, why was I complaining? Simply because although Informix has done a pretty good job in preventing the number of extents to grow too much, we had a very low limit for the number of extents. In platforms with a system page size of 2K this was around 220-240 extents (max), and for 4K platforms is was around the double of that (440-480). With version 10 we started to be able to have greater page sizes, and that increases the maximum number of extents per partition.
Why didn't we have a fix limit and why was it different in several platforms? In order to explain that we must dive a bit deeper in the structure of a dbspace and tables. Each partition in Informix has a partition header. Each partition header is stored in exactly one Informix page. There is a special partition in every dbspace (tablespace tablespace) that holds every partition headers from that dbspace. This special partition starts in a specific page but then, it can contain more than one extent.
Also important to understand this is the notion of slot. Most Informix pages contain several slots. For a data page, a slot contains a row (in the simplest cases). A partition header is a page that contains 5 slots:
  1. Slot 1
    This contains the partition structure (things like creation date, partition flags, maximum row size, number of special columns - VARCHAR and BLOB -, number of keys - if it's an index or has index pages -, number of extents and a lot of other stuff. If you want to see all the details check the sysptnhdr table in $INFORMIXDIR/etc/sysmaster.sql. It's basically an SQL interface for the partition headers in the instance.
    In version 11.50 this slot should occupy 100 bytes. Previous versions can have less (no serial 8, and bigserial)
  2. Slot 2
    Contains the database name, the partition owner, the table name and the NLS collation sequence
  3. Slot 3
    Contains details about the special columns. If there are no special columns this slot will be empty
  4. Slot 4
    Contains the description for each key (if it's an index or a mix). Starting with version 9.40, by default the indexes are stored in their own partitions. This was not the case in previous versions. A single partition could contain index pages interleaved with data pages.
    Currently, by default, a partition used for data should not have any key, so this slot will be empty
  5. Slot 5
    Finally, this is the slot that contains the list of extents.
Now we know the list of extents must be stored in the partition header. And the partition header has 5 slots, and the size of first four may vary. This means that the free space for slot 5 (extent list) is variable. These are the reasons why we had a limit and why that limit was not fixed. It would vary with the table structure for example. And naturally it would vary with the page size.
A table that reached it's maximum number of extents was a very real and serious problem in Informix. If you reach the table limit for number of extents and all your table's data pages are full, the engine would need to allocate one more extent in order to complete new INSERTs. But for that it would require some free space in the partition header. If there was no space left, any INSERT would fail with error -136:

-136 ISAM error: no more extents.

After hitting this nasty situation there were several ways to solve it, but all of them would need temporary table unavailability, which in our days is rare... We tend to use 24x7 systems. Even systems that have a maintenance window would suffer with this, because most of the time the problem was noticed during "regular" hours...

So, I've been talking in the past... This used to be a problem. Why isn't it a problem anymore? Because Panther (v11.7) introduced two great features:
  1. The first one is that it is able to automatically extend the partition header when slot 5 (the extent list) becomes full. When this happens it will allocate a new page for the partition header that will be used for the extent list. So you should not see error -136 caused by reaching the extent limit. At first you may think like my customer DBA: "wow! Isn't that dangerous? Will I get tables/partitions with tens of thousands of extents?". The answer is simple. You won't get that high number of extents because all the nice features that were always there (automatic extent concatenation, extent doubling...) are still there. This will just avoid the critical situation where the use of the table would become impossible (new INSERTs). And naturally it doesn't mean that you should not care about the number of extents. For performance reasons it's better to keep them low
  2. The second great feature is an online table defragmenter. They can grow forever, but that's not good. Once you notice you have a table with too many extents you can ask the engine to defragment it. I will not dig into this simply because someone else already did it. I recommend you check the recent DeveloperWorks article entitled "Understand the Informix Server V11.7 defragmenter"

Versão Portuguesa:

De volta à Panther... Apesar de não estar no vídeo à direita, eu adoro o Informix. Isso não significa que ignore alguns problemas que ele tem (ou tinha neste caso particular). Uma coisa que preocupa qualquer DBA Informix é o número de extents das suas tabelas. Porquê? Porque esse número tinha um máximo, e porque esse máximo era bastante baixo (se comparado com outras bases de dados). Mas o que é um extent? De forma simples, um extent é uma sequência contígua de páginas (ou blocos) que pertencem a uma tabela ou partição de tabela. Uma partição (uma tabela tem uma ou mais partições) tem um ou mais extents.
Antes de continuar, e para estabelecer uma comparação, gostaria de transmitir algum feedback que ao longo de anos tive de um DBA (essencialmente Oracle, mas também geria uma instância Informix):

  • Há alguns anos atrás passou bastante tempo a executar processos para reduzir o número de extents de uma base de dados concorrente do Informix. Essa base de dados tinha tabelas que atingiram um número incrível de extents (na casa das centenas de milhar). Isto foi causado por tabelas verdadeiramente grandes e cláusulas de alocação de espaço realmente mal definidas
  • Recentemente informei esse mesmo cliente que o Informix ia eliminar o limite de extents, e a mesma pessoa disse-me que tinha receio que isso pudesse levar a situações como a de cima. Ele acrescentou, e cito: "Se há coisa que sempre admirei foi a maneira como o Informix gere os extents".
Assim sendo, se um DBA de um cliente diz que admira a maneira como geríamos os extents e ele próprio receia a eliminação de limites, porque é que eu me queixo do passado? Como em muitas outras situações, as coisas não são bem a preto e branco... Vejamos o que o Informix sempre fez bem:

  1. Após cada 16 novos extents adicionados, o Informix automaticamente duplica o tamanho do próximo extent da tabela. Isto diminui o número de vezes que tenta reservar um novo extent. Usando apenas esta regra (o que não é correcto como veremos a seguir), se criar uma tabela com o extent mínimo (16KB), a tabela pode crescer até aos 4GB com cerca de 225 extents.
  2. Se o Informix conseguir reservar um novo extent que seja contíguo a um que já esteja alocado à mesma tabela, então em vez de criar um novo, vai alargar o já existente (portanto não aumenta o número de extents). Esta é a razão porque a regra anterior pode não ser verificada na práctica. Por outras palavaras é mais que provável que consiga atingir os 4GB com menos de 225 extents.
  3. Salvo algum erro, na versão 11.50 foi introduzida uma melhoria para prevenir a duplicação excessiva do tamanho do próximo extent (regra 1). Se o tamanho do próximo extent for X, mas o dbspace só tiver um máximo de Y espaço livre contíguo (Y < X) o Informix vai criá-lo com o tamanho Y e nem se queixará de nada. Se isto acontecer muitas vezes, podemos acabar por ter um número de páginas efectivas de uma tabela ou partição relativamente pequeno e um tamanho para o próximo extent muito grande. Existe um problema real nisto: Se nessas cirunstâncias for criado um novo chunk nesse dbspace, e a tabela precisar de novo extent, pode acontecer que o motor reserve grande parte, ou mesmo a totalidade do novo chunk para a tabela (possivelmente muito mais que o tamanho já reservado até então). Para evitar isto, a duplicação do tamanho do próximo extent só acontece quando o novo tamanho tem uma relação razoável com o espaço reservado até então. Caso contrário o tamanho do próximo extent a alocar não é duplicado.
  4. A informação dos extents em Informix nunca foi guardada nas tabelas de catálogo. Isto faz com que a sua gestão seja mais simples e eficiente. Comparada com outras bases de dados que faziam a gestão no catálogo, estas tendiam a encontrar problemas e constrangimentos próprios da camada de SQL, e ao mesmo tempo eram mais lentas. Um dos concorrentes mudou isto há umas versões atrás e os seus utilizadores viram benefícios bem notórios (mas tiveram de converter). O Informix sempre trabalhou da melhor forma...
Estes são os pontos positivos. Mais uma vez, porque é que me estava a queixar? Simplesmente porque apesar de o Informix sempre ter feito um trabalho extraordinário na prevenção contra um elevado número de extents, nós tinhamos um limite, e era muito baixo. Em plataformas com um tamanho de página de sistema de 2KB este limite rondava os 220-240 extents, e em plataformas de 4KB o limite era cerca do dobro (440-480). Com a versão 10 pudemos passar a ter páginas maiores, e isso aumenta o limite.
Porque é que o limite não é fixo, e porque é diferente consoante a plataforma? Para explicar isto temos de nos debruçar de forma mais detalhada na estrutura física de um dbspace e tabela. Cada partição em Informix tem um cabeçalho. Cada cabeçalho de partição é guardado numa página Informix. Existe uma partição especial em cada dbspace (designada habitualmente por tablespace tablespace) que guarda todos os cabeçalhos das partições criadas nesse dbspace. Esta partição especial começa numa página específica do primeiro chunk do dbspace, mas pode ter mais que um extent.
Igualmente importante para compreender isto é a noção de slot. A maioria das páginas Informix estão divididas em slots. Para uma página de dados um slot contém uma linha de dados da tabela (caso mais simples). Um cabeçalho de partição é uma página que contém cinco slots:

  1. Slot 1
    Este contém a estrutura da partição (coisas como a data de criação, flags, tamanho máximo de uma linha, numéro de colunas ditas especiais - VARCHAR e BLOBs -, número de chaves - se for um indíce ou tiver páginas de indíce -, número de extents e uma série de outros detalhes. Se tiver curiosidade em saber o que lá está guardado consulte a tabela sysptnhdr na base de dados sysmaster (ou o ficheiro $INFORMIXDIR/etc/sysmaster.sql). Basicamente esta tabela é um interface SQL sobre todos os cabeçalhos de partição da instância Informix.
    Na versão 11.50 este slot ocupa 100 bytes. Versões anteriores podem ocupar menos (ausência do serial8 e bigserial)
  2. Slot 2
    Contém o nome da base de dados, dono da partição, nome da tabela e a NLS collation sequence
  3. Slot 3
    Contém detalhes sobre todas as colunas especiais. Se não existirem colunas especiais (VARCHAR e BLOB) este slot estará vazio. Se existirem, o tamanho ocupado dependerá da estrutura da tabela.
  4. Slot 4
    Contém a descrição de cada chave (se for um índice ou um mix). Desde a versão 9.40, por omissão os indíces são guardados em partição à parte. Isto não era assim em versões anteriores. Uma partição podia conter páginas de indíces e de dados.
    Actualmente, por omissão, uma partição usada para dados não deve ter nenhuma chave, e assim este slot deve estar vazio
  5. Slot 5
    Finalmente, este é o slot que contém a lista dos extents.

Agora sabemos que a lista de estents tem de ser guardada no cabeçalho da partição. E este contém cinco slots sendo que o tamanho dos primeiros quatro varia. Isto implica que o espaço livre para o slot cinco (a lista de extents) é variável. Estas são as razões porque tinhamos um limite e porque esse limite era variável. Variava por exemplo com a estrutura da tabela. E naturalmente variava com o tamanho da página.
Uma tabela que atingisse o número máximo de extents tornava-se num problema sério em Informix. Quando tal acontece, se todas as páginas de dados estiverem cheias, o motor terá de reservar um novo extent para completar novos INSERTs. Mas para isso necessitaria de espaço livre no cabeçalho da partição. Portanto, não havendo aí espaço livre todos os INSERTs falhariam com o erro -136:

-136 ISAM error: no more extents.

Depois de batermos nesta situação havia várias formas de a resolver, mas todas elas necessitavam de indisponibilidade temporária da tabela, o que nos dias que correm é um bem raro... A tendência é usarmos sistemas 24x7. Mesmo sistemas que tenham janela de manutenção sofreriam com isto, porque na maioria das vezes o problema manifestava-se durante o horário normal ou produtivo...

Bom, mas tenho estado a falar no passado.... Isto costumava ser um problema. Porque é que já não o é? Porque a versão 11.7 (Panther) introduziu duas excelentes funcionalidades:

  1. A primeira é que a partir de agora é possível estender automaticamente o cabeçalho da partição quando o slot cinco enche. Nesta situação, uma nova página é reservada para o cabeçalho da partição e a lista de extents pode crescer. Portanto não deverá voltar a ver o erro -136 causado por atingir o limite de extents. À primeira vista pode ter a mesma reacção que o DBA do meu cliente. "Epa! Mas isso não é perigoso? Vou passar a ter tabelas/partições com dezenas de milhares de extents?". A resposta é simples. Não vai atingir esses números de extents porque todas as boas características que sempre existiram (junção automática de extents, duplicação de tamanho do próximo extent...) ainda estão presentes e funcionais. Isto apenas evitará a situação crítica em que o uso da tabela se tornava impossível (para novos INSERTs). E naturalmente isto não significa que passemos a ignorar o número de extents das nossas tabelas. Por questões de desempenho é melhor mantê-los baixos.
  2. A segunda grande funcionalidade é um desfragmentador online de tabelas ou partições. O número de extents pode crescer indefinidamente, mas isso não é bom. Assim que notar que tem uma partição com um número elevado de extents pode pedir ao motor que a desfragmente. Não vou aprofundar este tema, simplemente porque já foi feito. Recomendo que consulte um artigo recente do DeveloperWorks intitulado "Understand the Informix Server V11.7 defragmenter". Infelizmente o artigo só tem versão em Inglês

Computer 101: Don't be Afraid to Do it by Yourself

Yes that's correct do not be afraid to explore and do things on computer. Do not just be a passive user of that wonderful machine that has help you a lot in so many ways. Understanding the inner working of your computer is the at the first and foremost important. How do you start to learn what's under the hood of your machine. Well there's the big INTERNET where you can find all sort of information about almost anything this days. Other of information is your group friends maybe one of them is in the information technology world and he or she just might  be able to help you out. Now why do we need to blog about this, this is just to remind everyone that it is important to get to know your computer, what are it's inner working. Okay you ask, what the heck em i must need to know, well there' a whole of them. First have ever heard of the word PROCESSOR, Central Processing Unit or CPU, then there's the memory, hard disk, graphics card, web cam, printer and a whole lot more of other words that pertains to the inner working of your computer. If not and you'd been using a computer for more than half of your life. Then i suggest you get started to learn about them. How they work together so that you can enjoy the usefulness of your computer for a long time and what will you do if somethings go wrong with your machine.


CRT monitor

First use the Internet to get a good picture of this pieces of devices under the hood of your machine. Just the the word on the search bar of your preferred search engine then select the IMAGES option on your search engine and then click the button or just press the enter key of the computer to begin the search. Let's say you type the word CPU or Processor, then it should display what a CPU or processor look like. I'm so busy i don't have the time to do all this stuff. Hey there is no rush in learning. Take it one at a time. I'm sure somewhere in time you'll fine you free time and maybe you'll be able to begin the learning process. It doesn't have to be structured learning.

System Unit


 Make your learning fun so that you will be able to absorb it better and you'll be able to do it again in again until before you know it. You now now more compare last week or last month. Also it is cool to learn about this technical stuff. More people will look up to you for help in almost aspect of the computer. You'll be surprised on what they are expecting that you should know.The important thing is to take the first step to learning but not at all at once but one at a time. Focused on one topic and learn everything you can about it. Another is do not be afraid to ask those who know this things. Yea the tech guy in your company or your neighbor. They just waiting for you to ask and your be surprised to the answer they give you. No sale's talk just pure information and a few tips and trick if they know your interested in what your asking about.


Wednesday, November 24, 2010

Computer 101: Using the Windows Back-up Tool - 2

Greetings, to continue on this back-up thing; let’s review what we have talked about, first there’s your checklist of item on what do need before you start the actual back-up, second the option whether what to use in the actual back-up which is whether to use a third party software or use the windows native back-up system. Again i must state that this information is applicable only to Windows user up to the Vista version. What only up to Vista, what happen if i have a windows 7 version on my laptop or desktop.  Well in windows 7 there is a slight difference compared with the old windows back-up user interface. Take a look at the image below. They the same user interface right.

Now after clicking on the back-up now button, this is where the new user interface suddenly shows itself. Remember only the user interface that is different from the rest of the other previous windows system the function is still the same. Now if you press the Back-up Now button you will the picture below.
 SMBWBE58H2ZT




Yes folks the clever guy back at the windows HQ has change the old user interface if your familiar with the old one. The picture below present a more challenging option than the old ones atleast for most people. Now where do we go from here? Which option should i choose in order to start the back-up process. Dont panic its right therein front of you, see the text that said SETUP BACKUP, click that and the next screen will appear to guide on what to do next.





Now the picture aboved appeared after you click thesetup backup this interface will for a few second and after that the next picture will appear.




Tada, what does this mean? Well this will bring us back to the requirements we taled about. Notice that on the picture there several items worth investigating. First there is a question asking SELECT WHERE YOU WANT TO SAVE YOUR BAKC-UP then the second lines said WE RECOMMEND THAT YOU SAVE YOUR BACK-UP ON AN EXTERNAL DRIVE. What does this first two instructions and question means. Let go back remember i mentioned that we have several choices of what back-up device we need to use. One of those device is the External drive. But i dont see any external drive on the picture. This is becuase the external drive it is not yet connected to the laptop or desktop. I will connect my external drive to my computer show you what will be added to the picture below if your preffered device for back-up is connected before you start the back-up process.




Now as you can see on the picture above, it is highligted a red box a nes item is added to the choices where only the DVD RW drive is present now after connecting the external drive and pressing the REFRESH button the other options now appeared on the interface. Also it is good to know that the people at microsoft out a guidlines for choosing the backup destination feature. If you want to explore it just click the link below to see the guidlines. Now i mentioned before that it is important for you to connect the backup device or media your going to use because the back tool will look for it. And the tool will not allow you to use your hard drive as a backup destination. You need a separate device for your backup.

<!--b51fccde302343cf801274844008e320-->

UDRs: In transaction? / Em transacção?

This article is written in English and Portuguese
Este artigo está escrito em Inglês e Português

English version:

Introduction

I just checked... This will be post 100!!!... I've never been so active in the blog... We have Panther (full of features that I still haven't covered), I did some work with OAT and tasks that I want to share, and besides that I've been trying some new things... Yes... Although I've been working with Informix for nearly 20 years (it's scaring to say this but it's true...) there are aspects that I usually don't work with. I'd say the one I'm going to look into today is not used by the vast majority of the users. And that's a shame because:
  1. It can solve problems that we aren't able to solve in any other way
  2. If it was more used, it would be improved faster
Also, many people think that this is what marked the decline of the Informix company. You probably already figured out that I'm talking about extensibility. To recall a little bit of history, in 1995, Informix had the DSA architecture in version 7. And it acquired the Illustra company, founded by Michael Stonebraker and others. Mr. Stonebraker already had a long history of innovation (which he kept improving up to today) and he stayed with Informix for some years. All the technology around Datablades and extensibility in Informix comes from there... Informix critics say that the company got so absorbed in the extensibility features (that it believed would be the "next wave") that it loosed the market focus. Truth is that the extensibility never became a mainstream feature neither in Informix or in other databases, and all of them followed Informix launch of Universal Server (1996): Oracle, IBM DB2 etc.

But, this article will not focus on the whole extensibility concept. It would be impossible and tedious to try to cover it in one blog article. Instead I'll introduce one of it's aspects: User Defined Routines (UDRs), and in particular routines written using the C language.

There is a manual about UDRs, and I truly recommend that you read it. But here I'll follow another approach: We'll start with a very simple problem that without C UDRs would be impossible to solve, define a solution for it, and go all the way to implement it and use it with an example.


The problem

Have you ever faced a situation where you're writing a stored procedure in SPL, and you want to put some part of it inside a transaction, but you're afraid that the calling code is already in a transaction?
You could workaround this by initiating the transaction and catching the error (already in transaction) with an ON EXCEPTION block.
But this may have other implications (ON EXCEPTION blocks are tricky when the procedure is called from a trigger). So it would be nice to check if the session is already in a transaction. A natural way to do that would be a call to DBINFO(...), but unfortunately current versions (up to 11.7.xC1) don't allow that. Meaning there is no DBINFO() parameter that makes it return that information.


Solution search

One important part of Informix extensibility is the so called Datablade API. It's a set of programmable interfaces that we can use inside Datablades code and also inside C UDRs. The fine infocenter has a reference manual for the Datablade API functions. A quick search there for "transaction" makes a specific function come up: mi_transaction_state()
The documentation states that when calling it (no parameters needed) it will return an mi_integer (let's assume integer for now) type with one of these values:
  • MI_NO_XACT
    meaning we don't have a transaction open
  • MI_IMPLICIT_XACT
    meaning we have an implicit transaction open (for example if we're connected to an ANSI mode database)
  • MI_EXPLICIT_XACT
    meaning we have an explicit transaction open
This is all we need conceptually.... Now we need to transform ideas into runnable code!

Starting the code

In order to implement a C UDR function we should proceed through several steps:
  1. Create the C code skeleton
  2. Create the C code function using the Datablade API
  3. Create a makefile that has all the needed instructions to generate the executable code in a format the engine can use
  4. Compile the code
  5. Use SQL to define the new function, telling the engine where it can find the function and the interface to call it, as well as the language and other function attributes
  6. Test it!



Create the C code skeleton

Informix provides a tool called DataBlade Developers Kit (DBDK) which includes several components: Blade Manager, Blade Pack and Bladesmith. Blade Manager allows us to register the datablades against the databases, the Blade Pack does the "packaging" of all the Datablades files (executable libraries, documentation files, SQL files etc.) that make up a datablade. Finally Bladesmith helps us to create the various components and source code files. It's a development tool that only runs on Windows but can also be used to prepare files for Unix/Linux. For complex projects it may be a good idea to use Bladesmith, but for this very simple example I'll do it by hand. Also note I'm just creating a C UDR. These tools are intended to deal with much more complex projects. A Datablade can include new datatypes, several functions etc.
So, for our example I took a peek at the recent Informix Developer's Handbook to copy the examples.

Having looked at the examples above, it was easy to create the C code:


/*
This simple function returns an integer to the calling SQL code with the following meaning:
0 - We're not within a transaction
1 - We're inside an implicit transaction
2 - We're inside an explicit (BEGIN WORK...) transaction
-1 - Something unexpected happened!
*/

#include <milib.h>

mi_integer get_transaction_state_c( MI_FPARAM *fp)
{
mi_integer i,ret;
i=mi_transaction_state();
switch(i)
{
case MI_NO_XACT:
ret=0;
break;
case MI_IMPLICIT_XACT:
ret=1;
break;
case MI_EXPLICIT_XACT:
ret=2;
break;
default:
ret=-1;
}
return (ret);
}

I've put the above code in a C source file called get_transaction_state_c.c

Create the makefile

Again, for the makefile I copied some examples and came up with the following. Please consider this as an example only. I'm not an expert on makefile building and this is just a small project.


include $(INFORMIXDIR)/incl/dbdk/makeinc.linux

MI_INCL = $(INFORMIXDIR)/incl
CFLAGS = -DMI_SERVBUILD $(CC_PIC) -I$(MI_INCL)/public $(COPTS)
LINKFLAGS = $(SHLIBLFLAG) $(SYMFLAG)


all: get_transaction_state.so

clean:
rm -f get_transaction_state.so get_transaction_state_c.o


get_transaction_state_c.o: get_transaction_state_c.c
$(CC) $(CFLAGS) -o $@ -c $?

get_transaction_state.so: get_transaction_state_c.o
$(SHLIBLOD) $(LINKFLAGS) -o $@ $?


Note that this is a GNU Make makefile. The first line includes a makefile that IBM supplies with Informix. It basically contains variables or macro definitions. You should adapt the include directive to your system (the name of the makefile can vary with the platform) and make sure that the variables I use are also defined in your system base makefile.
After that I define some more variables and I create the makefile targets. I just want it to build the get_transaction_state.so dynamically loadable library and for that I'm including the object (get_transaction_state_c.o) generated from my source code (get_transaction_state_c.c). Pretty simple if you have basic knowledge about makefiles

Compile the code

Once we have the makefile we just need to run a simple command to make it compile:


cheetah@pacman.onlinedomus.net:informix-> make
cc -DMI_SERVBUILD -fpic -I/usr/informix/srvr1150uc7/incl/public -g -o get_transaction_state_c.o -c get_transaction_state_c.c
gcc -shared -Bsymbolic -o get_transaction_state.so get_transaction_state_c.o
cheetah@pacman.onlinedomus.net:informix->
The two commands run are the translation of the macros/variables defined in the makefile(s) and they simply compile the source code (1st command) and then generate the dynamic loadable library. If all goes well (as it naturally happened in the output above), we'll have a library on this location, ready for usage by Informix:


cheetah@pacman.onlinedomus.net:informix-> ls -lia *.so
267913 -rwxrwxr-x 1 informix informix 5639 Nov 23 22:06 get_transaction_state.so
cheetah@pacman.onlinedomus.net:informix-> file *.so
get_transaction_state.so: ELF 32-bit LSB shared object, Intel 80386, version 1 (GNU/Linux), dynamically linked, not stripped
cheetah@pacman.onlinedomus.net:informix->

Use SQL to define the function

Now that we have executable code, in the form of a dynamic loadable library, we need to instruct Informix to use it. For that we will create a new function, telling the engine that it's implemented in C language and the location where it's stored. For that I created a simple SQL file:


cheetah@pacman.onlinedomus.net:informix-> ls *.sql
get_transaction_state_c.sql
cheetah@pacman.onlinedomus.net:informix-> cat get_transaction_state_c.sql
DROP FUNCTION get_transaction_state_c;

CREATE FUNCTION get_transaction_state_c () RETURNING INTEGER
EXTERNAL NAME '/home/informix/udr_tests/get_transaction_state/get_transaction_state.so'
LANGUAGE C;
cheetah@pacman.onlinedomus.net:informix->


So, let's run it...:


cheetah@pacman.onlinedomus.net:informix-> dbaccess stores get_transaction_state_c.sql

Database selected.


674: Routine (get_transaction_state_c) can not be resolved.

111: ISAM error: no record found.
Error in line 1
Near character position 36

Routine created.


Database closed.

cheetah@pacman.onlinedomus.net:informix->


Note that the -674 error is expected, since my SQL includes a DROP FUNCTION. If I were using 11.7 (due to several tests I don't have it ready at this moment) I could have used the new syntax "DROP IF EXISTS...".

So, after this step I should have a function callable from the SQL interface with the name get_transaction_state_c(). It takes no arguments and returns an integer value.

Test it!

Now it's time to see it working. I've opened a session in stores database and did the following:
  1. Run the function. It returned "0", meaning no transaction was opened.
  2. Than I opened a transaction and run it again. It returned "2", meaning an explicit transaction was opened
  3. I closed the transaction and run the function by the third time. As expected it returned "0"
Here is the output:


cheetah@pacman.onlinedomus.net:informix-> dbaccess stores -

Database selected.

> EXECUTE FUNCTION get_transaction_state_c();


(expression)

0

1 row(s) retrieved.

> BEGIN WORK;

Started transaction.

> EXECUTE FUNCTION get_transaction_state_c();


(expression)

2

1 row(s) retrieved.

> ROLLBACK WORK;

Transaction rolled back.

> EXECUTE FUNCTION get_transaction_state_c();


(expression)

0

1 row(s) retrieved.

>

We haven't seen it returning "1". That happens when we're inside an implicit transaction. This situation can be seen if we use the function in an ANSI mode database. For that I'm going to use another database (stores_ansi), and naturally I need to create the function there (using the previous SQL statements). Then I repeat more or less the same steps and the result is interesting:


cheetah@pacman.onlinedomus.net:informix-> dbaccess stores_ansi -

Database selected.

> EXECUTE FUNCTION get_transaction_state_c();


(expression)

0

1 row(s) retrieved.

> SELECT COUNT(*) FROM systables;


(count(*))

83

1 row(s) retrieved.

> EXECUTE FUNCTION get_transaction_state_c();


(expression)

1

1 row(s) retrieved.

>
If you notice it, the first execution returns "0". Since I have not done any operations there is no transaction opened. But just after a simple SELECT, the return is "1", meaning an implicit transaction is opened. This has to do with the nature and behavior of ANSI mode databases.
If you use them and you intend to use this function you must take that into consideration. Or you could simply map the "1" and "2" output of the mi_transaction_state() function return into simply a "1". This would signal that a transaction is opened (omitting the distinction between implicit and explicit transactions).

Final considerations

Please keep in mind that this article serves more as a light introduction to the C language UDRs than to solve a real problem. If you need to know if you're already in transaction (inside a stored procedure for example) you can use this solution, but you could as well try to open a transaction and capture and deal with the error inside an ON EXCEPTION block.

Also note that if this is a real problem for your applications, even if you're inside an already opened transaction, you can make your procedure code work as a unit, by using the SAVEPOINT functionality introduced in 11.50. So, in simple pseudo-code it would be done like this:

  1. Call get_transaction_state_c()
  2. If we're inside a transaction then set TX="SVPOINT" and create a savepoint called "MYSVPOINT" and goto 4)
  3. If we're not inside a transaction than set TX="TX" and create one. Goto 4
  4. Run our procedure code
  5. If any error happens test TX variable. Else goto 8
  6. If TX=="TX" then ROLLBACK WORK. Return error
  7. Else, if TX=="SVPOINT" then ROLLBACK WORK TO SAVEPOINT 'MYSVPOINT'. Return error
  8. Return success
After this introduction, I hope to be able to write a few more articles related to this topic. The basic idea is that sometimes it's very easy to extend the functionality of Informix. And I feel that many customers don't take advantage of this.
Naturally, there are implications on writing C UDRs. The example above is terribly simple, and it will not harm the engine. But when you're writing code that will be run by the engine a lot of questions pop up.... Memory usage, memory leaks, security stability... But there are answers to this concerns. Hopefully some of them (problems and solutions) will be covered in future articles.


Versão Portuguesa:

Introdução

Acabei de verificar.... Este será o centésimo artigo!!! Nunca estive tão activo no blog... Temos a versão Panther (11.7) (cheia de funcionalidades sobre as quais ainda não escrevi), fiz algum trabalho com tarefas do OAT que quero partilhar, e para além disso tenho andado a testar coisas novas... Sim... Apesar de já trabalhar com Informix há perto de 20 anos (é assustador dizer isto, mas é verdade...) há áreas de funcionalidade com as quais não lido habitualmente. Diria que aquela sobre a qual vou debruçar-me hoje não é usada pela maioria dos utilizadores. E isso é uma pena porque:
  1. Permite resolver problemas que não têm outra solução
  2. Se fosse mais usada seria melhorada mais rapidamente
Adicionalmente, existe muita gente que pensa que isto foi o que marcou o declínio da empresa Informix. Possivelmente já percebeu que estou a falar da extensibilidade. Para relembrar um pouco de história, em 1995, a Informix tinha a arquitectura DSA (Dynamic Scalable Architecture) na versão 7. E adquiriu a empresa Illustra, fundada por Michael Stonebraker e outros. O senhor Stonebraker já tinha um longo passado de inovação (que prossegue ainda actualmente) e permaneceu na Informix durante alguns anos. Toda a tecnologia à volta dos datablades e extensibilidade teve aí a sua origem.... Os críticos da Informix dizem que a companhia ficou tão absorvida pelas funcionalidades de extensibilidade (que acreditava serem a próxima "vaga") que perdeu o foco do mercado. A verdade é que a extensibilidade nunca se tornou em algo generalizado nem no Informix nem em outras bases de dados, e todas elas seguiram o lançamento do Informix Universal Server (1996): Oracle, IBM DB2 etc.

Mas este artigo não irá focar todo o conceito de extensibilidade. Seria impossível e entediante tentar cobrir tudo isso num artigo de blog. Em vez disso vou apenas introduzir um dos seus aspectos: User Defined Routines (UDRs), e em particular rotinas escritas usando linguagem C.

Existe um manual que cobre os UDRs, e eu recomendo vivamente a sua leitura. Mas aqui seguirei outra abordagem: Começarei com um problema muito simples, que sem um UDR em C seria impossível de resolver, definirei uma solução para o mesmo, e prosseguirei até à implementação e utilização da solução com um exemplo.

O problema

Alguma vez esteve numa situação em que estivesse a escrever um procedimento em SPL, e quisesse colocar parte dele dentro de uma transacção, mas tivesse receio que o código que chama o procedimento já estivesse com uma transacção aberta?

Poderia contornar o problema iniciando uma transacção e apanhando o erro (already in transaction) com um bloco de ON EXCEPTION

Mas isto teria outras implicações (os blocos de ON EXCEPTION podem criar problemas se o procedimento for chamado de um trigger). Portanto seria bom poder verificar se a sessão já está no meio de uma transacção. Uma forma natural de o fazer seria recorrer à função DBINFO(...), mas infelizmente as versões actuais (até à 11.7.xC1) não permitem isso. Ou seja, não há nenhum parâmetro desta função que permita obter a informação que necessitamos.

Pesquisa da solução

Uma parte importante da extensibilidade no Informix é a chamada Datable API. É um conjunto de interfaces programáveis que podemos usar dentro de datablades e também dentro de UDRs em C. O infocenter tem um manual de referência das funções do Datablade API. Uma pesquisa rápida por "transaction" faz aparecer uma função: mi_transaction_state()

A documentação indica que quando a chamamos (não requer parâmetros) irá retornar um valor do tipo mi_integer (equivale a um inteiro) com um destes valores:
  • MI_NO_XACT
    significa que não temos uma transacção aberta
  • MI_IMPLICIT_XACT
    significa que temos uma transacção implícita aberta (por exemplo se estivermos conectados a uma base de dados em modo ANSI)
  • MI_EXPLICIT_XACT
    significa que temos uma transacção explícita aberta
Isto é tudo o que necessitamos conceptualmente.... Agora precisamos de transformar uma ideia em código executável!

Começando o código

Para implementarmos um UDR em C necessitamos de efectuar vários passos:
  1. Criar o esqueleto do código C
  2. Criar a função com código C usando o datablade API
  3. Criar um makefile que tenha todas as instruções necessárias para gerar o código executável num formato que possa ser usado pelo motor
  4. Compilar o código
  5. Usar SQL para definir uma nova função, indicando ao motor onde pode encontrar a função, o interface para a chamar bem como a linguagem usada e outros atributos da função
  6. Testar!

Criar o código em C

O Informix fornece uma ferramenta chamada DataBlade Developers Kit (DBDK) que incluí vários componentes: Blade Manager, Blade Pack e Bladesmith. O Blade Manager permite-nos registar datablades em bases de dados, o Blade Pack faz o "empacotamento" de todos os ficheiros de um datablade (bibliotecas executáveis, ficheiros de documentação, ficheiros SQL, etc.). Finalmente o Bladesmith ajuda-nos a criar vários componentes e código fonte. É uma ferramenta de desenvolvimento que apenas corre em Windows mas que pode ser usado para preparar ficheiros para Unix/Linux. Para projectos complexos será boa ideia usar o Bladesmith mas para este exemplo simples farei tudo à mão. Apenas estou a criar um UDR em C. Estas ferramentas destinam-se a lidar com projectos muito mais complexos. Um Datablade pode incluir novos tipos de dados, várias funções etc.
Assim, para o nosso exemplo dei uma espreitadela ao recente Informix Developer's Handbook para copiar alguns exemplos.

Depois de ver os exemplos referidos, foi fácil criar o código em C:
/*
This simple function returns an integer to the calling SQL code with the following meaning:
0 - We're not within a transaction
1 - We're inside an implicit transaction
2 - We're inside an explicit (BEGIN WORK...) transaction
-1 - Something unexpected happened!
*/

#include <milib.h>

mi_integer get_transaction_state_c( MI_FPARAM *fp)
{
mi_integer i,ret;
i=mi_transaction_state();
switch(i)
{
case MI_NO_XACT:
ret=0;
break;
case MI_IMPLICIT_XACT:
ret=1;
break;
case MI_EXPLICIT_XACT:
ret=2;
break;
default:
ret=-1;
}
return (ret);
}

Coloquei o código acima num ficheiro chamado get_transaction_state_c.c


Criar o makefile

Também para o makefile, limitei-me a copiar alguns exemplos e gerei o seguinte. Por favor considere isto apenas como um exemplo. Não sou especialista em construção de makefiles e isto é apenas um pequeno projecto.


include $(INFORMIXDIR)/incl/dbdk/makeinc.linux

MI_INCL = $(INFORMIXDIR)/incl
CFLAGS = -DMI_SERVBUILD $(CC_PIC) -I$(MI_INCL)/public $(COPTS)
LINKFLAGS = $(SHLIBLFLAG) $(SYMFLAG)


all: get_transaction_state.so

clean:
rm -f get_transaction_state.so get_transaction_state_c.o


get_transaction_state_c.o: get_transaction_state_c.c
$(CC) $(CFLAGS) -o $@ -c $?

get_transaction_state.so: get_transaction_state_c.o
$(SHLIBLOD) $(LINKFLAGS) -o $@ $?


Este makefile destina-se ao GNU Make. A primeira linha incluí um makefile fornecido pela IBM com o Informix. Este, basicamente, contém definições de variáveis e macros. Deve adaptar a directiva include ao seu sistema (o nome do makefile pode variar com a plataforma) e garanta que as variáveis que usei estão definidas no makefile base do seu sistema.
Depois disso defini mais algumas variáveis e criei os targets. Apenas quero que gere a biblioteca dinâmica get_transaction_state.so e para isso estou a incluir o objecto (get_transaction_state_c.o) gerado a partir do meu código fonte (get_transaction_state_c.c). Bastante simples se tiver conhecimentos básicos de makefiles.


Compilar o código

Depois de termos o makefile apenas necessitamos de um comando simples para executar a compilação:


cheetah@pacman.onlinedomus.net:informix-> make
cc -DMI_SERVBUILD -fpic -I/usr/informix/srvr1150uc7/incl/public -g -o get_transaction_state_c.o -c get_transaction_state_c.c
gcc -shared -Bsymbolic -o get_transaction_state.so get_transaction_state_c.o
cheetah@pacman.onlinedomus.net:informix->
Os dois comandos executados são a tradução dos macros/variáveis definidos no(s) makefiles(s), e apenas compilam o código fonte (primeiro comando) e depois geram a biblioteca dinâmica. Se tudo correr bem (como naturalmente aconteceu no output acima), teremos a biblioteca nesta localização, pronta a ser usada pelo Informix:
cheetah@pacman.onlinedomus.net:informix-> ls -lia *.so
267913 -rwxrwxr-x 1 informix informix 5639 Nov 23 22:06 get_transaction_state.so
cheetah@pacman.onlinedomus.net:informix-> file *.so
get_transaction_state.so: ELF 32-bit LSB shared object, Intel 80386, version 1 (GNU/Linux), dynamically linked, not stripped
cheetah@pacman.onlinedomus.net:informix->

Usar SQL para definir a função

Agora que temos o código executável, na forma de uma biblioteca dinâmica, precisamos de instruir o Informix para usá-la. Para isso vamos criar uma nova função, dizendo ao motor que está implementada em linguagem C e qual a localização onde está guardada. Faremos isso com um script SQL simples:

cheetah@pacman.onlinedomus.net:informix-> ls *.sql
get_transaction_state_c.sql
cheetah@pacman.onlinedomus.net:informix-> cat get_transaction_state_c.sql
DROP FUNCTION get_transaction_state_c;

CREATE FUNCTION get_transaction_state_c () RETURNING INTEGER
EXTERNAL NAME '/home/informix/udr_tests/get_transaction_state/get_transaction_state.so'
LANGUAGE C;
cheetah@pacman.onlinedomus.net:informix->


Vamos executá-lo...:


cheetah@pacman.onlinedomus.net:informix-> dbaccess stores get_transaction_state_c.sql

Database selected.


674: Routine (get_transaction_state_c) can not be resolved.

111: ISAM error: no record found.
Error in line 1
Near character position 36

Routine created.


Database closed.

cheetah@pacman.onlinedomus.net:informix->


Repare que o erro -674 é expectável, dado que o meu SQL incluí a instrução DROP FUNCTION (e ela ainda não existe). Se estivesse a usar a versão 11.7 (devido a vários testes não a tenho operacional agora) podia ter usado a nova sintaxe "DROP IF EXISTS".

Portanto depois deste passo, devo ter uma função que pode ser chamada pela interface SQL com o nome get_transaction_state_c(). Não recebe argumentos e retorna um valor inteiro.


Testar!

Agora é tempo de a ver a trabalhar. Abri uma sessão na base de dados stores e fiz o seguinte:
  1. Corri a função. Retornou "0", o que significa que não havia transacção aberta
  2. Depois abri uma transacção e executei a função novamente. Retornou "2", o que significa que uma transacção explícita estava aberta
  3. Fechei a transacção e corri a função pela terceira vez. Como esperado retornou "0"
Aqui está o output:


cheetah@pacman.onlinedomus.net:informix-> dbaccess stores -

Database selected.

> EXECUTE FUNCTION get_transaction_state_c();


(expression)

0

1 row(s) retrieved.

> BEGIN WORK;

Started transaction.

> EXECUTE FUNCTION get_transaction_state_c();


(expression)

2

1 row(s) retrieved.

> ROLLBACK WORK;

Transaction rolled back.

> EXECUTE FUNCTION get_transaction_state_c();


(expression)

0

1 row(s) retrieved.

>

Não vimos o retorno "1". Isso acontece quando estamos dentro de uma transacção implícita. Esta situação pode ser vista se a função estiver a ser executada numa base de dados em modo ANSI. Para isso vou usar uma outra base de dados (stores_ansi), e naturalmente necessito de criar a função aqui (usando as instruções SQL anteriores). Depois repito mais ou menos os mesmos passos e o resultado é interessante:

cheetah@pacman.onlinedomus.net:informix-> dbaccess stores_ansi -

Database selected.

> EXECUTE FUNCTION get_transaction_state_c();


(expression)

0

1 row(s) retrieved.

> SELECT COUNT(*) FROM systables;


(count(*))

83

1 row(s) retrieved.

> EXECUTE FUNCTION get_transaction_state_c();


(expression)

1

1 row(s) retrieved.

>
Se reparar, a primeira execução retornou "0". Como ainda não tinha efectuado nenhuma operação não havia transacção aberta. Mas logo a seguir a um simples SELECT já retorna "1", o que significa que uma transacção implícita estava aberta. Isto prende-se com a natureza e comportamento das bases de dados em modo ANSI.
Se as usa e pretende usar esta função terá de ter isto em consideração. Ou poderá simplesmente mapear o retorno "1" e "2" da função mi_transaction_state() no retorno "1" da função criada por si. Isto sinalizaria que uma transacção estava aberta (omitindo a distinção entre transacção implícita e explícita).

Considerações finais

Relembro que este artigo serve mais como introdução aos UDRs na linguagem C que propriamente para resolver um problema real.
Se necessitar de saber se já está numa transacção (dentro de uma stored procedure por exemplo) pode usar esta solução, mas também podia tentar abrir uma transacção e capturar e gerir o erro dentro de um bloco ON EXCEPTION.

Chamo a atenção também para que se isto é um problema real das suas aplicações, mesmo que esteja já dentro de uma transacção, pode fazer com que o código da sua stored procedure trabalhe como uma unidade, usando a funcionalidade dos SAVEPOINTs, introduzida na versão 11.50. Em pseudo-código seria feito assim:

  1. Chamar a get_transaction_state_c()
  2. Se estamos dentro de uma transacção então estabelecer TX="SVPOINT" e criar um savepoint chamado "MYSVPOINT". Ir para 4)
  3. Se não estamos dentro de uma transacção então estabelecer TX="TX" e criar uma. Ir para 4)
  4. Correr o código da procedure
  5. Se ocorrer algum erro testat a variável TX. Ir para 8)
  6. Se TX =="TX" então ROLLBACK WORK. Retornar erro.
  7. Senão, SE TX=="SVPOINT" então ROLLBACK WORK TO SAVEPOINT 'MYSVPOINT'. Retornar erro
  8. Retornar sucesso
Depois desta introdução espero conseguir escrever mais alguns artigos relacionados com este tópico. A ideia base é que algumas vezes é muito fácil estender a funcionalidade base do Informix. E sinto que muitos clientes não tiram partido disto.
Naturalmente há implicações em escrever UDRs em C. O exemplo acima é terrivelmente simples, e não trará prejuízo ao motor. Mas quando escrevemos código que será executado pelo motor surgem uma série de questões... Utilização de memória, fugas de memória, segurança, estabilidade.... Mas existem respostas para estas preocupações. Espero que alguns (problema e soluções) sejam cobertos em artigos futuros.

Saturday, November 20, 2010

The Power of the PLN

It started with this blog post. A teacher commented in his blog that he was trying to create a new course, and he asked for help. He created a Google doc (the address is shared in his blog post) and asked for ideas. Visit the document and take a look at how his internet friends, his PLN, responded.

Is this powerful or what?

Mind Mapping in the Cloud with Comapping

As I try to move more and more of my work to the cloud I keep going back to one application time and time again and that is Comapping. Comapping is a simple and easy to use mind mapping application that runs within the browser and gives me access to my maps from anywhere that I have access to the web. I should note up front, that Comapping has really become a great way for me to share information when I am presenting or teaching my graduate courses. It is easy to place web links and attach documents to the map which then gives my students access to the information that I need to provide them.

In many ways my Comapping maps can be thought up as a way for me to transport information that I need to share with others. One of the key features of Comapping is the ability to publish the information in such a way that it is easy to re-purpose it on a wiki, Blog, Google Site, or within Moodle. I have developed a number of Comapping maps for my graduate classes that I teach which is ideal since Comapping provides me with the embed code to publish it right within Moodle. This feature alone is worth its weight in gold. Now my students have access to web resources that are just a click away or they can download PDF files that I have attached to the map. If you haven't tried Comapping I urge you to take a look at it and see how it can help you manage the information more efficiently.

Here is an example of a Comapping map that I have used for some of my presentations:


Post weekly (weekly)


Posted from Diigo. The rest of my favorite links are here.

Qwiki- New Informational Video Mashup

I recently came across this new informational  mashup service that is in beta called Qwiki which automatically creates a video complete with audio on a topic of your choice. The service is very engaging and I thought would be an ideal way for students to get an overview on a topic by watching the Qwiki video. There are invitations available for the service while it is still in beta - but it is very engaging and has lots of potential for the work we do. So if you have a chance check it out and let me know what you think.

Thursday, November 18, 2010

Free PaperShow for Teachers Demo

Join me on Monday November 29th at 10 am EST for a free demonstration of PaperShow for Teachers.Find out how this innovative presentation tool can be used in the classroom, boardroom, or for webinars. Click here to sign up.PaperShow for Teachers is a cost effective tool to spice up lessons, presentations and webinars. Learn how you can use PaperShow for Teachers for brainstorming sessions or for capturing ideas in the classroom. Once you have captured the information you can easily share it as a PDF file. PaperShow for Teachers also lets you annotate images or your PowerPoint slides to make for richer and more engaging presentations. So sign up for this free webinar and learn about the power of this cost effect presentation tool. Click here to sign up.  Once you sign up you will receive a link for the webinar. Hope to see you there! Brian

Wednesday, November 17, 2010

Computer 101: Using the Windows Back-Up Tool

Now to continue after clicking on the back-up now the picture below will appear. But before proceeding to back-up your file make sure that the back-up destination drive is currently attached to your computer. This will make it easier for you and your computer to determine were to put your files once you started the back-up process.After the back-up now button wait for a while for the welcome page to load.

Back Up Tools Welcome Page
Notice on the welcome page that a check mark has been put on the wizard mode, this means that if press the YES button the back up tool will start in wizard mode. Wizard mode is the easiest way and faster way to create your back-up. It is for beginners like us to used and to understand. While the advance mode is for the technical guy who needs to fine tune the options before proceeding with the back-up. Its is recommended to used wizard mode if you are new to kind of stuff. Okay after clicking the NEXT button the next picture below will appear.

Back or Restore Wizard

Notice there are two options on this picture. The Back files and settings and the Restore files and settings. Also note that the default is set on the first option which the Back-up files and settings. You do not need to change the setting for this one just press the NEXT button to proceed to the next instruction. Which is the what to back-up options. Please see picture below for detailed information.


What to Back-up Option

Int this options we have several to choose from. Now how are you going to choose which options is the right option for you. First determined where all you files are located. Check and double check everything so that when you select the correct option all you important files and documents will be included in the back-up. If you are the type of person where you only save all your files in the My document folder of your computer then i suggest choosing the the first option which the My Documents and Setting. Now after selecting this options press the next button to go to the next part of the back-up process.


Back information

Now on this picture you can see that there several options as well, namely the select the back-up type which is disabled. It is in grayed colored and you can click this one. The other options is the one your going to configure.The choose a place to save your back-up and the Type a name for this back-up. More on my next post.

Why Do You Need The Whole Internet, Anyway?

Last week I had the wonderful opportunity to work with about 400 teachers and instructional coaches from PA. I heard some wonderful tales of some excellent and exciting work that is going on around the state. It was SO inspiring to hear those stories. I saw a sample lesson where the teacher used the Classroom 2.0 ning to find other teachers who were interested in a joint project with their classes. They used Google docs to flesh out the project details. They used a wiki for their project. They blogged about their learning, And, they used a number of online tools to create their final projects.

And I heard the other side of the coin, as well. I heard from several who said that, while they loved that project idea, they wouldn't be able to do it, as ALL of those sites are blocked. Who is making that decision, anyway?

One coach even told me that she was asked by one of her board members who was concerned about their budget, "Why do you need the WHOLE Internet anyway?" Seriously! You can't make this stuff up! How do you respond to that? How confident can you possibly be in the sense that your school board is making intelligent decisions for the education of all the children in the district? How empowered does that make you feel?

I also talked to a number of coaches, including the 1:1 district coaches where Google Docs, wikispaces, blogs, and much more are blocked. I heard of their intense frustrations as they fight to get these tools opened up, only to be told no. Worse, the reasons given are completely WRONG. Total lack of understanding and an unwillingness to learn.

By their actions, those districts are saying, "We embrace technology - but only so far as it lets us do what we always did before."

Now, if you'll excuse me, I've got to scream, now.

 
Design by Free WordPress Themes | Bloggerized by Lasantha - Premium Blogger Themes | Sweet Tomatoes Printable Coupons