Is it safe to hardcode a PPK file into my code? - c#

I created an app that stores and downloads data from a server (it's key-based authentication, not password btw). However, I want to make it things simpler for everyone by hardcoding the key file location. On one hand, it will save a bit of time for people using it, but on the other hand, I am concerned about the security, lest someone abuses the data in the server. If I share my app with a third party, is this practice safe, since anyone can access the server? It's not like I'm sharing the source code. I'm just sharing the program itself.
Code
private void button1_Click_1(object sender, EventArgs e) //Browsing for Key File
{
OpenFileDialog keyOfd = new OpenFileDialog();
keyOfd.Title = "Browse for Key File";
keyOfd.Filter = "Key Files(*.pem;*.ppk)|*.pem;*.ppk";
if (keyOfd.ShowDialog() == DialogResult.OK)
{
textBox1.Text = keyOfd.FileName;
var privateKey = new PrivateKeyFile(textBox1.Text);
populateData();
using (var client = new SftpClient(Host, Port, Username, new[] { privateKey }))
{
client.Connect();
const string workingdirectory = "/home/ubuntu/";
client.ChangeDirectory(workingdirectory);
}
}
}
void button2_Click_1(object sender, EventArgs e)
{
try
{
var privateKey = new PrivateKeyFile(textBox1.Text);
const string workingdirectory = "/home/ubuntu/";
using (var client = new SftpClient(Host, Port, Username, new[] { privateKey }))
{
client.Connect();
client.ChangeDirectory(workingdirectory);
string uploadFile = System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDoc‌​uments), "User Data\\") + "userData.csv";
using (var fileStream = new FileStream(uploadFile, FileMode.Open))
{
client.BufferSize = 4 * 1024; // bypass Payload error large files
client.UploadFile(fileStream, Path.GetFileName(uploadFile));
}
}
}
catch (Exception err)
{
ErrorWindow eWindow = new ErrorWindow();
eWindow.label4.Text = err.GetType().ToString();
eWindow.errorDetails.Text = err.Message;
eWindow.ShowDialog();
}
this.Close();
}

Related

C# Receiving console writeline in richtextbox from windows forms

