CSDNCurrent de:Beispielprojekt

Aus Cryptshare Documentation
Version vom 7. März 2022, 06:50 Uhr von Maintenance script (Diskussion | Beiträge) (Imported from text file)
(Unterschied) ← Nächstältere Version | Aktuelle Version (Unterschied) | Nächstjüngere Version → (Unterschied)
Wechseln zu:Navigation, Suche



Einrichten der Entwicklungsumgebung

Wir empfehlen Ihnen, für das Tutorial eine IDE zu verwenden. Der Code wurde erfolgreich mit Visual Studio Community getestet. Nachdem Sie die IDE gestartet, sowie die Visual Studio Solution und Project erstellt haben, sollten Sie die Cryptshare.API.dll als Referenz dem Projekt hinzufügen: 58294669.png 58294670.png Stellen Sie auch sicher, dass mithilfe des Visual Studio Installers die ".NET desktop development" Tools installiert sind: 58294671.png

Versenden des ersten Transfers

Anbei finden Sie ein Beispielprogramm, welches einen Cryptshare Transfer von einem bestimmten Absender an einen bestimmten Empfänger versendet. Sie können die individuellen Eigenschaften Ihren Wünschen entsprechend anpassen und, falls alle Voraussetzungen erfüllt sind, den Transfer starten.

Ausklappen, um Quellcode einzusehen...  Expand source

using Cryptshare.API;
using System;
using System.Collections.Generic;

namespace CryptshareTransfer
{
	class Program
	{
		private static readonly string SenderEmailAddress = "alice@example.com";
		private static readonly string SenderName = "Alice";
		private static readonly string SenderPhoneNumber = "+1 (123) 4567 890";
		private static readonly string ServerUrl = "https://cryptshare.example.com";
		// New "client.store" file will be created if it doesn't already exist.
		// However, make sure the folder exists and is writable by the user running this program!
		private static readonly string ClientStoreLocation = @"C:\temp";
		private static readonly string RecipientEmailAddress = "bob@example.com";
		private static readonly List<string> FilePaths = new List<string>() { @"C:\temp\pdf-sample.pdf" };

		static void Main(string[] args)
		{
			try
			{
				// Initialize the Client object.
				Client client = new Client(
					SenderEmailAddress,
					new CryptshareConnection(new WebServiceUri(ServerUrl)),
					ClientStoreLocation
				);
				// Initialize the Transfer object.
				Transfer transfer = new Transfer();

				// Define the sender and recipient information.
				transfer.SenderName = SenderName;
				transfer.SenderPhone = SenderPhoneNumber;
				transfer.Recipients.Add(new Recipient(RecipientEmailAddress));

				// Define the list of files to be sent.
				transfer.Files = FilePaths;

				// Optional: Let the Cryptshare Server handle the email sending process.
				transfer.SendEmails = true;
				transfer.NotifySender = true;
				transfer.NotifyRecipients = true;
				transfer.InformAboutDownload = true;

				// Ensure that the client is verified.
				CheckVerificationResult checkVerificationResult = client.CheckVerification();
				if (!checkVerificationResult.Verified)
				{
					if (checkVerificationResult.VerificationMode == VerificationMode.Client)
					{
						Console.WriteLine("Please authorize the following Client ID on the Cryptshare Server:");
						Console.WriteLine(client.ClientId);
						return;
					}
					else
					{
						Console.WriteLine($"Requesting a verification code for {client.UserEmailAddress}...");
						client.RequestSenderVerification();
						Console.WriteLine($"Please enter the code below and confirm with [Enter]:");
						string code = Console.ReadLine().Trim();
						client.ConfirmSenderVerification(code);
					}
				}

				// Request a generated password of a minimum length specified by the server.
				transfer.PasswordMode = PasswordMode.Generated;
				int minimumPasswordLength = client.RequestPasswordPolicy().MinimumLength;
				transfer.Password = client.RequestGeneratedPassword(minimumPasswordLength);

				// Set the transfer expiration date to the maximum storage duration.
				Policy policy = client.RequestPolicy(transfer.Recipients.ConvertAll(recipient => recipient.EmailAddress));
				transfer.ExpirationDate = DateTime.Now.AddDays(policy.StorageDuration);

				client.PerformTransfer(transfer,
									   HandleUploadProgressChanged,
									   HandleUploadComplete,
									   HandleUploadInterrupted,
									   HandleUploadCancelled);
			}
			catch (Exception e)
			{
				Console.Error.WriteLine("An error has occurred: " + e);
			}
			finally
			{
				Console.WriteLine("Press any key to terminate the program.");
				Console.ReadKey();
			}
		}

