El TecnoBaúl de Kiquenet

Kiquenet boring stories

Archive for 29 julio 2010

osql.exe y encoding UTF8

Posted by kiquenet en 29 julio 2010

OSQL accepts ANSI and Unicode encoded files, BUT I tried opening my file with notepad++ changed the encoding to UTF-8 and I got similar errors.

MS SQL Server’s osql utility (SQL Server 2000) is deprecated.

Mejor usar SQLCMD.

I have been trying to run MS SQL Server’s osql utility (SQL Server 2000) to insert some default data. My SQLServer’s target database collation is Croatian_CI_AS. After some time I’ve realized a few things about the ways in which you can save the input file.

Using Notepad++ as my editor I thought that formatting a file as UTF-8 would cause everything to be wonderful and magically work.

Not so. In fact, osql will not even read the UTF-8 encoded file (this was a real surprise)! That was a weird thing but I kept on getting this error message about first line and some weird character displayed there. Turns out that osql accepts unicode or ANSI encoded files (and there’s no way to control the input file encoding from the command line so we’re stuck with that … which is not that bad after all).
So, no.1: don’t format your input file for osql as UTF-8. That’s a different animal from a unicode encoded file.

Notepad++ offers several formatting options. Turns out that UCS-2 Little Endian is the wizard. For those interested, read on UCS-2 on wikipedia. I just realized it was actually a 16-bit Unicode encoding. Just looking at it in the list of encodings in Notepad++ didn’t ring bells.

I’m not sure why UCS-2 Big Endian encoding does not play nice (I get gibberish for most of my special characters).

Formatting a file as ANSI in Notepad++ and then running through osql was a bit of a surprise that it did not work (special characters like diacritics became gibberish, although osql did execute everything). I even changed my Windows code page to Croatian in hope that it will all somehow sort itself out but it didn’t. From what I can tell,osql will read the ANSI encoded file as probably English Latin encoding and loose the special characters in the process.

So, bottom line, UCS-2 Little Endian is our friend. Use that for encoding files that are to be executed with osql

 

osql.exe and unicode files – how to save your sql scripts with encoding

osql.exe is a great application for running sql scripts in a batch.  I use a batch file to execute multiple sql scripts that I use to rebuild my current application database from scratch.  When developing a brand new application, deploying a database in this way makes it really easy to recreate the database just like it will be created on Day 1 when you build out the Production environment. This requires scripting out all of your sql objects and then also having a way to execute all of those sql scripts easily.  That is where osql.exe comes in handy.

But osql.exe does have one issue that I ran into this week where it does not like UTF-8 (codepage 65001) or UTF-7 (codepage 65000) encoded files.  And sometimes you need to include unicode characters in your sql scripts.  At first I thought osql just did not support unicode but that is not the case… it just does not like the UTF-8 or UTF-7 encoding.

Trying to run a UTF-8 (codepage 65001) or UTF-7 (codepage 65000) encoded file with osql.exe will give you errors such as:

Incorrect syntax near ‘+’.
Incorrect syntax near ‘ ‘.
Incorrect syntax near ‘ï’.

Saving the same file with Unicode Encoding (codepage 1200) will work just fine.  Here is how to save sql scripts in Microsoft SQL Server Management Studio with a particular encoding (you can also use this method to see what type of encoding the file is saved in in the first place).  One other thing to note is that Visual Studio has this same type of Save As… functionality.

From the Microsoft SQL Server Management Studio (or Visual Studio) File menu chooseSave [FILENAME] As…

image

Then when the Save File As dialog appears you will see a little black arrow (inverted triangle) as part of the Save button.

image

Clicking the just the inverted triangle portion of the button will give you a menu.

image

Choosing the Save with Encoding… option will then present you with an Advanced Save Options dialog.

image

image

Here is where you can specify the encoding to use for the file.  For osql.exe make sure you specify either Western European (Windows) – Codepage 1252 or Unicode – Codepage 1200.  Do not select UTF-8 (codepage 65001) or UTF-7 (codepage 65000) or osql.exe will give errors when trying to parse the file.

http://weblogs.asp.net/jeffwids/archive/2009/10/14/osql-exe-and-unicode-files-how-to-save-your-sql-scripts-with-encoding.aspx

http://kiribao.blogspot.com/2008/03/osql-and-input-file-encodings.html

Anuncios

Posted in Comandos, SQL | Etiquetado: , , | Leave a Comment »

Handling Custom Error Codes with MSBuild

Posted by kiquenet en 28 julio 2010

If you are running an external EXE using the "<Exec" task, then if the EXE is returning a code other than "0" as the success code, then MSBuild still takes it as as failure.

<Exec Command=’"C:\Some.exe"’>
              <Output TaskParameter="ExitCode" PropertyName="ErrorCode"/>
  </Exec>
  <Message Text="The exit code is $(ErrorCode)"/>

