Beispiel #1
0
        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}");
            }
        }
Beispiel #2
0
        public virtual async Task <bool> SaveLocalCopyAsync(
            string targetFilename,
            PackCntRuntimeOptions runtimeOptions = null)
        {
            await Task.Yield();

            return(false);
        }
Beispiel #3
0
        private OpenIdClientInstance.UiLambdaSet GenerateUiLambdaSet(PackCntRuntimeOptions runtimeOptions = null)
        {
            var res = new OpenIdClientInstance.UiLambdaSet();

            if (runtimeOptions?.ShowMesssageBox != null)
            {
                res.MesssageBox = (content, text, title, buttons) =>
                                  runtimeOptions.ShowMesssageBox(content, text, title, buttons);
            }

            return(res);
        }
Beispiel #4
0
        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,
            PackageContainerListBase containerList       = null,
            PackageContainerOptionsBase containerOptions = null,
            PackCntRuntimeOptions runtimeOptions         = null)
        {
            var task = Task.Run(() => GuessAndCreateForAsync(
                                    packageCentral, location, fullItemLocation, overrideLoadResident,
                                    takeOver, containerList, containerOptions, runtimeOptions));

            return(task.Result);
        }
Beispiel #7
0
        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, 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);
            }
        }
Beispiel #8
0
        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 <PackageContainerLocalFile> CreateAndLoadAsync(
            PackageCentral packageCentral,
            string location,
            string fullItemLocation,
            bool overrideLoadResident,
            PackageContainerBase takeOver = null,
            PackageContainerOptionsBase containerOptions = null,
            PackCntRuntimeOptions runtimeOptions         = null)
        {
            var res = new PackageContainerLocalFile(
                CopyMode.Serialized, takeOver,
                packageCentral, location, containerOptions);

            if (overrideLoadResident || true == res.ContainerOptions?.LoadResident)
            {
                await res.LoadFromSourceAsync(fullItemLocation, runtimeOptions);
            }

            return(res);
        }
Beispiel #10
0
        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);
        }
