C# string from one function to another - c#

in a c# program that i made, i read some values from an INI file,put them in string, in function UPLOAD and i make a database manager for those values to connect the user to a db. Now, i need to read those strings from another function, you see it below. What shall i do ?
public Upload()
{
#region INI PROPERTIES and Variables
INIFile inif = new INIFile(#".\Settings\AppSettings.ini");
//Values for DatabaseManager dbm
//Hosting Server IP
string srv_ip = inif.Read("DatabaseSettings", "IP_adress");
//Database Username
string srv_uname = inif.Read("DatabaseSettings", "Admin_Username");
//Database Password
string srv_pass = inif.Read("DatabaseSettings", "Admin_Password");
//Database Name
string srv_dbname = inif.Read("DatabaseSettings", "Database_Name");
//Values for DatabaseManager dbm
//Fingerprint of Hosting Server IP
string ftp_fingerprint = inif.Read("ProgramSettings", "fingerprint");
//Host
string ftp_host = inif.Read("ProgramSettings", "host");
//Username
string ftp_username = inif.Read("ProgramSettings", "username");
//Password
string ftp_pass = inif.Read("ProgramSettings", "password");
#endregion
InitializeComponent();
DatabaseManager dbm = new DatabaseManager(srv_ip, srv_uname, srv_pass, srv_dbname);
dbm.Init();
}
And the other function. I need from the first to store the variables into the strings that you can see on the second.
private void upload_btn_MouseDown(object sender, MouseButtonEventArgs e)
{
string fingerprint = ftp_fingerprint;
string host = ftp_host;
string username = ftp_username;
string password = ftp_pass;
FtpManager ftpm = new FtpManager(host, username, password, fingerprint, ProgressCallback);
string remoteFolder = "/var/whatever"; // Name of directory to upload
string remoteName; // Name of file to save on server
//some more code
}
Problem solved by making those variables fields. Thank you all for your answers i appreciate each one of you for your time.

The simplest way to go is to make them fields.
private string ftp_fingerprint;
private string ftp_host;
private string ftp_username;
private string ftp_pass;
public Upload()
{
#region INI PROPERTIES and Variables
INIFile inif = new INIFile(#".\Settings\AppSettings.ini");
//Values for DatabaseManager dbm
//Hosting Server IP
string srv_ip = inif.Read("DatabaseSettings", "IP_adress");
//Database Username
string srv_uname = inif.Read("DatabaseSettings", "Admin_Username");
//Database Password
string srv_pass = inif.Read("DatabaseSettings", "Admin_Password");
//Database Name
string srv_dbname = inif.Read("DatabaseSettings", "Database_Name");
//Values for DatabaseManager dbm
//Fingerprint of Hosting Server IP
ftp_fingerprint = inif.Read("ProgramSettings", "fingerprint");
//Host
ftp_host = inif.Read("ProgramSettings", "host");
//Username
ftp_username = inif.Read("ProgramSettings", "username");
//Password
ftp_pass = inif.Read("ProgramSettings", "password");
#endregion
InitializeComponent();
DatabaseManager dbm = new DatabaseManager(srv_ip, srv_uname, srv_pass, srv_dbname);
dbm.Init();
}
private void upload_btn_MouseDown(object sender, MouseButtonEventArgs e)
{
string fingerprint = ftp_fingerprint;
string host = ftp_host;
string username = ftp_username;
string password = ftp_pass;
FtpManager ftpm = new FtpManager(host, username, password, fingerprint, ProgressCallback);
string remoteFolder = "/var/whatever"; // Name of directory to upload
string remoteName; // Name of file to save on server
//some more code
}

Related

How do I assign a uuid value to UserName in AWS Cognito?

I need to assign an immutable value UserName = uid, all my attempts were unsuccessful.
static string GetUUID()
{
return System.Guid.NewGuid().ToString();
}
var signUpRequest = new SignUpRequest
{
UserAttributes = userAttrsList,
Username = uuid ,
ClientId = appClientId,
Password = password
};
When I switch to the function confirm the code, uuid is assigned a new one.

how to change a username and password stored in a text file only for the correct user

i am currently making a application for my a level computing coursework. for my coursework i am required to make a login and registration system which requires me to store the user details in a text file this is only for my coursework so security isent important. my registration and login system works fine but i am also required to have a change account details screen in which the user can change their username and password.
my problem is that my code that i have currently changes the password for every user with the same password ie if 2 users have password123 as a password both their passwordds gets changed to the new password
private void btnUpdatePassword_Click(object sender, EventArgs e)
{
string oldusername = txtBoxOldUsername.Text;
string newusername = txtBoxNewUsername.Text;
string oldpassword = txtBoxOldPassword.Text;
string newpassword = txtBoxNewPassword.Text;
string text = File.ReadAllText("users.txt");
text = text.Replace(oldpassword, newpassword).Replace(oldusername, newusername);
File.WriteAllText("users.txt", text);
}
my problem is that i dont know how to change the password for only the correct user. it would be great if anyone could help thanks. also i HAVE to use a text file to do this meaning i cant use jason on xml etc
this is what my text file looks like
first user ~username~password
second user ~username123~password
third user ~username1234~password
and this is the code i use to write to the text file
FileStream fileStream = new FileStream("users.txt", FileMode.Append, FileAccess.Write);
StreamWriter streamWriter = new StreamWriter(fileStream);
try
{
streamWriter.WriteLine(fullname + "~" + username + "~" + password + "~" + lastlogin);
MessageBox.Show("User registered successfully", "Registration Successful");
this.Hide();
var homeForm = new HomeForm();
homeForm.Closed += (s, args) => this.Close();
homeForm.Show();
}
catch (Exception)
{
MessageBox.Show("Error registering the user", "Please try again");
}
finally
{
streamWriter.Close();
fileStream.Close();
}
Here is an idea on how to implement it. My first suggestion is to add a comma deliminator to your text file so your values in users.txt will be in the following form
second user~username123~password,
third user~username1234~password,
first user~username~smelly,
Import all the users from users.txt at once and split them by our deliminator ','
var users = File.ReadAllText(#"C:\users.txt").Split(',').ToList().Where(x=> !String.IsNullOrWhiteSpace(x));
Note this clause .Where(x=> !String.IsNullOrWhiteSpace(x) will be needed because when I rewrite the file , for simplicity sake I add a comma to each entry. As last entry will have a comma we end up with an extra empty object. This clause will rectify it.
Create a class which will contains all the user properties:
private class User
{
public string Name { get; set; }
public string UserName { get; set; }
public string Password { get; set; }
public string PrepareForFile()
{
return Name + "~" + UserName + "~" + Password + ",";
}
}
Loop through all the retrieved users information from file and build a list of user:
List<User> myUsers = new List<User>();
foreach (var user in users)
{
var information = user.Split('~');
User temp = new User();
temp.Name = information[0].Trim();
temp.UserName = information[1].Trim();
temp.Password = information[2].Trim();
myUsers.Add(temp);
}
Now you have a manageable structure and you can perform all the desired operations. Once finished use the method PrepareForFile() to create a string like second user~username123~password to be written into file.
Putting it all together(this is a console app):
static class Program
{
private class User
{
public string Name { get; set; }
public string UserName { get; set; }
public string Password { get; set; }
public string PrepareForFile()
{
return Name + "~" + UserName + "~" + Password + ",";
}
}
static void Main(string[] args)
{
var users = File.ReadAllText(#"C:\users.txt").Split(',').ToList().Where(x=> !String.IsNullOrWhiteSpace(x));
List<User> myUsers = new List<User>();
foreach (var user in users)
{
var information = user.Split('~');
User temp = new User();
temp.Name = information[0].Trim();
temp.UserName = information[1].Trim();
temp.Password = information[2].Trim();
myUsers.Add(temp);
}
var selectedUser = myUsers.Where(x => x.UserName == "username").SingleOrDefault();
myUsers.Remove(selectedUser);
selectedUser.Password = "Leo";
myUsers.Add(selectedUser);
List<string> formatForFile = new List<string>();
foreach(var item in myUsers)
{
formatForFile.Add(item.PrepareForFile());
}
File.WriteAllLines(#"C:\users.txt", formatForFile.ToArray());
}
}
Changing username1234 password from "password" to "AlexLeo":
Before
After
You can store the username with the password when saving the password and delete the username when it is extracted from the password and add the username when adding the password.
for example:
private void btnUpdatePassword_Click(object sender, EventArgs e)
{
string oldusername = txtBoxOldUsername.Text;
string newusername = txtBoxNewUsername.Text;
string oldpassword = txtBoxOldPassword.Text;
string newpassword = txtBoxNewPassword.Text;
string text = File.ReadAllText("users.txt");
text = text.Replace(oldpassword + oldusername, newpassword + newusername).Replace(oldusername, newusername);
File.WriteAllText("users.txt", text);
}
Based on your updated OP
string str = System.IO.File.ReadAllText(fileName);
var users = str.Split(new []{Environment.NewLine},StringSplitOptions.RemoveEmptyEntries)
.Select(x=>
{
var strArray = x.Split(new []{"~"},StringSplitOptions.RemoveEmptyEntries);
return new
{
FirstName = strArray[0],
User = strArray[1],
Password = strArray[2]
};
}
);
var usernameToUpdate = "username123";
var newPassword = "Thisisnewpassword";
var updatedList = users.Select(x => x.User.Equals(usernameToUpdate) ?
$"{x.FirstName} ~{x.User}~{newPassword}"
: $"{x.FirstName} ~{x.User}~{x.Password}").ToList();
var newFileData = String.Join(Environment.NewLine,
updatedList);
File.WriteAllText(fileName, newFileData);

An Application Connect with Multiple database and set Membership cookies

I'm writing a method that set all of database connection string with it.The method has some parameters like connection string and cookie domain (for single sign on state) , ...
I can get Membership and role Information with specified connection string that send as a parameter.
//membership
System.Web.Security.SqlMembershipProvider mp = new System.Web.Security.SqlMembershipProvider();
System.Collections.Specialized.NameValueCollection config_Membership = new System.Collections.Specialized.NameValueCollection();
config_Membership.Add("connectionString", connectionstring);
config_Membership.Add("applicationName", "/");
mp.Initialize("SQL_test_Membership", config_Membership);
var u = mp.GetUser(username, false);
int TotalRecords = 0;
var p = mp.GetAllUsers(0, 1, out TotalRecords);
//login
bool valid = mp.ValidateUser(username, password);
System.Web.Security.SqlRoleProvider rp = new System.Web.Security.SqlRoleProvider();
System.Collections.Specialized.NameValueCollection config_Role = new System.Collections.Specialized.NameValueCollection();
config_Role.Add("connectionString", connectionstring);
config_Role.Add("applicationName", "/");
rp.Initialize("SQL_test_Role", config_Role);
var roles = rp.GetRolesForUser(username);
I want to get ProfileBase Information like above code
https://technet.microsoft.com/nl-nl/library/system.web.profile.profilebase.initialize(v=vs.85).aspx
and I found below code:
System.Web.Profile.ProfileBase pro = new System.Web.Profile.ProfileBase();
System.Collections.Specialized.NameValueCollection config_profile = new System.Collections.Specialized.NameValueCollection();
config_profile.Add("connectionString", connectionstring);
config_profile.Add("applicationName", "/");
pro.Initialize(?????)
but I dont know how to send parameter to pro.Initialize(), can any one help me? Thanks.
My problem solved. My code was changed :
//login
bool valid = mp.ValidateUser(username, password);
if (valid)
{
System.Web.Profile.ProfileBase pro = new System.Web.Profile.ProfileBase();
System.Collections.Specialized.NameValueCollection config_profile = new System.Collections.Specialized.NameValueCollection();
config_profile.Add("connectionString", connectionstring);
config_profile.Add("applicationName", "/");
pro.Initialize(username, true);
string Name = pro.GetPropertyValue("Name").ToString();
string Family = pro.GetPropertyValue("Family").ToString();
string phone = pro.GetPropertyValue("Phone").ToString();
string address = pro.GetPropertyValue("Address").ToString();
}

check for IP address and download the data

I have two devices having separate IP addresses and want to check if any one is connected and if connected download the database from the device and any given time only one device is connected.My query works fine for one device how to check which one is connected. I have updated my code but not sure how is it gone work.
private void button7_Click(object sender, EventArgs e)// 1)first download database to local system.
{
this.Process1();
}
public void Process1()
{
string _ftpURL = #"131.000.00.0"; // fake Host URL or address of the SFTP server
/* how to check for another IP adddress if exists */
string _UserName = "root"; //fake User Name of the SFTP server
string _Password = "3term"; // fake Password of the SFTP server
int _Port = 2222; //Port No of the SFTP server (if any)
string _ftpDirectory = "/home/root/systools/WM/WebMobility.db"; //The directory in SFTP server where the files will be uploaded
string LocalDirectory = "F:\\Explor\\final test"; //Local directory from where the files will be uploaded
try
{
Sftp Connection = new Sftp(_ftpURL, _UserName, _Password);
Connection.Connect(_Port);
Connection.Get(_ftpDirectory, LocalDirectory);
Connection.Close();
}
catch (Exception ex)
{
if (ex is SshConnectionException || ex is SocketException)
{
_ifwInstance.Error(string.Format("Ignoring {0} during listing directory", ex.Message));
}
else
{
string _ftpURL = #"131.111.11.11"; // fake Host URL or address of the SFTP server
/* how to check for another IP adddress if exists */
string _UserName = "root"; //fake User Name of the SFTP server
string _Password = "3term"; // fake Password of the SFTP server
int _Port = 2222; //Port No of the SFTP server (if any)
string _ftpDirectory = "/home/root/systools/WM/WebMobility.db"; //The directory in SFTP server where the files will be uploaded
string LocalDirectory = "F:\\Explor\\final test"; //Local directory from where the files will be uploaded
throw new Exception("Login to SFT FAILED", ex);
}
}
}
updated Code:
string[] _ftpURL = { #"100.100.0.0", #"101.0.0.0" }; //Array of address to SFTP servers
string _UserName = "root"; //fake User Name of the SFTP server
string _Password = "310rp3"; // fake Password of the SFTP server
int _Port = 2222; //Port No of the SFTP server (if any)
string _ftpDirectory = "/home/root/systools/WM/WebMobility.db"; //The directory in SFTP server where the files will be uploaded
string LocalDirectory = "F:\\Explor\\final test"; //Local directory from where the files will be uploaded
bool online = false;
foreach(string furl in _ftpURL)
{
Sftp Connection = new Sftp(furl, _UserName, _Password);
try
{
Connection.Connect(_Port);
online = true;
}
catch
{
online = false;
}
if(online == true)
{
Connection.Get(_ftpDirectory, LocalDirectory);
Connection.Close();
break;
}
}
Add these two methods to some class and call public DownloadSftpFile from your desktop code.
// returns true if the file had downloaded
public static bool DownloadSftpFile(string[] hosts, int port, string username, string password, string remotePathAndFile, string localPath)
{
foreach (var host in hosts)
{
try
{
DownloadSftpFile(host, port, username, password, remotePathAndFile, localPath);
return true;
}
catch(SshConnectionException exception)
{
// log
}
catch(SocketExcpetion exception)
{
// log
}
}
return false;
}
private static void DownloadSftpFile(string host, int port, string username, string password, string remotePathAndFile, string localPath)
{
using (var sftp = new Sftp(host, username, password))
{
sftp.Connect(port);
sftp.Get(remotePathAndFile, localPath);
}
}

Get user and password from ConnectionStringSettings

How can I get the user and password from such a connectionString in the app.config with a .NET function?
Of course I could read that string and get the value after the ID= and Password=.
<connectionStrings>
<add name="MyConString" connectionString="Data Source=(local);Initial Catalog=MyDatabase;Persist Security Info=True;User ID=MyUsername Password=MyPassword;Connect providerName="System.Data.SqlClient"/>
</connectionStrings>
use the ConnectionBuilderClass
SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder("Your connection string");
string password = builder.Password;
together with the
string connString = ConfigurationManager.ConnectionStrings["MyConString"].ConnectionString;
to achieve this.
If you need a more generic approach for parsing the connection string (one that doesn't deal with the specifics of one database provider) you can also use
System.Data.Common.DbConnectionStringBuilder
which is a base class for other classes like SqlConnectionStringBuilder etc.
You can create an instance of DbConnectionStringBuilder and in my case I needed to have one configurable connection string that I could get information from -- regardless of the database provider type. A few options if you need this flexibility -- you could create the appropriate ConnectionStringBuilder for your provider as others have suggested -- this would likely be required for most cases where provider-specific properties are needed.
Or if you want to read just a couple generic properties, you could use DbConnectionStringBuilder if you just need the user id and password for example.
This sample should work for ANY connection string that includes user id and password.
DbConnectionStringBuilder db = new DbConnectionStringBuilder();
db.ConnectionString = ConfigurationManager.ConnectionStrings["myConnectionString"].ConnectionString;
var username = db["User Id"].ToString();
var password = db["Password"].ToString();
SqlConnectionStringBuilder con = new SqlConnectionStringBuilder(ConfigurationManager.ConnectionStrings["ConnString"].ConnectionString);
string myUser = con.UserID;
string myPass = con.Password;
var builder = new SqlConnectionStringBuilder(ConfigurationManager.ConnectionStrings["MyConString"].ConnectionString)
var user = builder.UserID;
var password = builder.Password;
You can get the connection string from the following
SqlConnectionStringBuilder yourconn = new SqlConnectionStringBuilder(ConfigurationManager.ConnectionStrings["ConnString"].ConnectionString);
string password = yourconn.Password;
You can then get the substring you are looking for .
Just to add a bit to Tomas Walek's answer.
This approach would work only if "User ID" in the connection string is capitalized correctly. Oracle provider accepted "User Id" OK, but SqlConnectionStringBuilder did not work.
public static class DbConnectionFactory
{
public static ConnectionStringSettings AppConnectionSettings = ConfigurationManager.ConnectionStrings["{A connection string name}"];
public static SqlConnectionStringBuilder AppConnBuilder = new SqlConnectionStringBuilder(AppConnectionSettings.ConnectionString);
public static string DbUserID
{
get
{
return AppConnBuilder.UserID;
}
set { }
}
}
add a reference to System.Configuration and then use:
using System.Configuration;
string MyDBConnection = ConfigurationManager.ConnectionStrings["MyDBConnection"].ConnectionString;
SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(MyDBConnection);
string UserID = builder.UserID;
string Password = builder.Password;
string ServerName = builder.DataSource;
string DatabaseName = builder.InitialCatalog;
public static string GetConnectionSettings(string searchSetting )
{
var con = ConfigurationManager.ConnectionStrings["yourConnectionHere"]‌​.ConnectionString;
String[] myString = con.Split(';');
Dictionary<string, string> dict = new Dictionary<string, string>();
for (int i = 0; i < myString.Count(); i++)
{
String[] con3 = myString[i].Split('='); dict.Add(con3[0], con3[1]);
}
return dict[searchSetting];
}
for searchSetting you can use what you want "User Is" or password.
another way is to use regular expression (which I did), with a more forgiving pattern, to handle different ways a user id could be provided on the connection string:
public static string GetUserIdFromConnectionString(string connectionString)
{
return new Regex("USER\\s+ID\\=\\s*?(?<UserId>\\w+)",
RegexOptions.IgnoreCase)
.Match(connectionString)
.Groups["UserId"]
?.Value;
}
Extension method to get "User Id" from connectionString in DbConnection:
using System;
using System.Data.Common;
using System.Text.RegularExpressions;
namespace DemoProject.Helpers
{
public static class DbConnectionExtensions
{
public static string GetUserId(this DbConnection connection)
{
const string userIdPattern1 = "User[ ]*Id";
const string userIdPattern2 = "UID";
var connectionString = connection.ConnectionString;
foreach (var item in connectionString.Split(';'))
{
var index = item.IndexOf('=');
if (index == -1)
continue;
var property = item.Substring(0, index).Trim();
if (Regex.IsMatch(property, userIdPattern1, RegexOptions.IgnoreCase) ||
Regex.IsMatch(property, userIdPattern2, RegexOptions.IgnoreCase))
{
var userId = item.Substring(index + 1).Trim();
return userId;
}
}
throw new Exception("Couldn't find \"User Id\" in connectionString");
}
}
}
Example #1 of using:
using DemoProject.Helpers;
using Oracle.ManagedDataAccess.Client;
namespace DemoProject
{
class Program
{
static void Main(string[] args)
{
const string connectionString = "Data Source=(DESCRIPTION=" +
"(ADDRESS=(PROTOCOL=TCP)(HOST=oracle19c-vm)(PORT=1521))" +
"(CONNECT_DATA=(SERVICE_NAME=ORCLPDB1)));" +
"User Id=JOHN;" +
"Password=pwd123";
var connection = new OracleConnection(connectionString);
var userId = connection.GetUserId();
}
}
}
Example #2 of using:
using DemoProject.Helpers;
using Npgsql;
namespace DemoProject
{
class Program
{
static void Main(string[] args)
{
const string connectionString = "Server=postgre-vm;" +
"User Id=JOHN;" +
"Password=pwd123;" +
"Database=DEV1";
var connection = new NpgsqlConnection(connectionString);
var userId = connection.GetUserId();
}
}
}
Also you can add the 2nd extension method to get the password
var connString = ConfigurationManager.ConnectionStrings["MyConString"].ConnectionString;
var tokens = connString.Split(';');
string userId;
string password;
for(var i = 0; i < tokens.Length; i++) {
var token = tokens[i];
if(token.StartsWith("User ID"))
userId = token.Substring(token.IndexOf("=") + 1);
if(token.StartsWith("Password"))
password = token.Substring(token.IndexOf("=") + 1);
}
string connectionString = ConfigurationManager.ConnectionStrings["MyConString"].ConnectionString;
var tokens = connectionString.Split(';').Select(n => n.Split('=');
string userId = tokens.First(n => n[0].Equals("User ID").Select(n => n[1]);
string password = tokens.First(n => n[0].Equals("Password").Select(n => n[1]);

Categories