The execution does not even come to the "<Message" and it just exits assuming that "-1" is afailure.
As a workaround, you can use this method.

<Target Name="ExecuteSomeEXE">
<Exec Command=’"C:\Some.exe"’ ContinueOnError=’true’>
              <Output TaskParameter="ExitCode" PropertyName="ErrorCode"/>
  </Exec>
  <Message Text="The exit code is $(ErrorCode)"/>
  <Error Text="Error while executing Some EXE" Condition="’$(ErrorCode)’ > ‘0’" />
<OnError ExecuteTargets="MessageErrorHandler"/>
</Target>
<Target Name="MessageErrorHandler">
        <Message Text="An error has occurred while executing SomeEXE"/>
</Target>

This way you can manage any error code returned by the executable.

http://geekswithblogs.net/SudheersBlog/archive/2007/10/19/116171.aspx

Posted in .NET, MsBuild | Etiquetado: , , | Leave a Comment »

El maravilloso mundo de las Transacciones

Posted by kiquenet en 21 julio 2010

Nested Transaction Scopes

three TransactionScopeOption settings:

  • Required: the contained code depends on a transaction for atomicity, isolation, and compensation, and could be part of a broader transaction.
  • RequiresNew: the contained code depends on a transaction, but must be independently committed or rolled back.
  • Suppress: the contained code performs its own compensation, so must not be part of a transaction.

The first setting is the default, under the assumption that if you are creating a TransactionScope, you probably want a transaction. In that case, the normal situation is one where the operation you’re about to do can be reasonably integrated into a transaction that already active.

The second setting is for cases where the contained code block does require a transaction for its consistency, and provides a feature that demands that it be separate from any transaction that might already be active. One typical example would be a function that provides activity logging to, say, a database. It may be implemented such that it required a transaction to provide consistency, but it couldn’t accept an outer rollback to undo the record of the attempted activity.

The final setting, Suppress, handles case where the contained code needs to be sure that it is not executing as part of any transaction. This is fairly uncommon for a local operations — the only real case for this would be if the contained code was designed to handle its own compensation, yet used recoverable resources, such as SQL, to do its actions.

However, the reality is slightly more subtle. Complete means just what the name suggests — that the code within the TransactionScope has completed (successfully) all the operations it intended to do as part of the transaction. Note that this is also why you can’t call Complete twice. To do so would mean that at least one of the two calls wasn’t the last intended operation.

When a TransactionScope is disposed it first looks to see if it was completed successfully. If it was not, the transaction is immediately rolled back. If it was, and this was the TransactionScope that created the transaction in the first place, the transaction is committed. Finally, in both cases, the current transaction is replaced with the value that was current when the TransactionScope was created.

Thus we have, for success:

// no transaction is active here
using (TransactionScope s = new TransactionScope ())
{
    // transaction ‘a’ is active here
    using (TransactionScope t = new TransactionScope
                (TransactionScopeOption.RequiresNew))
    {
        // transaction ‘b’ is active here
        t.Complete ();
    } // the transaction from ‘s’ is put into Current.

    // transaction ‘a’ is active here
    using (TransactionScope u = new TransactionScope ())
    {
        // transaction ‘a’ is active here
        u.Complete ();
    } // the transaction from ‘s’ is put into Current.

    // transaction ‘a’ is active here
    s.Complete ();
}

// ‘a’ commits at this point
// no transaction is active here

For a failure case we have:

// no transaction is active here
using (TransactionScope s = new TransactionScope ())
{
    // transaction ‘a’ is active here
    using (TransactionScope t = new TransactionScope(
                  TransactionScopeOption.RequiresNew))
    {
        // transaction ‘b’ is active here
        t.Complete ();
    }

    // transaction ‘a’ is active here
    using (TransactionScope u = new TransactionScope ())
    {
        // transaction ‘a’ is active here
        //u.Complete ();
    } // ‘a’ rolls back here,
      //the transaction from ‘s’ is put into Current.

    // transaction ‘a’ is current, but aborted here
    s.Complete ();

}  // ‘a’ is already aborted, so is just removed at this point
// no transaction is active here

There was a massive upgrade to the error handling within SQL Server 2005. These articles are fairly extensive:

Error Handling in SQL 2005 and Later by Erland Sommarskog
http://www.sommarskog.se/error_handling_2005.html

Error Handling in SQL 2000 – a Background by Erland Sommarskog
http://www.sommarskog.se/error-handling-I.html

http://stackoverflow.com/questions/2701934/transactionscope-and-transactions

MSDN:

http://msdn.microsoft.com/en-us/library/ms973865.aspx

Posted in .NET, DataAccess | Etiquetado: , | Leave a Comment »

How to clear your Internet Explorer (version 7) cache from the command line

