0

I created a class for connection and using with register.aspx without any problem. When i try to move codes from register.aspx.cs to regpartial.cs then i get an conflict error: "connection conn = new connection();"

I would like to move codes register.aspx.cs to mypartial.cs. I think it will be better but i'm not sure how can i solve conflict problem.

Register.aspx.cs (final)

using System;
using System.Data;
using System.Data.SqlClient;
using System.Collections.Generic;
using System.Web.UI;
using System.Web.UI.WebControls;
using test.App_Code;


namespace test
{   
    public partial class register: System.Web.UI.Page
    {
        private void Page_Load(object sender, EventArgs e)
        {

        }

Connection.cs (final try)

using System;
using System.Data;
using System.Data.SqlClient;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI.WebControls;

namespace test.App_Code
{
    public class connection
    {

        public SqlConnection connect()
        {
            SqlConnection conn= new SqlConnection("Data Source=******;Initial Catalog=****;Integrated Security=False;User Id=****;Password=*****;MultipleActiveResultSets=True");
            baglanti.Open();
            return (conn);
        }
}

regpartial.cs (Final try)

using System;
using System.Data;
using System.Data.SqlClient;
using System.Collections.Generic;
using System.Web.UI;
using System.Web.UI.WebControls;


namespace test.App_Code.partials
{
    connection conn = new connection();
    public partial class regpartial : register
    {

    }
}
Cagatay
  • 333
  • 1
  • 3
  • 13
  • Why do you think you need a partial class in the first place? – mason Jan 28 '16 at 17:35
  • connection is outside class – csharpfolk Jan 28 '16 at 17:38
  • yes, that is the idea (connection is outside class) i am using on every aspx page but didn't use on partialclass. There is a lot of code in register and other pages and that is why i would like to move page's codes to partial classes. – Cagatay Jan 28 '16 at 18:11
  • C# does not allow you to declare members outside of a class. And there's no need for a partial. Perhaps it would work best if you told us what you're trying to accomplish rather than how you're trying to accomplish it. Are you trying to create a data layer responsible for pulling information from a database? – mason Jan 28 '16 at 18:12
  • You should also **never** be using a string literal for a connection string. You should be using connection strings configuration https://www.connectionstrings.com/store-connection-string-in-webconfig/ – Chris Marisic Jan 28 '16 at 18:12
  • 1
    @ChrisMarisic i would like to learn about somehing. If you have a lot lof code in aspx.cs file, what do you do? I am trying to know, if we can move codes to the class and use it from there, that can help us. There is a lot of controls on aspx file and click events in *.cs file too. I see also click events works in partial class. Do you have any idea? How can we seperate codes like that? Thanks for information about connection. – Cagatay Jan 28 '16 at 18:29
  • 1
    If you have a lot of code in a single class, making it a partial class is *not* the correct solution. Instead, you should refactor the code so that it's only doing what it needs to do. It's normal to have all your events handled in your `.aspx.cs` class for example, but it's not normal to do data access or calculations in your `.aspx.cs`. You would create new classes that can encapsulate that logic into reusable components. A good rule of thumb is if you're using anything from `System.Data.SqlClient` in your code behind (.aspx.cs) then you're doing it wrong. – mason Jan 28 '16 at 18:32
  • @Cagatay wanting to learn is the number one thing that matters. – Chris Marisic Jan 28 '16 at 18:57

1 Answers1

1

In general you shouldn't have much code inside your aspx.cs files.

You want to separate the logic that is directly your view/presentation logic (stuff that makes the .aspx pages work) from your business logic (sequencing, transformation, validation), and finally you want to have your Data Access / Resource Access to be isolated.

I'd also recommend using Dapper.NET over raw ADO.NET/SqlConnection.

I'm going to string together a very basic example of how you can separate this. This is not guaranteed to compile c# code but it will very close pseudocode.

Inside registration.aspx.cs

private void btnRegister_Click(object sender, EventArgs e)
{
    var email = txtEmail.Text;
    var password = txtPassword.Text;

    var registration = new Registration { Email = email, Password = password }

    var bizService = new RegistrationService();

    var response = bizService.Register(registration);

    if(response.Success) Response.Redirect("~/registration/success");

    ltlError.Text = response.FailureMessage;

}

RegistrationService.cs

public class RegistrationService {

    public RegistrationResponse Register(Registration req)
    {
        var regDAL = new RegistrationAccess();

        var isEmailDuplicated = regDal.DoesEmailExist(req.Email)

        if(isEmailDuplicated) 
              return new RegistrationResponse { 
                    Success = false,
                    FailureMessage = "Email exists, did you mean to login instead? 
                }

        regDAL.InsertNewRegistration(req)

        return new RegistrationResponse { Success = true };   
    }
}

Lastly you should have a RegistrationAccess.cs that contains only code for reading and writing to SQL Server / other database / file system.

Note how the aspx.cs file has no knowledge of RegistrationAccess. Your view should not be directly calling the database. The other thing to note is that RegistrationService has no knowledge of the view. It receives a Registration type, then executes business logic and calls out to the DAL. The DAL class will have zero knowledge of both the view and the RegistrationService, it will know only one thing, the database.

This is the basis of a very simple ASP.NET webforms solution. A better solution would use the MVP/MVVM patterns and the Dependency Inversion Principle but those aren't worth using if you don't understand basic separation of concerns yet.

Chris Marisic
  • 32,487
  • 24
  • 164
  • 258