We help IT Professionals succeed at work.

We've partnered with Certified Experts, Carl Webster and Richard Faulkner, to bring you a podcast all about Citrix Workspace, moving to the cloud, and analytics & intelligence. Episode 2 coming soon!Listen Now

x

convert vb.net code to c# code

fwsteal
fwsteal asked
on
Medium Priority
722 Views
Last Modified: 2012-08-14
How do I write the following in C#?

'JS Indicator Repeater
Dim conG2 As SqlConnection
Dim cmdSelect2 As SqlCommand
Dim dtrIndicators2 As SqlDataReader
'retrieve records from db
conG2 = New SqlConnection("Server=MyServer;UID=MyUID;PWD=MyPWDs;Database=MyDB")
cmdSelect2 = New SqlCommand("Select * from MyTable", conG2)
conG2.Open()
dtrIndicators2 = cmdSelect2.ExecuteReader
'bind to repeater
rpJS.DataSource = dtrIndicators2
rpJS.DataBind()
'close connections
dtrIndicators2.Close()
conG2.Close()
Comment
Watch Question

CERTIFIED EXPERT
Commented:

Not the solution you were looking for? Getting a personalized solution is easy.

Ask the Experts
Carl TawnSenior Systems and Integration Developer
CERTIFIED EXPERT
Commented:
SqlConnection conG2;
SqlCommand cmdSelect2;
SqlDataReader dtrIndicators2

// retrieve records from db
conG2 = new SqlConnection("Server=MyServer;UID=MyUID;PWD=MyPWDs;DataBase=MyDB");
cmdSelect2 = new SqlCommand("SELECT * FROM MyTable", conG2);
conG2.Open();

dtrIndicators2 = cmdSelect2.ExecuteReader();

// bind to repeater
rpJS.DataSource = dtrIndicators2
rpJS.DataBind();

// close connections
dtrIndicators2.Close();
conG2.Close();

Not really that different :o)

Hope this helps.
CERTIFIED EXPERT

Commented:
SqlConnection conG2;
SqlCommand cmdSelect2;
SqlDataReader dtrIndicators2;
conG2 = new SqlConnection("Server=MyServer;UID=MyUID;PWD=MyPWDs;Database=MyDB");
cmdSelect2 = new SqlCommand("Select * from MyTable", conG2);
conG2.Open();
dtrIndicators2 = cmdSelect2.ExecuteReader;
rpJS.DataSource = dtrIndicators2;
rpJS.DataBind();
dtrIndicators2.Close();
conG2.Close();
Carl TawnSenior Systems and Integration Developer
CERTIFIED EXPERT

Commented:
How close was that :o)
CERTIFIED EXPERT

Commented:
jinx
CERTIFIED EXPERT

Commented:
haha :)

Author

Commented:
using System.Data.SqlClient;


SqlConnection conG2;
SqlCommand cmdSelect2;
SqlDataReader dtrIndicators2;
conG2 = new SqlConnection("Server=MyServer;UID=MyUID;PWD=MyPWDs;Database=MyDB");
cmdSelect2 = new SqlCommand("Select * from MyTable", conG2);
conG2.Open();
dtrIndicators2 = cmdSelect2.ExecuteReader; //error here
rpJS.DataSource = dtrIndicators2;
rpJS.DataBind();
dtrIndicators2.Close();
conG2.Close();

Error: Cannot convert method group 'ExecuteReader' to non-delegate type 'System.Data.SqlClient.SqlDataReader'. Did you intend to invoke the method?

?

Author

Commented:
this is VS 2005 2.0
CERTIFIED EXPERT
Commented:
public SqlDataReader CreateMySqlDataReader(string mySelectQuery,string myConnectionString)
{
   SqlConnection myConnection = new SqlConnection(myConnectionString);
   SqlCommand myCommand = new SqlCommand(mySelectQuery, myConnection);
   myConnection.Open();
   SqlDataReader myReader = myCommand.ExecuteReader(CommandBehavior.CloseConnection);
   return myReader
}