Posted by kiquenet en 20 julio 2010

Normally, you have to open IE and choose Tools | Delete Browsing History | Delete All…

Another way would be to open the command line and type the following commands:

  • RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 255 (Deletes ALL History)
  • RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 1 (Deletes History Only)
  • RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 2 (Deletes Cookies Only)
  • RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 8 (Deletes Temporary Internet Files Only)
  • RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 16 (Deletes Form Data Only)
  • RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 32 (Deletes Password History Only)

    Delete All – “Also delete files and settings stored by add-ons”
    RunDll32.exe InetCpl.cpl,ClearMyTracksByProcess 4351

These commands should work in Internet Explorer 7 on XP or on Windows Vista.

http://blogs.techrepublic.com.com/window-on-windows/?p=574

http://www.howtogeek.com/howto/windows/clear-ie7-browsing-history-from-the-command-line/

Posted in Comandos, IE, Scripts | Etiquetado: , , | Leave a Comment »

How to set the MaxItemsInObjectGraph configuration.

Posted by kiquenet en 20 julio 2010

Symptoms/Exceptions:

("System.Runtime.Serialization.SerializationException : Maximum number of items that can be serialized or deserialized in an object graph is ‘65536’. Change the object graph or increase the MaxItemsInObjectGraph quota.").

"System.ServiceModel.CommunicationException: The underlying connection was closed: The connection was closed unexpectedly"

Solution

You need to modify both the configuration file for the service as well as the client.

For the services configuration should look like this:

<system.serviceModel>   
<services>
      <service
behaviorConfiguration="Umea.se.EventReactor.ServiceTier.ServiceViewEventBehavior"
       name="Umea.se.EventReactor.ServiceTier.ServiceViewEvent">
        <endpoint address="" binding="wsHttpBinding" contract="Umea.se.EventReactor.ServiceTier.IServiceViewEvent">
          <identity>
            <dns value="localhost" />
          </identity>
        </endpoint>
        <endpoint address="mex" binding="mexHttpBinding" contract="IMetadataExchange" />
      </service>
    </services>
    <behaviors>
      <serviceBehaviors>
        <behavior name="Umea.se.EventReactor.ServiceTier.ServiceViewEventBehavior">
          <serviceMetadata httpGetEnabled="true" />
          <serviceDebug includeExceptionDetailInFaults="false" />
<dataContractSerializer maxItemsInObjectGraph="2147483647" />
        </behavior>
      </serviceBehaviors>
    </behaviors>
  </system.serviceModel>

The client configuration should look like this:

<system.serviceModel>
    <client>
<endpoint address="
http://localhost:3379/ServiceViewEvent.svc" behaviorConfiguration="ServiceViewEventBehavior"
        binding="wsHttpBinding" bindingConfiguration="WSHttpBinding_IServiceViewEvent"
        contract="ServiceReferenceViewEvent.IServiceViewEvent" name="WSHttpBinding_IServiceViewEvent">
        <identity>
          <dns value="localhost" />
        </identity>
      </endpoint>
</client>
<behaviors>
      <endpointBehaviors>
        <behavior name="ServiceViewEventBehavior">
<dataContractSerializer maxItemsInObjectGraph="2147483647"/>
        </behavior>
      </endpointBehaviors>
</behaviors>
  </system.serviceModel>

http://blog.hill-it.be/post/2007/08/22/MaxItemsInObjectGraph-and-keeping-references-when-serializing-in-WCF

http://processmentor.com/community/blogs/scott_middleton/archive/2007/06/08/169.aspx

Posted in .NET | Etiquetado: , , | Leave a Comment »

Singleton genérico

Posted by kiquenet en 9 julio 2010

public abstract class Singleton<T> where T : class
    {
        private static T _instance = (T)Activator.CreateInstance(typeof(T), true);

        public static T Instance
        {
            get { return _instance; }
        }
    }

La implementación:

public class FooBarSvc : Singleton<FooBarSvc>

{

private FooBarSvc() { }

public void Foo(){ ...}

}

Uso: FooBarSvc.Instance.Foo();

http://scottwhite.blogspot.com/2010/03/when-you-implement-non-threadsafe.html

Posted in .NET | Etiquetado: , | Leave a Comment »

Cómo saber si un assembly esta compilado en modo Debug o Release

Posted by kiquenet en 9 julio 2010

Necesidad de conocer cual era el modo en el cual fue compilado cierto assembly. La primer herramienta a la que acudí me dió una respuesta: Reflector de Lutz Roeder.

El compilador agrega el attributo DebuggableAttribute como información del assembly. Los modos de debug fijados por el compilador dependerán de los parámetros que le pasemos al compilador por línea de comandos o el tipo de compilación que definamos en el proyecto de Visual Studio.

En el caso de haber compilado con Visual Studio 2005 ó 2008 en modo Release, nos encontraremos con la siguiente línea:

[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]

En caso de haber compilado en modo Debug:

[assembly: Debuggable(DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.EnableEditAndContinue | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.Default)]

Les recomiendo la lectura de la documnetación correspondiente a los valores del enumerado System.Diagnostics.DebuggableAttributes.DebuggingModes

A continuación un ejemplo de código que revela el modo de compilación:

La propiedad DebuggableAttributes.IsJITTrackingEnabled controla si en tiempo de ejecución el CLR hace un seguimiento de la información que es importante para el depurador mientras se genera el código. Esta información contribuye a que el depurador mejore la depuración.

public static bool EnsambladoCompiladoEnModoDebug(string filePath)
        {
            var asm = Assembly.LoadFile(Path.GetFullPath(filePath));
            foreach (Attribute att in asm.GetCustomAttributes(false))
            {
                if (att is System.Diagnostics.DebuggableAttribute)
                {
                    var debug = ((DebuggableAttribute)att).IsJITTrackingEnabled;
                    Console.WriteLine("Modo Debug: {0}", debug);
                    if (debug) return true;
                }
            }
            return false;

        }

http://msmvps.com/blogs/cwalzer/archive/2008/04/28/assemblydebugrelease.aspx

Posted in .NET, VisualStudio | Etiquetado: , , | Leave a Comment »

Diez cosas que nunca deberías meter en tu CV

Posted by kiquenet en 5 julio 2010

studios, trabajos, idiomas… Sabemos cómo rellenas tu CV, pero toma nota de las cosas que no deberías incluir nunca en tu historial, pues corres el riesgo de que quedarte sin empleo.

En estas fechas, las empresas reciben montones de currículos. Todos se parecen. Pero hay cosas que no deberías meter nunca.
1. Foto. No lo hagas especialmente si es una multinacional norteamericana. En las empresas de EEUU y sus filiales se toman muy en serio la discriminación. Así que para evitar rumores, los directores de personal lanzan directamente a la papelera los CV con foto pues les podrían acusar de no aceptar a una persona por fiarse de su apariencia: raza, sexo, aspecto físico.
2. Muy largo. ¿Has metido más de una página de información en tu CV? ¿Acaso tres páginas? ¿Cinco? ¿Quién te crees? ¿Un premio nobel? Incluso las personas más preparadas presentan currículos sencillos. No más de una página.
3. Inglés "medio alto". Todos dicen lo mismo cuando llegan a los idiomas: inglés "medio alto". Pero bueno, ¿qué es eso de "medio alto"? ¿Un viaje de fin de curso a Irlanda? No señor. Medio alto es el nivel de una persona que habla inglés por lo menos una vez al mes. Y que ve películas, series o lee periódicos semanalmente en ese idioma.
4. Tu dirección de Facebook. O sea, que no has tenido reparo en meter tu perfil de Facebook. ¿Has olvidado que apareces allí en el último botellón? ¿Sigue ahí esa foto enseñando el trasero? ¿Y aquella echando la pota en la playa? Has cometido un error.
5. Mi Tuenti. ¿Tuenti? ¿A tu edad? Eres muy jovencito, chaval, y todavía no sabes lo que es la vida, ni la crisis. Nada de Tuenti. Eso es para niños.
6. Tu blog de sexo. Claro, eres especialista en sexo y has abierto un blog. No está mal. Viva la libertad de expresión. Pero procura no dar ese dato en tu CV especialmente si la empresa para la que quieres trabajar es muy conservadora.
7. Tus extraños hobbies. ¿Coleccionas ratas disecadas? ¿Te gusta vestirte de otaku? ¿Eres gore? Mejor no lo pongas en el apartado "hobbies". Apuesta por manías más sencillas como la literatura islandesa o el ikebana, el arte japonés de las flores.
8. Trabajos populares. Cuando llegue el apartado ‘experiencias’, trata de poner cosas profesionales. Evita eso que "hice guiñoles en la piñata de la parroquia", o "payaso en Diversiones Manolo".
9. ¿Seguro que sabes escribir? En otros conocimientos, la mayoría pone que sabe escribir en Word. ¿Ah, sí? ¿Y qué más? ¿Sabes encender y apagar un ordenador? Se supone que eso lo tienes que dominar. No pongas tonterías.
10. Me gusta la soledad. En el apartado en que te describes a ti mismo (algo que gusta cada vez más a los reclutadores) no pongas eso de "me gusta la soledad", "trabajo de forma individual". No señor. Lo que mola es trabajar en equipo. Aunque lo detestes, tienes que trabajar en equipo. Ya se sabe lo que es un equipo: un grupo de personas que mira atentamente al único que trabaja.

http://es.biz.yahoo.com/reportajes/el-rincon-de-carlos-salas/

Posted in Trabajo | Leave a Comment »