		private static void HandleUploadProgressChanged(string currentFileNo,
														string currentFileName,
														double bytesUploaded,
														double bytesTotal,
														long bytesPerSecond)
		{
			// Print a status line every time the upload progress has changed.
			int percent = (int)(bytesUploaded / bytesTotal * 100);
			string speedInMbs = $"{((double)bytesPerSecond / 1024 / 1024).ToString("0.00")} MB/s";
			string statusLine = $"Filename: {currentFileName}\tProgress: {percent}%\tSpeed: {speedInMbs}";
			Console.Write($"\r{statusLine}");
		}

		private static void HandleUploadComplete(IDictionary<string, string> urlMappings,
												 IDictionary<string, string> smtpMappings,
												 string serverGenPassword,
												 TransferError transferError,
												 string trackingID)
		{
			// Reveal the final transfer information to the sender.
			Console.WriteLine("\nUpload finished!");
			Console.WriteLine("URL mappings:");
			foreach (var mapping in urlMappings)
			{
				Console.WriteLine($"{mapping.Key} => {mapping.Value}");
			}
			Console.WriteLine("SMTP mappings:");
			foreach (var mapping in smtpMappings)
			{
				Console.WriteLine($"{mapping.Key} => {mapping.Value}");
			}
			Console.WriteLine($"Tracking ID: {trackingID}");
		}

		private static void HandleUploadInterrupted(CryptshareException exception)
		{
			Console.WriteLine("The upload has been interrupted by the server!");
		}
		private static void HandleUploadCancelled()
		{
			Console.WriteLine("The upload has been cancelled by the user!");
		}
	}
}

Beispiel: Cryptshare Folder Watcher

Während das oben stehende Beispiel den Haupteinsatzzweck von Cryptshare – das Versenden vertraulicher Dateien und Nachrichten – veranschaulicht, lassen sich mithilfe der .NET API eine ganze Reihe von Anwendungenzwecken abdecken. Wir demonstrieren nachfolgend ein Programm, welches auf das oben stehende Beispielprogramm aufbaut und dabei auf neue Dateien innerhalb eines bestimmten Verzeichnisses wartet, um diese synchron an einen bestimmten Empfänger zu transferieren. Das Beispiel ist bewusst einfach gehalten, um den Fokus auf die API-Funktionalität zu legen.

Ausklappen, um Quellcode einzusehen...  Expand source

using Cryptshare.API;
using System;
using System.Collections.Generic;
using System.IO;

namespace CryptshareFolderWatcher
{
	class Program
	{
		private static readonly string SenderEmailAddress = "alice@example.com";
		private static readonly string SenderName = "Alice";
		private static readonly string SenderPhoneNumber = "+1 (123) 4567 890";
		private static readonly string ServerUrl = "https://cryptshare.example.com";
		// New "client.store" file will be created if it doesn't already exist.
		// However, make sure the folder exists and is writable by the user running this program!
		private static readonly string ClientStoreLocation = @"C:\temp";
		private static readonly string RecipientEmailAddress = "bob@example.com";

		private static string WatchPath;
		private static string DonePath;

		static void Main(string[] args)
		{
			try
			{
				if (args.Length != 2)
					throw new ArgumentException("Exactly two path parameters need to be provided.");
				WatchPath = args[0];
				DonePath = args[1];
				using (FileSystemWatcher watcher = new FileSystemWatcher())
				{
					watcher.Path = WatchPath;
					watcher.NotifyFilter = NotifyFilters.FileName;
					watcher.Created += OnCreated;
					watcher.EnableRaisingEvents = true;
					Console.WriteLine($"Watching directory {WatchPath}... press 'q' and [Enter] to quit watching.");
					while (Console.Read() != 'q') ;
				}
			}
			catch (Exception e)
			{
				Console.Error.WriteLine("An error has occurred: " + e);
			}
			finally
			{
				Console.WriteLine("Press any key to terminate the program.");
				Console.ReadKey();
			}
		}

		private static void OnCreated(object sender, FileSystemEventArgs e)
		{
			SendFile(e.FullPath);
			File.Move(e.FullPath, Path.Combine(DonePath, e.Name));
		}