Beispiel #11
0
        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} .. ");

            // Token existing?
            var clhttp = ContainerList as PackageContainerListHttpRestBase;
            var oidc   = clhttp?.OpenIdClient;

            if (oidc == null)
            {
                runtimeOptions?.Log?.Info("  no ContainerList available. No OpecIdClient possible!");
                if (clhttp != null && OpenIDClient.email != "")
                {
                    clhttp.OpenIdClient          = new OpenIdClientInstance();
                    clhttp.OpenIdClient.email    = OpenIDClient.email;
                    clhttp.OpenIdClient.ssiURL   = OpenIDClient.ssiURL;
                    clhttp.OpenIdClient.keycloak = OpenIDClient.keycloak;
                    oidc = clhttp.OpenIdClient;
                }
            }
            if (oidc != null)
            {
                if (oidc.token != "")
                {
                    runtimeOptions?.Log?.Info($"  using existing bearer token.");
                    client.SetBearerToken(oidc.token);
                }
                else
                {
                    if (oidc.email != "")
                    {
                        runtimeOptions?.Log?.Info($"  using existing email token.");
                        client.DefaultRequestHeaders.Add("Email", OpenIDClient.email);
                    }
                }
            }

            bool repeat = true;

            while (repeat)
            {
                // get response?
                var response = await client.GetAsync(requestPath,
                                                     HttpCompletionOption.ResponseHeadersRead);

                if (clhttp != null &&
                    response.StatusCode == System.Net.HttpStatusCode.TemporaryRedirect)
                {
                    string redirectUrl = response.Headers.Location.ToString();
                    // ReSharper disable once RedundantExplicitArrayCreation
                    string[] splitResult = redirectUrl.Split(new string[] { "?" },
                                                             StringSplitOptions.RemoveEmptyEntries);
                    splitResult[0] = splitResult[0].TrimEnd('/');
                    var    queryString = HttpUtility.ParseQueryString(splitResult[1]);
                    string authType    = queryString["authType"];
                    if (authType == "keycloak")
                    {
                        OpenIDClient.keycloak = splitResult[0];
                    }

                    if (splitResult.Length < 1)
                    {
                        runtimeOptions?.Log?.Error("TemporaryRedirect, but url split to successful");
                        break;
                    }

                    runtimeOptions?.Log?.Info("Redirect to: " + splitResult[0]);
                    runtimeOptions?.Log?.Info("AuthType: " + authType);

                    if (oidc == null)
                    {
                        runtimeOptions?.Log?.Info("Creating new OpenIdClient..");
                        oidc = new OpenIdClientInstance();
                        clhttp.OpenIdClient          = oidc;
                        clhttp.OpenIdClient.email    = OpenIDClient.email;
                        clhttp.OpenIdClient.ssiURL   = OpenIDClient.ssiURL;
                        clhttp.OpenIdClient.keycloak = OpenIDClient.keycloak;
                    }

                    oidc.authServer = splitResult[0];

                    runtimeOptions?.Log?.Info($".. authentication at auth server {oidc.authServer} needed");

                    var response2 = await oidc.RequestTokenAsync(null,
                                                                 GenerateUiLambdaSet(runtimeOptions));

                    if (oidc.keycloak == "" && response2 != null)
                    {
                        oidc.token = response2.AccessToken;
                    }
                    if (oidc.token != "" && oidc.token != null)
                    {
                        client.SetBearerToken(oidc.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
                {
                    Log.Singleton.Error("DownloadFromSource Server gave: Operation not allowed!");
                    throw new PackageContainerException($"Server operation not allowed!");
                }
            }
        }
        /// <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 ..");

                    string aasId = match.Groups[2].ToString().Trim();
                    var    split = ll.Split('/');
                    if (split.Length >= 3)
                    {
                        aasId = split[split.Length - 1];
                    }
                    return(new PackageContainerGuess()
                    {
                        Location = location,
                        GuessedType = typeof(PackageContainerNetworkHttpFile),
                        HeadOfPath = match.Groups[1].ToString().Trim(),
                        AasId = aasId
                    });
                }

                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);
        }
    }
        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, prefFmt: prefFmt);
                }

                // do a close, execute and re-open cycle
                try
                {
                    Env.TemporarilySaveCloseAndReOpenPackage(
                        prefFmt: prefFmt, lambda: () =>
                    {
                        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();
        }
Beispiel #14
0
 public virtual async Task SaveToSourceAsync(string saveAsNewFileName = null,
                                             AdminShellPackageEnv.SerializationFormat prefFmt = AdminShellPackageEnv.SerializationFormat.None,
                                             PackCntRuntimeOptions runtimeOptions             = null)
 {
     await Task.Yield();
 }
Beispiel #15
0
 public virtual async Task LoadFromSourceAsync(
     string fullItemLocation,
     PackCntRuntimeOptions runtimeOptions = null)
 {
     await Task.Yield();
 }
Beispiel #16
0
        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;

            // new http client
            var client = new HttpClient(handler);

            // Token existing?
            var clhttp = ContainerList as PackageContainerListHttpRestBase;
            var oidc   = clhttp?.OpenIdClient;

            if (oidc == null)
            {
                runtimeOptions?.Log?.Info("  no ContainerList available. No OpecIdClient possible!");
            }
            else
            {
                if (oidc.token != "")
                {
                    runtimeOptions?.Log?.Info($"  using existing bearer token.");
                    client.SetBearerToken(oidc.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)
                {
                    Log.Singleton.Error("UploadToServerAsync Server gave: Operation not allowed!");
                    throw new PackageContainerException($"Server operation not allowed!");
                }
            }
        }
Beispiel #17
0
        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}");
            }
        }
        public static async Task <PackageContainerBase> GuessAndCreateForAsync(
            PackageCentral packageCentral,
            string location,
            string fullItemLocation,
            bool overrideLoadResident,
            PackageContainerBase takeOver                = null,
            PackageContainerListBase containerList       = 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, containerList,
                    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 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 <AnyUiDialogueListItem>();

            li1.Add(new AnyUiDialogueListItem("AAAAAAAAAAAAAAAAAAAAAAAAAAA", "A"));
            li1.Add(new AnyUiDialogueListItem("bbbbbbbbbbbb", "B"));
            li1.Add(new AnyUiDialogueListItem("CCCCCCCCCCCCCCCCCC  CCCCC", "C"));

            var waitLi1 = new TaskCompletionSource <AnyUiDialogueListItem>();

            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 <AnyUiDialogueListItem>();

            li2.Add(new AnyUiDialogueListItem("111111111", "A"));
            li2.Add(new AnyUiDialogueListItem("222222222222222222222222", "B"));
            li2.Add(new AnyUiDialogueListItem("3333333333333  3333", "C"));

            var waitLi2 = new TaskCompletionSource <AnyUiDialogueListItem>();

            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, null, containerOptions, ro));
        }
Beispiel #20
0
 public ProgressableStreamContent(byte[] content, PackCntRuntimeOptions runtimeOptions = null)
     : this(content, _defaultBufferSize, runtimeOptions)
 {
 }