Scott Hanselman

Why the using statement is better than a sharp stick in the eye, and a SqlConnection refactoring example

July 2, '04 Comments [3] Posted in Programming
Sponsored By

A friend of mine sent me some code just now where he was experimenting with Close and Dispose on SqlConnection.  Reflectoring into SqlConnection shows it closes open connections in Dispose().  So, here's the before and after code.  I think it shows good examples on why the using statement exists, and when to avoid (hide) superfluous try/catches.  I also changed a few nits for readability by using certain overloaded constructors as well as String.Format().

BEFORE - The code I was given:

private void RunScriptOnDB(string filename,string DB)
{
    SqlConnection sqlcon = new SqlConnection();
    sqlcon.ConnectionString ="Persist Security Info=False;Integrated Security=SSPI;Initial Catalog="+DB+";Data Source=(local);";
    SqlCommand com = new SqlCommand();
    com.Connection = sqlcon;
    try
    {
        StreamReader sr = Utility.GetStreamOfFile(filename);
        com.CommandText = sr.ReadToEnd();
        sr.Close();
    }
    catch(FileNotFoundException fileex)
    {
        msg.Text = fileex.Message;
        return;
    }
    try
    {
        sqlcon.Open();
        com.ExecuteNonQuery();
        msg.Text = "Successful";
    }
    catch( SqlException sqlex)
    {
        msg.Text = sqlex.Message;
    }
    finally
    {

        if(closingMethod.SelectedValue == "c") //SDH: He's trying different closing methods based on a Radio Button, this won't be needed in a refactor
        {
            sqlcon.Close();
        }
        else if(closingMethod.SelectedValue == "d")
        {
            sqlcon.Dispose();
        }
        else
        {
            sqlcon.Close();
            sqlcon.Dispose();
        }
    }
}

AFTER - My quickie refactor/clean:

private void RunScriptOnDB(string filename, string database)
{
   string commandText = String.Empty;
   try
   {
      using (StreamReader sr = Utility.GetStreamOfFile(filename))
      {
         commandText = sr.ReadToEnd();
      }
   }
   catch (FileNotFoundException fileEx)
   {
      msg.Text = fileEx.Message;
      return;
   }
   using (SqlConnection connection = new SqlConnection(String.Format("Persist Security Info=False;Integrated Security=SSPI;Initial Catalog={0};Data Source=(local);",database))
   {
      using (SqlCommand command = new SqlCommand(commandText, connection))
      {
         try
         {
            connection.Open();
            command.ExecuteNonQuery();
            msg.Text = "Successful";
         }
         catch (SqlException sqlEx)
         {
            msg.Text = sqlEx.Message;
         }
      }
   }
}

About Scott

Scott Hanselman is a former professor, former Chief Architect in finance, now speaker, consultant, father, diabetic, and Microsoft employee. He is a failed stand-up comic, a cornrower, and a book author.

facebook twitter subscribe
About   Newsletter
Sponsored By
Hosting By
Dedicated Windows Server Hosting by SherWeb

VB6->VB.NET->VB.NET/Whidbey Collection Class change

July 1, '04 Comments [0] Posted in Programming
Sponsored By

Remember all the weirdness around Collections and VB6 when VB.NET came out?  I just noticed this breaking change as we move from 1.1 to Whidbey.  Previously added workaround code will have to be removed.

VB collections have weird implementation of IList: 0 based for read and -1 based for insertion
Affected APIs none
: Ilist implementation of VB collection is fixed
Affected Assemblies\Dll(s): Microsoft.VisualBasic.dll
Affected Scenarios: Upgraded apps that use VB Collection through inconsistent implementation of Ilist (very unlikely scenario) may be broken.
Description: An instance of Collection type is casted to Ilist and then used via Ilist interface. To make this work in 7.0, 7.1 you would need to specialcase access to Ilist if it holds Collection
Workaround Code that has special-case warkarounds to use Collections casted to Ilist, will have to remove workarounds.

About Scott

Scott Hanselman is a former professor, former Chief Architect in finance, now speaker, consultant, father, diabetic, and Microsoft employee. He is a failed stand-up comic, a cornrower, and a book author.

facebook twitter subscribe
About   Newsletter
Sponsored By
Hosting By
Dedicated Windows Server Hosting by SherWeb

Doc/Literal/Bare in XML Web Services - my thoughts on all this.

July 1, '04 Comments [7] Posted in Web Services | XML
Sponsored By

Apparently Craig Andera and Tim Ewald were recently working on an MSDN code rewrite and were talking about building doc/literal/bare Web Services vs. doc/literal/wrapped.

I'm a little confused by their respective posts, as they appear to say too different things.  (Coming up on Fox, When Smart People Disagree!) They were both in the same house, coding the same stuff, but Craig's conclusion about how to use SoapParameterStyle.Bare is very different than Tim's (and mine).

Tim suggests that getting an AddResponse type "for free" when writing code like this:

//SDH: This is bad, avoid it
[WebMethod]
[return: XmlElement("sum")]
public int Add(int x, int y) { return x + y; }

is lame, and I agree.  The generared AddResponse type is totally magic, coming (by magic) from the Method name, which is a little too tightly-coupled for my tastes.

Instead, your functions should take as parameters and return as reponses formal types that you control.  Then you can use the [SoapDocumentMethod(ParameterStyle = SoapParameterStyle.Bare)] attribute to avoid any extra automagically-added wrapped elements.  This is purely a coding convention, it's not expressed in WSDL. 

//SDH: This is not bad, embrace it.
[WebMethod]
[SoapDocumentMethod(ParameterStyle = SoapParameterStyle.Bare)]
[return: XmlElement("AddResponse")]
public AddResponse Add(AddRequest req)
{
  AddResponse resp = new AddResponse();
  resp = req.x + req.y;
  return resp;
}

Tim's right on with this.  We do the same thing at Corillian with our code-generation stuff (maybe I'll present on it sometime.)  You can reuse the Request and Response messages this way, as well as take and return base classes.