		private static void SendFile(string filePath)
		{
			// Initialize the Client object.
			Client client = new Client(
				SenderEmailAddress,
				new CryptshareConnection(new WebServiceUri(ServerUrl)),
				ClientStoreLocation
			);
			// Initialize the Transfer object.
			Transfer transfer = new Transfer();

			// Define the sender and recipient information.
			transfer.SenderName = SenderName;
			transfer.SenderPhone = SenderPhoneNumber;
			transfer.Recipients.Add(new Recipient(RecipientEmailAddress));

			// Request a generated password of a minimum length specified by the server.
			transfer.PasswordMode = PasswordMode.Generated;
			int minimumPasswordLength = client.RequestPasswordPolicy().MinimumLength;
			transfer.Password = client.RequestGeneratedPassword(minimumPasswordLength);

			// Define the list of files to be sent.
			transfer.Files = new List<string>() { filePath };

			// Optional: Let the Cryptshare Server handle the email sending process.
			transfer.SendEmails = true;
			transfer.NotifySender = true;
			transfer.NotifyRecipients = true;
			transfer.InformAboutDownload = true;

			// Ensure that the client is verified.
			CheckVerificationResult checkVerificationResult = client.CheckVerification();
			if (!checkVerificationResult.Verified)
			{
				if (checkVerificationResult.VerificationMode == VerificationMode.Client)
				{
					Console.WriteLine("Please authorize the following Client ID on the Cryptshare Server:");
					Console.WriteLine(client.ClientId);
					return;
				}
				else
				{
					Console.WriteLine($"Requesting a verification code for {client.UserEmailAddress}...");
					client.RequestSenderVerification();
					Console.WriteLine($"Please enter the code below and confirm with [Enter]:");
					string code = Console.ReadLine().Trim();
					client.ConfirmSenderVerification(code);
				}
			}

			// Set the transfer expiration date to the maximum storage duration.
			Policy policy = client.RequestPolicy(transfer.Recipients.ConvertAll(recipient => recipient.EmailAddress));
			transfer.ExpirationDate = DateTime.Now.AddDays(policy.StorageDuration);

			client.PerformTransfer(transfer,
								   HandleUploadProgressChanged,
								   HandleUploadComplete,
								   HandleUploadInterrupted,
								   HandleUploadCancelled);
		}

		private static void HandleUploadProgressChanged(string currentFileNo,
														string currentFileName,
														double bytesUploaded,
														double bytesTotal,
														long bytesPerSecond)
		{
			// Print a status line every time the upload progress has changed.
			int percent = (int)(bytesUploaded / bytesTotal * 100);
			string speedInMbs = $"{((double)bytesPerSecond / 1024 / 1024).ToString("0.00")} MB/s";
			string statusLine = $"Filename: {currentFileName}\tProgress: {percent}%\tSpeed: {speedInMbs}";
			Console.Write($"\r{statusLine}");
		}

		private static void HandleUploadComplete(IDictionary<string, string> urlMappings,
												 IDictionary<string, string> smtpMappings,
												 string serverGenPassword,
												 TransferError transferError,
												 string trackingID)
		{
			// Reveal the final transfer information to the sender.
			Console.WriteLine("\nUpload finished!");
			Console.WriteLine("URL mappings:");
			foreach (var mapping in urlMappings)
			{
				Console.WriteLine($"{mapping.Key} => {mapping.Value}");
			}
			Console.WriteLine("SMTP mappings:");
			foreach (var mapping in smtpMappings)
			{
				Console.WriteLine($"{mapping.Key} => {mapping.Value}");
			}
			Console.WriteLine($"Tracking ID: {trackingID}");
		}

		private static void HandleUploadInterrupted(CryptshareException exception)
		{
			Console.WriteLine("The upload has been interrupted by the server!");
		}
		private static void HandleUploadCancelled()
		{
			Console.WriteLine("The upload has been cancelled by the user!");
		}
	}
}

Das daraus resultierende Programm sollte wie folgt bedienbar sein:

Your browser does not support the HTML5 video element

Ergebnis

Wie Sie sehen können ist es sehr einfach, auf Basis der Cryptshare .NET API individuelle Lösungen zu entwickeln und die Funktionsweise des Cryptshare Servers bedeutend zu erweitern. Wir hoffen, dass dieser Leitfaden Ihnen dabei hilft, Cryptshare in Ihren Automatisierungsworkflow einzubinden.