Link to home
Start Free TrialLog in
Avatar of passion420
passion420

asked on

Error in the C# Code, unable to convert dbconnection to sqlconnection

I am getting error in the code specified below:

Compiler Error Message: CS0266: Cannot implicitly convert type 'System.Data.Common.DbConnection' to 'System.Data.SqlClient.SqlConnection'. An explicit conversion exists (are you missing a cast?)

Source Error:

 

Line 106:            SqlConnection conn = new SqlConnection();
Line 107:
Line 108:            conn = f.CreateConnection();--------error here
Line 109:
Line 110:            conn.ConnectionString = s.ConnectionString;
 

public static string GetConn(string strConn)
        {
 
            System.Configuration.ConnectionStringSettings s = System.Configuration.ConfigurationManager.ConnectionStrings[strConn];
 
 
            System.Data.Common.DbProviderFactory f = System.Data.Common.DbProviderFactories.GetFactory(s.ProviderName);
 
 
            SqlConnection conn = new SqlConnection();
 
            conn = f.CreateConnection();
 
            conn.ConnectionString = s.ConnectionString;
 
            GetConn = conn.ConnectionString;
 
        }

Open in new window

codefile.txt
Avatar of MoreHeroic
MoreHeroic

I know it sounds silly, but have you tried:

public static string GetConn(string strConn)
        {
 
            System.Configuration.ConnectionStringSettings s = System.Configuration.ConfigurationManager.ConnectionStrings[strConn];
 
 
            System.Data.Common.DbProviderFactory f = System.Data.Common.DbProviderFactories.GetFactory(s.ProviderName);
 
 
            SqlConnection conn = new SqlConnection();
 
            conn = (System.Data.SqlClient.SqlConnection)f.CreateConnection();
 
            conn.ConnectionString = s.ConnectionString;
 
            GetConn = conn.ConnectionString;
 
        }
Avatar of passion420

ASKER

Getting new erro now :(, when I am using the above method :

Compiler Error Message: CS1656: Cannot assign to 'GetConn' because it is a 'method group'

Source Error:
Line 110:            conn.ConnectionString = s.ConnectionString;
Line 111:
Line 112:            GetConn = conn.ConnectionString;  ---------error here
Line 113:
Line 114:        }
 
Hi

Can you please put a break point at line 7 and post the value of s.ProviderName.

Most of all I think the error is caused by the value of s.ProviderName specifying something other than SqlClient.
Hi there,

Try this:

 public static string GetConn(string strConn)
    {
        System.Configuration.ConnectionStringSettings s = System.Configuration.ConfigurationManager.ConnectionStrings[strConn];
        System.Data.Common.DbProviderFactory f = System.Data.Common.DbProviderFactories.GetFactory(s.ProviderName);
        SqlConnection conn = new SqlConnection();
        conn = (SqlConnection)f.CreateConnection();
        conn.ConnectionString = s.ConnectionString;
        Return conn.ConnectionString; // Here your line GetConn = 
//conn.ConnectionString; is not going to work, is not a valid         // declaration. What exactly do you want to return in the function?
 
 
  }

Open in new window

Hi Juan_Barrera: Still getting the error when I use the above suggested method by you, it says ; is expected at return con.connectionstring;

All I want is to convert this VB.net code into C# code, please if somebody can help me its really urgent  and see where am i going wrong? Attached Below is the vb.net code I am trying to convert into c# and I am getting error in there in one of the function




