Monday, October 31, 2011

Outlook folder renamed

I noticed today that a folder in my Outlook 2010 mailbox had been renamed by some strange force. This is what I could see. So, I googled for this issue, and found that a few folks have had this problem with their Inbox being renamed to image001.jpg. For me, it was the Outbox folder though. The fix was the same, to start Outlook with a switch.

Outlook.exe /resetfoldernames

BEFORE
AFTER

http://www.slickit.ca/2010/03/outlook-2007-inbox-renamed.html

Thursday, October 20, 2011

Unix Shell Commands

Re-learnt this
The usual command to list all files and directories in the Unix shell is
ls
similar to dir in DOS

This just shows the names though. To get more details such as timestamp, the command is
ls -l

Wednesday, October 19, 2011

ConnectionState

I was writing this common method that helps in managing SQL Connections. I came to the point of closing and disposing of connections. I guess having a connection object in a using block will not do, since we wont be able to close the connection before it gets disposed. So, I initialized, opened and used it in a try block, and attempted to close it in the finally block, like this

            finally
            {
                if (connection != null && connection.State != ConnectionState.Closed)
                    connection.Close();
            }
I put in this additional validation to check for the connection state, perhaps from my WCF experience. When I explored the possible state of values in the System.Data.ConnectionState enum, it appears that other than Open and Closed, the 4 other states were "reserved for future versions of the product". Well, the only thing this validation protects from now is if the connection is attempted to be closed when it already is closed.
http://msdn.microsoft.com/en-us/library/system.data.connectionstate.aspx

Here's my DataHelper class:
    internal class DataHelper
    {
        private static readonly string sqlConnectionString = "ConnectionStringLiteral Or MethodCall Goes Here";
        internal static int ExecuteNonQuery(string storedProcName, SqlParameter[] parameters = null)
        {
            SqlConnection connection = null;
            int rowsAffectedCount;
            try
            {
                connection = new SqlConnection(sqlConnectionString);
                using (SqlCommand command = new SqlCommand(storedProcName, connection))
                {
                    SetCommandProperties(command, parameters);
                    rowsAffectedCount = command.ExecuteNonQuery();
                }
            }
            finally
            {
                if (connection != null && connection.State != ConnectionState.Closed)
                    connection.Close();
            }
            return rowsAffectedCount;
        }
        internal static DataSet ExecuteQuery(string storedProcName, SqlParameter[] parameters = null)
        {
            SqlConnection connection = null;
            DataSet dataSet = new DataSet();
            try
            {
                connection = new SqlConnection(sqlConnectionString);
                using (SqlCommand command = new SqlCommand(storedProcName, connection))
                {
                    SetCommandProperties(command, parameters);
                    new SqlDataAdapter(command).Fill(dataSet);
                }
            }
            finally
            {
                if (connection != null && connection.State != ConnectionState.Closed)
                    connection.Close();
            }
            return dataSet;
        }
        private static void SetCommandProperties(SqlCommand command, SqlParameter[] parameters)
        {
            command.CommandType = CommandType.StoredProcedure;
            if (parameters != null)
                command.Parameters.AddRange(parameters);
        }
    }

Identity field - int or not

I have an identity field in my SQL Server database's table. And I have this stored procedure which inserts a row in this table. The stored proc also returns a few other calculated values other than the new id created. So, I have a SELECT query at the end of the stored proc which goes like this

SELECT SCOPE_IDENTITY() as SomeId, @bar as SomethingImportant

And I use this code in C# to extract this id
int id = (int)rows[0]["SomeId"];

This gives me an invalid cast. Upon inspection, I notice that the value returned from the db call is decimal, not int! Why? Because SCOPE_IDENTITY, and even @@IDENTITY and IDENT_CURRENT(tablename) have the return type defined as NUMERIC(38, 0). This causes .Net to consider it as a decimal.

http://msdn.microsoft.com/en-us/library/ms190315.aspx
http://msdn.microsoft.com/en-us/library/ms187342.aspx
http://msdn.microsoft.com/en-us/library/ms175098.aspx

I ended up using it like this
int id = (int)(decimal)rows[0]["SomeId"];

UPDATE: In my second version, I assigned the value from SCOPE_IDENTITY() to a locally declared INT variable in the stored procedure, and returned that instead. That way, the C# code also takes it as in int.

Tuesday, October 18, 2011

SQL Server in-built functions

Some basic programming in SQL Server that comes handy.
Need to pad your number with zeroes? Use this
RIGHT('00000' + cast(@i as varchar(6)), 6)

Need a random 3-digit access code? Use this
RIGHT('00' + CAST(floor(rand()*1000) as VARCHAR(3)), 3)

