public bool TakeOver(PackageContainerBase container) { try { // close old one if (Container != null) { if (Container.IsOpen) { Container.Close(); } Container = null; } // figure out, what to load Container = container; // success! return(true); } catch (Exception ex) { throw new PackageCentralException( $"PackageCentral: while performing takeover " + $"at {AdminShellUtil.ShortLocation(ex)} gave: {ex.Message}"); } }
public static AdminShell.ConceptDescription CreateSparseConceptDescription( string lang, string idType, string idShort, string id, string definitionHereString, AdminShell.Reference isCaseOf = null) { // access if (idShort == null || idType == null || id == null) { return(null); } // create CD var cd = AdminShell.ConceptDescription.CreateNew(idShort, idType, id); var dsiec = cd.CreateDataSpecWithContentIec61360(); dsiec.preferredName = new AdminShellV20.LangStringSetIEC61360(lang, "" + idShort); dsiec.definition = new AdminShellV20.LangStringSetIEC61360(lang, "" + AdminShellUtil.CleanHereStringWithNewlines(nl: " ", here: definitionHereString)); // options if (isCaseOf != null) { cd.IsCaseOf = new List <AdminShell.Reference>(new[] { isCaseOf }); } // ok return(cd); }
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}"); } }
private static AdminShellV20.AdministrationShell CreateAdminShell(AdminShellV20.AdministrationShellEnv env) { var adminShell = new AdminShellV20.AdministrationShell() { identification = new AdminShellV20.Identification( AdminShellV20.Identification.IRI, AdminShellUtil.GenerateIdAccordingTemplate(Options.Curr.TemplateIdAas)) }; env.AdministrationShells.Add(adminShell); return(adminShell); }
public void RedrawElementView() { if (DisplayElements == null) { return; } // the AAS will cause some more visual effects var tvlaas = DisplayElements.SelectedItem as VisualElementAdminShell; if (thePackageEnv != null && tvlaas != null && tvlaas.theAas != null && tvlaas.theEnv != null) { // AAS // update graphic left // what is AAS specific? this.AasId.Text = WrappingWpfString(AdminShellUtil.EvalToNonNullString("{0}", tvlaas.theAas.identification.id, "<id missing!>")); // what is asset specific? this.AssetPic.Source = null; this.AssetId.Text = "<id missing!>"; var asset = tvlaas.theEnv.FindAsset(tvlaas.theAas.assetRef); if (asset != null) { // text id if (asset.identification != null) { this.AssetId.Text = WrappingWpfString(AdminShellUtil.EvalToNonNullString("{0}", asset.identification.id, "")); } // asset thumbail try { var bi = new BitmapImage(); bi.BeginInit(); bi.CacheOption = BitmapCacheOption.OnLoad; bi.StreamSource = thePackageEnv.GetLocalThumbnailStream(); bi.EndInit(); this.AssetPic.Source = bi; // this.AssetPic.Source = new BitmapImage(new Uri("Resources/USB_Hexagon_offen.jpeg", UriKind.RelativeOrAbsolute)); } catch { // no error, intended behaviour, as thumbnail might not exist / be faulty in some way (not violating the spec) // Log.Error(ex, "Error loading package's thumbnail"); } } } // for all, prepare the display PrepareDispEditEntity(thePackageEnv, DisplayElements.SelectedItem, MenuItemWorkspaceEdit.IsChecked, MenuItemWorkspaceHints.IsChecked); }
private void UserControl_Loaded(object sender, RoutedEventArgs e) { // init with defaults this.ThisInit(1, 1, 4); // caption if (_caption != null) { TextBlockCaption.Text = _caption; } // if preset, load first preset if (this.Presets != null && this.Presets.Count > 0) { this.ThisFromPreset(this.Presets[0]); } // placeholders TextBoxPlaceholders.Text = AdminShellUtil.CleanHereStringWithNewlines( @"All placeholders delimited by %{..}%, {} = set arithmetics, [] = optional {Referable}.{idShort, category, description[@en..], elementName, elementShort, elementShort2, elementAbbreviation, kind, parent}, {Referable|Identifiable} = {SM, SME, CD}, depth, indent} {Identifiable}.{identification[.{idType, id}], administration.{ version, revision}}, {Qualifiable}.qualifiers, {Qualifiable}.multiplicity {Reference}, {Reference}[0..n], {Reference}[0..n].{type, local, idType, value}, {Reference} = {semanticId, isCaseOf, unitId} SME.value, Property.{value, valueType, valueId}, MultiLanguageProperty.{value, vlaueId}, Range.{valueType, min, max}, Blob.{mimeType, value}, File.{mimeType, value}, ReferenceElement.value, RelationshipElement.{first, second}, SubmodelElementCollection.{value = #elements, ordered, allowDuplicates}, Entity.{entityType, asset} CD.{preferredName[@en..], shortName[@en..], unit, unitId, sourceOfDefinition, symbol, dataType, definition[@en..], valueFormat} Special: %*% = match any, %stop% = stop if non-empty, %seq={ascii}% = split sequence by char {ascii}, %opt% = optional match Commands for header cells include: %fg={color}%, %bg={color}% with {color} = {#a030a0, Red, blue, ..}, %halign={left, center, right}%, %valign={top, center, bottom}%, %font={bold, italic, underline}, %frame={0,1,2,3}% (only whole table)"); // combo Presets ComboBoxPreset.Items.Clear(); if (this.Presets != null && this.Presets.Count > 0) { foreach (var p in this.Presets) { ComboBoxPreset.Items.Add("" + p.Name); } ComboBoxPreset.SelectionChanged += ComboBoxPreset_SelectionChanged; ComboBoxPreset.SelectedIndex = 0; } // combo Formats ComboBoxFormat.Items.Clear(); foreach (var f in ExportTableRecord.FormatNames) { ComboBoxFormat.Items.Add("" + f); } ComboBoxFormat.SelectedIndex = 0; }
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 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); } }
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 void Close() { try { // close old one if (Container != null) { if (Container.IsOpen) { Container.Close(); } Container = null; } } catch (Exception ex) { throw new PackageCentralException( $"PackageCentral: while performing close " + $"at {AdminShellUtil.ShortLocation(ex)} gave: {ex.Message}"); } }
public void DoSearch() { // access if (TheSearchOptions == null || TheSearchResults == null || TheAasEnv == null) { return; } // do not accept empty field if (TheSearchOptions.findText == null || TheSearchOptions.findText.Length < 1) { this.ButtonToolsFindInfo.Text = "no search!"; return; } // execution try { AdminShellUtil.EnumerateSearchable(TheSearchResults, TheAasEnv, "", 0, TheSearchOptions); } catch (Exception ex) { AasxPackageExplorer.Log.Singleton.Error(ex, "When searching for results"); } // try to go to 1st result CurrentResultIndex = -1; if (TheSearchResults.foundResults != null && TheSearchResults.foundResults.Count > 0 && ResultSelected != null) { CurrentResultIndex = 0; var sri = TheSearchResults.foundResults[0]; SetFindInfo(1 + CurrentResultIndex, TheSearchResults.foundResults.Count, sri); ResultSelected(sri); } else { this.ButtonToolsFindInfo.Text = "not found!"; } }
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 static AdminShellV20.Submodel CreateSubmodel( AdminShellV20.AdministrationShellEnv env, AdminShellV20.AdministrationShell adminShell, Iec61360Data data) { // We need this to ensure that we don't use the same AAS ID twice when importing multiple submodels (as // GenerateIdAccordingTemplate uses the timestamp as part of the ID). Thread.Sleep(1000); var submodel = new AdminShellV20.Submodel() { identification = new AdminShellV20.Identification( AdminShell.Identification.IRI, AdminShellUtil.GenerateIdAccordingTemplate(Options.Curr.TemplateIdSubmodelInstance)), idShort = data.IdShort, kind = AdminShellV20.ModelingKind.CreateAsInstance(), }; AddDescriptions(submodel, data); AddDataSpecification(env, submodel, data); adminShell.AddSubmodelRef(submodel.GetReference() as AdminShellV20.SubmodelRef); env.Submodels.Add(submodel); return(submodel); }
/// <summary> /// This function accesses the AAS, Asset and Submodel information of the environment and /// re-calculates the particulare lists of ids. If the tag and/ or description is empty, /// it will also build a generated tag or descriptions /// </summary> public void CalculateIdsTagAndDesc(bool force = false) { // Ids CleanIds(); Env?.AasEnv?.Assets?.ForEach((x) => { if (true == x?.identification?.id.HasContent()) { _assetIds.Add(x?.identification.id); } }); Env?.AasEnv?.AdministrationShells?.ForEach((x) => { if (true == x?.identification?.id.HasContent()) { _aasIds.Add(x?.identification.id); } }); Env?.AasEnv?.Submodels?.ForEach((x) => { if (true == x?.identification?.id.HasContent()) { _submodelIds.Add(x?.identification.id); } }); // get some descriptiive data var threeFn = Path.GetFileNameWithoutExtension(Location); var asset0 = Env?.AasEnv?.Assets?.FirstOrDefault(); var aas0 = Env?.AasEnv?.AdministrationShells?.FirstOrDefault(); // Tag if (!Tag.HasContent() || force) { // ReSharper disable ConditionIsAlwaysTrueOrFalse var tag = ""; try { tag = ""; if (asset0 != null) { tag = AdminShellUtil.ExtractPascalCasingLetters(asset0.idShort).SubstringMax(0, 3); } if (tag == null || tag.Length < 2) { tag = AdminShellUtil.ExtractPascalCasingLetters(threeFn).SubstringMax(0, 3); } if ((tag == null || tag.Length < 2) && aas0 != null) { tag = ("" + aas0.idShort).SubstringMax(0, 3).ToUpper(); } if (tag == null || tag.Length < 3) { tag = ("" + threeFn).SubstringMax(0, 3).ToUpper(); } } catch (Exception ex) { AdminShellNS.LogInternally.That.SilentlyIgnoredError(ex); } Tag = tag; // ReSharper enable ConditionIsAlwaysTrueOrFalse } // Description if (!Description.HasContent() || force) { var desc = ""; if (aas0?.idShort.HasContent() == true) { desc += $"{aas0.idShort}"; } if (asset0?.idShort.HasContent() == true) { if (desc.HasContent()) { desc += ","; } desc += $"{asset0.idShort}"; } Description = desc; } }
public string CreateTempFileForKeyboardShortcuts() { try { // create a temp HTML file var tmpfn = System.IO.Path.GetTempFileName(); // rename to html file var htmlfn = tmpfn.Replace(".tmp", ".html"); File.Move(tmpfn, htmlfn); // create html content as string var htmlHeader = AdminShellUtil.CleanHereStringWithNewlines( @"<!doctype html> <html lang=en> <head> <style> body { background-color: #FFFFE0; font-size: small; font-family: Arial, Helvetica, sans-serif; } table { font-family: arial, sans-serif; border-collapse: collapse; width: 100%; } td, th { border: 1px solid #dddddd; text-align: left; padding: 8px; } tr:nth-child(even) { background-color: #fffff0; } </style> <meta charset=utf-8> <title>blah</title> </head> <body>"); var htmlFooter = AdminShellUtil.CleanHereStringWithNewlines( @"</body> </html>"); var html = ""; html += "<h3>Keyboard shortcuts</h3>" + Environment.NewLine; html += AdminShellUtil.CleanHereStringWithNewlines( @"<table style=""width:100%""> <tr> <th>Modifiers & Keys</th> <th>Function</th> <th>Description</th> </tr>"); var rowfmt = AdminShellUtil.CleanHereStringWithNewlines( @"<tr> <td>{0}</th> <td>{1}</th> <td>{2}</th> </tr>"); if (_displayContext?.KeyShortcuts != null) { foreach (var sc in _displayContext.KeyShortcuts) { // Keys var keys = ""; if (sc.Modifiers.HasFlag(ModifierKeys.Shift)) { keys += "[Shift] "; } if (sc.Modifiers.HasFlag(ModifierKeys.Control)) { keys += "[Control] "; } if (sc.Modifiers.HasFlag(ModifierKeys.Alt)) { keys += "[Alt] "; } keys += "[" + sc.Key.ToString() + "]"; // Function var fnct = ""; if (sc.Element is AnyUiButton btn) { fnct = "" + btn.Content; } // fill html += String.Format(rowfmt, "" + keys, "" + fnct, "" + sc.Info); } } html += AdminShellUtil.CleanHereStringWithNewlines( @"</table>"); // write System.IO.File.WriteAllText(htmlfn, htmlHeader + html + htmlFooter); return(htmlfn); } catch (Exception ex) { Log.Singleton.Error(ex, "Creating HTML file for keyboard shortcuts"); } return(null); }
public void AddByAas(AdminShell.AdministrationShellEnv env, AdminShell.AdministrationShell aas, string fn) { // access if (env == null || aas?.identification == null) { return; } var aasId = "" + aas.identification.id; // demand also asset var asset = env.FindAsset(aas.assetRef); if (asset?.identification == null) { return; } var assetId = "" + asset.identification.id; // try determine tag // ReSharper disable ConditionIsAlwaysTrueOrFalse var tag = ""; try { var threeFn = Path.GetFileNameWithoutExtension(fn); tag = AdminShellUtil.ExtractPascalCasingLetters(asset.idShort); if (tag == null || tag.Length < 2) { tag = AdminShellUtil.ExtractPascalCasingLetters(threeFn).SubstringMax(0, 3); } if (tag == null || tag.Length < 2) { tag = ("" + asset.idShort).SubstringMax(0, 3).ToUpper(); } if (tag == null || tag.Length < 3) { tag = ("" + threeFn).SubstringMax(0, 3).ToUpper(); } } catch (Exception ex) { AdminShellNS.LogInternally.That.SilentlyIgnoredError(ex); } // ReSharper enable ConditionIsAlwaysTrueOrFalse // build description var desc = ""; if (aas.idShort.HasContent()) { desc += $"\"{aas.idShort}\""; } if (asset.idShort.HasContent()) { if (desc.HasContent()) { desc += ","; } desc += $"\"{asset.idShort}\""; } // ok, add var fi = new FileItem( assetId: assetId, aasId: aasId, fn: fn, tag: "" + tag, description: desc); fi.VisualState = FileItem.VisualStateEnum.ReadFrom; fi.VisualTime = 2.0; this.Add(fi); }
// // Referable // public void DisplayOrEditEntityReferable(StackPanel stack, AdminShell.Referable referable, DispEditInjectAction injectToIdShort = null, HintCheck[] addHintsCategory = null, bool categoryUsual = false) { // access if (stack == null || referable == null) { return; } // members this.AddGroup(stack, "Referable:", levelColors[1][0], levelColors[1][1]); // members this.AddHintBubble(stack, hintMode, new[] { new HintCheck(() => { return(referable.idShort == null || referable.idShort.Length < 1); }, "idShort is meanwhile mandatory for all Referables. It is a short, " + "unique identifier that is unique just in its context, its name space. ", breakIfTrue: true), new HintCheck( () => { if (referable.idShort == null) { return(false); } return(!AdminShellUtil.ComplyIdShort(referable.idShort)); }, "idShort shall only feature letters, digits, underscore ('_'); " + "starting mandatory with a letter..") }); this.AddKeyValueRef( stack, "idShort", referable, ref referable.idShort, null, repo, v => { referable.idShort = v as string; return(new ModifyRepo.LambdaActionNone()); }, auxButtonTitles: DispEditInjectAction.GetTitles(null, injectToIdShort), auxButtonToolTips: DispEditInjectAction.GetToolTips(null, injectToIdShort), auxButtonLambda: injectToIdShort?.auxLambda ); if (!categoryUsual) { this.AddHintBubble( stack, hintMode, new HintCheck(() => { return(referable.category != null && referable.category.Trim().Length >= 1); }, "The use of category is unusual here.", severityLevel: HintCheck.Severity.Notice)); } this.AddHintBubble(stack, hintMode, this.ConcatHintChecks(null, addHintsCategory)); this.AddKeyValueRef( stack, "category", referable, ref referable.category, null, repo, v => { referable.category = v as string; return(new ModifyRepo.LambdaActionNone()); }, comboBoxItems: AdminShell.Referable.ReferableCategoryNames, comboBoxIsEditable: true); this.AddHintBubble( stack, hintMode, new[] { new HintCheck( () => { return(referable.description == null || referable.description.langString == null || referable.description.langString.Count < 1); }, "The use of an description is recommended to allow the consumer of an Referable " + "to understand the nature of it.", breakIfTrue: true, severityLevel: HintCheck.Severity.Notice), new HintCheck( () => { return(referable.description.langString.Count < 2); }, "Consider having description in multiple langauges.", severityLevel: HintCheck.Severity.Notice) }); if (this.SafeguardAccess(stack, repo, referable.description, "description:", "Create data element!", v => { referable.description = new AdminShell.Description(); return(new ModifyRepo.LambdaActionRedrawEntity()); })) { this.AddHintBubble( stack, hintMode, new HintCheck( () => { return(referable.description.langString == null || referable.description.langString.Count < 1); }, "Please add some descriptions in your main languages here to help consumers " + "of your Administration shell to understand your intentions.")); this.AddKeyListLangStr(stack, "description", referable.description.langString, repo); } }
// // Identifiable // public void DisplayOrEditEntityIdentifiable(AnyUiStackPanel stack, AdminShell.Identifiable identifiable, string templateForIdString, DispEditInjectAction injectToId = null, bool checkForIri = true) { // access if (stack == null || identifiable == null) { return; } // members this.AddGroup(stack, "Identifiable:", levelColors.SubSection); this.AddHintBubble(stack, hintMode, new[] { new HintCheck( () => { return(identifiable.identification == null); }, "Providing a worldwide unique identification is mandatory.", breakIfTrue: true), new HintCheck( () => { return(checkForIri && identifiable.identification.idType != AdminShell.Identification.IRI); }, "Check if identification type is correct. Use of IRIs is usual here.", severityLevel: HintCheck.Severity.Notice), new HintCheck( () => { return(identifiable.identification.id.Trim() == ""); }, "Identification id shall not be empty. You could use the 'Generate' button in order to " + "generate a worldwide unique id. " + "The template of this id could be set by commandline arguments.") }); if (this.SafeguardAccess( stack, repo, identifiable.identification, "identification:", "Create data element!", v => { identifiable.identification = new AdminShell.Identification(); this.AddDiaryEntry(identifiable, new DiaryEntryStructChange()); return(new AnyUiLambdaActionRedrawEntity()); })) { this.AddKeyValueRef( stack, "idType", identifiable, ref identifiable.identification.idType, null, repo, v => { var dr = new DiaryReference(identifiable); identifiable.identification.idType = v as string; this.AddDiaryEntry(identifiable, new DiaryEntryStructChange(), diaryReference: dr); return(new AnyUiLambdaActionNone()); }, comboBoxItems: AdminShell.Key.IdentifierTypeNames); this.AddKeyValueRef( stack, "id", identifiable, ref identifiable.identification.id, null, repo, v => { var dr = new DiaryReference(identifiable); identifiable.identification.id = v as string; this.AddDiaryEntry(identifiable, new DiaryEntryStructChange(), diaryReference: dr); return(new AnyUiLambdaActionNone()); }, auxButtonTitles: DispEditInjectAction.GetTitles(new[] { "Generate" }, injectToId), auxButtonLambda: (i) => { if (i == 0) { var dr = new DiaryReference(identifiable); identifiable.identification.idType = AdminShell.Identification.IRI; identifiable.identification.id = AdminShellUtil.GenerateIdAccordingTemplate( templateForIdString); this.AddDiaryEntry(identifiable, new DiaryEntryStructChange(), diaryReference: dr); return(new AnyUiLambdaActionRedrawAllElements(nextFocus: identifiable)); } if (i >= 1) { var la = injectToId?.auxLambda?.Invoke(i - 1); return(la); } return(new AnyUiLambdaActionNone()); }); } this.AddHintBubble(stack, hintMode, new[] { new HintCheck( () => { return(identifiable.administration == null); }, "Check if providing admistrative information on version/ revision would be useful. " + "This allows for better version management.", breakIfTrue: true, severityLevel: HintCheck.Severity.Notice), new HintCheck( () => { return(identifiable.administration.version.Trim() == "" || identifiable.administration.revision.Trim() == ""); }, "Admistrative information fields should not be empty.", severityLevel: HintCheck.Severity.Notice) }); if (this.SafeguardAccess( stack, repo, identifiable.administration, "administration:", "Create data element!", v => { identifiable.administration = new AdminShell.Administration(); this.AddDiaryEntry(identifiable, new DiaryEntryStructChange()); return(new AnyUiLambdaActionRedrawEntity()); })) { this.AddKeyValueRef( stack, "version", identifiable.administration, ref identifiable.administration.version, null, repo, v => { identifiable.administration.version = v as string; this.AddDiaryEntry(identifiable, new DiaryEntryStructChange()); return(new AnyUiLambdaActionNone()); }); this.AddKeyValueRef( stack, "revision", identifiable.administration, ref identifiable.administration.revision, null, repo, v => { identifiable.administration.revision = v as string; this.AddDiaryEntry(identifiable, new DiaryEntryStructChange()); return(new AnyUiLambdaActionNone()); }); } }
protected ContextResult CreateBodyCD( ImportCellMatchContextBase context, AdminShell.AdministrationShellEnv env) { // access if (context?.Sme == null || context?.CD == null || env == null || _options == null) { return(null); } // first test, if the CD already exists var test = env.FindConceptDescription(context.Sme.semanticId); if (test != null) { return new ContextResult() { Elem = test } } ; // a semanticId is required to link the Sme and the CD together if (context.Sme.semanticId == null || context.Sme.semanticId.Count < 1) { // generate a new one for SME + CD // this modifies the SME! var id = new AdminShell.Identification( AdminShell.Identification.IRI, AdminShellUtil.GenerateIdAccordingTemplate(_options.TemplateIdConceptDescription)); context.Sme.semanticId = new AdminShell.SemanticId( new AdminShell.Key(AdminShell.Key.ConceptDescription, true, id.idType, id.id)); } // create, add var cd = new AdminShell.ConceptDescription(context?.CD); env.ConceptDescriptions.Add(cd); var res = new ContextResult() { Elem = cd }; // link CD to SME var sid = context.Sme.semanticId.GetAsExactlyOneKey(); if (sid == null) { // should not happen, see above return(null); } cd.identification = new AdminShell.Identification(sid.idType, sid.value); // some further attributes if (!cd.idShort.HasContent()) { cd.idShort = context.Sme.idShort; } // ok return(res); }
public void AtLine32AndColumn12() { Assert.AreEqual("some__name", AdminShellUtil.FilterFriendlyName("some!;name")); }
public static string ReportOptions(ReportOptionsFormat fmt, OptionsInformation options = null) { var sb = new StringBuilder(); // // small lambdas // Action appendTableHeader = () => { sb.AppendLine($"| {"JSON option",-35} | {"Command line",-20} " + $"| {"Argument",-20} | Description |"); sb.AppendLine($"|-{new String('-', 35)}-|-{new String('-', 20)}-" + $"|-{new String('-', 20)}-|-------------|"); }; Action <string, string, string, string> appendTableRow = (json, cmd, arg, description) => { sb.AppendLine($"| {MdEsc(json),-35} | {MdEsc(cmd),-20} " + $"| {MdEsc(arg),-20} | {MdEsc(description)} |"); }; // // Regular options // if (fmt == ReportOptionsFormat.Markdown) { sb.AppendLine("# Regular options for JSON and command line"); sb.AppendLine(); sb.AppendLine(AdminShellUtil.CleanHereStringWithNewlines( @"The following options can be used either directly in the command line of the exectable or in a JSON-file for configuration (via the ""-read-json"" option).")); sb.AppendLine(); } var fields = typeof(OptionsInformation).GetFields(BindingFlags.Public | BindingFlags.Instance); var first = true; foreach (var fi in fields) { foreach (var fia in fi.GetCustomAttributes(typeof(OptionDescription), true)) { if (fia is OptionDescription fiaod) { if (fmt == ReportOptionsFormat.Markdown) { if (first) { first = false; appendTableHeader(); } appendTableRow(fi.Name, fiaod.Cmd, fiaod.Arg, fiaod.Description); } } } } sb.AppendLine(); // // Special options // if (fmt == ReportOptionsFormat.Markdown) { sb.AppendLine("# Special options for JSON and command line"); sb.AppendLine(); sb.AppendLine(AdminShellUtil.CleanHereStringWithNewlines( @"The following options are also be provided.")); sb.AppendLine(); appendTableHeader(); appendTableRow("", "-read-json", "<path>", "Reads a JSON formatted options file."); appendTableRow("", "-write-json", "<path>", "Writes the currently loaded options " + "into a JSON formatted file."); } sb.AppendLine(); // // Report current options? // if (options != null) { var jsonStr = JsonConvert.SerializeObject(options, Formatting.Indented); if (fmt == ReportOptionsFormat.Markdown) { sb.AppendLine("# Current options"); sb.AppendLine(); sb.AppendLine(AdminShellUtil.CleanHereStringWithNewlines( @"The following options are currently loaded or set by default.")); sb.AppendLine(); sb.AppendLine("```"); sb.AppendLine(jsonStr); sb.AppendLine("```"); sb.AppendLine(); } } // // End of report // return(sb.ToString()); }
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(); }
public void AtLine43AndColumn12() { Assert.IsTrue(AdminShellUtil.HasWhitespace(" ")); }
// // Hinting // public void AddHintBubble(StackPanel view, bool hintMode, HintCheck[] hints) { // access if (!hintMode || view == null || hints == null) { return; } // check, if something to do. Execute all predicates List <string> textsToShow = new List <string>(); HintCheck.Severity highestSev = HintCheck.Severity.Notice; foreach (var hc in hints) { if (hc.CheckPred != null && hc.TextToShow != null) { try { if (hc.CheckPred()) { textsToShow.Add(hc.TextToShow); if (hc.SeverityLevel == HintCheck.Severity.High) { highestSev = HintCheck.Severity.High; } if (hc.BreakIfTrue) { break; } } } catch (Exception ex) { textsToShow.Add($"Error while checking hints: {ex.Message} at {AdminShellUtil.ShortLocation(ex)}"); highestSev = HintCheck.Severity.High; } } } // some? if (textsToShow.Count < 1) { return; } // show! var bubble = new HintBubble(); bubble.Margin = new Thickness(2, 4, 2, 0); bubble.Text = string.Join("\r\n", textsToShow); if (highestSev == HintCheck.Severity.High) { bubble.Background = (SolidColorBrush)(new BrushConverter().ConvertFrom("#D42044")); bubble.Foreground = (SolidColorBrush)(new BrushConverter().ConvertFrom("#ffffff")); } if (highestSev == HintCheck.Severity.Notice) { bubble.Background = (SolidColorBrush)(new BrushConverter().ConvertFrom("#cce0ff")); bubble.Foreground = (SolidColorBrush)(new BrushConverter().ConvertFrom("#003380")); } view.Children.Add(bubble); }
public void AtLine47AndColumn12() { Assert.IsFalse(AdminShellUtil.HasWhitespace("aabb")); }
// // Start page // private async void ProceedOnPageStart() { // make runtime options to link to this dialogue var ro = new PackCntRuntimeOptions() { Log = _logger, ProgressChanged = (state, tfs, tbd) => { if (state == PackCntRuntimeOptions.Progress.Ongoing) { // determine if (tfs == null) { tfs = 5 * 1024 * 1024; } var frac = Math.Min(100.0, 100.0 * tbd / tfs.Value); var bshr = AdminShellUtil.ByteSizeHumanReadable(tbd); SetProgressBar(frac, $"{bshr} transferred"); } if (state == PackCntRuntimeOptions.Progress.Final) { SetProgressBar(0.0, ""); } }, AskForSelectFromList = (caption, items, propRes) => { TabItemSelectFromList.Dispatcher.BeginInvoke( System.Windows.Threading.DispatcherPriority.Background, new Action(() => { StartPageSelectFromList(caption, items, (li) => { // never again _selectFromListAction = null; // call propRes?.TrySetResult(li); }); })); }, AskForCredentials = (caption, propRes) => { TabItemCredentials.Dispatcher.BeginInvoke( System.Windows.Threading.DispatcherPriority.Background, new Action(() => { StartPageAskCredentials(caption, (pcc) => { // never again _askedUserCredentials = null; // call propRes?.TrySetResult(pcc); }); })); } }; // Log var location = TextBoxStartLocation.Text; _logger?.Info($"Connect (integrated): Trying to connect to {location} .."); // try do the magic try { // quickly parse out container options var copts = PackageContainerOptionsBase.CreateDefault(Options.Curr, loadResident: true); copts.StayConnected = true == CheckBoxStayConnected.IsChecked; if (Int32.TryParse("" + TextBoxUpdatePeriod.Text, out int i)) { copts.UpdatePeriod = Math.Max(OptionsInformation.MinimumUpdatePeriod, i); } // create container var x = await PackageContainerFactory.GuessAndCreateForAsync( _packageCentral, location, location, overrideLoadResident : true, containerOptions : copts, runtimeOptions : ro); // returning "x" is the only way to end the dialogue successfuly if (x != null) { // prepare result _logger?.Info($"Connect (integrated): guessing and creating container package " + $"succeeded with {x.ToString()} !"); this.Result = true; this.ResultContainer = x; // close now? if (true == CheckBoxStayAutoClose.IsChecked) { // trigger close ControlClosed?.Invoke(); } else { // proceed to summary page StartPageSummary(); } } } catch (Exception ex) { _logger?.Error(ex, "when guessing for packager container!"); } }
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 async Task <List <PackageContainerRepoItem> > GenerateRepositoryFromEndpointAsync() { // access if (!IsValid()) { throw new PackageConnectorException("PackageConnector::GenerateRepositoryFromEndpoint() " + "connection not valid!"); } // results var res = new List <PackageContainerRepoItem>(); // Log Log.Singleton.Info($"Building repository items for aas-list from {this.ToString()} .."); // sync-query for the list var aasItems = new List <ListAasItem>(); try { if (OpenIDClient.auth) { var responseAuth = _client.GetAsync("/authserver").Result; if (responseAuth.IsSuccessStatusCode) { var content = responseAuth.Content.ReadAsStringAsync().Result; if (content != null && content != "") { OpenIDClient.authServer = content; var response2 = await OpenIDClient.RequestTokenAsync(null); OpenIDClient.token = response2.AccessToken; OpenIDClient.auth = false; } } } if (OpenIDClient.token != "") { _client.SetBearerToken(OpenIDClient.token); } // query var listAasResponse = await _client.GetAsync( StartQuery("server", "listaas")); listAasResponse.EnsureSuccessStatusCode(); var listAasString = await listAasResponse.Content.ReadAsStringAsync(); // get some structures dynamic listAas = Newtonsoft.Json.Linq.JObject.Parse(listAasString); foreach (var li in listAas.aaslist) { string line = "" + li; var arr = line.Trim().Split(new[] { " : " }, StringSplitOptions.RemoveEmptyEntries); if (arr.Length == 4) { aasItems.Add(new ListAasItem() { Index = arr[0].Trim(), AasIdShort = arr[1].Trim(), AasId = arr[2].Trim(), Fn = arr[3].Trim() }); } } } catch (Exception ex) { Log.Singleton.Error(ex, $"when parsing /server/listaas/ for {this.ToString()}"); } // go thru the list foreach (var aasi in aasItems) { try { // query var x = await GetAasAssetCore(aasi.Index); if (x.Item1 == null || x.Item2 == null) { Log.Singleton.Error($"when retrieving /aas/{aasi.Index}/, some null contents for AAS or" + $"Asset were found."); } // file item var fi = new PackageContainerRepoItem() { ContainerOptions = PackageContainerOptionsBase.CreateDefault(Options.Curr), Location = CombineQuery(_client.BaseAddress.ToString(), _endPointSegments, "server", "getaasx", aasi.Index), Description = $"\"{"" + x.Item1?.idShort}\",\"{"" + x.Item2?.idShort}\"", Tag = "" + AdminShellUtil.ExtractPascalCasingLetters(x.Item1?.idShort).SubstringMax(0, 3) }; fi.AasIds.Add("" + x.Item1?.identification?.id); fi.AssetIds.Add("" + x.Item2?.identification?.id); res.Add(fi); } catch (Exception ex) { Log.Singleton.Error(ex, $"when parsing index {aasi.Index}"); } } // return results return(res); }
public void AtLine68AndColumn12() { Assert.IsTrue(AdminShellUtil.ComplyIdShort("")); }