Imports System.Web
Imports System.Data
Imports System.Data.SqlClient
 
 
Namespace EHSServiceCenter
 
    Public Class LogonUser
        Inherits System.Web.UI.Page
 
        Protected WithEvents SqlConnection1 As System.Data.SqlClient.SqlConnection
 
        Public Function ValidateUser() As Boolean
            ValidateUser = True
            CheckUser()
            Dim count As Integer = 0
            Dim strSQL As String
            Dim strConnection As String = GetConn("aid0540ConnectionString")
            Dim objConnection As New System.Data.SqlClient.SqlConnection(strConnection)
            strSQL = "Select * FROM dbo.tblUsers WHERE Delete_flag='n'"
            Dim myCommand As New SqlCommand(strSQL, objConnection)
            Dim objReader As SqlDataReader
            objConnection.Open()
            ' Retrieve dataset
            objReader = myCommand.ExecuteReader
            ' loop while we have data
            Do While objReader.Read
                If UCase(Trim(objReader("LANID").ToString)) = UCase(Trim(Session("LOGON_USER"))) Then
                    count = 1
                    Session("UserRole") = objReader("UserRole")
                End If
            Loop
            If count > 0 Then
                ValidateUser = True
            Else
                ValidateUser = False
            End If
            objConnection.Close()
            objReader.Close()
        End Function
 
        Public Shared Function GetConn(ByVal strConn As String) As String
            Dim conn As SqlConnection = Nothing
            Dim s As ConnectionStringSettings = ConfigurationManager.ConnectionStrings(strConn)
            Dim f As SqlClientFactory = Common.DbProviderFactories.GetFactory(s.ProviderName)
            conn = f.CreateConnection
            conn.ConnectionString = s.ConnectionString
            GetConn = conn.ConnectionString
            'GetConn = System.Configuration.ConfigurationManager.AppSettings.Get(strConn)
        End Function
 
        Function CheckUser()
            ' Check to see if the session variable is already populated.
            If Session("LOGON_USER") = "" Then
                ' Check to see if the user has logged on at all.
                If HttpContext.Current.Request.ServerVariables("LOGON_USER") = "" Then
                    ' Force authentication if not.
                    HttpContext.Current.Response.Clear()
                    HttpContext.Current.Response.Status = "401 Access Denied"
                    HttpContext.Current.Response.End()
                Else
                    ' Store the client's user name in a session variable.
                    Session("LOGON_USER") = HttpContext.Current.Request.ServerVariables("LOGON_USER")
                    ' Strip out an NT domain from the user name.
                    If InStr(Session("LOGON_USER"), "\") Then
                        Session("LOGON_USER") = Mid(Session("LOGON_USER"), InStr(Session("LOGON_USER"), "\") + 1)
                    End If
                End If
            End If
            Return Session("LOGON_USER")
        End Function
 
    End Class
 
End Namespace

Open in new window

Hi Juan_Barrera: Still getting the error when I use the above suggested method by you, it says ; is expected at return con.connectionstring;

All I want is to convert this VB.net code into C# code, please if somebody can help me its really urgent  and see where am i going wrong? Attached Below is the vb.net code I am trying to convert into c# and I am getting error in there in one of the function


Imports System.Web
Imports System.Data
Imports System.Data.SqlClient
 
 
Namespace EHSServiceCenter
 
    Public Class LogonUser
        Inherits System.Web.UI.Page
 
        Protected WithEvents SqlConnection1 As System.Data.SqlClient.SqlConnection
 
        Public Function ValidateUser() As Boolean
            ValidateUser = True
            CheckUser()
            Dim count As Integer = 0
            Dim strSQL As String
            Dim strConnection As String = GetConn("aid0540ConnectionString")
            Dim objConnection As New System.Data.SqlClient.SqlConnection(strConnection)
            strSQL = "Select * FROM dbo.tblUsers WHERE Delete_flag='n'"
            Dim myCommand As New SqlCommand(strSQL, objConnection)
            Dim objReader As SqlDataReader
            objConnection.Open()
            ' Retrieve dataset
            objReader = myCommand.ExecuteReader
            ' loop while we have data
            Do While objReader.Read
                If UCase(Trim(objReader("LANID").ToString)) = UCase(Trim(Session("LOGON_USER"))) Then
                    count = 1
                    Session("UserRole") = objReader("UserRole")
                End If
            Loop
            If count > 0 Then
                ValidateUser = True
            Else
                ValidateUser = False
            End If
            objConnection.Close()
            objReader.Close()
        End Function
 
        Public Shared Function GetConn(ByVal strConn As String) As String
            Dim conn As SqlConnection = Nothing
            Dim s As ConnectionStringSettings = ConfigurationManager.ConnectionStrings(strConn)
            Dim f As SqlClientFactory = Common.DbProviderFactories.GetFactory(s.ProviderName)
            conn = f.CreateConnection
            conn.ConnectionString = s.ConnectionString
            GetConn = conn.ConnectionString
            'GetConn = System.Configuration.ConfigurationManager.AppSettings.Get(strConn)
        End Function
 
        Function CheckUser()
            ' Check to see if the session variable is already populated.
            If Session("LOGON_USER") = "" Then
                ' Check to see if the user has logged on at all.
                If HttpContext.Current.Request.ServerVariables("LOGON_USER") = "" Then
                    ' Force authentication if not.
                    HttpContext.Current.Response.Clear()
                    HttpContext.Current.Response.Status = "401 Access Denied"
                    HttpContext.Current.Response.End()
                Else
                    ' Store the client's user name in a session variable.
                    Session("LOGON_USER") = HttpContext.Current.Request.ServerVariables("LOGON_USER")
                    ' Strip out an NT domain from the user name.
                    If InStr(Session("LOGON_USER"), "\") Then
                        Session("LOGON_USER") = Mid(Session("LOGON_USER"), InStr(Session("LOGON_USER"), "\") + 1)
                    End If
                End If
            End If
            Return Session("LOGON_USER")
        End Function
 
    End Class
 
End Namespace
 

Open in new window


using System.Web;
using System.Data;
using System.Data.SqlClient;
 
 
namespace EHSServiceCenter
{
 
    public class LogonUser : System.Web.UI.Page
    {
 
        protected System.Data.SqlClient.SqlConnection SqlConnection1;
 
        public bool ValidateUser()
        {
            CheckUser();
            int count = 0;
            string strSQL = null;
            string strConnection = System.Configuration.ConfigurationManager.ConnectionStrings["aid0540ConnectionString"].ConnectionString;
            using (System.Data.SqlClient.SqlConnection objConnection = new System.Data.SqlClient.SqlConnection(strConnection))
            {
                strSQL = "Select * FROM dbo.tblUsers WHERE Delete_flag='n'";
                using (SqlCommand myCommand = new SqlCommand(strSQL, objConnection))
                {
                    objConnection.Open();
                    // Retrieve dataset
                    using (SqlDataReader objReader = myCommand.ExecuteReader)
                    {
                        // loop while we have data
                        while (objReader.Read)
                        {
                            if (Strings.UCase(Strings.Trim(objReader("LANID").ToString)) == Strings.UCase(Strings.Trim(Session("LOGON_USER"))))
                            {
                                count = 1;
                                Session("UserRole") = objReader("UserRole");
                            }
                        }
                    }
                    if (count > 0)
                    {
                        return true;
                    }
                    else
                    {
                        return false;
 
                    }
                }
            }
        }
 
    
        public string CheckUser()
        {
            // Check to see if the session variable is already populated.
            if (string.IsNullOrEmpty(Session("LOGON_USER")))
            {
                // Check to see if the user has logged on at all.
                if (string.IsNullOrEmpty(HttpContext.Current.Request.ServerVariables("LOGON_USER")))
                {
                    // Force authentication if not.
                    HttpContext.Current.Response.Clear();
                    HttpContext.Current.Response.Status = "401 Access Denied";
                    HttpContext.Current.Response.End();
                }
                else
                {
                    // Store the client's user name in a session variable.
                    Session("LOGON_USER") = HttpContext.Current.Request.ServerVariables("LOGON_USER");
                    // Strip out an NT domain from the user name.
                    if (string.InStr(Session("LOGON_USER"), "\\"))
                    {
                        Session("LOGON_USER") = Strings.Mid(Session("LOGON_USER"), Strings.InStr(Session("LOGON_USER"), "\\") + 1);
                    }
                }
            }
            return Session("LOGON_USER").ToString();
        }
    }
 
}

Open in new window

Hi Juan_Barrera:
I am Getting Error : after using the above code. Error is attached below

Also  if (Strings.UCase(Strings.Trim(objReader("LANID").ToString)) == Strings.UCase(Strings.Trim(Session("LOGON_USER"))))
                 
I think that should be :

  if (objReader["LANID"] == Session["LOGON_USER"])     ??  I have used the same line of code before and it says strings.ucase........is not reconginzed.







Compiler Error Message: CS0428: Cannot convert method group 'ExecuteReader' to non-delegate type 'System.Data.SqlClient.SqlDataReader'. Did you intend to invoke the method?
 
Source Error:
 
 
 
Line 37:                     objConnection.Open();
Line 38:                     // Retrieve dataset
Line 39:                     using (SqlDataReader objReader = myCommand.ExecuteReader)
Line 40:                     {
Line 41:                         // loop while we have data
 

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of Juan_Barrera
Juan_Barrera
Flag of New Zealand image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Ok . I oet two errors now:

Object reference not set to an instance of an object.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.

Source Error:


Line 95:             }
Line 96:            
Line 97:             return Session["LOGON_USER"].ToString();
Line 98:         }
Line 99:     }
 


-----And if I solve it somehow to proceed, I get next error pasted below, Oh God its killing me now :(

Also I used this code inplace of :
if (string.InStr(Session["LOGON_USER"], "\\"))
                    {
                        Session["LOGON_USER"] = string.Mid(Session["LOGON_USER"], string.InStr[Session["LOGON_USER"], "\\") ++ 1);
                    }


as

  if (s.IndexOf("\\") != -1)
                    {
                        Session["LOGON_USER"] = (s.Substring(7, s.IndexOf("\\") + 1));

                    }


so this portion is working fine. Ned to remove these 2 errors now
Object reference not set to an instance of an object. 
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code. 
 
Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.
 
Source Error: 
 
 
Line 30:             int count = 0;
Line 31:             string strSQL = null;
Line 32:             string strConnection = System.Configuration.ConfigurationManager.ConnectionStrings["aid0540ConnectionString"].ConnectionString;-------error here
Line 33:             using (System.Data.SqlClient.SqlConnection objConnection = new System.Data.SqlClient.SqlConnection(strConnection))
Line 34:             {
 

Open in new window