public override async Task LoadFromSourceAsync( string fullItemLocation, PackCntRuntimeOptions runtimeOptions = null) { // buffer to temp file try { await DownloadFromSource(new Uri(fullItemLocation), runtimeOptions); } catch (Exception ex) { throw new PackageContainerException( $"While buffering aasx from {Location} full-location {fullItemLocation} via HttpClient " + $"at {AdminShellUtil.ShortLocation(ex)} gave: {ex.Message}"); } // open try { Env = new AdminShellPackageEnv(TempFn, indirectLoadSave: false); runtimeOptions?.Log?.Info($".. successfully opened as AASX environment: {Env?.AasEnv?.ToString()}"); } catch (Exception ex) { throw new PackageContainerException( $"While opening buffered aasx {TempFn} from source {this.ToString()} " + $"at {AdminShellUtil.ShortLocation(ex)} gave: {ex.Message}"); } }
public virtual async Task <bool> SaveLocalCopyAsync( string targetFilename, PackCntRuntimeOptions runtimeOptions = null) { await Task.Yield(); return(false); }
public ProgressableStreamContent(byte[] content, int bufferSize, PackCntRuntimeOptions runtimeOptions = null) { if (bufferSize <= 0) { throw new ArgumentOutOfRangeException(nameof(bufferSize)); } this._content = content ?? throw new ArgumentNullException(nameof(content)); this._bufferSize = bufferSize; this._runtimeOptions = runtimeOptions; }
public override async Task LoadFromSourceAsync( string fullItemLocation, PackCntRuntimeOptions runtimeOptions = null) { // check extension if (IsFormat == Format.Unknown) { throw new PackageContainerException( "While loading aasx, unknown file format/ extension was encountered!"); } // buffer var fn = fullItemLocation; try { if (IndirectLoadSave) { TempFn = CreateNewTempFn(fullItemLocation, IsFormat); fn = TempFn; System.IO.File.Copy(fullItemLocation, fn); } else { TempFn = null; } } catch (Exception ex) { throw new PackageContainerException( $"While buffering aasx from {this.ToString()} full-location {fullItemLocation} " + $"at {AdminShellUtil.ShortLocation(ex)} gave: {ex.Message}"); } // open try { // TODO (MIHO, 2020-12-15): consider removing "indirectLoadSave" from AdminShellPackageEnv Env = new AdminShellPackageEnv(fn, indirectLoadSave: false); } catch (Exception ex) { throw new PackageContainerException( $"While opening aasx {fn} from source {this.ToString()} " + $"at {AdminShellUtil.ShortLocation(ex)} gave: {ex.Message}"); } await Task.Yield(); }
public static PackageContainerBase GuessAndCreateFor( PackageCentral packageCentral, string location, string fullItemLocation, bool overrideLoadResident, PackageContainerBase takeOver = null, PackageContainerOptionsBase containerOptions = null, PackCntRuntimeOptions runtimeOptions = null) { var task = Task.Run(() => GuessAndCreateForAsync( packageCentral, location, fullItemLocation, overrideLoadResident, takeOver, containerOptions, runtimeOptions)); return(task.Result); }
public bool Load( PackageCentral packageCentral, string location, string fullItemLocation, bool overrideLoadResident, PackageContainerOptionsBase containerOptions = null, PackCntRuntimeOptions runtimeOptions = null) { try { // close old one if (Container != null) { if (Container.IsOpen) { Container.Close(); } Container = null; } // figure out, what to load var task = Task.Run(async() => await PackageContainerFactory.GuessAndCreateForAsync( packageCentral, location, fullItemLocation, overrideLoadResident, null, containerOptions, runtimeOptions)); var guess = task.Result; if (guess == null) { return(false); } // success! Container = guess; return(true); } catch (Exception ex) { throw new PackageCentralException( $"PackageCentral: while performing load from {location} " + $"at {AdminShellUtil.ShortLocation(ex)} gave: {ex.Message}", ex); } }
public async Task <bool> SaveAsAsync(string saveAsNewFileName = null, AdminShellPackageEnv.SerializationFormat prefFmt = AdminShellPackageEnv.SerializationFormat.None, PackCntRuntimeOptions runtimeOptions = null) { try { await Container.SaveToSourceAsync(saveAsNewFileName, prefFmt, runtimeOptions); return(true); } catch (Exception ex) { throw new PackageCentralException( $"PackageCentral: while saving {"" + Container?.ToString()} " + $"with new filename {"" + saveAsNewFileName}" + $"at {AdminShellUtil.ShortLocation(ex)} gave: {ex.Message}"); } }
public static async Task <PackageContainerNetworkHttpFile> CreateAndLoadAsync( PackageCentral packageCentral, string location, string fullItemLocation, bool overrideLoadResident, PackageContainerBase takeOver = null, PackageContainerOptionsBase containerOptions = null, PackCntRuntimeOptions runtimeOptions = null) { var res = new PackageContainerNetworkHttpFile(CopyMode.Serialized, takeOver, packageCentral, location, containerOptions); if (overrideLoadResident || true == res.ContainerOptions?.LoadResident) { await res.LoadFromSourceAsync(fullItemLocation, runtimeOptions); } return(res); }
public override async Task <bool> SaveLocalCopyAsync( string targetFilename, PackCntRuntimeOptions runtimeOptions = null) { // Location shall be present if (!Location.HasContent()) { return(false); } // buffer to temp file try { await DownloadFromSource(new Uri(Location), runtimeOptions); } catch (Exception ex) { throw new PackageContainerException( $"While buffering aasx from {Location} via HttpClient " + $"at {AdminShellUtil.ShortLocation(ex)} gave: {ex.Message}"); } // copy temp file try { File.Copy(TempFn, targetFilename, overwrite: true); } catch (Exception ex) { throw new PackageContainerException( $"While copying local copy buffered aasx {TempFn} from source {this.ToString()} " + $"to target file {targetFilename} " + $"at {AdminShellUtil.ShortLocation(ex)} gave: {ex.Message}"); } // ok ?! return(true); }
public virtual async Task SaveToSourceAsync(string saveAsNewFileName = null, AdminShellPackageEnv.SerializationFormat prefFmt = AdminShellPackageEnv.SerializationFormat.None, PackCntRuntimeOptions runtimeOptions = null) { await Task.Yield(); }
public virtual async Task LoadFromSourceAsync( string fullItemLocation, PackCntRuntimeOptions runtimeOptions = null) { await Task.Yield(); }
public static async Task <PackageContainerBase> Demo( PackageCentral packageCentral, string location, bool overrideLoadResident, PackageContainerOptionsBase containerOptions = null, PackCntRuntimeOptions ro = null) { // Log location ro?.Log?.Info($"Perform Demo() for location {location}"); // ask for a list var li1 = new List <SelectFromListFlyoutItem>(); li1.Add(new SelectFromListFlyoutItem("AAAAAAAAAAAAAAAAAAAAAAAAAAA", "A")); li1.Add(new SelectFromListFlyoutItem("bbbbbbbbbbbb", "B")); li1.Add(new SelectFromListFlyoutItem("CCCCCCCCCCCCCCCCCC CCCCC", "C")); var waitLi1 = new TaskCompletionSource <SelectFromListFlyoutItem>(); ro?.AskForSelectFromList?.Invoke("Testselect", li1, waitLi1); var xx = await waitLi1.Task; ro?.Log?.Info($".. selected item is {"" + xx?.Text}"); // ask for a list var li2 = new List <SelectFromListFlyoutItem>(); li2.Add(new SelectFromListFlyoutItem("111111111", "A")); li2.Add(new SelectFromListFlyoutItem("222222222222222222222222", "B")); li2.Add(new SelectFromListFlyoutItem("3333333333333 3333", "C")); var waitLi2 = new TaskCompletionSource <SelectFromListFlyoutItem>(); ro?.AskForSelectFromList?.Invoke("Testselect", li2, waitLi2); var xy = await waitLi2.Task; ro?.Log?.Info($".. selected item is {"" + xy?.Text}"); // ask for credentials var waitCre = new TaskCompletionSource <PackageContainerCredentials>(); ro?.AskForCredentials?.Invoke("Fill user credentials", waitCre); var xz = await waitCre.Task; ro?.Log?.Info($".. credentials are {"" + xz?.Username} and {"" + xz?.Password}"); // debug some important blocks of text ro?.Log?.Info(StoredPrint.Color.Yellow, "Showing fingerprint:"); var sum = ""; for (int i = 0; i < 1000; i++) { sum += $"{i} "; } ro?.Log?.Info($"Showing fingerprint: {sum}"); // done ro?.Log?.Info($".. demo loading from internet .."); return(await PackageContainerNetworkHttpFile.CreateAndLoadAsync( packageCentral, "http://admin-shell-io.com:51310/server/getaasx/0", "http://admin-shell-io.com:51310/server/getaasx/0", // "http://localhost:51310/server/getaasx/0", overrideLoadResident, null, containerOptions, ro)); }
public override async Task SaveToSourceAsync(string saveAsNewFileName = null, AdminShellPackageEnv.SerializationFormat prefFmt = AdminShellPackageEnv.SerializationFormat.None, PackCntRuntimeOptions runtimeOptions = null) { // apply possible new source name directly if (saveAsNewFileName != null) { SetNewLocation(saveAsNewFileName); } // check extension if (IsFormat == Format.Unknown) { throw new PackageContainerException( "While saving aasx, unknown file format/ extension was encountered!"); } // check open package if (Env == null) { Env = null; throw new PackageContainerException( "While saving aasx, package was indeed not existng!"); } // divert on indirect load/ save, to have dedicated try&catch if (IndirectLoadSave) { // the container or package might be new if (!Env.IsOpen || TempFn == null) { TempFn = CreateNewTempFn(Location, IsFormat); Env.SaveAs(TempFn); } // do a close, execute and re-open cycle try { Env.TemporarilySaveCloseAndReOpenPackage(() => { System.IO.File.Copy(Env.Filename, Location, overwrite: true); }); } catch (Exception ex) { throw new PackageContainerException( $"While indirect-saving aasx to source {this.ToString()} " + $"at {AdminShellUtil.ShortLocation(ex)} gave: {ex.Message}"); } } else { // new file? if (saveAsNewFileName != null) { // save as try { Env.SaveAs(saveAsNewFileName, prefFmt: prefFmt); } catch (Exception ex) { throw new PackageContainerException( $"While saving aasx to new source {saveAsNewFileName} " + $"at {AdminShellUtil.ShortLocation(ex)} gave: {ex.Message}"); } } else { // just save try { Env.SaveAs(Location); } catch (Exception ex) { throw new PackageContainerException( $"While direct-saving aasx to source {this.ToString()} " + $"at {AdminShellUtil.ShortLocation(ex)} gave: {ex.Message}"); } } } // fake async await Task.Yield(); }
public override async Task SaveToSourceAsync(string saveAsNewFileName = null, AdminShellPackageEnv.SerializationFormat prefFmt = AdminShellPackageEnv.SerializationFormat.None, PackCntRuntimeOptions runtimeOptions = null) { // check extension if (IsFormat == Format.Unknown) { throw new PackageContainerException( "While saving aasx, unknown file format/ extension was encountered!"); } // check open package if (Env == null || !Env.IsOpen) { Env = null; throw new PackageContainerException( "While saving aasx, package was indeed not existng or not open!"); } // will use an file-copy for upload var copyFn = CreateNewTempFn(Env.Filename, IsFormat); // divert on indirect load/ save, to have dedicated try&catch if (IndirectLoadSave) { // do a close, execute and re-open cycle try { Env.TemporarilySaveCloseAndReOpenPackage(() => { System.IO.File.Copy(Env.Filename, copyFn, overwrite: true); }); } catch (Exception ex) { throw new PackageContainerException( $"While indirect-saving aasx to temp-file {copyFn} " + $"at {AdminShellUtil.ShortLocation(ex)} gave: {ex.Message}"); } } else { // just save as a copy try { Env.SaveAs(copyFn, saveOnlyCopy: true); } catch (Exception ex) { throw new PackageContainerException( $"While direct-saving aasx to temp-file {copyFn} " + $"at {AdminShellUtil.ShortLocation(ex)} gave: {ex.Message}"); } } // now, try to upload this try { await UploadToServerAsync(copyFn, new Uri(Location), runtimeOptions); } catch (Exception ex) { throw new PackageContainerException( $"While uploading to {Location} from temp-file {copyFn} " + $"at {AdminShellUtil.ShortLocation(ex)} gave: {ex.Message}"); } }
private async Task UploadToServerAsync(string copyFn, Uri serverUri, PackCntRuntimeOptions runtimeOptions = null) { // read via HttpClient (uses standard proxies) var handler = new HttpClientHandler(); handler.DefaultProxyCredentials = CredentialCache.DefaultCredentials; var client = new HttpClient(handler); if (OpenIDClient.token != "") { client.SetBearerToken(OpenIDClient.token); } // BEGIN Workaround behind some proxies // Stream is sent twice, if proxy-authorization header is not set string proxyFile = Environment.GetFolderPath(Environment.SpecialFolder.Personal) + "/proxy.dat"; string username = ""; string password = ""; if (File.Exists(proxyFile)) { using (StreamReader sr = new StreamReader(proxyFile)) { // ReSharper disable MethodHasAsyncOverload sr.ReadLine(); username = sr.ReadLine(); password = sr.ReadLine(); // ReSharper enable MethodHasAsyncOverload } } if (username != "" && password != "") { var authToken = Encoding.ASCII.GetBytes(username + ":" + password); client.DefaultRequestHeaders.ProxyAuthorization = new AuthenticationHeaderValue("Basic", Convert.ToBase64String(authToken)); } // END Workaround behind some proxies client.BaseAddress = new Uri(serverUri.GetLeftPart(UriPartial.Authority)); var requestPath = serverUri.PathAndQuery; // Log runtimeOptions?.Log?.Info($"HttpClient() with base-address {client.BaseAddress} " + $"and request {requestPath} .. "); // make base64 var ba = File.ReadAllBytes(copyFn); var base64 = Convert.ToBase64String(ba); //// var msBase64 = new MemoryStream(Encoding.UTF8.GetBytes(base64)); // customised HttpContent to track progress var data = new ProgressableStreamContent(Encoding.UTF8.GetBytes(base64), runtimeOptions); // get response? using (var response = await client.PutAsync(requestPath, data)) { if (response.IsSuccessStatusCode) { await response.Content.ReadAsStringAsync(); } if (!response.IsSuccessStatusCode) { System.Windows.Forms.MessageBox.Show("Operation not allowed!", "Server Message", System.Windows.Forms.MessageBoxButtons.OK); throw new PackageContainerException($"Server operation not allowed!"); } } }
public static async Task <PackageContainerBase> GuessAndCreateForAsync( PackageCentral packageCentral, string location, string fullItemLocation, bool overrideLoadResident, PackageContainerBase takeOver = null, PackageContainerOptionsBase containerOptions = null, PackCntRuntimeOptions runtimeOptions = null) { // access if (location == null) { return(null); } var ll = location.ToLower(); // guess runtimeOptions?.Log?.Info($"Trying to guess package container for {location} .."); var guess = PackageContainerGuess.FromLocation(location, runtimeOptions); if (guess == null) { runtimeOptions?.Log?.Info("Aborting"); return(null); } // start runtimeOptions?.Log?.Info($".. with containerOptions = {containerOptions?.ToString()}"); // TODO (MIHO, 2021-02-01): check, if demo option is still required if (ll.Contains("/demo")) { return(await Demo(packageCentral, location, overrideLoadResident, containerOptions, runtimeOptions)); } // starts with http ? if (guess.GuessedType == typeof(PackageContainerNetworkHttpFile)) { var cnt = await PackageContainerNetworkHttpFile.CreateAndLoadAsync( packageCentral, location, fullItemLocation, overrideLoadResident, takeOver, containerOptions, runtimeOptions); if (cnt.ContainerOptions.StayConnected && guess.AasId.HasContent() && guess.HeadOfPath.HasContent()) { cnt.ConnectorPrimary = new PackageConnectorHttpRest(cnt, new Uri(guess.HeadOfPath + "/aas/" + guess.AasId)); } return(cnt); } // check FileInfo for (possible?) local file FileInfo fi = null; try { fi = new FileInfo(location); } catch (Exception ex) { LogInternally.That.SilentlyIgnoredError(ex); } // if file, try to open (might throw exceptions!) if (fi != null) { // seems to be a valid (possible) file return(await PackageContainerLocalFile.CreateAndLoadAsync( packageCentral, location, fullItemLocation, overrideLoadResident, takeOver, containerOptions)); } // no?? runtimeOptions?.Log?.Info($".. no any possible option for package container found .. Aborting!"); return(null); }
public ProgressableStreamContent(byte[] content, PackCntRuntimeOptions runtimeOptions = null) : this(content, _defaultBufferSize, runtimeOptions) { }
/// <summary> /// Guess the container type based on <c>location</c> and parse necessary arguments /// </summary> /// <param name="location"></param> /// <param name="runtimeOptions"></param> /// <returns></returns> public static PackageContainerGuess FromLocation( string location, PackCntRuntimeOptions runtimeOptions = null) { // access if (location == null) { return(null); } var ll = location.ToLower(); // Log? runtimeOptions?.Log?.Info($"Trying to guess package container for {location} .."); // starts with http ? if (ll.StartsWith("http://") || ll.StartsWith("https://")) { // direct evidence of /getaasx/ var match = Regex.Match(ll, @"^(.*)/server/getaasx/([^/])+(/|$)"); if (match.Success && match.Groups.Count >= 3) { // care for the aasx file runtimeOptions?.Log?.Info($".. deciding for networked HHTP file .."); return(new PackageContainerGuess() { Location = location, GuessedType = typeof(PackageContainerNetworkHttpFile), HeadOfPath = match.Groups[1].ToString().Trim(), AasId = match.Groups[2].ToString().Trim() }); } runtimeOptions?.Log?.Info($".. no adequate HTTP option found!"); } // check FileInfo for (possible?) local file FileInfo fi = null; try { fi = new FileInfo(location); } catch (Exception ex) { LogInternally.That.SilentlyIgnoredError(ex); } // if file, try to open (might throw exceptions!) if (fi != null) { // seems to be a valid (possible) file return new PackageContainerGuess() { Location = location, GuessedType = typeof(PackageContainerLocalFile) } } ; // no?? runtimeOptions?.Log?.Info($".. no any possible option for package container found"); return(null); } }
private async Task DownloadFromSource(Uri sourceUri, PackCntRuntimeOptions runtimeOptions = null) { // read via HttpClient (uses standard proxies) var handler = new HttpClientHandler(); handler.DefaultProxyCredentials = CredentialCache.DefaultCredentials; handler.AllowAutoRedirect = false; var client = new HttpClient(handler); client.DefaultRequestHeaders.Add("Accept", "application/aas"); client.BaseAddress = new Uri(sourceUri.GetLeftPart(UriPartial.Authority)); var requestPath = sourceUri.PathAndQuery; // Log runtimeOptions?.Log?.Info($"HttpClient() with base-address {client.BaseAddress} " + $"and request {requestPath} .. "); if (OpenIDClient.token != "") { client.SetBearerToken(OpenIDClient.token); } bool repeat = true; while (repeat) { // get response? var response = await client.GetAsync(requestPath, HttpCompletionOption.ResponseHeadersRead); if (response.StatusCode == System.Net.HttpStatusCode.TemporaryRedirect) { string redirectUrl = response.Headers.Location.ToString(); // ReSharper disable once RedundantExplicitArrayCreation string[] splitResult = redirectUrl.Split(new string[] { "?" }, StringSplitOptions.RemoveEmptyEntries); runtimeOptions?.Log?.Info("Redirect to:" + splitResult[0]); OpenIDClient.authServer = splitResult[0]; runtimeOptions?.Log?.Info($".. authentication at auth server {OpenIDClient.authServer} needed"); var response2 = await OpenIDClient.RequestTokenAsync(null); OpenIDClient.token = response2.AccessToken; client.SetBearerToken(OpenIDClient.token); repeat = true; continue; } repeat = false; if (response.IsSuccessStatusCode) { var contentLength = response.Content.Headers.ContentLength; var contentFn = response.Content.Headers.ContentDisposition?.FileName; // log runtimeOptions?.Log?.Info($".. response with header-content-len {contentLength} " + $"and file-name {contentFn} .."); var contentStream = await response?.Content?.ReadAsStreamAsync(); if (contentStream == null) { throw new PackageContainerException( $"While getting data bytes from {Location} via HttpClient " + $"no data-content was responded!"); } // create temp file and write to it var givenFn = Location; if (contentFn != null) { givenFn = contentFn; } TempFn = CreateNewTempFn(givenFn, IsFormat); runtimeOptions?.Log?.Info($".. downloading and scanning by proxy/firewall {client.BaseAddress} " + $"and request {requestPath} .. "); using (var file = new FileStream(TempFn, FileMode.Create, FileAccess.Write, FileShare.None)) { // copy with progress var bufferSize = 4024; var deltaSize = 512 * 1024; var buffer = new byte[bufferSize]; long totalBytesRead = 0; long lastBytesRead = 0; int bytesRead; runtimeOptions?.ProgressChanged?.Invoke(PackCntRuntimeOptions.Progress.Starting, contentLength, totalBytesRead); while ((bytesRead = await contentStream.ReadAsync(buffer, 0, buffer.Length, default(CancellationToken)).ConfigureAwait(false)) != 0) { await file.WriteAsync(buffer, 0, bytesRead, default(CancellationToken)).ConfigureAwait(false); totalBytesRead += bytesRead; if (totalBytesRead > lastBytesRead + deltaSize) { runtimeOptions?.Log?.Info($".. downloading to temp-file {TempFn}"); runtimeOptions?.ProgressChanged?.Invoke(PackCntRuntimeOptions.Progress.Ongoing, contentLength, totalBytesRead); lastBytesRead = totalBytesRead; } } // assume bytes read to be total bytes runtimeOptions?.ProgressChanged?.Invoke(PackCntRuntimeOptions.Progress.Final, totalBytesRead, totalBytesRead); // log runtimeOptions?.Log?.Info($".. download done with {totalBytesRead} bytes read!"); } } else { System.Windows.Forms.MessageBox.Show("Operation not allowed!", "Server Message", System.Windows.Forms.MessageBoxButtons.OK); throw new PackageContainerException($"Server operation not allowed!"); } } }