Tuesday, November 23, 2004

String.Format : Useful Tips

It is very tedious job, reading the code which have more string concatenation (if single and doubl;e quotes are also there..it will be more congested).
A simple case is shown below:

string strSQL = "Insert into Table1 Values ('" + strVal1 + "', '" + strVal2 + "')";

A much better approach would be to use the string.Format method which makes concatenations much more readable and will reduce the possibility of error.

The same example can be replaced with:

string INSERT_FORMAT = "Insert into Table1 Values ('{0}', '{1}')";
string strSQL = string.Format(INSERT_FORMAT,strVal1,strVal2);

Create placeholders by inserting {n} into the string, where n describes the position of the replacement parameter.The StringBuilder too comes with the AppendFormat which serves the same purpose.

Now, here is a small catch. What happens if the format string itself has "{" or "}".


string strProblemFormat = "{Now, this is a problem}, {0}";

In this case, you would end up getting a FormatException.


Solution is simple. Escape "{" with "{{" and "}" with "}}" in your format string.

string strProblemFormat = "{{Now, this is a problem}}, {0}";
string strDisplay = string.Format(strProblemFormat,"Not anymore!");


Monday, October 18, 2004

How we can run a DTS Package from ASP

Every programming language has its own beauty and wealth. But as a developer we know only things what we need at the time of coding. Like that here it is another thing. We can run a DTS package from Active Server Pages where it is very need to us, sometimes.
When one of my friend asked how to access a DTS Package from ASP, after he met some authentication problem. He also noted that the DTS Package well executed when tried in Query Analyzer. Both of us know there was a problem in some authentication, but don't know the solution. And again Google helps and we found at MS KB article. And it explore new things (may be, new for me). If You also want to know about, just read the article under the heading Execute a SQL Server DTS Package from Active Server Pages at the URLstep (like..doorstep) http://support.microsoft.com/default.aspx?kbid=252987.