SqlConnection conG2;
SqlCommand cmdSelect2;
SqlDataReader dtrIndicators2;
conG2 = new SqlConnection("Server=MyServer;UID=MyUID;PWD=MyPWDs;Database=MyDB");
cmdSelect2 = new SqlCommand("Select * from MyTable", conG2);
conG2.Open();
dtrIndicators2 = CreateMySqlDataReader(jjjjjjj
rpJS.DataSource = dtrIndicators2;
rpJS.DataBind();
dtrIndicators2.Close();
conG2.Close();

Author

Commented:
dtrIndicators2 = CreateMySqlDataReader(jjjjjjj

?
CERTIFIED EXPERT

Commented:
jjjjjjj fill out the parameters

Author

Commented:
like?

dtrIndicators2 = CreateMySqlDataReader("Select * from MyTable", "Server=MyServer;UID=MyUID;PWD=MyPWDs;Database=MyDB");
CERTIFIED EXPERT

Commented:
yep

Author

Commented:
I'm trying to connect this to the following and get the error below:

<asp:Repeater id="rpJS" runat="server" EnableViewState="False">
  <ItemTemplate>
    document.getElementById('<%# Container.DataItem("IName")%>').style.display="none";  // collapse
  </ItemTemplate>
</asp:Repeater>


Error:      'System.Web.UI.WebControls.RepeaterItem.DataItem' is a 'property' but is used like a 'method'

CERTIFIED EXPERT

Commented:
its something you set not call

Commented:
You guys really should use the using statement to ensure proper closing of the unmanaged resources. Here's how I'd rewrite that code:


// retrieve records from db
using( SqlConnection conG2 = new SqlConnection("Server=MyServer;UID=MyUID;PWD=MyPWDs;Database=MyDB") )
{
      using( SqlCommand cmdSelect2 = new SqlCommand("Select * from MyTable", conG2) )
      {
            using( SqlDataReader dtrIndicators2 = cmdSelect2.ExecuteReader() )
            {
                  // bind to repeater
                  rpJS.DataSource = dtrIndicators2
                  rpJS.DataBind()
            }
      }
}
Carl TawnSenior Systems and Integration Developer
CERTIFIED EXPERT

Commented:
Well....there are differing trains of thought about whether or not to use the "using" block, but its certainly an option.

Commented:
As far as your other question, about the binding in the ASPX to the repeater, here's what you should do instead:

<asp:Repeater id="rpJS" runat="server" EnableViewState="False">
  <ItemTemplate>
    document.getElementById('<%# DataBinder.Eval(Container.DataItem, "IName") %>').style.display="none";  // collapse
  </ItemTemplate>
</asp:Repeater>

But what is IName anyhow?

If you need to reference any "runat='server'" controls from client Javascript, you should use their ClientID property. For example:

document.getElementById('<%= YourASPNETControl.ClientID %>').style.display = "none"; // collapse

Commented:
"Well....there are differing trains of thought about whether or not to use the "using" block, but its certainly an option."

Huh? What different thought is there?

You should ALWAYS use using() unless you need to return an unmanaged resource from the function. And even then, you probably should look into a different way. Rather than returning a live data reader from a method, consider passing in a delegate that uses the reader, or have the method return a managed data object populated with the relevant data from the reader.

I'd be interested in hearing an argument why you shouldn't use using(). I'd be surprised if there were any valid ones.

At any rate, doing this:

con.Open()
// do some stuff
con.Close()

is VERY DANGEROUS because what if "do some stuff" throws an exception?!!!

Now your connection is left open until the GC gets around to cleaning it up (which could be minutes).

In a live web application that's being pounded, your connection pool will get zapped in a few seconds and then you have REAL problems.

Commented:
I forgot something in my code example. I never opened the SqlConnection!

Also, you can stack usings, so the code might be a little cleaner if you did this:

// retrieve records from db
using( SqlConnection conG2 = new SqlConnection("Server=MyServer;UID=MyUID;PWD=MyPWDs;Database=MyDB") )
{
     conG2.Open();

     using( SqlCommand cmdSelect2 = new SqlCommand("Select * from MyTable", conG2) )
     using( SqlDataReader dtrIndicators2 = cmdSelect2.ExecuteReader() )
     {
          // bind to repeater
          rpJS.DataSource = dtrIndicators2
          rpJS.DataBind()
      }
}

Commented:
just my 2 cents for c_myers

what about using try-catch-finally - it's not any worse or better than using and the level of indentation can be less then for using, hence the readability is better...

and for the discussion:

<%# DataBinder.Eval( Container.DataItem, "column_name" ) %>

this way the style is ignored.

you can't do DataItem( "whatever" ) since DataItem IS a member (variable) and () are used for method (functions).

good luck,
yurich

Commented:
try/catch/finally is better readability than using(){}? How so? Then you have even more {}'s and levels of indentation. That makes no sense.

Commented:
hmm... what do you mean by levels?? it's only two levels:

try
{
  // one indentation
}
catch
{
  // still the same indentation
}
finally
{
  // and again the same indentation
}

using( connection )
{
  using( command )
  {
     using( data reader )
     {
        // see the difference??
     }
  }
}

and you may want to use several command and re-use data readers, so it will add even more jumping right and left.

but that's completely subjective - just don't be categorical, if you like cucumbers more, it doesn't mean they're better from tomatos.

regards,
yurich

Commented:
FYI, using(){} writes out a try/finally block in the IL. So you can do a try/finally block, but it's just more code, and if you don't do it write, you could make matters worse.

The C# team put the using(){} block there for a reason (to ENSURE that all IDisposable instances get properly freed).

Commented:
yurich:

1.) You can stack usings(), so that essentially negates your argument
2.) In your example, the finally block would be very complicated (because, how would you know which things you needed to dispose?).

You mentioned "You might want to use several commands and re-use data readers".
Using the try/finally block, like you suggested, here's how the code would look:

SqlConnection sqlCon;
SqlCommand sqlCmd1;
SqlCommand sqlCmd2;
SqlCommand sqlCmd3;
SqlDataReader rdr;