Need your guid without the hyphens? Use this
REPLACE(CAST(NEWID() AS varchar(36)), '-', '')

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

Monday, October 17, 2011

Reset IDENTITY field

Let us say you have an an IDENTITY field in your table in SQL Server, and have deleted all rows from it, and now wish to insert fresh data. But on doing so, you would notice that this table still remembers the identity value of the last row inserted into it. To start afresh, you would need to do an identity reset. And here is the syntax to do it
DBCC CHECKIDENT (tablename, RESEED, currentvalue)

So, if you want your orders table's identity field to start from 1, you need to use this as
DBCC CHECKIDENT (orders, RESEED, 0)

Reference: http://www.howtogeek.com/howto/database/reset-identity-column-value-in-sql-server/

Friday, October 14, 2011

SQL Server 2008 Editions

This is where you can get SQL Server 2008 Management Studio Express (free SQL client)
http://www.microsoft.com/download/en/details.aspx?id=7593

This is where you can get SQL Server 2008 Express (free SQL host)
http://www.microsoft.com/sqlserver/en/us/editions/express.aspx

And this is where you can find more about the other editions
http://www.microsoft.com/sqlserver/en/us/product-info/compare.aspx

I just noticed today that some people actually write (not just say) SQL as Sequel. :)
Found a discussion about it here as well.
http://discuss.fogcreek.com/joelonsoftware/default.asp?cmd=show&ixPost=62158

New datatype - DateTime2

Want to know more about the datetime data type in SQL Server?http://technet.microsoft.com/en-us/library/ms187819.aspx

The first thing they will tell you is about the new datetime2 data type.
http://technet.microsoft.com/en-us/library/bb677335.aspx
"Use the datetime2 data type for new work. This type aligns with the SQL Standard. It is more portable."

The interesting thing is that it has more seconds precision with the same storage size of 8 bytes. In fact, it takes only 7 bytes for a precision of 3 or 4 digits, and 6 bytes for less than 3 digits.

datetime2 in SQL Server also has the same date range as that of DateTime defined in .Net, from
January 1, 0001 00:00:00.0000000
through
9999-12-31 23:59:59.9999999
as defined by DateTime.MinValue and DateTime.MaxValue
http://msdn.microsoft.com/en-us/library/system.datetime.minvalue.aspx
http://msdn.microsoft.com/en-us/library/system.datetime.maxvalue.aspx

The earlier datatype (datetime) in SQL Server has a lesser range and lesser precision.
January 1, 1753 00:00:00.000
through
December 31, 9999 23:59:59.997

So, beware when you use DateTime.MinValue or MaxValue in .Net and send it to a datetime parameter in SQL Server. Use datetime2 instead.

It seems System.Data.DbType.DateTime2 is also defined in .Net from framework 3.5 onwards.
http://msdn.microsoft.com/en-us/library/system.data.dbtype.aspx

Transfer data from remote server to local

We have a stored procedure on a SQL Server 2005 box which returns us a result-set. We wanted to execute this stored procedure from a SQL Server 2008 box and store the results into a table locally. So, we created a SQL user on the local (2008) box, a linked server to the 2005 box and executed the stored procedure

exec[linkedserver].[db].[schema].[storedproc]
This works fine.

But, if I try to insert this data into a table variable or a temp table, it gives me an error.
DECLARE @temp ASTABLE (column1 datatype, column2 datatype)
INSERT INTO @temp exec [linkedserver].[db].[schema].[storedproc]
The error is

OLE DB provider "SQLNCLI10" for linked server "linkedserver" returned message "The partner transaction manager has disabled its support for remote/network transactions.".
Msg 7391, Level 16, State 2, Line 2
The operation could not be performed because OLE DB provider "SQLNCLI10" for linked server "linkedserver" was unable to begin a distributed transaction.

We didnt want to turn on MSDTC for this since there were no distributed transactions involved. So, we decided to use OPENQUERY, like this.
DECLARE @temp ASTABLE (column1 datatype, column2 datatype)
INSERT INTO @temp exec [linkedserver].[db].[schema].[storedproc]
INSERT INTO @temp SELECT * FROM OPENQUERY([linkedserver],'[db].[schema].[storedproc]')

Note that the last argument to OPENQUERY is the command that gets executed on the remote server locally. So, make sure you dont have the linked server prefix in the stored proc's name.

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

Also posted this on
http://social.msdn.microsoft.com/forums/en-US/transactsql/thread/2da5983c-2256-4394-82e0-c0c26c663a7e/

Thursday, October 13, 2011

Clustering, log shipping or mirroring

Good details on the different options available in SQL Server for high availability.
http://sql-articles.com/articles/high-availability/comparison-between-mirroring-vs-log-shipping-and-mirroring-vs-clustering/

