public void EndNode(AstNode node) { if (nodeStack.Pop() != node) { throw new InvalidOperationException(); } if (!(node.Annotation <MethodDebugInfoBuilder>() is null)) { Debug2.Assert(!(currentMethodDebugInfoBuilder is null)); if (context.CalculateILSpans) { foreach (var ns in context.UsingNamespaces) { currentMethodDebugInfoBuilder.Scope.Imports.Add(ImportInfo.CreateNamespace(ns)); } } output.AddDebugInfo(currentMethodDebugInfoBuilder.Create()); currentMethodDebugInfoBuilder = parentMethodDebugInfoBuilder.Pop(); } var mms = node.Annotation <List <Tuple <MethodDebugInfoBuilder, List <ILSpan> > > >(); if (!(mms is null)) { Debug.Assert(mms == multiMappings); if (mms == multiMappings) { foreach (var mm in mms) { output.AddDebugInfo(mm.Item1.Create()); } multiMappings = null; } } }
/// <summary> /// Adds a child ImportInfo to this ImportInfo. /// </summary> /// <param name="importInfo">The child ImportInfo to add.</param> /// <returns>The added and updated ImportInfo.</returns> public ImportInfo AddChild(ImportInfo importInfo) { Childs.Add(importInfo); importInfo.Parent = this; return(importInfo); }
private static void AddAdjustmentChild(Transaction parent, Transactions availableTransactions, decimal amount , TransactionReason transactionReason, string adjustmentTag) { ImportInfo matcherImportInfo; if (availableTransactions.HasImportInfo(ImportInfoId)) { matcherImportInfo = availableTransactions.GetImportInfo(ImportInfoId); } else { matcherImportInfo = new ImportInfo(ImportInfoId, ImportInfoId, null, null, ImportInfoId, null); //TODO: how can we accomodate manufatured import? } AccountInfo accountInfo = availableTransactions.GetAccountInfo(parent.AccountId); if (amount != 0) { var tx = new Transaction(matcherImportInfo.Id, accountInfo, new Transaction.ImportedValues() { Amount = amount, EntityName = "{0} - {1}".FormatEx(adjustmentTag, parent.EntityName), EntityNameNormalized = "{0} - {1}".FormatEx(adjustmentTag, parent.EntityName), InstituteReference = "{0}.{1}".FormatEx(adjustmentTag, parent.InstituteReference), RequiresParent = true, SubAccountName = parent.SubAccountName, TransactionDate = parent.TransactionDate, TransactionReason = transactionReason, LineNumber = null }); availableTransactions.AddNew(tx, accountInfo, matcherImportInfo, false); availableTransactions.RelateParentChild(parent.Id, tx.Id); } }
public void IsEnabled_ReferenceLineWithGeometry_ReturnTrue() { // Setup var mocks = new MockRepository(); var assessmentSection = mocks.Stub <IAssessmentSection>(); assessmentSection.Stub(a => a.ReferenceLine).Return(ReferenceLineTestFactory.CreateReferenceLineWithGeometry()); mocks.ReplayAll(); var failureMechanism = new GrassCoverErosionInwardsFailureMechanism(); var context = new DikeProfilesContext(failureMechanism.DikeProfiles, failureMechanism, assessmentSection); using (var plugin = new GrassCoverErosionInwardsPlugin()) { ImportInfo importInfo = GetImportInfo(plugin); // Call bool isEnabled = importInfo.IsEnabled(context); // Assert Assert.IsTrue(isEnabled); } mocks.VerifyAll(); }
public void CreateFileImporter_Always_ReturnFileImporter() { // Setup var mocks = new MockRepository(); IAssessmentSection assessmentSection = AssessmentSectionTestHelper.CreateAssessmentSectionStub(mocks); mocks.ReplayAll(); var context = new StabilityPointStructuresCalculationGroupContext(new CalculationGroup(), null, new StabilityPointStructuresFailureMechanism(), assessmentSection); using (var plugin = new StabilityPointStructuresPlugin()) { ImportInfo info = GetImportInfo(plugin); // Call IFileImporter fileImporter = info.CreateFileImporter(context, "test"); // Assert Assert.IsInstanceOf <StabilityPointStructuresCalculationConfigurationImporter>(fileImporter); } mocks.VerifyAll(); }
public void VerifyUpdates_NoProbabilisticCalculations_ReturnsTrue() { // Setup var mocks = new MockRepository(); var inquiryHelper = mocks.StrictMock <IInquiryHelper>(); var assessmentSection = mocks.Stub <IAssessmentSection>(); mocks.ReplayAll(); var failureMechanism = new PipingFailureMechanism(); failureMechanism.CalculationsGroup.Children.Add(new SemiProbabilisticPipingCalculationScenario { Output = PipingTestDataGenerator.GetRandomSemiProbabilisticPipingOutput() }); var context = new PipingFailureMechanismSectionsContext(failureMechanism, assessmentSection); ImportInfo <PipingFailureMechanismSectionsContext> importInfo = GetImportInfo(inquiryHelper); // Call bool updatesVerified = importInfo.VerifyUpdates(context); // Assert Assert.IsTrue(updatesVerified); mocks.VerifyAll(); }
private void ImportData() { var info = new ImportInfo { inputFilename = importDataPanel.FullFilename, outputFilename = importDataPanel.GetOutputFilename(), fieldIndex = importDataPanel.fieldDropdown.value, site = importDataPanel.Site, newSiteName = importDataPanel.SiteName, group = importDataPanel.Group, newGroupName = importDataPanel.GroupName, layer = importDataPanel.Layer, newLayerName = importDataPanel.LayerName, newLayerColor = importDataPanel.LayerColor, level = importDataPanel.Level, year = importDataPanel.Year, month = importDataPanel.Month, units = importDataPanel.Units, resolution = importDataPanel.Resolution, needsResampling = importDataPanel.NeedsResampling, metadata = importDataPanel.GetMetadata(), OnFinishImport = OnFinishImport }; InitInfoCategories(info); var dataImporter = new GameObject("DataImporter").AddComponent <DataImporter>(); dataImporter.Import(info); wizardDlg.CloseDialog(DialogAction.Ok); }
public void VerifyUpdates_CalculationWithOutputs_AlwaysReturnsExpectedInquiryMessage(bool isActionConfirmed) { // Setup string expectedInquiryMessage = "Als u een vakindeling importeert, dan worden de resultaten van alle probabilistische piping berekeningen verwijderd." + $"{Environment.NewLine}{Environment.NewLine}Weet u zeker dat u wilt doorgaan?"; var mocks = new MockRepository(); var inquiryHelper = mocks.StrictMock <IInquiryHelper>(); inquiryHelper.Expect(ih => ih.InquireContinuation(expectedInquiryMessage)) .Return(isActionConfirmed); var assessmentSection = mocks.Stub <IAssessmentSection>(); mocks.ReplayAll(); var failureMechanism = new PipingFailureMechanism(); var calculationWithOutput = new ProbabilisticPipingCalculationScenario { Output = PipingTestDataGenerator.GetRandomProbabilisticPipingOutputWithIllustrationPoints() }; failureMechanism.CalculationsGroup.Children.Add(calculationWithOutput); var context = new PipingFailureMechanismSectionsContext(failureMechanism, assessmentSection); ImportInfo <PipingFailureMechanismSectionsContext> importInfo = GetImportInfo(inquiryHelper); // Call bool updatesVerified = importInfo.VerifyUpdates(context); // Assert Assert.AreEqual(isActionConfirmed, updatesVerified); mocks.VerifyAll(); }
public void IsEnabled_ReferenceLineWithoutGeometry_ReturnFalse() { // Setup var mocks = new MockRepository(); var assessmentSection = mocks.Stub <IAssessmentSection>(); assessmentSection.Stub(a => a.ReferenceLine).Return(new ReferenceLine()); mocks.ReplayAll(); var failureMechanism = new HeightStructuresFailureMechanism(); var context = new HeightStructuresContext(failureMechanism.HeightStructures, failureMechanism, assessmentSection); using (var plugin = new HeightStructuresPlugin()) { ImportInfo importInfo = GetImportInfo(plugin); // Call bool isEnabled = importInfo.IsEnabled(context); // Assert Assert.IsFalse(isEnabled); } mocks.VerifyAll(); }
/// <summary> /// Imports a mod to the current selected KSP install path. /// </summary> /// <param name="importInfo">The ImportInfo </param> /// <param name="copyDest">Flag to determine if the destination should be copied or if the auto destination detection should be used.</param> /// <param name="addOnly">Flag to determine if the mod should be installed or only added to the ModSelection.</param> private static void ImportMod(ImportInfo importInfo, bool copyDest, bool addOnly) { ModInfo modInfo = importInfo.ModInfo; ModNode addedMod = ModSelectionController.AddMods(new ModInfo[] { modInfo }, false).FirstOrDefault(); if (addedMod != null) { if (copyDest) { // remove all destinations and uncheck all nodes. ModNodeHandler.SetDestinationPaths(addedMod, string.Empty); addedMod._Checked = false; // copy destination UpdateMessage(string.Format(Messages.MSG_COPY_MOD_DESTINATION_0, addedMod.Name)); if (!ModNodeHandler.TryCopyDestToMatchingNodes(importInfo, addedMod)) { UpdateMessage(string.Format(Messages.MSG_COPY_MOD_0_DESTINATION_FAILED, addedMod.Name)); UpdateMessage(string.Format(Messages.MSG_IMPORT_0_FAILED, importInfo.Name), importInfo); return; } } // install the mod. if (!addOnly) { UpdateMessage(string.Format(Messages.MSG_INSTALLING_MOD_0, addedMod.Name)); ModSelectionController.ProcessMods(new ModNode[] { addedMod }); } } else { UpdateMessage(string.Format(Messages.MSG_IMPORT_0_FAILED, importInfo.Name), importInfo); } }
/// <summary> /// Shows the import form and returns the values of the fields to the caller /// </summary> /// <param name="defaultImportSettings">Values to pre-populate the dialog</param> /// <returns>The values selected in the form</returns> public static ImportDialogResult Execute(ImportInfo defaultImportSettings) { lock (_instanceLock) { if (__instance == null) { __instance = new ImportFileForm(); } __instance._importResult = new ImportDialogResult(); __instance._importResult.DialogResult = DialogResult.Cancel; if (defaultImportSettings != null && defaultImportSettings.Parser != null) { SelectBoxItemByText(defaultImportSettings.Parser.Name, __instance._boxParserDll); __instance._importResult.ImportInfo = defaultImportSettings; if (defaultImportSettings.Sender != null) { __instance._checkSender.Visible = true; if ((defaultImportSettings.Parser.ImportSupport & ImportMode.Objects) != 0) { __instance._checkSender.Checked = true; } else { __instance._checkSender.Checked = false; __instance._boxTargetPath.Text = String.Join("|", __instance._importResult.ImportInfo.TargetFiles.ToArray()); } } } __instance.ShowDialog(); } return(__instance._importResult); }
public void VerifyUpdates_CalculationWithoutOutputs_ReturnsTrue() { // Setup var mocks = new MockRepository(); var assessmentSection = mocks.Stub <IAssessmentSection>(); var mainWindow = mocks.Stub <IMainWindow>(); var gui = mocks.Stub <IGui>(); gui.Stub(g => g.MainWindow).Return(mainWindow); mocks.ReplayAll(); using (var plugin = new HeightStructuresPlugin()) { plugin.Gui = gui; var failureMechanism = new HeightStructuresFailureMechanism(); failureMechanism.CalculationsGroup.Children.Add(new StructuresCalculation <HeightStructuresInput>()); var structures = new StructureCollection <HeightStructure>(); var context = new HeightStructuresContext(structures, failureMechanism, assessmentSection); ImportInfo importInfo = GetImportInfo(plugin); // Call bool updatesVerified = importInfo.VerifyUpdates(context); // Assert Assert.IsTrue(updatesVerified); mocks.VerifyAll(); } }
public void CreateFileImporter_Always_ReturnFileImporter() { // Setup var mocks = new MockRepository(); var failureMechanism = mocks.Stub <ICalculatableFailureMechanism>(); var assessmentSection = mocks.Stub <IAssessmentSection>(); assessmentSection.Stub(a => a.ReferenceLine).Return(new ReferenceLine()); mocks.ReplayAll(); var foreshoreProfiles = new ForeshoreProfileCollection(); var importTarget = new ForeshoreProfilesContext(foreshoreProfiles, failureMechanism, assessmentSection); using (var plugin = new RiskeerPlugin()) { ImportInfo importInfo = GetImportInfo(plugin); // Call IFileImporter importer = importInfo.CreateFileImporter(importTarget, "test"); // Assert Assert.IsInstanceOf <ProfilesImporter <ForeshoreProfileCollection> >(importer); } mocks.VerifyAll(); }
public void CreateFileImporter_Always_ReturnFileImporter() { // Setup var mocks = new MockRepository(); var assessmentSection = mocks.Stub <IAssessmentSection>(); assessmentSection.Stub(a => a.ReferenceLine).Return(new ReferenceLine()); mocks.ReplayAll(); var failureMechanism = new HeightStructuresFailureMechanism(); var importTarget = new HeightStructuresContext(failureMechanism.HeightStructures, failureMechanism, assessmentSection); using (var plugin = new HeightStructuresPlugin()) { ImportInfo importInfo = GetImportInfo(plugin); // Call IFileImporter importer = importInfo.CreateFileImporter(importTarget, "test"); // Assert Assert.IsInstanceOf <HeightStructuresImporter>(importer); } mocks.VerifyAll(); }
public void ImportOn_MultipleSupportedImportInfos_ShowsDialogWithOptions(bool hasFileFilterGenerator) { // Setup const string importInfoAName = "nameA"; var importInfoA = new ImportInfo <object> { Name = importInfoAName, FileFilterGenerator = hasFileFilterGenerator ? new FileFilterGenerator("extensionA") : null }; const string importInfoBName = "nameB"; var importInfoB = new ImportInfo <object> { Name = importInfoBName, FileFilterGenerator = hasFileFilterGenerator ? new FileFilterGenerator("extensionB") : null }; var mockRepository = new MockRepository(); var inquiryHelper = mockRepository.Stub <IInquiryHelper>(); mockRepository.ReplayAll(); var listViewItems = new ListViewItem[0]; DialogBoxHandler = (name, wnd) => { using (new FormTester(name)) { var listView = (ListView) new ControlTester("listViewItemTypes").TheObject; listViewItems = listView.Items.OfType <ListViewItem>().ToArray(); } }; using (var form = new TestViewParentForm()) { var importHandler = new GuiImportHandler(form, Enumerable.Empty <ImportInfo>(), inquiryHelper); // Call importHandler.ImportOn(new object(), new ImportInfo[] { importInfoA, importInfoB }); } // Assert Assert.AreEqual(2, listViewItems.Length); string expectedItemNameA = hasFileFilterGenerator ? $"{importInfoA.Name} (*.{importInfoA.FileFilterGenerator.Extension})" : importInfoA.Name; Assert.AreEqual(expectedItemNameA, listViewItems[0].Name); string expectedItemNameB = hasFileFilterGenerator ? $"{importInfoB.Name} (*.{importInfoB.FileFilterGenerator.Extension})" : importInfoB.Name; Assert.AreEqual(expectedItemNameB, listViewItems[1].Name); mockRepository.VerifyAll(); }
private async Task GetCodeActionsAsync(IDocumentAnalysis analysis, Diagnostic[] diagnostics, Input input, List <CodeAction> codeActions, CancellationToken cancellationToken) { var importFullNameMap = new Dictionary <string, ImportInfo>(); await AddCandidatesFromIndexAsync(analysis, input.Identifier, importFullNameMap, cancellationToken); var interpreter = analysis.Document.Interpreter; var pathResolver = interpreter.ModuleResolution.CurrentPathResolver; // find installed modules matching the given name. this will include submodules var languageVersion = Parsing.PythonLanguageVersionExtensions.ToVersion(interpreter.LanguageVersion); var includeImplicit = !ModulePath.PythonVersionRequiresInitPyFiles(languageVersion); foreach (var moduleFullName in pathResolver.GetAllImportableModulesByName(input.Identifier, includeImplicit)) { cancellationToken.ThrowIfCancellationRequested(); importFullNameMap[moduleFullName] = new ImportInfo(moduleImported: false, memberImported: false, isModule: true); } // find members matching the given name from modules already loaded. var moduleInfo = new ModuleInfo(analysis); foreach (var module in interpreter.ModuleResolution.GetImportedModules(cancellationToken)) { if (module.ModuleType == ModuleType.Unresolved) { continue; } // module name is full module name that you can use in import xxxx directly CollectCandidates(moduleInfo.Reset(module), input.Identifier, importFullNameMap, cancellationToken); Debug.Assert(moduleInfo.NameParts.Count == 1 && moduleInfo.NameParts[0] == module.Name); } // check quick bail out case where we know what module we are looking for if (input.ModuleFullNameOpt != null) { if (importFullNameMap.ContainsKey(input.ModuleFullNameOpt)) { // add code action if the module exist, otherwise, bail out empty codeActions.AddIfNotNull(CreateCodeAction(analysis, input.Context, input.ModuleFullNameOpt, diagnostics, locallyInserted: false, cancellationToken)); } return; } // regular case FilterCandidatesBasedOnContext(analysis, input.Context, importFullNameMap, cancellationToken); // this will create actual code fix with certain orders foreach (var fullName in OrderFullNames(importFullNameMap)) { cancellationToken.ThrowIfCancellationRequested(); codeActions.AddIfNotNull(CreateCodeAction(analysis, input.Context, fullName, diagnostics, locallyInserted: false, cancellationToken)); } }
public void Path_With_Brackets() { var file = @"c:\Program Files(x86)\test\child.cs"; var info = new ImportInfo($"{file.EscapeDirectiveDelimiters()},preserve_main", null); Assert.Equal(file, info.file); Assert.True(info.preserveMain); }
public PageImportViewModel() { ClickImportCommand = new DelegateCommand(new Action(ClickImportExecute)); Info = new ImportInfo(); Info.BtnVisibility = Visibility.Visible; Info.TipsVisibility = Visibility.Hidden; Info.Info = string.Empty; }
public override bool Walk(ImportStatement node) { var iinfo = new ImportInfo("", node.Span); GlobalScope.Imports[node] = iinfo; int len = Math.Min(node.Names.Count, node.AsNames.Count); for (int i = 0; i < len; i++) { var impNode = node.Names[i]; var newName = node.AsNames[i]; var strImpName = impNode.MakeString(); iinfo.Types.Add(new[] { strImpName, newName }); var saveName = (String.IsNullOrEmpty(newName)) ? strImpName : newName; ModuleReference modRef; var def = Scopes[Scopes.Length - 1].CreateVariable(impNode, _unit, saveName); if (!ProjectState.Modules.TryGetValue(strImpName, out modRef)) { var builtinModule = ProjectState.ImportModule(strImpName, impNode.Names.Count > 1 && !String.IsNullOrEmpty(newName)); if (builtinModule != null) { builtinModule.InterpreterModule.Imported(_unit.DeclaringModule.InterpreterContext); def.AddTypes(impNode, _unit, builtinModule.SelfSet); continue; } } if (modRef != null) { if (modRef.Module != null) { ModuleInfo mi = modRef.Module as ModuleInfo; if (mi != null) { mi.ModuleDefinition.AddDependency(_unit); } BuiltinModule builtinModule = modRef.Module as BuiltinModule; if (builtinModule != null) { builtinModule.InterpreterModule.Imported(_unit.DeclaringModule.InterpreterContext); } def.AddTypes(impNode, _unit, modRef.Module.SelfSet); continue; } } else { ProjectState.Modules[strImpName] = modRef = new ModuleReference(); } } return(true); }
public TrafficViewerForm(ImportInfo startupImportInfo, string startupTVF) { InitializeComponent(); _nameAndVersion = String.Format("{0} {1} ({2} {3})", TrafficViewerConstants.APP_NAME, TrafficViewerConstants.VERSION, Resources.Build, TrafficViewerConstants.BUILD); //initialize the progress dialog _progressDialog = new ProgressDialog(); //create a callback to be passed to asyncroneus operations to stop the progress dialog _asyncCallback = new AsyncCallback(BackgroundOperationCallback); //create a new traffic viewer file NewTVF(); //attach a handler to when the user modifies a request to know that the current //traffic data has changed _requestViewer.TrafficView.SaveRequested += new RequestTrafficViewSaveEvent(TrafficViewSaveRequested); //attach stop load command to request list _requestsList.StopLinkClick += new EventHandler(RequestsListOnStopLinkClicked); //points the unpacked folder dialog to the temp folder _dialogFolderBrowser.SelectedPath = Environment.GetEnvironmentVariable("temp"); //initializes the analysis modules menu LoadAnalysisModules(); //initializes the exploiters menu LoadExploiters(); _menuStrip.ExploiterItemClicked += ExploiterItemClicked; //hooks a method to the analysis module click event _menuStrip.AnalysisModuleClicked += new AnalysisModuleClickEvent(MenuStripAnalysisModuleClicked); //hook up to the traffic visualizer click _menuStrip.VisualizeTraffic += new EventHandler(VisualizeTraffic); TrafficViewer.Instance.ExceptionMessageHandler = new ErrorBox(); //search _searchForm = new SearchForm(); _searchForm.SearchIndexChanged += new SearchIndexChangedEvent(SearchIndexChanged); _searchForm.SearchExecuted += new SearchExecutedEvent(SearchExecuted); _searchForm.ReplaceRequestedEvent += new ReplaceEvent(ReplaceRequested); //initialize the request trap with the request trap form //HttpTrap.Instance.RequestTrapped += new RequestTrapEvent(RequestTrapEvent); //HttpTrap.Instance.ResponseTrapped += new RequestTrapEvent(ResponseTrapEvent); HttpTrap.Instance.TrapOn += HttpTrapOn; HttpTrap.Instance.TrapOff += HttpTrapOff; //initialize the arguments, they will be processed on LOAD _startupImportInfo = startupImportInfo; _currentTVFilePath = startupTVF; HttpAuthenticationManager.Instance.CredentialsProvider = new CredentialsForm(this); }
public void Path_With_MainPreserve_CompactArgs() { var file = @"c:\test dir\child.cs"; var info = new ImportInfo($"\"{file}\",preserve_main", null); Assert.Equal(file, info.file); Assert.True(info.preserveMain); }
public void Path_WithSpaces() { var file = @"c:\test dir\child.cs"; var info = new ImportInfo($"\"{file}\"", null); Assert.Equal(file, info.file); Assert.False(info.preserveMain); }
public void Path_Simple() { var file = @"c:\test\child.cs"; var info = new ImportInfo($"{file}", "parent.cs"); Assert.Equal(file, info.file); Assert.False(info.preserveMain); }
/// <summary> /// Gets the ImportInfos from a XmlNode. /// </summary> /// <param name="mod">The XmlNode to get the ImportInfos from.</param> /// <returns>The ImportInfos from a XmlNode.</returns> private static ImportInfo GetImportInfo(XmlNode mod) { ImportInfo importInfo = new ImportInfo(); if (mod.Attributes == null) { return(null); } foreach (XmlAttribute att in mod.Attributes) { if (att.Name == Constants.KEY) { importInfo.LocalPath = att.Value; } else if (att.Name == Constants.NAME) { importInfo.Name = att.Value; } else if (att.Name == Constants.VERSIONCONTROLERNAME) { importInfo.SiteHandlerName = att.Value; } else if (att.Name == Constants.PRODUCTID) { importInfo.ProductID = att.Value; } else if (att.Name == Constants.MODURL) { importInfo.ModURL = att.Value; } else if (att.Name == Constants.FORUMURL) { importInfo.AdditionalURL = att.Value; } else if (att.Name == Constants.ISFILE) { importInfo.IsFile = (att.Value == ONE); } else if (att.Name == Constants.INSTALL) { importInfo.Install = (att.Value == ONE); } else if (att.Name == Constants.INSTALLDIR) { importInfo.InstallDir = att.Value; } } foreach (XmlNode child in mod.ChildNodes) { importInfo.AddChild(GetImportInfo(child)); } return(importInfo); }
public override bool Walk(FromImportStatement node) { ModuleReference moduleRef; Namespace userMod = null; var modName = node.Root.MakeString(); if (!ProjectState.Modules.TryGetValue(modName, out moduleRef)) { userMod = ProjectState.ImportModule(modName); } if (moduleRef != null) { userMod = moduleRef.Module; } else if (userMod == null) { moduleRef = ProjectState.Modules[modName] = new ModuleReference(); } var asNames = node.AsNames ?? node.Names; var impInfo = new ImportInfo(node.Root.MakeString(), node.Span); GlobalScope.Imports[node] = impInfo; int len = Math.Min(node.Names.Count, asNames.Count); for (int i = 0; i < len; i++) { var impName = node.Names[i]; var newName = asNames[i]; if (impName == null) { // incomplete import statement continue; } else if (impName == "*") { // Handle "import *" if (userMod != null) { foreach (var varName in GetModuleKeys(userMod)) { WalkFromImportWorker(node, userMod, varName, null); } } } else { WalkFromImportWorker(node, userMod, impName, newName); } } return(true); }
/// <summary> /// Starts an asyncroneus import operation /// </summary> /// <param name="parser"></param> /// <param name="pathsToFilesToImport"></param> /// <param name="options"></param> /// <param name="callback"></param> public void BeginImport(ITrafficParser parser, List <string> pathsToFilesToImport, ParsingOptions options, AsyncCallback callback) { ImportInfo info = new ImportInfo(); info.Parser = parser; info.TargetFiles = pathsToFilesToImport; info.Profile = options; BeginImport(info, callback); }
/// <summary> /// Starts an asyncroneus import operation /// </summary> /// <param name="parser"></param> /// <param name="sender"></param> /// <param name="options"></param> /// <param name="callback"></param> public void BeginImport(ITrafficParser parser, object sender, ParsingOptions options, AsyncCallback callback) { ImportInfo info = new ImportInfo(); info.Parser = parser; info.Sender = sender; info.Profile = options; BeginImport(info, callback); }
public void VerifyUpdates_CalculationWithOutputs_AlwaysReturnsExpectedInquiryMessage(bool isActionConfirmed) { // Setup var mocks = new MockRepository(); var assessmentSection = mocks.Stub <IAssessmentSection>(); var mainWindow = mocks.Stub <IMainWindow>(); var gui = mocks.Stub <IGui>(); gui.Stub(g => g.MainWindow).Return(mainWindow); mocks.ReplayAll(); using (var plugin = new GrassCoverErosionInwardsPlugin()) { plugin.Gui = gui; var failureMechanism = new GrassCoverErosionInwardsFailureMechanism(); failureMechanism.CalculationsGroup.Children.Add(new GrassCoverErosionInwardsCalculation { Output = new TestGrassCoverErosionInwardsOutput() }); var dikeProfiles = new DikeProfileCollection(); var context = new DikeProfilesContext(dikeProfiles, failureMechanism, assessmentSection); ImportInfo importInfo = GetImportInfo(plugin); string textBoxMessage = null; DialogBoxHandler = (name, wnd) => { var helper = new MessageBoxTester(wnd); textBoxMessage = helper.Text; if (isActionConfirmed) { helper.ClickOk(); } else { helper.ClickCancel(); } }; // Call bool updatesVerified = importInfo.VerifyUpdates(context); // Assert string expectedInquiryMessage = "Als u dijkprofielen importeert, " + "dan worden alle rekenresultaten van dit faalmechanisme " + $"verwijderd.{Environment.NewLine}{Environment.NewLine}Weet u zeker dat u wilt doorgaan?"; Assert.AreEqual(expectedInquiryMessage, textBoxMessage); Assert.AreEqual(isActionConfirmed, updatesVerified); mocks.VerifyAll(); } }
public void ImportOn(object target, IEnumerable <ImportInfo> supportedImportInfos) { ImportInfo importInfo = SelectImportInfo(target, supportedImportInfos.ToArray()); if (importInfo == null) { return; } ImportItemsUsingDialog(importInfo, target); }
private static bool AreCompatible(ImportInfo import, ExportInfo export) { if (!import.Options.IncludeNamedExportsFromUnnamedImports && export.Name != null && import.Name == null) { return(false); } return(export.Name == import.Name || import.Name == null); }
/// <summary> /// Builds ASymbol. /// </summary> /// <param name="shape">The shape of the AType.</param> /// <param name="symbolLengths">The lengths of the ASymbols contained by the AType.</param> /// <param name="info">The class containing the informations for importing.</param> /// <returns></returns> private AType BuildSymbolArray(List<int> shape, IEnumerable<int> symbolLengths, ImportInfo info) { AType result = Utils.ANull(); if (shape.Count == 0) { StringBuilder toSymbol = new StringBuilder(); int length = symbolLengths.First(); for (int i = 0; i < length; i++) { toSymbol.Append((char)info.Data[info.DataIndex]); info.DataIndex++; } result = ASymbol.Create(toSymbol.ToString()); } else { List<int> nextShape = (shape.Count > 1) ? shape.GetRange(1, shape.Count - 1) : new List<int>(); int subDimensionLength = nextShape.Product(); for (int i = 0; i < shape[0]; i++) { IEnumerable<int> nextSymbolLengths = symbolLengths.Skip(i * subDimensionLength).Take(subDimensionLength); result.Add(BuildSymbolArray(nextShape, nextSymbolLengths, info)); // advance the bytestream further. } } return result; }
/// <summary> /// Imports an AType from a byte array. /// </summary> /// <param name="argument">The byte array.</param> /// <returns>The AType created from the byte array.</returns> public AType Import(byte[] argument) { if (argument.Length < HeaderStartIndex || argument[0] != CDRConstants.CDRFlag) { throw new Error.Domain("sys.imp"); } ImportInfo info = new ImportInfo(argument) { HeaderIndex = HeaderStartIndex }; // the first 4 byte of the header contains the cdr flag, plus the length of the message. byte[] headerByteLength = { 0, argument[1], argument[2], argument[3] }; int headerLength = IPAddress.NetworkToHostOrder(BitConverter.ToInt32(headerByteLength, 0)); info.DataIndex = headerLength; return ExtractItems(info); }
/// <summary> /// Creates a new import using the specified import info /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='collectionName'> /// The workspace collection name /// </param> /// <param name='workspaceId'> /// The workspace id /// </param> /// <param name='datasetDisplayName'> /// The display name of the dataset /// </param> /// <param name='importInfo'> /// The import to post /// </param> /// <param name='nameConflict'> /// Determines what to do if a dataset with the same name already exists /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<Import> PostImportAsync(this IImports operations, string collectionName, string workspaceId, string datasetDisplayName, ImportInfo importInfo, string nameConflict = default(string), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.PostImportWithHttpMessagesAsync(collectionName, workspaceId, datasetDisplayName, importInfo, nameConflict, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } }
public ActionResult SaveNewProduct(ImportInfo info) { ImportInfoList list = ImportInfoList.NewProductImportInfoList(); list.Add(info); ImportWizard.ImportProductList(list); Product product = Product.GetProductByName(string.Empty); return this.Direct(new {}); }
void TryImportDraggedClips() { int i; ImportInfo info; for( i = 0; i < _draggedClips.Count; i++ ) { info = new ImportInfo( _draggedClips[ i ] ); if( _soundBank.Contains( info.GUID ) ) { EditorGUIUtility.PingObject( info.Clip ); if( EditorUtility.DisplayDialog( "Cannot Import", string.Format( "AudioClip {0} is already in Sound Bank!", info.Clip.name ), "Skip", "Cancel" ) ) { continue; } else return; } else { if( info.PathInResources == null ) { EditorGUIUtility.PingObject( info.Clip ); if( EditorUtility.DisplayDialog( "Cannot Import", string.Format( "Cannot import AudioClip {0}, it is not in a Resources folder.", info.Clip.name ), "Skip", "Cancel" ) ) { continue; } else return; } #if UNITY_5 AudioImporterSampleSettings sampleSettings = info.Importer.defaultSampleSettings; if( sampleSettings.loadType != AudioClipLoadType.DecompressOnLoad ) { EditorGUIUtility.PingObject( info.Clip ); if( EditorUtility.DisplayDialog( "Cannot Import", string.Format( "AudioClip {0}'s load type import settings should be set to * load into memory *.", info.Clip.name ), "Fix", "Cancel" ) ) { sampleSettings.loadType = AudioClipLoadType.DecompressOnLoad; info.Importer.defaultSampleSettings = sampleSettings; } else return; } #else if( info.Importer.format == AudioImporterFormat.Native ) { if( info.Importer.loadType == AudioImporterLoadType.StreamFromDisc ) { EditorGUIUtility.PingObject( info.Clip ); if( EditorUtility.DisplayDialog( "Cannot Import", string.Format( "AudioClip {0}'s load type import settings should be set to * load into memory *.", info.Clip.name ), "Fix", "Cancel" ) ) { info.Importer.loadType = AudioImporterLoadType.DecompressOnLoad; } else return; } } else if( info.Importer.loadType != AudioImporterLoadType.DecompressOnLoad ) { EditorGUIUtility.PingObject( info.Clip ); if( EditorUtility.DisplayDialog( "Cannot Import", string.Format( "AudioClip {0}'s load type import settings should be set to * decompress on load *.", info.Clip.name ), "Fix", "Cancel" ) ) { info.Importer.loadType = AudioImporterLoadType.DecompressOnLoad; } else return; } #endif if( info.Clip.frequency != _soundBank.SampleRate ) { EditorGUIUtility.PingObject( info.Clip ); if( EditorUtility.DisplayDialog( "Cannot Import", string.Format( "AudioClip {0}'s sample rate does not match the Sound Bank's.", info.Clip.name ), "Skip", "Cancel" ) ) { continue; } else return; } } _soundBank.AddSample( info.PathInResources, info.GUID, info.Clip.channels, info.Clip.samples, info.IsStreamingAsset ); //AssetDatabase.ImportAsset( info.Path ); } EditorUtility.SetDirty( _soundBank ); _draggedClips.Clear(); }
/// <summary> /// Builds a box/boxarray. /// </summary> /// <param name="shape">The shape of the AType.</param> /// <param name="info">The class containing the informations for importing.</param> /// <returns></returns> private AType BuildBox(List<int> shape, ImportInfo info) { AType result; if (shape.Count == 0) { result = ABox.Create(ExtractItems(info)); } else { List<int> subshape = shape.GetRange(1, shape.Count - 1); result = AArray.Create(ATypes.ABox); for (int i = 0; i < shape[0]; i++) { result.Add(BuildBox(subshape, info)); } } return result; }
/// <summary> /// Gets the ImportInfos from a XmlNode. /// </summary> /// <param name="mod">The XmlNode to get the ImportInfos from.</param> /// <returns>The ImportInfos from a XmlNode.</returns> private static ImportInfo GetImportInfo(XmlNode mod) { ImportInfo importInfo = new ImportInfo(); if (mod.Attributes == null) return null; foreach (XmlAttribute att in mod.Attributes) { if (att.Name == Constants.KEY) importInfo.LocalPath = att.Value; else if (att.Name == Constants.NAME) importInfo.Name = att.Value; else if (att.Name == Constants.VERSIONCONTROLERNAME) importInfo.SiteHandlerName = att.Value; else if (att.Name == Constants.PRODUCTID) importInfo.ProductID = att.Value; else if (att.Name == Constants.MODURL) importInfo.ModURL = att.Value; else if (att.Name == Constants.FORUMURL) importInfo.AdditionalURL = att.Value; else if (att.Name == Constants.ISFILE) importInfo.IsFile = (att.Value == ONE); else if (att.Name == Constants.INSTALL) importInfo.Install = (att.Value == ONE); else if (att.Name == Constants.INSTALLDIR) importInfo.InstallDir = att.Value; } foreach (XmlNode child in mod.ChildNodes) importInfo.AddChild(GetImportInfo(child)); return importInfo; }
/// <summary> /// Gets the ModInfo from a ImportInfo class. /// </summary> /// <param name="importInfo">The ImportInfo class to get the ModInfos from.</param> /// <returns>The ModInfo from a ImportInfo class.</returns> private static ModInfo GetModInfo(ImportInfo importInfo) { ModInfo modInfo = new ModInfo(); if (importInfo.ModInfo != null) modInfo = importInfo.ModInfo; else { modInfo.ModURL = importInfo.ModURL; modInfo.AdditionalURL = importInfo.AdditionalURL; modInfo.LocalPath = importInfo.LocalPath; modInfo.Name = importInfo.Name; modInfo.ProductID = importInfo.ProductID; modInfo.SiteHandlerName = importInfo.SiteHandlerName; } return modInfo; }
/// <summary> /// Determines the lengths of the ASymbols to build, and then calls BuildSymbolArray to build it. /// </summary> /// <param name="shape">The shape of the AType.</param> /// <param name="info">The class containing the informations for importing.</param> /// <returns></returns> private AType BuildSymbol(List<int> shape, ImportInfo info) { int numberOfSymbols = shape.Product(); int totalLength = 0; List<int> symbolLengths = new List<int>(); for (int i = 0; i < numberOfSymbols; i++) { // because of the structure of the CDR type descriptor int actualLength = IPAddress.NetworkToHostOrder(BitConverter.ToInt32(info.Data, info.HeaderIndex)); info.HeaderIndex += ASymbolDescriptorLength; totalLength += actualLength; symbolLengths.Add(actualLength); } AType result = BuildSymbolArray(shape, symbolLengths, info); return result; }
/// <summary> /// Adds a child ImportInfo to this ImportInfo. /// </summary> /// <param name="importInfo">The child ImportInfo to add.</param> /// <returns>The added and updated ImportInfo.</returns> public ImportInfo AddChild(ImportInfo importInfo) { Childs.Add(importInfo); importInfo.Parent = this; return importInfo; }
/// <summary> /// Downloads the mod from ModURL. /// </summary> /// <param name="importInfo">The ImportInfo of the mod to download.</param> /// <returns>True if download was successful, otherwise false.</returns> private static bool DownloadMod(ref ImportInfo importInfo) { ISiteHandler siteHandler = importInfo.SiteHandler; if (siteHandler != null) { ModInfo modInfo = siteHandler.GetModInfo(importInfo.ModURL); importInfo.DownloadSuccessfull = siteHandler.DownloadMod(ref modInfo); importInfo.ModInfo = modInfo; } return importInfo.DownloadSuccessfull; }
/// <summary> /// Creates a new import using the specified import info /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='collectionName'> /// The workspace collection name /// </param> /// <param name='workspaceId'> /// The workspace id /// </param> /// <param name='datasetDisplayName'> /// The display name of the dataset /// </param> /// <param name='importInfo'> /// The import to post /// </param> /// <param name='nameConflict'> /// Determines what to do if a dataset with the same name already exists /// </param> public static Import PostImport(this IImports operations, string collectionName, string workspaceId, string datasetDisplayName, ImportInfo importInfo, string nameConflict = default(string)) { return Task.Factory.StartNew(s => ((IImports)s).PostImportAsync(collectionName, workspaceId, datasetDisplayName, importInfo, nameConflict), operations, CancellationToken.None, TaskCreationOptions.None, TaskScheduler.Default).Unwrap().GetAwaiter().GetResult(); }
protected override void OnError(string message, Exception exception, ImportInfo import) { BackgroundErrorLogger.Log(exception, "Static Dependency Injection - " + message, "Rock.Core", "ImportInfo:\r\n" + import); base.OnError(message, exception, import); }
/// <summary> /// Extract the AType elements from the header and the data. /// </summary> /// <param name="info">The class containing the informations for importing.</param> /// <returns>The AType created from the import informations.</returns> private AType ExtractItems(ImportInfo info) { AType result; List<int> shape = new List<int>(); // The format of the CDR type descriptor int count = IPAddress.NetworkToHostOrder(BitConverter.ToInt32(info.Data, info.HeaderIndex)); info.HeaderIndex += SizeOfCount; short typeCode = IPAddress.NetworkToHostOrder(BitConverter.ToInt16(info.Data, info.HeaderIndex)); info.HeaderIndex += SizeOfType; short rank = IPAddress.NetworkToHostOrder(BitConverter.ToInt16(info.Data, info.HeaderIndex)); info.HeaderIndex += SizeOfRank; for (short i = 0; i < rank; i++) { shape.Add(IPAddress.NetworkToHostOrder(BitConverter.ToInt32(info.Data, info.HeaderIndex))); info.HeaderIndex += SizeOfShape; } if (typeCode == CDRConstants.CDRBoxShort) { if (count == 0) { // if an item is ANull, the header contains 20 bytes (more in CDR spec) result = Utils.ANull(); info.HeaderIndex += ANullDescriptorLength; } else { short nestedType = IPAddress.NetworkToHostOrder(BitConverter.ToInt16(info.Data, info.HeaderIndex + 4)); // `sym is always boxed (see more in CDR spec) if (nestedType == CDRConstants.CDRSymShort) { result = BuildSymbol(shape, info); } else { result = BuildBox(shape, info); } } } else if (typeCode == CDRConstants.CDRSymShort) { result = BuildSymbol(shape, info); } else { int length = shape.Product(); ATypes type; if (CDRConstants.IntegerTypes.Contains(typeCode)) { length *= sizeof(Int32); type = ATypes.AInteger; } else if (CDRConstants.FloatTypes.Contains(typeCode)) { length *= sizeof(Double); type = ATypes.AFloat; } else if (typeCode == CDRConstants.CDRCharShort) { length *= sizeof(Char) / 2; // sizeof(Char) == 2 in C# type = ATypes.AChar; } else { throw new Error.Domain("sys.imp"); } byte[] data = info.Data; result = ATypeConverter.Instance.BuildArray(shape, ref data, type, info.DataIndex); info.DataIndex += length; } return result; }