I have looked at all similar questions. I cant seem to figure out why my situation does not work. I created a test app using the following class:
public class TextBoxStreamWriter : TextWriter
{
RichTextBox _output = null;
public TextBoxStreamWriter(RichTextBox output)
{
_output = output;
}
public override void Write(char value)
{
base.Write(value);
_output.AppendText(value.ToString()); // When character data is written, append it to the text box.
}
public override Encoding Encoding
{
get { return System.Text.Encoding.UTF8; }
}}
My Form Code
public partial class Form1 : Form
{
TextWriter _writer = null;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
_writer = new TextBoxStreamWriter(richTextBox1);
// Redirect the out Console stream
Console.SetOut(_writer);
//Console.WriteLine("Now redirecting output to the text box");
}
private void button1_Click(object sender, EventArgs e)
{
// Writing to the Console now causes the text to be displayed in the text box.
Console.WriteLine("Hello world");
}
}
This works every time I click the button. Now the reason for my question is why does it work there and not in my project. I created a Youtube uploader app using API 3 it uploads completes but the console writeline show the messages but my richtextbox only shows my intial Video uploading message. Altimately I only want to capture the write for a couple of reasons Show any errors, Get progress to for progressbar and get video.ID when I call Console.writeline my richtextbox does not get updated heres the code being used
/// <summary>
/// Upload video to youtube
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void button2_Click(object sender, EventArgs e)
{
//lblstatus.Text = "uploading video";
Console.WriteLine("uploading video");
try
{
Thread thead = new Thread(() =>
{
Run().Wait();
});
thead.IsBackground = true;
thead.Start();
}
catch (AggregateException ex)
{
Console.WriteLine("Error: " + ex.Message);
// MessageBox.Show(ex.Message);
}
}
private async Task Run()
{
UserCredential credential;
using (var stream = new FileStream("client_secret", FileMode.Open, FileAccess.Read))
{
credential = await GoogleWebAuthorizationBroker.AuthorizeAsync(
GoogleClientSecrets.FromStream(stream).Secrets,
// This OAuth 2.0 access scope allows an application to upload files to the
// authenticated user's YouTube channel, but doesn't allow other types of access.
new[] { YouTubeService.Scope.YoutubeUpload },
"user",
CancellationToken.None
);
}
var youtubeService = new YouTubeService(new BaseClientService.Initializer()
{
HttpClientInitializer = credential,
ApplicationName = Assembly.GetExecutingAssembly().GetName().Name
});
var video = new Video();
video.Snippet = new VideoSnippet();
video.Snippet.Title = txtTitle.Text;
video.Snippet.Description = txtDescription.Text;
string[] tagSeo = Regex.Split(txtTagSeo.Text, ",");
video.Snippet.Tags = tagSeo;
video.Snippet.CategoryId = "22"; // See https://developers.google.com/youtube/v3/docs/videoCategories/list
video.Status = new VideoStatus();
video.Status.PrivacyStatus = "public"; // or "private" or "public"
var filePath = txtPath.Text; // Replace with path to actual movie file.
Console.WriteLine(filePath);
using (var fileStream = new FileStream(filePath, FileMode.Open))
{
var videosInsertRequest = youtubeService.Videos.Insert(video, "snippet,status", fileStream, "video/*");
videosInsertRequest.ProgressChanged += videosInsertRequest_ProgressChanged;
videosInsertRequest.ResponseReceived += videosInsertRequest_ResponseReceived;
await videosInsertRequest.UploadAsync();
}
}
void videosInsertRequest_ProgressChanged(Google.Apis.Upload.IUploadProgress progress)
{
switch (progress.Status)
{
case UploadStatus.Uploading:
Console.WriteLine("{0} bytes sent.", progress.BytesSent);
//lblstatus.Text = String.Format("{0} bytes sent.", progress.BytesSent);
break;
case UploadStatus.Failed:
//lblstatus.Text = String.Format("An error prevented the upload from completing.{0} ", progress.Exception);
Console.WriteLine("An error prevented the upload from completing.\n{0}", progress.Exception);
break;
}
}
void videosInsertRequest_ResponseReceived(Video video)
{
Console.WriteLine("Video id '{0}' was successfully uploaded.", video.Id);
MessageBox.Show("Video id '{0}' was successfully uploaded.", video.Id);
}
I was unable to make the above code work so I went to plan B. I started with getting the Video ID only because I only get 6 tries per day I choose to use the Video ID as string. I eliminated the TextBoxStreamWriter class all together and went with creating a new thread and delegate. I will work on the progressbar value next. here's how I did it for anyone else who may have a similar problem.
Created a delegate to update my video ID Label as follows
public delegate void LabelDelegate(string s);
void UpdateVideoID(string text)
{
if (lblVideoID.InvokeRequired)
{
LabelDelegate LDEL = new LabelDelegate(UpdateVideoID);
lblVideoID.Invoke(LDEL, text);
}
else
lblVideoID.Text = text;
}
void videosInsertRequest_ResponseReceived(Video video)
{
Thread th = new Thread(() => UpdateVideoID(video.Id));
th.Start();
Console.WriteLine("Video id '{0}' was successfully uploaded.", video.Id);
}

C # ListBox how to export a file with the name I pass from the listbox

**sorry for my english but i don't know very well in google translate i do translation.
I want from my listbox the file that I choose to be exported with the same name that it has in my listbox**
private void downloadFile(object sender, EventArgs e)
{
string ip = txt_ip.Text;
string user = txt_user.Text;
string pass = txt_pass.Text;
//string pathLocalFile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "download_sftp_file.txt");
try
{
SftpClient client = new SftpClient(ip, user, pass);
client.Connect();
string rmDer = dr_finder.Text;
var files = client.ListDirectory(rmDer);
if (rmDer == "")
{
client.Connect();
string rmDerNow = "/";
var filesName = client.ListDirectory(rmDerNow);
foreach (var file in filesName)
{
DirList.Items.Add(file.Name);
string result = Path.GetFileNameWithoutExtension(file.Name);
DirList.Items.Add(System.IO.Path.GetFileName(file.Name));
}
MessageBox.Show("List Directory Success!");
}
string pachRemFile = DirList.SelectedItem.ToString();
string pachlocalFile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop),"Server Ftp File.txt");
Stream Filestream = File.OpenWrite(pachlocalFile);
client.DownloadFile(pachRemFile,Filestream);
client.Disconnect();
}
catch (Exception error)
{
MessageBox.Show(error.Message);
}
}
this object is the solution I finally didn't find anyone to help me. so I helped myself.
and I thought he had good programmers on this site
SaveFileDialog savefile = new SaveFileDialog(); /* this here is my solution get a save as. */
if (savefile.ShowDialog() == DialogResult.OK)
{
string pachRemFile = DirList.SelectedItem.ToString();
Stream Filestream = File.Open(savefile.FileName, FileMode.CreateNew);
StreamWriter sw = new StreamWriter(Filestream);
client.DownloadFile(pachRemFile, Filestream);
client.Disconnect();
}