However, Craig had a different view.  He simply added the bare attribute to the method call:

//SDH: This is bad, think twice
[WebMethod]
[SoapDocumentMethod(ParameterStyle=SoapParameterStyle.Bare)]
public int Add(int x, int y) { return x + y; }

which results in

<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns:xsd="http://www.w3.org/2001/XMLSchema"
        xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
  <soap:Body>
    <x xmlns="http://tempuri.org/">int</x>
    <y xmlns="http://tempuri.org/">int</y>
  </soap:Body>
</soap:Envelope>

Which is a non-WS-I Basic Profile compliant Web Service, as it has more than one child node under <soap:Body>.  Craig muses "To me, this just seems like nicer XML; more like how I would do it if I were just using XmlWriter and raw sockets."  I totally disagree with that statement, as XML Web Services are decidedly NOT about that level of abstraction.  If you like talking with XmlWriter and raw sockets, why not yank the <soap:envelope> and those pesky namespaces? ;) If so, there's already a spec for you

Additionally this places even more pressure on the HTTP SOAPAction header, which was always a bad idea.  Fundamentally (at least in my World View) SOAP messages should be transport neutral and that's what wsa:Action is for.

So, conclusion?  Be explicit.  Use Request and Response messages as ins and outs for your Web Services, call them out and use SoapParameterStyle.Bare to avoid the extra wrapping element.  Tim's list of reasons why is excellent.

About Scott

Scott Hanselman is a former professor, former Chief Architect in finance, now speaker, consultant, father, diabetic, and Microsoft employee. He is a failed stand-up comic, a cornrower, and a book author.

facebook twitter subscribe
About   Newsletter
Sponsored By
Hosting By
Dedicated Windows Server Hosting by SherWeb

If ever there was a goodness...the iTunes Album Art Importer for Windows, written in .NET 1.1

July 1, '04 Comments [4] Posted in Web Services
Sponsored By

Thank you YVG Software Services as you have saved me time.  The way to a programmer's heart is by saving him/her time.  You wrote the iTunes Art Importer, and it was your FIRST VB.NET Application.  It uses the Amazon.com Web Service to find Album Covers for my iTunes collection - and it just works.  Kudos to you, and God bless you. :)  And thank you iTunes for having a COM Automation interface.  Ain't that something, a little .NET, a little Web Services, a little OLE Automation and a hard problem is solved n times.

(See their importer, there below iTunes itself?  Shiny, eh? I've set it off to find art for 4700+ songs.  A few hundred in, and I've got a 90% hit rate.)

About Scott

Scott Hanselman is a former professor, former Chief Architect in finance, now speaker, consultant, father, diabetic, and Microsoft employee. He is a failed stand-up comic, a cornrower, and a book author.

facebook twitter subscribe
About   Newsletter
Sponsored By
Hosting By
Dedicated Windows Server Hosting by SherWeb

Mono 1.0 was just released

July 1, '04 Comments [2] Posted in ASP.NET | DasBlog | Bugs
Sponsored By

Congrats to all! Anyone out there running their dasBlog on Mono?

Mono is a comprehensive open source development platform based on the .NET framework that allows IT and ISV developers to build Linux and cross-platform applications with unprecedented productivity.

Mono's .NET implementation is based on the ECMA standards for C# and the Common Language InfrastructureMono includes a compiler for the C# language, an ECMA-compatible runtime engine (the Common Language Runtime, or CLR),and class libraries. The libraries include Microsoft .NET compatibility libraries (including ADO.NET and ASP.NET), Mono's own and third party class libraries. Mono's runtime can be embedded into applications for simplified packaging and shipping. In addition, the Mono project offers an IDE, debugger, and documentation browser.

If you have questions about the project, read the project launch statement or visit our list of Frequently Asked QuestionsFor details on the project's future direction, read the roadmap, and download Mono 1.0.

About Scott

Scott Hanselman is a former professor, former Chief Architect in finance, now speaker, consultant, father, diabetic, and Microsoft employee. He is a failed stand-up comic, a cornrower, and a book author.

facebook twitter subscribe
About   Newsletter
Sponsored By
Hosting By
Dedicated Windows Server Hosting by SherWeb

Disclaimer: The opinions expressed herein are my own personal opinions and do not represent my employer's view in any way.