Sending table data to a stored procedure

For context, please refer my earlier post at http://wilth.blogspot.com/2011/10/cant-open-symmetric-keys-in-udfs.html

So, since we couldnt use our UDF and had to use a stored proc instead, the trouble with using a stored proc is that it cant directly go into the VALUES clause of an INSERT INTO---SELECT statement, like a UDF could. This means we would need to execute multiple (about a million, seriously) INSERT statements by looping on a temp table.

An alternative would be to have the remote stored proc instead do all the work of opening the key, executing the INSERT INTO---SELECT statement and then closing the key. This has the added benefit of not exposing the TABLE to the remote user. How do we do it? Using TABLE-type parameters. They just came up in SQL Server 2008.
http://msdn.microsoft.com/en-us/library/bb510489.aspx
explained more in
http://www.sqlservercentral.com/articles/Stored+Procedures/2977/

And so, we made this stored proc. But sadly, the DB server that makes the call is still on SQL Server 2005, and so could not invoke this stored procedure. The alternative, it seems, is to send an XML parameter.
http://www.sqlservercentral.com/articles/News/3182/

Web Code Snippet tester for web

If you want to try out some HTML, CSS, JavaScript or even jQuery, here is a convenient way to do so instead of on your dev box. Once you create a snippet, you can even share it with your friends.
http://jsfiddle.net/

Wednesday, October 12, 2011

Get caller's type

If I write a method in C#, can I get to know what type invoked this method? It seems we can, by inspecting the stack trace. But, a better design is just to accept a System.Type parameter and have the caller send that information.

Reference:
http://stackoverflow.com/questions/266115/pass-an-instantiated-system-type-as-a-type-parameter-for-a-generic-class

Secure Network Protocols

SSH - Secure SHell
used to execute remote shell commands over a secure network
replacement for rsh (remote shell) protocol
http://en.wikipedia.org/wiki/Secure_Shell
SSH Communications Security (now Tectia) is a Finnish company that developed the Secure Shell protocol.

SCP - Secure CoPy
http://en.wikipedia.org/wiki/Secure_copy
uses SSH, used to securely transfer files between a local and a remote host
replacement for rcp, which stands for remote copy command in Unix
command-line arguments are based on the cp command to copy files locally

SFTP - Ssh File Transfer Protocol
http://en.wikipedia.org/wiki/SSH_file_transfer_protocol
extension of SSH2 to provide secure file transfers
not to be confused with FTPS which is FTP over SSL
http://en.wikipedia.org/wiki/FTPS

More to read
http://en.wikipedia.org/wiki/Portal:Cryptography

TLS/SSL
http://en.wikipedia.org/wiki/Transport_Layer_Security

TCP
http://en.wikipedia.org/wiki/Transmission_Control_Protocol

UDP
http://en.wikipedia.org/wiki/User_Datagram_Protocol

Packet analyzer
http://en.wikipedia.org/wiki/Packet_analyzer

Cant open symmetric keys in UDFs

We had planned to abstract the use of our encryption logic inside a user-defined function in SQL Server 2008 R2. The caller would send the plain text and we could just send back the encrypted content without having the user to worry about with keys, certificates, encryption algorithms and the daily grind.

But, it appears its not so straightforward, since one would get this error if one attempted to create such a UDF:
"Invalid use of side-effecting or time-dependent operator in 'OPEN SYMMETRIC KEY' within a function."

The workaround is to write this logic in a stored procedure and have that executed by the caller. Of course, it isnt as nice as using the UDF in an INSERT statement directly. But, I guess we can live with that for now.

Reference:
http://social.msdn.microsoft.com/forums/en-US/sqlsecurity/thread/b56f3ef4-10d4-46c1-ade1-dedeee36ac33

Best cash back credit cards in the US

http://creditcardforum.com/content/best-cash-back-credit-cards-4/

Looks like I will go for one from Amex. Dunno yet if I should get the Costco one, or one of the Blue Cash ones.

Blog Name

I initially thought about this blog-site as WILT, with this in the description.

An honest attempt to capture "What I Learned Today". The acronym WILT is an attempt to be sarcastic about the ironical pun on the word of wilt, which means to lose strength, such as used in "to wilt after a day's hard work". Of course, the intent is quite the opposite - to provide energy in the form of knowledge.

But since the sub-domain name wilt was already being used in blogspot, I used wilth instead, with the h being for honestly.

Then, I turned to look for LRKG (Lambi Race Ka Ghoda). But, it seemed that sub-domain name was taken up as well. So, I used 1100010010 for a while.

And now, I have turned to techthirstday. Until last year, our team used to meet every Thursday, to discuss what we have learnt recently. And I thought I could use the same name for this. Sounds nice. :)