Image does not display in gallery after download

I am developing a Xamarin app which retrives info from DB, take/choose photo and upload them to remote server, display this images from the remote server and the user can delete them by tap on and press a button and download the images from the remote server to the local device.
Everything works without problem, but when I download the image and after I go to the gallery for check it, the image does not appear, whereas I can see it and open in the file explorer. When I reboot the phone, the image appear in the gallery.
Below my current button download method:
private void button_download_image_Clicked(object sender, EventArgs e)
{
Uri image_url_format = new Uri(image_url);
WebClient webClient = new WebClient();
try
{
byte[] bytes_image = webClient.DownloadData(image_url_format);
Stream image_stream = new MemoryStream(bytes_image);
string dest_folder = Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryDownloads).ToString();
string file_name = System.IO.Path.GetFileName(image_url_format.LocalPath);
string dest_path = System.IO.Path.Combine(dest_folder, file_name);
using (var fileStream = new FileStream(dest_path, FileMode.Create, FileAccess.Write))
{
image_stream.CopyTo(fileStream);
}
}
catch (Exception ex)
{
DisplayAlert("Error", ex.ToString(), "OK");
}
DisplayAlert("Alert", "Download completed!", "OK");
}
I tried in another device, but I got the same behavior.
Probably there is a sort of thing which does not refresh the gallery.
Any idea how to force the gallery to refresh or something similar?
You need to refresh your gallery after inserting or deleting any pictures in storage.
You can try this.
var mediaScanIntent = new Intent(Intent.ActionMediaScannerScanFile);
mediaScanIntent.SetData(Android.Net.Uri.FromFile(new Java.IO.File(dest_path)));
Xamarin.Forms.Forms.Context.SendBroadcast(mediaScanIntent);
Add these lines below your code.
Make it like
private void button_download_image_Clicked(object sender, EventArgs e)
{
Uri image_url_format = new Uri(image_url);
WebClient webClient = new WebClient();
try
{
byte[] bytes_image = webClient.DownloadData(image_url_format);
Stream image_stream = new MemoryStream(bytes_image);
string dest_folder = Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryDownloads).ToString();
string file_name = System.IO.Path.GetFileName(image_url_format.LocalPath);
string dest_path = System.IO.Path.Combine(dest_folder, file_name);
using (var fileStream = new FileStream(dest_path, FileMode.Create, FileAccess.Write))
{
image_stream.CopyTo(fileStream);
}
var mediaScanIntent = new Intent(Intent.ActionMediaScannerScanFile);
mediaScanIntent.SetData(Android.Net.Uri.FromFile(new Java.IO.File(dest_path)));
//for old xamarin forms version
Xamarin.Forms.Forms.Context.SendBroadcast(mediaScanIntent);
//for new xamarin forms version
//Android.App.Application.SendBroadcast(mediaScanIntent);
}
catch (Exception ex)
{
DisplayAlert("Error", ex.ToString(), "OK");
return;
}
DisplayAlert("Alert", "Download completed!", "OK");
}
You need to just refresh the file you have downloaded. It's helpful.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT){
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
File f = new File("file://"+ Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES));
Uri contentUri = Uri.fromFile(f);
mediaScanIntent.setData(contentUri);
this.sendBroadcast(mediaScanIntent);
}else{
sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://" + Environment.getExternalStorageDirectory())));
}
Make sure required permission given on both platforms.
Use in your class:
bool success = await DependencyService.Get<IPhotoLibrary>().SavePhotoAsync(data, folder, filename);
Common Interface
public interface IPhotoLibrary
{
Task<bool> SavePhotoAsync(byte[] data, string folder, string filename);
}
In Android service
public async Task<bool> SavePhotoAsync(byte[] data, string folder, string filename)
{
try
{
File picturesDirectory = Environment.GetExternalStoragePublicDirectory(Environment.DirectoryPictures);
File folderDirectory = picturesDirectory;
if (!string.IsNullOrEmpty(folder))
{
folderDirectory = new File(picturesDirectory, folder);
folderDirectory.Mkdirs();
}
using (File bitmapFile = new File(folderDirectory, filename))
{
bitmapFile.CreateNewFile();
using (FileOutputStream outputStream = new FileOutputStream(bitmapFile))
{
await outputStream.WriteAsync(data);
}
// Make sure it shows up in the Photos gallery promptly.
MediaScannerConnection.ScanFile(MainActivity.Instance,
new string[] { bitmapFile.Path },
new string[] { "image/png", "image/jpeg" }, null);
}
}
catch (System.Exception ex)
{
return false;
}
return true;
}
In iOS service:
public Task<bool> SavePhotoAsync(byte[] data, string folder, string filename)
{
NSData nsData = NSData.FromArray(data);
UIImage image = new UIImage(nsData);
TaskCompletionSource<bool> taskCompletionSource = new TaskCompletionSource<bool>();
image.SaveToPhotosAlbum((UIImage img, NSError error) =>
{
taskCompletionSource.SetResult(error == null);
});
return taskCompletionSource.Task;
}
also you can refer this one just to save an image and to reflect it in media, no need to use skiasharp for that. https://learn.microsoft.com/en-us/xamarin/xamarin-forms/user-interface/graphics/skiasharp/bitmaps/saving
Hope this may resolve your issue.
Refer to Blu's answer,
I changed this Xamarin.Forms.Forms.Context.SendBroadcast(mediaScanIntent); to Android.App.Application.Context.SendBroadcast(mediaScanIntent); and all works.

