What's new

C# C# Maui .net

caparadc

Honorary Poster
Established
Joined
Oct 16, 2016
Posts
241
Solutions
1
Reaction
257
Points
187
Hello, sinubukan kopo pag aralan at gumawa po ng mobile app sa Maui .net with Mongodb pero tama naman po yung connectionString ko pero ito po yung error ano po kaya yung error dito? [DOTNET] Error during admin insertion: The list of configured name servers must not be empty. (Parameter 'servers')

this is my DBConnection class


Code:
public class DBConnection
    {
        private IMongoDatabase _database;

        public DBConnection()
        {
            try
            {
               
                var mongoClient = new MongoClient("mongodb+srv://<username>:<password>@cluster0.4jhaesp.mongodb.net/?retryWrites=true&w=majority");

                _database = mongoClient.GetDatabase("homefinder");
                Console.WriteLine("Connection to the database is successful.");
            }
            catch (MongoException ex)
            {
                Console.WriteLine($"Error during database connection: {ex.Message}");
                throw;
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Unexpected error during database connection: {ex}");
                throw;
            }
        }

        public IMongoDatabase GetDatabase()
        {
            if (_database == null)
            {
                throw new InvalidOperationException("Database is not initialized. Make sure DBConnection constructor is called successfully.");
            }

            return _database;
        }
    }

this is my SignupViewModel


Code:
public class Admins
    {
        [BsonId]
        public ObjectId Id { get; set; }
        public string Fullname { get; set; }
        public string Username { get; set; }
        public string PasswordHash { get; set; }
        public string Role { get;set; }
    }

public class SignupViewModel : BindableObject
    {
        private string _fullname;
        private string _username;
        private string _password;
        private string _selectedRole;

        public string Fullname
        {
            get => _fullname;
            set
            {
                _fullname = value;
                OnPropertyChanged(nameof(Fullname));
            }
        }

        public string Username
        {
            get => _username;
            set
            {
                _username = value;
                OnPropertyChanged(nameof(Username));
            }
        }

        public string Password
        {
            get => _password;
            set
            {
                _password = value;
                OnPropertyChanged(nameof(Password));
            }
        }

        public string SelectedRole
        {
            get => _selectedRole;
            set
            {
                _selectedRole = value;
                OnPropertyChanged(nameof(SelectedRole));
            }
        }

        private async Task Signup(string password)
        {
            try
            {
                if (string.IsNullOrWhiteSpace(Fullname) || string.IsNullOrWhiteSpace(Username) || string.IsNullOrWhiteSpace(Password))
                {
                    Console.WriteLine("Please fill in all required fields.");
                    return;
                }

                var hashedPassword = BCrypt.Net.BCrypt.HashPassword(Password);

                var admin = new Admins
                {
                    Fullname = Fullname,
                    Username = Username,
                    PasswordHash = hashedPassword,
                    Role = SelectedRole
                };

                await InsertAdminAsync(admin);

                await App.Current.MainPage.Navigation.PushAsync(new MainPage());
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error during signup: {ex.Message}");
            }
        }

        private async Task InsertAdminAsync(Admins admin)
        {
            try
            {
                var dbConnection = new DBConnection();
                var database = dbConnection.GetDatabase();
                var adminsCollection = database.GetCollection<Admins>("admins");

                await adminsCollection.InsertOneAsync(admin);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error during admin insertion: {ex.Message}");
            }
            
        }
        

    public Command<string> SignupCommand => new Command<string>(async (password) => await Signup(password));
    }


Code:
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             xmlns:local="clr-namespace:homefinderpro.ViewModels"
             x:Class="homefinderpro.Page.SignupPage"
             Title="SignupPage">

    


    <StackLayout Background="#4F59DE" Padding="30">
        <Label Text="SIGN UP" 
               TextColor="White" FontFamily="Poppins-Bold" FontSize="30"
               HorizontalOptions="Center" />

        <Frame BackgroundColor="White" Padding="20" CornerRadius="10">
            <StackLayout>
                <Entry x:Name="FullnameEntry" Placeholder="Full Name" Text="{Binding Fullname}" />
                <Entry x:Name="UsernameEntry" Placeholder="Username" Text="{Binding Username}" />
                <Entry x:Name="PasswordEntry" Placeholder="Password" IsPassword="True" Text="{Binding Password}"/>

                <Picker x:Name="RolePicker" Title="Select Role" SelectedItem="{Binding SelectedRole, Mode=TwoWay}"/>
                        
                <Button Text="SIGN UP"
                        Background="Orange" TextColor="White"
                        Command="{Binding SignupCommand}"/>
            </StackLayout>
        </Frame>

        <Button Text="Already have an account? Login"
                BackgroundColor="Orange" TextColor="White"
                Margin="0,20,0,0"/>
    </StackLayout>
