Search code examples
c#mongodbvariablesconcatenationuser-input

How to use user input stored as a variable in another method


My job has an application that uses a database(mongodB) to store data. I want to change that data after the program has finished installing. But the user sets this before the app is installed.

I have one function to ask for user input then install the app and another function to change the mongodB after the app has finished installing.

My problem is my 'change mongo' function says the variables does not exist in the current context.

How would I store the results of console.readline() in a variable inside function A and use that variable to concatenate string inside function B??

public static void downloadAndInstall37CineAgent()
{
    Console.Write("Enter Path to Cert: ");
    string certPath = Console.ReadLine();
    Console.Write("Enter Password to Cert: ");
    string certPass = Console.ReadLine();

    Console.Write("Network Manager Host: ");
    var HostName = Console.ReadLine();

    Console.Write("Streaming Engine Host Name: ");
    var streamName = Console.ReadLine();
    changeMongo();
}

public static void changeMongo()
{
    var client = new MongoClient("mongodb://localhost:27017");
    IMongoDatabase db = client.GetDatabase("CineNetGlobalSettings");
    var collection = db.GetCollection<BsonDocument>("CineNetSettings");

    var filter = Builders<BsonDocument>.Filter.Eq("_id", "NetworkManagerHost");
    var update = Builders<BsonDocument>.Update.Set("Value", hostname);
    var filterUrl = Builders<BsonDocument>.Filter.Eq("_id", "NetworkManagerUrl");
    var updateUrl = Builders<BsonDocument>.Update.Set("Value", hostname);
    var filterStream = Builders<BsonDocument>.Filter.Eq("_id", "WowzaIpAddress");
    var updateStream = Builders<BsonDocument>.Update.Set("Value", streamName);
}

Solution

  • Variables are only accessible in the context they are defined in.

    Unless you define the variables as global variables, these variables from one method do not get passed on to the next method or back to the calling method unless you properly pass or return these variables.

    For your project, you will need to change your method as well as how you are calling it,

    public static void changeMongo(string hostname, string streamName)
    

    and you would update the call you are making to include the two arguments,

    changeMongo(Hostname, streamName);
    

    In essence, you are calling changeMongo and passing two values that will get used within that method. Note that the name of the variables are bound to the name of the variables initialized within the function. changeMongo function has hostName instead of HostName (which is part of the downloadAndInstall37CineAgent method). Hostname gets translated to hostName since thats the "first" argument on the changeMongo method.