Displaying Output from SSH.NET

I am fairly new with C# and I am trying to write an SSH console application using the SSH.NET framework. So far I was able to connect to my server successfully, but now I am trying to run commands and have it display the result. Yet, my console comes out blank when I run my application. My end goal was to execute a set of commands and see the results at the end of it.
Program.cs
using Renci.SshNet;
class Program
{
//Login Parameter
const String Hostname = "somePort";
const int PortNumber = 22;
const String Username = "username";
const String Password = "root";
static void Main(string[] args)
{
//Bypass Keyboard authentication
KeyboardInteractiveAuthenticationMethod kauth = new KeyboardInteractiveAuthenticationMethod(Username);
PasswordAuthenticationMethod pauth = new PasswordAuthenticationMethod(Username, Password);
kauth.AuthenticationPrompt += new EventHandler<Renci.SshNet.Common.AuthenticationPromptEventArgs>(HandleKeyEvent);
//Grab info for connections
ConnectionInfo connectionInfo = new ConnectionInfo(Hostname, PortNumber, Username, pauth, kauth);
//Connect
using (SshClient client = new SshClient(connectionInfo))
{
try
{
//Connect to server
client.Connect();
Console.WriteLine("Connection successful");
var command = client.CreateCommand("ls");
var result = command.Execute();
command.Execute();
Console.WriteLine(result);
//Disconnect from server
client.Disconnect();
}
//Show exp message
catch (Exception exp)
{
throw exp;
}
}
}
//Handle two step auth
static void HandleKeyEvent(Object sender, Renci.SshNet.Common.AuthenticationPromptEventArgs e)
{
foreach (Renci.SshNet.Common.AuthenticationPrompt prompt in e.Prompts)
{
if (prompt.Request.IndexOf("Password:", StringComparison.InvariantCultureIgnoreCase) != -1)
{
prompt.Response = Password;
}
}
}
}
I don't know if you have resolved this issue yet, but the solution is simple in this case.
The function:
command.Execute()
doesn't return your result.
You have to execute like you did, but then grab the result via
command.Result
It would look something like this:
var command = client.CreateCommand("ls");
command.Execute();
var result = command.Result;
Hope i could help you.

UDL File not found exception on Application Start

I have written the following code to implement common connection string so that all the forms use the connection string provided in Login Form of my application.The application works fine on my machine but when I run my application on any other machine I get the error "Connection to the server could not be established" ie it enters the catch block. even when the UDL file is available on the machine.Can anyone help me to rectify this.
Thanks
public void FrmLogin_Load(object sender, EventArgs e)
{
btncancel.CausesValidation = false;
try
{
string FileName = "Intellect_LeadMt.udl";
if (!File.Exists(FileName))
{
MessageBox.Show(FileName + " File is not available in current folder!");
//return;
this.Close();
}
string[] str = File.ReadAllLines(FileName);
con = new OleDbConnection(str[2]);
con.Open();
add = new AddModify_Lead(this);
foll = new Follow_Lead(this);
rem = new Reminder_Lead(this);
ContctAdd = new AddContact(this);
UtilityMaster = new UtilityMasters(this);
LeadManagerForm = new LeadManager(this);
Register = new FrmRegistration(this);
Mainform = new Form1(this);
Ld = new LoginDetails(this);
Ul = new UserLog(this);
Mc = new Modify_Client(this);
}
catch
{
MessageBox.Show("Connection to Database currently is unavailable!\n Please Check udl and start application once again.\n Sorry For the inconvenience", "Connection Error", MessageBoxButtons.OK, MessageBoxIcon.Information);
Application.Exit();
}
}

Categories