</ContentPage>

sinubukan kona po idebug pero ayaw parin mag mag store ng data saking mongodb database
 
The error message you provided suggests that there is an issue with the list of configured name servers in your MongoDB connection string. However, upon reviewing your code, it seems that you haven't specified the connection string correctly.

In your DBConnection class, you have the following line of code:

C#:
var mongoClient = new MongoClient("mongodb+srv://<username>:<password>@cluster0.4jhaesp.mongodb.net/?retryWrites=true&w=majority");

Make sure to replace <username> and <password> with your actual MongoDB Atlas username and password. Additionally, you need to specify the name of the cluster in the connection string, which in your case should be cluster0. Modify the connection string to look like this:

C#:
var mongoClient = new MongoClient("mongodb+srv://<username>:<password>@cluster0.4jhaesp.mongodb.net/homefinder?retryWrites=true&w=majority");

Replace <username> and <password> with your actual credentials.

Also, make sure that you have whitelisted your IP address in the MongoDB Atlas cluster settings to allow connections from your application.

After making these changes, try running your application again and see if the data is successfully stored in the MongoDB database.
 
The error message you provided suggests that there is an issue with the list of configured name servers in your MongoDB connection string. However, upon reviewing your code, it seems that you haven't specified the connection string correctly.

In your DBConnection class, you have the following line of code:

C#:
var mongoClient = new MongoClient("mongodb+srv://<username>:<password>@cluster0.4jhaesp.mongodb.net/?retryWrites=true&w=majority");

Make sure to replace <username> and <password> with your actual MongoDB Atlas username and password. Additionally, you need to specify the name of the cluster in the connection string, which in your case should be cluster0. Modify the connection string to look like this:

C#:
var mongoClient = new MongoClient("mongodb+srv://<username>:<password>@cluster0.4jhaesp.mongodb.net/homefinder?retryWrites=true&w=majority");

Replace <username> and <password> with your actual credentials.

Also, make sure that you have whitelisted your IP address in the MongoDB Atlas cluster settings to allow connections from your application.

After making these changes, try running your application again and see if the data is successfully stored in the MongoDB database.
var mongoClient = new MongoClient("mongodb+srv://adbcd:0cd4r4@cluster0.4jhaesp.mongodb.net/?retryWrites=true&w=majority"); ito yung Mongo Client string ko pero ang lumalabas na error ay [DOTNET] Error during admin insertion: The list of configured name servers must not be empty. (Parameter 'servers')
 
var mongoClient = new MongoClient("mongodb+srv://adbcd:0cd4r4@cluster0.4jhaesp.mongodb.net/?retryWrites=true&w=majority"); ito yung Mongo Client string ko pero ang lumalabas na error ay [DOTNET] Error during admin insertion: The list of configured name servers must not be empty. (Parameter 'servers')
The error message suggests that there might be an issue with the MongoDB connection string. Here are a few suggestions to troubleshoot the problem:

1. Check the MongoDB connection string: Ensure that the connection string is correct and doesn't contain any typos. Double-check the username, password, and cluster name in the connection string.

2. Verify network connectivity: Ensure that you have a stable internet connection and can access the MongoDB Atlas cluster. Try pinging the cluster's hostname or connecting to it using a MongoDB client such as MongoDB Compass.

3. Check firewall or network restrictions: If you are running the application within a network with strict firewall rules, make sure that the necessary ports (typically 27017 and 27018) are open to allow connections to MongoDB Atlas.

4. Verify MongoDB Atlas configuration: Double-check the MongoDB Atlas cluster configuration. Ensure that the cluster is active and accessible and that the IP whitelist includes the IP address from where the application is running.

If the issue persists after going through these steps, it might be helpful to review the MongoDB driver's documentation and check for any specific requirements or considerations for connecting to MongoDB Atlas using the .NET driver.
 

Similar threads

Back
Top