public String Connect(string address, int port, string password, string oldPass)
{
// Check for a last-saved connection - if present, oldPass must match
var Oldsettings = LoadServerSettings("Last", "Server");
if (Oldsettings != null)
{
// Only overwrite the last-saved connection if the passwords match
if (Oldsettings.Password == oldPass)
{
try
{
// Disconnect from current server
MessageQueue.Clear();
CommHandler.Disconnect();
// Attempt to connect to the new server - if this fails, we leave the old "last server" entry in Table Store
CommHandler.Connect(address, port, password);
// Update the "last server" entry in Table Store
Oldsettings.Address = address;
Oldsettings.Port = port;
Oldsettings.Password = password;
Oldsettings.PartitionKey = "Last";
Oldsettings.RowKey = "Server";
var updateOp = TableOperation.Replace(Oldsettings);
CredTable.Execute(updateOp);
return "Connected to " + address;
}
catch (Exception e)
{
Log(System.Reflection.MethodBase.GetCurrentMethod().Name, e.Message);
// Oops, the Connect failed - reconnect to our last known server
LoadExistingConnection();
throw new ArgumentException(e.Message);
}
}
else
{
throw new ArgumentException("Old password was incorrect.");
}
}
else
{
try
{
// Disconnect from current server
MessageQueue.Clear();
CommHandler.Disconnect();
// Attempt to connect to new server
// If this fails, we do not change the last-saved connection
CommHandler.Connect(address, port, password);
// Add the new "last server" entry in Table Store
var settings = new ServerConfig(address, port, password);
settings.PartitionKey = "Last";
settings.RowKey = "Server";
var insertOp = TableOperation.Insert(settings);
CredTable.Execute(insertOp);
return "Connected to " + address;
}
catch (Exception e)
{
Log(System.Reflection.MethodBase.GetCurrentMethod().Name, e.Message);
// Oops, the Connect failed - reconnect to our last known server
LoadExistingConnection();
throw new ArgumentException(e.Message);
}
}
}