[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 708
  • Last Modified:

convert vb.net code to c# code

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()
0
fwsteal
Asked:
fwsteal
  • 8
  • 8
  • 5
  • +2
3 Solutions
 
Carl TawnSystems and Integration DeveloperCommented:
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.
0
 
Mikal613Commented:
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();
0
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
Carl TawnSystems and Integration DeveloperCommented:
How close was that :o)
0
 
Mikal613Commented:
jinx
0
 
Mikal613Commented:
haha :)
0
 
fwstealAuthor 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?

?
0
 
fwstealAuthor Commented:
this is VS 2005 2.0
0
 
Mikal613Commented:
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();
0
 
fwstealAuthor Commented:
dtrIndicators2 = CreateMySqlDataReader(jjjjjjj

?
0
 
Mikal613Commented:
jjjjjjj fill out the parameters
0
 
fwstealAuthor Commented:
like?

dtrIndicators2 = CreateMySqlDataReader("Select * from MyTable", "Server=MyServer;UID=MyUID;PWD=MyPWDs;Database=MyDB");
0
 
Mikal613Commented:
yep
0
 
fwstealAuthor 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'

0
 
Mikal613Commented:
its something you set not call
0
 
c_myersCommented:
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()
            }
      }
}
0
 
Carl TawnSystems and Integration DeveloperCommented:
Well....there are differing trains of thought about whether or not to use the "using" block, but its certainly an option.
0
 
c_myersCommented:
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
0
 
c_myersCommented:
"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.
0
 
c_myersCommented:
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()
      }
}

0
 
YurichCommented:
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
0
 
c_myersCommented:
try/catch/finally is better readability than using(){}? How so? Then you have even more {}'s and levels of indentation. That makes no sense.

0
 
YurichCommented:
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

0
 
c_myersCommented:
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).
0
 
c_myersCommented:
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.
0
 
YurichCommented:
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
0
 
c_myersCommented:
*** 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).

0

Featured Post

Prep for the ITIL® Foundation Certification Exam

December’s Course of the Month is now available! Enroll to learn ITIL® Foundation best practices for delivering IT services effectively and efficiently.

  • 8
  • 8
  • 5
  • +2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now