try
{
    sqlCon = new SqlConnection(...);
    sqlCon.Open();

    sqlCmd1 = new SqlCommand( ... , sqlCon );  
    rdr = sqlCmd1.ExecuteReader();
    // ... reader code here, same whether you're using using() or not  
    rdr.Close();

    sqlCmd2 = new SqlCommand( ..., sqlCon );
    rdr = sqlCmd2.ExecuteReader();
    // ... reader code here, same whether you're using using() or not  
    rdr.Close();

    sqlCmd3 = new SqlCommand( ..., sqlCon );
    rdr = sqlCmd3.ExecuteReader();
    // ... reader code here, same whether you're using using() or not  
    rdr.Close();

}
finally
{
    // now it gets ugly -- NOTE: Use .NET Reflector to see the generated IL from a using(){} statement, it looks almost just like this
    if( rdr != null )
        try{ ((IDisposable)rdr).Dispose(); }catch{}

    if( sqlCmd3 != null )
        try{ ((IDisposable)sqlCmd3).Dispose(); }catch{}

    if( sqlCmd2 != null )
        try{ ((IDisposable)sqlCmd2).Dispose(); }catch{}

    if( sqlCmd1 != null )
       try{ ((IDisposable)sqlCmd1).Dispose(); }catch{}

    if( sqlCon != null )
       try{ ((IDisposable)sqlCon).Dispose(); }catch{}      
}

Now, the same code using 'using':

//////////////////////////////////////////////////////////////////////////////////////////

using( SqlConnection sqlCon = new SqlConnection(...) )
{
    sqlCon.Open();

    using( SqlCommand sqlCmd1 = new SqlCommand(..., sqlCon ) )
    using( SqlCommand sqlCmd2 = new SqlCommand(..., sqlCon ) )
    using( SqlCommand sqlCmd3 = new SqlCommand(..., sqlCon ) )
    {
         using( SqlDataReader rdr = sqlCmd1.ExecuteReader() )
         {
            // ... reader code here, same whether you're using using() or not  
         }
         using( SqlDataReader rdr = sqlCmd2.ExecuteReader() )
         {
            // ... reader code here, same whether you're using using() or not  
         }
         using( SqlDataReader rdr = sqlCmd3.ExecuteReader() )
         {
            // ... reader code here, same whether you're using using() or not  
         }
    }  
}

I dunno, yeah there are more levels of indentation (kind of), but the code is much cleaner, also you don't have to worry about how or whether things got disposed-of properly because you can be GUARANTEED by the using(){} statement.

Commented:
as I said - whatever makes you happy... for me, try-catch-finally is more convinient - i never tried to convince you that one or another is better and I know how it's interpreted into IL, just your statement about different thoughts - of course there can be different thoughts and that's what I showed.

and FYI, you were quite biased creating "my side" of the code - Why would you ever have try in finally?? why do you need to use dispose?? it can be done a lot easier and nicer. You would never have more than one data reader as it one way only, so in my case it would always one reader and dreader.Close() at the end and in yours a whole set of using for each data reader invokation. I would continue on a few points but it doesn make sense - if you like using, just use it, but don't say there is no alternative.

regs,
yurich

Commented:
*** My argument is that the differing thoughts, so far, are wrong -- they do not lead to more robust code, they are, generally, not more readible (and thus maintainable)...

*** Why would you do try/finally? Because you don't want to intercept the exception (you wish the exception to bubble up), but you still MUST release the UNMANAGED resources.

As a general rule, handle/catch exceptions where you can do something with them. In the middle of data-access logic is generally NOT a good place to be catching exceptions. Therefore, you'd use try/finally to handle closing the connections, readers, etc.

And if you're doing to do a try/finally... why not just do a using(){}? It's more readible, it's more reliable, and it's well-tested where as your/mine/whoever's finally{} code isn't likely to be as well-tested (since we don't have the army of test engineers MSFT does! :) )

*** Why do I use Dispose()? Because that's what the using(){} pattern does and I was trying to simulate what the best-practice is.

*** "if you like using, just use it, but don't say there is no alternative." -- I'm not saying there is no alternative, I'm just saying there are FEW GOOD alternatives and you should ONLY be using those alternatives under VERY SPECIFIC circumstances.

So far, no one has made a compelling argument for NOT using using(){} except as a matter of personal preference. No offense, but making code/design decisions based on "personal perference" -- ESPECIALLY in the face of better wisdom, more robust code, generally accepted practices, recommendations FROM THE COMPILER WRITERS THEMSELVES -- makes no sense whatsoever unless your goal is to write code that looks good to you and not WHAT WORKS THE BEST (most of the time, under almost every circumstance).

Access more of Experts Exchange with a free account
Thanks for using Experts Exchange.

Create a free account to continue.

Limited access with a free account allows you to:

  • View three pieces of content (articles, solutions, posts, and videos)
  • Ask the experts questions (counted toward content limit)
  • Customize your dashboard and profile

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

OR

Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.