コード例 #1
0
ファイル: ImportHandler.cs プロジェクト: jncc/topcat
        public void Import(ImportOptions options)
        {
            var mapping = InstantiateMapping(options);
            var importer = Importer.CreateImporter(db, mapping);

            importer.SkipBadRecords = options.SkipBadRecords;
            importer.Import(options.File);

            string errorFilePath = GetErrorFilePath(options);
            WriteErrorsToFile(importer.Results, errorFilePath);

            db.SaveChanges();

            int successes = importer.Results.Count(r => r.Success);
            int failures = importer.Results.Count(r => !r.Success);

            Console.WriteLine("Imported {0} records.", successes);
            Console.WriteLine("Skipped {0} records.", failures);

            if (failures > 0)
            {
                Console.WriteLine("See error file for details.");
                Console.WriteLine(errorFilePath);
            }
        }
コード例 #2
0
ファイル: ImportHandler.cs プロジェクト: jncc/topcat
        IMapping InstantiateMapping(ImportOptions options)
        {
            var type = typeof(IMapping).Assembly.GetType("Catalogue.Data.Import.Mappings." + options.Mapping);

            if (type  == null)
                throw new Exception(String.Format("The import mapping '{0}' couldn't be found or does not exist.", options.Mapping));

            return (IMapping) Activator.CreateInstance(type);
        }
コード例 #3
0
ファイル: Import.cs プロジェクト: r2i-sitecore/dotless
        private Import(Node path, Value features, ImportOptions option)
        {
            if (path == null)
                throw new ParserException("Imports do not allow expressions");

            OriginalPath = path;
            Features = features;
            ImportOptions = option;
        }
コード例 #4
0
ファイル: Importer.cs プロジェクト: dpawatts/zeus
 public virtual void Import(IImportRecord record, ContentItem destination, ImportOptions options)
 {
     ResetIDs(record.ReadItems);
     if ((options & ImportOptions.AllItems) == ImportOptions.AllItems)
     {
         record.RootItem.AddTo(destination);
         persister.Save(record.RootItem);
     }
     else if ((options & ImportOptions.Children) == ImportOptions.Children)
     {
         RemoveReferences(record.ReadItems, record.RootItem);
         while (record.RootItem.Children.Count > 0)
         {
             ContentItem child = record.RootItem.Children[0];
             child.AddTo(destination);
             persister.Save(child);
         }
     }
     else
     {
         throw new NotImplementedException("This option isn't implemented, sorry.");
     }
 }
コード例 #5
0
        protected override bool TargetAudiencesCompleted()
        {
            ImportOptions options = new ImportOptions
              {
            Filename = FileUtil.MapPath("/temp/" + FileUtil.GetFileName(this.Filename.Value)),
            MappedProperties = this.MappedProperties,
            Root = this.Root,
            DomainName = this.DomainInput.Value
              };
              string str = Context.ClientPage.ClientRequest.Form[this.SkipUser.Name];
              if (string.IsNullOrEmpty(str) || str.Equals(this.SkipUser.Value))
              {
            options.ConflictOption = ImportOptions.ConflictOptions.SkipUser;
              }
              else
              {
            options.ConflictOption = str.Equals(this.OverwriteProperties.Value) ? ImportOptions.ConflictOptions.OverwriteProperties : ImportOptions.ConflictOptions.KeepProperties;
              }

              List<string> roles = new List<string>();
              try
              {
            this.AddOptInRoles(roles);
            this.AddOptOutRoles(roles);
            this.AddAdvancedRoles(roles);
              }
              catch (Exception exception)
              {
            SheerResponse.Alert(exception.Message, new string[0]);
            return false;
              }

              options.Roles = roles.ToArray();
              StartImportJob("Import Users", "PerformImport", CoreFactory.Instance.GetRecipientImporter(), new object[] { options });
              this.CheckImport();
              return true;
        }
コード例 #6
0
    public void DownloadEntryAssets(Entry entry, string serverURL)
    {
        // Check if Unity is supported
        //if (entry.getSupportedSDKs()[Entry.SDKs.UNITY.ordinal()])
        if (true)
        {
            // Get hologram type
            Hologram.hologramType hologramType = entry.getHologram().getType();
            // Handle model hologram
            if (hologramType.Equals(Hologram.hologramType.MODEL_HOLOGRAM))
            {
                // Get model names and ID
                ModelHologram modelHologram = (ModelHologram)entry.getHologram();

                List <string> filenames = new List <string>();
                filenames.Add(modelHologram.getFilename());
                if (modelHologram.getMaterialFilename() != null)
                {
                    filenames.Add(modelHologram.getMaterialFilename());
                }
                if (modelHologram.getTextureFilenames() != null)
                {
                    filenames.AddRange(modelHologram.getTextureFilenames());
                }

                List <string> fileStorageIDs = new List <string>();
                fileStorageIDs.Add(modelHologram.getStorageID());
                if (modelHologram.getMaterialStorageID() != null)
                {
                    fileStorageIDs.Add(modelHologram.getMaterialStorageID());
                }
                if (modelHologram.getTextureStorageIDs() != null)
                {
                    fileStorageIDs.AddRange(modelHologram.getTextureStorageIDs());
                }

                // Import Options
                ImportOptions importOptions = ParseAdditionalData(entry.getAdditionalData());

                // Instantiate model based on type
                if (modelHologram.getFilename().EndsWith(".glb"))
                {
                    // Instantiate model without downloading it
                    StartCoroutine(InstantiateModel(entry, filenames, importOptions));
                }
                else
                {
                    // Download model files and then instantiate
                    StartCoroutine(DownloadFiles(entry, serverURL, filenames, fileStorageIDs, importOptions));
                }
                // Handle video hologram
            }
            else if (hologramType.Equals(Hologram.hologramType.VIDEO_HOLOGRAM))
            {
                // Get video
                VideoHologram videoHologram = (VideoHologram)entry.getHologram();

                // Create primitive plane for the video to appear on
                GameObject videoPlane = GameObject.CreatePrimitive(PrimitiveType.Plane);

                // Set video plane position
                videoPlane.transform.parent   = this.gameObject.transform;
                videoPlane.transform.position = this.gameObject.transform.position;

                // Set video plane size
                string value  = "";
                float  height = (entry.getAdditionalData() != null && entry.getAdditionalData().TryGetValue("height", out value)) ? float.Parse(value) * 0.01f : 1;
                float  width  = (entry.getAdditionalData() != null && entry.getAdditionalData().TryGetValue("width", out value)) ? float.Parse(value) * 0.01f : 2;

                // Scale video plane
                videoPlane.transform.localScale = new Vector3(width, height, height);

                // Attach VideoPlayer to video plane
                var videoPlayer = videoPlane.AddComponent <VideoPlayer>();
                videoPlayer.playOnAwake = false;

                // Attach a CustomBehaviour Component
                videoPlane.AddComponent <CustomBehaviour>().entry = entry;

                // Set gameobject name to video name
                videoPlane.name = videoHologram.getFilename();

                // Set video URL
                videoPlayer.url = serverURL + "&file=" + videoHologram.getStorageID();

                // Play video
                videoPlayer.Play();

                // Mute
                if (entry.getAdditionalData() != null && entry.getAdditionalData().TryGetValue("mute", out value) && value.Equals("true"))
                {
                    for (ushort i = 0; i < videoPlayer.controlledAudioTrackCount; ++i)
                    {
                        videoPlayer.SetDirectAudioMute(i, true);
                    }
                }
                // Handle image hologram
            }
            else if (hologramType.Equals(Hologram.hologramType.IMAGE_HOLOGRAM))
            {
                // Get image
                ImageHologram imageHologram = (ImageHologram)entry.getHologram();

                // Create primitive plane for the image to appear on
                GameObject imagePlane = GameObject.CreatePrimitive(PrimitiveType.Plane);

                // Set image plane position
                imagePlane.transform.parent   = this.gameObject.transform;
                imagePlane.transform.position = this.gameObject.transform.position;

                // Set image plane size
                string value  = "";
                float  height = (entry.getAdditionalData() != null && entry.getAdditionalData().TryGetValue("height", out value)) ? float.Parse(value) * 0.01f : 1;
                float  width  = (entry.getAdditionalData() != null && entry.getAdditionalData().TryGetValue("width", out value)) ? float.Parse(value) * 0.01f : 1;

                // Scale image plane
                imagePlane.transform.localScale = new Vector3(width, height, height);

                // Set gameobject name to image name
                imagePlane.name = imageHologram.getFilename();

                // Set image URL
                string imageURL = (entry.getAdditionalData() != null && entry.getAdditionalData().TryGetValue("compressedImageStorageID", out value)) ?
                                  serverURL + "&file=" + value :
                                  serverURL + "&file=" + imageHologram.getStorageID();

                // Download image file and then instantiate
                StartCoroutine(DownloadandInitiateImage(entry, imageURL, imagePlane));
            }
        }
    }
コード例 #7
0
    IEnumerator InstantiateModel(Entry entry, List <string> filenames, ImportOptions importOptions)
    {
        Debug.Log("Instantiating model " + filenames[0]);

        // Refresh assets in editor
        #if UNITY_EDITOR
        if (Application.isEditor)
        {
            UnityEditor.AssetDatabase.Refresh();
        }
        #endif

        // Set shader
        string shader = null;
        if (entry.getAdditionalData() != null)
        {
            entry.getAdditionalData().TryGetValue("shader", out shader);
        }
        if (shader == null)
        {
            shader = "Legacy Shaders/Diffuse";                 // Force legacy shader for glb/glTf on mobile
        }
        // Import model
        string filepath  = Application.persistentDataPath + "/" + filenames[0];
        string extension = Path.GetExtension(filepath).ToLower();
        // Load file by extension
        if (extension == ".glb")
        {
            GameObject result = new GameObject();
            result.name = filenames[0];
            var glb = result.AddComponent <GLTFast.GlbAsset>();
            glb.shader = shader;
            glb.url    = serverURL + "&file=" + ((ModelHologram)entry.getHologram()).getStorageID();
            result.AddComponent <CustomBehaviour>().entry = entry;
            // Set game object parent and position
            result.transform.parent   = this.gameObject.transform;
            result.transform.position = this.gameObject.transform.position;
            #if UNITY_EDITOR
            // Caculate render times
            glb.onLoadComplete += calcRenderTime;
            renderIndex         = filenames[0];
            calcRenderTime(false, null);
            #endif
        }
        else if (extension == ".gltf")
        {
            GameObject result = Importer.LoadFromFile(filepath, shader);
            result.name = filenames[0];
            result.AddComponent <CustomBehaviour>().entry = entry;
            // Set game object parent and position
            result.transform.parent   = this.gameObject.transform;
            result.transform.position = this.gameObject.transform.position;
        }
        else if (extension == ".obj")
        {
            // Check how many files were uploaded to console
            int           numFiles = filenames.Count;
            List <string> texNames = new List <string>();
            if (numFiles >= 3)
            {
                texNames = filenames.GetRange(2, numFiles - 2);
            }
            gameObject.AddComponent <ObjectImporter>().ImportModelAsync(entry, Path.GetFileNameWithoutExtension(filenames[0]), filepath, texNames, null, importOptions, shader);
        }

        yield return(null);
    }
コード例 #8
0
        protected override void OnExecute(Command command, ExecutionContext context, System.Drawing.Rectangle buttonRect)
        {
            base.OnExecute(command, context, buttonRect);

            Window activeWindow = Window.ActiveWindow;
            Part   activePart   = (activeWindow.Scene as Part);

            Layer tabLayer = NoteHelper.CreateOrGetLayer(activeWindow.ActiveContext.Context.Document, "Tabs", System.Drawing.Color.Fuchsia);

            IDesignEdge iDesignEdge = activeWindow.ActiveContext.SingleSelection as IDesignEdge;

            if (iDesignEdge == null)
            {
                return;
            }

            if (iDesignEdge.Faces.Count != 1)
            {
                return;
            }

            IDesignFace iDesignFace = null;

            foreach (IDesignFace testFace in iDesignEdge.Faces)
            {
                iDesignFace = testFace;
            }

            Debug.Assert(iDesignFace != null);

            Point startPoint = iDesignEdge.Shape.StartPoint;
            Point endPoint   = iDesignEdge.Shape.EndPoint;

            if (areTabsFlipped)
            {
                Point tempPoint = startPoint;
                startPoint = endPoint;
                endPoint   = tempPoint;
            }

            SurfaceEvaluation surfEval   = iDesignFace.Shape.ProjectPoint(startPoint);
            Direction         faceNormal = surfEval.Normal;
            Point             midpoint   = startPoint + (endPoint - startPoint) / 2;
            Double            edgeLength = iDesignEdge.Shape.Length;
            Direction         xDir       = (endPoint - startPoint).Direction;

            List <Window> tabWindows = null;
            string        tabFile    = string.Empty;

            if (!isTabStartSlot)
            {
                tabFile = @"C:\Users\bcr.SPACECLAIM\Documents\Models\Dodecahedron Foldcrease\Tab-Circle-Male.scdoc";
            }
            else
            {
                tabFile = @"C:\Users\bcr.SPACECLAIM\Documents\Models\Dodecahedron Foldcrease\Tab-Circle-Female.scdoc";
            }

            try {
                tabWindows = new List <Window>(Document.Open(tabFile, ImportOptions.Create()));
            }
            catch (Exception exception) {
                System.Windows.Forms.MessageBox.Show(SpaceClaim.Api.V10.Application.MainWindow, exception.Message);
            }

            DesignBody tabDesignBody = null;

            foreach (DesignBody testBody in (tabWindows[0].Scene as Part).Bodies)
            {
                tabDesignBody = testBody;
            }

            Debug.Assert(tabDesignBody != null);

            tabDesignBody = DesignBody.Create(activePart, "tab", tabDesignBody.Shape.Body.Copy());

            foreach (Window window in tabWindows)
            {
                window.Delete();
            }

            Matrix scale = Matrix.CreateScale(edgeLength / 0.02, Point.Origin);
            Matrix trans = Matrix.CreateMapping(Frame.Create(midpoint, xDir, Direction.Cross(faceNormal, xDir)));

            tabDesignBody.Transform(trans * scale);
            tabDesignBody.Layer = tabLayer;
        }
コード例 #9
0
 public MainFrm()
 {
     InitializeComponent();
     importOptions = new ImportOptions();
 }
コード例 #10
0
ファイル: frmMain.cs プロジェクト: chuckfrazier/DataPlatform
 private void RunImport(ImportOptions options)
 {
     //Thread.Sleep(1000 * 30);
     ImportRunner runner = new ImportRunner(options, SystemDataProvider);
     runner.Execute();
 }
コード例 #11
0
    /// <summary>
    /// Uploads the file.
    /// </summary>
    public void UploadFile()
    {
        if (uplFile.UploadedFiles.Count == 0)
            return;

        lblFileRequired.Visible = false;
        lblRequiredMsg.Visible = false;
        try
        {
            if (txtConfirmUpload.Value.Equals("F"))
            {
                uplFile.UploadedFiles.Clear();
            }

            if (txtConfirmUpload.Value.Equals("O"))
            {
                //elected to overwrite existing uploaded file
                ImportManager importManager = GetImportManager();
                importManager.SourceFileName = uplFile.UploadedFiles[0].FileName;
                importManager.ImportMaps.Clear();
                //importManager.SourceProperties.Clear();
                ImportOptions options = new ImportOptions();
                importManager.Options = options;
                Page.Session["importManager"] = importManager;
                txtConfirmUpload.Value = "T";
            }

            if (txtConfirmUpload.Value.Equals("T"))
            {
                UploadedFile file = uplFile.UploadedFiles[0];
                if (file != null)
                {
                    ImportManager importManager = Page.Session["importManager"] as ImportManager;
                    importManager.SourceFileName = file.FileName;
                    importManager.SourceReader = GetCSVReader(file, importManager.ToString());
                    Page.Session["importManager"] = importManager;
                }
            }
        }
        catch (Exception ex)
        {
            log.Error(ex.Message);
            DialogService.ShowMessage(ex.Message);
        }
    }
コード例 #12
0
        static void ImportFileIntoCollection(StringTableCollection collection, IFile file, LocaleIdentifier source, LocaleIdentifier target, ImportOptions importOptions)
        {
            if (collection == null)
            {
                throw new ArgumentNullException(nameof(collection));
            }

            var sourceTable = collection.GetTable(source) ?? collection.AddNewTable(source);
            var targetTable = collection.GetTable(target) ?? collection.AddNewTable(target);

            // Extract file comments?
            AddMetadataCommentsFromNotes(file, collection.SharedData.Metadata, NoteType.General, importOptions.ImportNotes);
            AddMetadataCommentsFromNotes(file, sourceTable, NoteType.Source, importOptions.ImportNotes);

            if (sourceTable != targetTable)
            {
                AddMetadataCommentsFromNotes(file, targetTable, NoteType.Target, importOptions.ImportNotes);
            }

            ImportIntoTables(file, sourceTable as StringTable, targetTable as StringTable, importOptions);

            LocalizationEditorSettings.EditorEvents.RaiseCollectionModified(null, collection);
        }
コード例 #13
0
ファイル: Import.cs プロジェクト: r2i-sitecore/dotless
 public Import(Quoted path, Value features, ImportOptions option)
     : this((Node)path, features, option)
 {
     OriginalPath = path;
 }
コード例 #14
0
        static void ImportFileNode(IFile file, LocaleIdentifier source, LocaleIdentifier target, ImportOptions importOptions)
        {
            // Find the string table and collection for this file
            var collection = FindProjectCollection(file);

            // Import translation units which have no groups.
            INoteCollection extraNodes = file;

            if (file.TranslationUnitCount > 0)
            {
                if (collection == null)
                {
                    var dir = importOptions.NewCollectionDirectory;
                    if (string.IsNullOrEmpty(dir))
                    {
                        dir = EditorUtility.SaveFolderPanel($"Create new String Table Collection {file.Id}", "Assets", file.Id);
                    }

                    if (!string.IsNullOrEmpty(dir))
                    {
                        var newCollection = LocalizationEditorSettings.CreateStringTableCollection(file.Id, dir);
                        extraNodes = null;
                        ImportFileIntoCollection(newCollection, file, source, target, importOptions);
                    }
                }
                else
                {
                    extraNodes = null;
                    ImportFileIntoCollection(collection, file, source, target, importOptions);
                }
            }

            for (int i = 0; i < file.GroupCount; ++i)
            {
                var group           = file.GetGroup(i);
                var groupCollection = FindProjectCollection(group) ?? collection;
                if (groupCollection == null)
                {
                    // Use the provided directory otherwise ask the user to provide one
                    var dir = importOptions.NewCollectionDirectory;
                    if (string.IsNullOrEmpty(dir))
                    {
                        dir = EditorUtility.SaveFolderPanel($"Create new String Table Collection {file.Id}", "Assets", file.Id);
                        if (string.IsNullOrEmpty(dir))
                        {
                            continue;
                        }
                    }
                    var collectionName = string.IsNullOrEmpty(group.Name) ? group.Id : group.Name;
                    groupCollection = LocalizationEditorSettings.CreateStringTableCollection(collectionName, dir);
                }

                ImportGroupIntoCollection(groupCollection, group, extraNodes, source, target, importOptions);
            }
        }
コード例 #15
0
        /// <summary>
        /// Import the XLIFF file into the collection.
        /// </summary>
        /// <param name="collection">The collection to import all the XLIFF data into.</param>
        /// <param name="file">The XLIFF file path.</param>
        /// <param name="importOptions">Optional import options which can be used to configure the importing behavior.</param>
        /// <param name="reporter">Optional reporter which can report the current progress.</param>
        public static void ImportFileIntoCollection(StringTableCollection collection, string file, ImportOptions importOptions = null, ITaskReporter reporter = null)
        {
            if (collection == null)
            {
                throw new ArgumentNullException(nameof(collection));
            }

            reporter?.Start("Importing XLIFF", $"Importing {file}");
            try
            {
                if (!File.Exists(file))
                {
                    throw new FileNotFoundException($"Could not find file {file}");
                }

                using (var stream = new FileStream(file, FileMode.Open, FileAccess.Read))
                {
                    reporter?.ReportProgress("Parsing XLIFF", 0.1f);
                    var document = XliffDocument.Parse(stream);

                    float progress = 0.3f;
                    reporter?.ReportProgress("Importing XLIFF into project", progress);

                    float progressStep = document.FileCount / 1.0f * 0.7f;
                    var   options      = importOptions ?? s_DefaultOptions;
                    for (int i = 0; i < document.FileCount; ++i)
                    {
                        var f = document.GetFile(i);
                        progress += progressStep;
                        reporter?.ReportProgress($"Importing({i + 1}/{document.FileCount}) {f.Id}", progress);
                        ImportFileIntoCollection(collection, f, document.SourceLanguage, document.TargetLanguage, options);
                    }

                    reporter?.Completed("Finished importing XLIFF");
                }
            }
            catch (Exception e)
            {
                reporter?.Fail(e.Message);
                throw;
            }
        }
コード例 #16
0
 public Import(Url path, Value features, ImportOptions option)
     : this((Node)path, features, option)
 {
     OriginalPath = path;
     Path         = path.GetUnadjustedUrl();
 }
コード例 #17
0
 public Import(Quoted path, Value features, ImportOptions option)
     : this((Node)path, features, option)
 {
     OriginalPath = path;
 }
コード例 #18
0
 public KBLogoImportStrategy(ImportOptions options, IOkapiClient okapiClient)
     : base(options, okapiClient)
 {
 }
コード例 #19
0
        protected override void Execute()
        {
            var projects = _controllers.TranscreateController.GetSelectedProjects();

            if (projects?.Count != 1)
            {
                Enabled = false;
                return;
            }

            var project = projects[0];

            if (project is BackTranslationProject)
            {
                return;
            }

            var studioProject = _controllers.ProjectsController.GetProjects()
                                .FirstOrDefault(a => a.GetProjectInfo().Id.ToString() == project.Id);

            if (studioProject == null)
            {
                return;
            }

            var studioProjectInfo = studioProject.GetProjectInfo();


            var backTranslationsFolder = Path.Combine(studioProjectInfo.LocalProjectFolder, "BackProjects");

            if (Directory.Exists(backTranslationsFolder))
            {
                var message01 = "The Back-Translations folder is not empty."
                                + Environment.NewLine + Environment.NewLine
                                + "'" + backTranslationsFolder + "'"
                                + Environment.NewLine + Environment.NewLine;
                var message02 = "Do you want to proceed and delete this folder?";

                var response = MessageBox.Show(message01 + message02, PluginResources.Plugin_Name,
                                               MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                if (response != DialogResult.Yes)
                {
                    return;
                }

                TryDeleteDirectory(backTranslationsFolder);
            }


            var taskContexts = new List <TaskContext>();

            var progressSettings = new ProgressDialogSettings(ApplicationInstance.GetActiveForm(), true, true, true);
            var result           = ProgressDialog.Execute("Create Back-Translation Projects", () =>
            {
                ProgressDialog.Current.Report(0, "Reading language files...");

                var dateTimeStamp         = DateTime.UtcNow;
                var dataTimeStampToString = DateTimeStampToString(dateTimeStamp);
                var workFlowPath          = GetPath(studioProjectInfo.LocalProjectFolder, "WorkFlow");
                var workingActionPath     = GetPath(workFlowPath, "Convert");
                var workingFolder         = GetPath(workingActionPath, dataTimeStampToString);

                var exportOptions = new ExportOptions();
                exportOptions.IncludeBackTranslations = true;
                exportOptions.IncludeTranslations     = true;
                exportOptions.CopySourceToTarget      = false;

                var importOptions = new ImportOptions();
                importOptions.OverwriteTranslations      = true;
                importOptions.OriginSystem               = "Transcreate Automation";
                importOptions.StatusTranslationUpdatedId = string.Empty;

                var analysisBands = _projectAutomationService.GetAnalysisBands(studioProject);

                var sdlxliffReader = new SdlxliffReader(_segmentBuilder, exportOptions, analysisBands);
                var sdlxliffWriter = new SdlxliffWriter(_segmentBuilder, importOptions, analysisBands);
                var xliffWriter    = new XliffWriter(Enumerators.XLIFFSupport.xliff12sdl);

                // Read the SDLXLIFF data
                var fileDataList = GetFileDataList(project, studioProjectInfo, sdlxliffReader);
                var filesWithEmptyTranslations = fileDataList.Count(a => a.HasEmptyTranslations);
                if (filesWithEmptyTranslations > 0)
                {
                    var message01 = string.Format(PluginResources.Found_empty_translations_in_0_files,
                                                  filesWithEmptyTranslations)
                                    + Environment.NewLine + Environment.NewLine;
                    var message02 = PluginResources.Proceed_and_copy_source_to_target_for_empty_translations;

                    var response = MessageBox.Show(message01 + message02, PluginResources.Plugin_Name,
                                                   MessageBoxButtons.YesNo, MessageBoxIcon.Question);
                    if (response != DialogResult.Yes)
                    {
                        return;
                    }
                }

                ProgressDialog.Current.ProgressBarIsIndeterminate = false;
                decimal maximum = project.TargetLanguages.Count;
                decimal current = 0;

                foreach (var targetLanguage in project.TargetLanguages)
                {
                    if (ProgressDialog.Current.CheckCancellationPending())
                    {
                        ProgressDialog.Current.ThrowIfCancellationPending();
                    }

                    current++;
                    var progress = current / maximum * 100;
                    ProgressDialog.Current.Report((int)progress, "Language: " + targetLanguage.CultureInfo.DisplayName);


                    var sourceFiles    = new List <string>();
                    var languageFolder = GetPath(workingFolder, targetLanguage.CultureInfo.Name);

                    var targetFiles = project.ProjectFiles.Where(a =>
                                                                 string.Compare(a.TargetLanguage, targetLanguage.CultureInfo.Name,
                                                                                StringComparison.CurrentCultureIgnoreCase) == 0);

                    var languageFileData = new List <FileData>();
                    foreach (var projectFile in targetFiles)
                    {
                        var fileData =
                            fileDataList.FirstOrDefault(a => a.Data.DocInfo.DocumentId == projectFile.FileId);
                        if (fileData == null)
                        {
                            continue;
                        }

                        SwitchSourceWithTargetSegments(fileData);

                        var xliffFolder   = GetPath(languageFolder, projectFile.Path);
                        var xliffFilePath = Path.Combine(xliffFolder,
                                                         projectFile.Name.Substring(0, projectFile.Name.Length - ".sdlxliff".Length));

                        // Write the XLIFF file
                        var success = xliffWriter.WriteFile(fileData.Data, xliffFilePath, true);
                        if (!success)
                        {
                            throw new Exception(string.Format(
                                                    PluginResources.Unexpected_error_while_converting_the_file, xliffFilePath));
                        }

                        sourceFiles.Add(xliffFilePath);
                        languageFileData.Add(fileData);
                    }

                    var iconPath = GetBackTranslationIconPath();

                    var newStudioProject = _projectAutomationService.CreateBackTranslationProject(
                        studioProject, targetLanguage.CultureInfo.Name, iconPath, sourceFiles, "BT");

                    _projectAutomationService.RunPretranslationWithoutTm(newStudioProject);

                    var taskContext = CreateBackTranslationTaskContext(newStudioProject, languageFileData,
                                                                       studioProjectInfo.LocalProjectFolder, sdlxliffReader, sdlxliffWriter, xliffWriter);

                    taskContext.Completed = true;
                    taskContexts.Add(taskContext);
                }
            }, progressSettings);

            if (result.Cancelled || result.OperationFailed)
            {
                TryDeleteDirectory(backTranslationsFolder);

                var message = result.Cancelled ? "Process cancelled by user." : result.Error?.Message;
                MessageBox.Show(message, PluginResources.Plugin_Name);
                return;
            }

            foreach (var taskContext in taskContexts)
            {
                ActivateProject(taskContext.FileBasedProject);
                _projectAutomationService.RemoveAllReports();
                UpdateProjectSettingsBundle(taskContext.FileBasedProject);
                _controllers.TranscreateController.UpdateBackTranslationProjectData(project, taskContext);
            }

            _controllers.TranscreateController.InvalidateProjectsContainer();

            Enabled = false;
        }
コード例 #20
0
        static void ImportGroupIntoCollection(StringTableCollection collection, IGroup group, INoteCollection extraNotes, LocaleIdentifier source, LocaleIdentifier target, ImportOptions importOptions)
        {
            if (collection == null)
            {
                throw new ArgumentNullException(nameof(collection));
            }

            var sourceTable = collection.GetTable(source) ?? collection.AddNewTable(source);
            var targetTable = collection.GetTable(target) ?? collection.AddNewTable(target);

            // Extract file comments?
            var generalNotes = AddMetadataCommentsFromNotes(group, collection.SharedData.Metadata, NoteType.General, importOptions.ImportNotes);
            var sourceNotes  = AddMetadataCommentsFromNotes(group, sourceTable, NoteType.Source, importOptions.ImportNotes);
            int targetNotes  = sourceTable != targetTable?AddMetadataCommentsFromNotes(group, targetTable, NoteType.Target, importOptions.ImportNotes) : 0;

            // If we are importing a group and the file contains notes that were not used then we can include them as extras here.
            if (extraNotes != null)
            {
                // If we imported some notes from the group then we need to switch to merge or we will lose those notes.
                var overrideBehavior = generalNotes > 0 ? ImportNotesBehavior.Merge : importOptions.ImportNotes;
                AddMetadataCommentsFromNotes(extraNotes, collection.SharedData.Metadata, NoteType.General, overrideBehavior);

                overrideBehavior = sourceNotes > 0 ? ImportNotesBehavior.Merge : importOptions.ImportNotes;
                AddMetadataCommentsFromNotes(extraNotes, sourceTable, NoteType.Source, overrideBehavior);

                overrideBehavior = targetNotes > 0 ? ImportNotesBehavior.Merge : importOptions.ImportNotes;
                if (sourceTable != targetTable)
                {
                    AddMetadataCommentsFromNotes(extraNotes, targetTable, NoteType.Target, overrideBehavior);
                }
            }

            ImportIntoTables(group, sourceTable as StringTable, targetTable as StringTable, importOptions);
            LocalizationEditorSettings.EditorEvents.RaiseCollectionModified(null, collection);
        }
コード例 #21
0
        protected internal virtual async Task ImportAsyncScenarioTest(DatabaseProvider databaseProvider)
        {
            var importOptions = new ImportOptions {
                DeleteAllOthers = true
            };

            using (var context = new Context(databaseProvider: databaseProvider))
            {
                var serviceProvider = context.ServiceProvider;
                await DatabaseHelper.MigrateDatabaseAsync(serviceProvider);

                // Step 1
                await this.ImportAsyncScenarioTest(
                    importOptions,
                    new List <ClientModel>
                {
                    new ClientModel
                    {
                        AllowedGrantTypes = new[] { "a", "b", "c" }.ToList(),
                        ClientId          = "client-1",
                        ClientSecrets     = new[] { new SecretModel("a"), new SecretModel("b"), new SecretModel("c") }.ToList(),
                        Description       = "client-1-description"
                    }
                },
                    7,
                    serviceProvider
                    );

                // Step 2
                await this.ImportAsyncScenarioTest(
                    importOptions,
                    new List <ClientModel>
                {
                    new ClientModel
                    {
                        AllowedGrantTypes = new[] { "a", "b", "c" }.ToList(),
                        ClientId          = "client-1",
                        ClientSecrets     = new[] { new SecretModel("a"), new SecretModel("b"), new SecretModel("c") }.ToList(),
                        Description       = "client-1-description"
                    }
                },
                    0,
                    serviceProvider
                    );

                // Step 3
                await this.ImportAsyncScenarioTest(
                    importOptions,
                    new List <ClientModel>
                {
                    new ClientModel
                    {
                        AllowedGrantTypes = new[] { "a" }.ToList(),
                        ClientId          = "client-1",
                        ClientSecrets     = new[] { new SecretModel("a") }.ToList(),
                        Description       = "client-1-description"
                    }
                },
                    4,
                    serviceProvider
                    );

                // Step 4
                await this.ImportAsyncScenarioTest(
                    importOptions,
                    new List <ClientModel>(),
                    1,
                    serviceProvider
                    );
            }
        }
コード例 #22
0
        static void ImportIntoTables(ITranslationUnitCollection unitCollection, StringTable source, StringTable target, ImportOptions importOptions = null)
        {
            var options         = importOptions ?? s_DefaultOptions;
            var sharedTableData = target.SharedData;

            EditorUtility.SetDirty(sharedTableData);

            if (importOptions.UpdateSourceTable)
            {
                EditorUtility.SetDirty(source);
            }

            if (importOptions.UpdateTargetTable)
            {
                EditorUtility.SetDirty(target);
            }

            for (int i = 0; i < unitCollection.TranslationUnitCount; ++i)
            {
                var tu = unitCollection.GetTranslationUnit(i);
                var sharedTableEntry = GetOrCreateEntryFromTranslationUnit(sharedTableData, tu);
                AddMetadataCommentsFromNotes(tu, sharedTableEntry.Metadata, NoteType.General, options.ImportNotes);

                if (options.UpdateSourceTable)
                {
                    var sourceEntry = source.AddEntry(sharedTableEntry.Id, tu.Source);
                    AddMetadataCommentsFromNotes(tu, sourceEntry, NoteType.Source, options.ImportNotes);
                }

                if (options.UpdateTargetTable)
                {
                    var targetEntry = target.AddEntry(sharedTableEntry.Id, tu.Target);
                    AddMetadataCommentsFromNotes(tu, targetEntry, NoteType.Target, options.ImportNotes);
                }
            }

            // Nested groups
            if (unitCollection is IGroupCollection groupCollection)
            {
                for (int i = 0; i < groupCollection.GroupCount; ++i)
                {
                    var group = groupCollection.GetGroup(i);
                    ImportIntoTables(group, source, target, options);
                }
            }
        }
コード例 #23
0
        private static void Main(string[] args)
        {
            var configuration = new ConfigurationBuilder()
                                .SetBasePath(Directory.GetCurrentDirectory())
                                .AddJsonFile("appsettings.json", optional: false, reloadOnChange: false)
                                .AddJsonFile($"appsettings.{Environment.MachineName.ToLowerInvariant()}.json", optional: true, reloadOnChange: false)
                                .AddEnvironmentVariables()
                                .AddCommandLine(args ?? new string[0])
                                .Build();

            var mailSettings = configuration.GetSection("ApplicationSettings").GetSection("SerilogMail");

            Log.Logger = new LoggerConfiguration()
                         .WriteTo.File("tracing.log", LogEventLevel.Verbose)
                         .WriteTo.Console(LogEventLevel.Information)
                         .WriteTo.SendGridSmtp(
                mailSettings["apiKey"],
                mailSettings["subject"],
                mailSettings["fromEmail"],
                mailSettings["toEmail"],
                (LogEventLevel)Enum.Parse(typeof(LogEventLevel), mailSettings["restrictedToMinimumLevel"], true))
                         .ReadFrom.Configuration(configuration)
                         .CreateLogger();

            var crabConnectionString = configuration.GetConnectionString("CRABEntities");
            Func <CRABEntities> crabEntitiesFactory = () => new CRABEntities(crabConnectionString);

            var settings = new SettingsBasedConfig(configuration.GetSection("ApplicationSettings"));

            try
            {
                var options = new ImportOptions(
                    args,
                    errors => WaitForExit(settings, "Could not parse commandline options."));

                MapLogging.Log = s => _commandCounter++;

                var commandProcessor = new CommandProcessorBuilder <int>(new StreetNameCommandGenerator(crabEntitiesFactory))
                                       .WithCommandLineOptions(options.ImportArguments)
                                       .UseSerilog(cfg => cfg
                                                   .WriteTo.File("tracing.log", LogEventLevel.Verbose)
                                                   .WriteTo.Console(LogEventLevel.Information))
                                       .UseHttpApiProxyConfig(settings)
                                       .UseCommandProcessorConfig(settings)
                                       .UseDefaultSerializerSettingsForCrabImports()
                                       .UseImportFeed(new ImportFeed {
                    Name = settings.FeedName
                })
                                       //.UseApiProxyFactory(FileBasedProxyFactory.BuildFileBasedProxyFactory)
                                       .Build();

                WaitForStart(settings);

                commandProcessor.Run(options, settings);

                WaitForExit(settings);
            }
            catch (Exception exception)
            {
                WaitForExit(settings, "General error occurred", exception);
            }
        }
コード例 #24
0
 private void LookForDataToProcess(ImportOptions importOptions, ProcessFileType fileType)
 { 
     if (options.HasFlag(importOptions))
     {
         ImportFile(ProcessType.InitialValidation, ProcessStatus.Successful, fileType);
     }
 }
コード例 #25
0
 // Sitecore.Modules.EmailCampaign.Core.RecipientImporter
 private int GetEmailColumnIndex(ImportOptions options, List<string> headers)
 {
     int result = -1;
       for (int i = 0; i < headers.Count; i++)
       {
     if (options.MappedProperties["Email"].Equals(headers[i]))
     {
       result = i;
       options.MappedProperties.Remove("Email");
       break;
     }
       }
       return result;
 }
コード例 #26
0
 /// <summary>
 /// Initializes a new instance of the ImportRunner class.
 /// </summary>
 public ImportRunner(ImportOptions options, ISystemDataProvider irmDbDataProvider)
 {
     this.options = options;
     SystemDataProvider = irmDbDataProvider;
 }
コード例 #27
0
 /// <summary>
 /// Gets the template list.
 /// </summary>
 private void GetImportTemplateList(ImportOptions options)
 {
     cboTemplates.Items.Clear();
     cboTemplates.Items.Add(GetLocalResourceObject("cboTemplates.None.Item").ToString());
     IList<IImportTemplate> list = ImportRules.GetImportTemplates();
     ListItem item;
     foreach (IImportTemplate template in list)
     {
         item = new ListItem();
         item.Text = template.TemplateName;
         item.Value = template.Id.ToString();
         if (options != null && item.Text.Equals(options.Template))
             item.Selected = true;
         cboTemplates.Items.Add(item);
     }
 }
コード例 #28
0
        private void PerformImport(Dictionary <TeamProjectInfo, List <WorkItemConfigurationItem> > teamProjectsWithCategories, ImportOptions options)
        {
            var numberOfSteps = teamProjectsWithCategories.Aggregate(0, (a, p) => a += p.Value.Count);
            var task          = new ApplicationTask("Importing work item categories", numberOfSteps, true);

            PublishStatus(new StatusEventArgs(task));
            var worker = new BackgroundWorker();

            worker.DoWork += (sender, e) =>
            {
                var tfs   = GetSelectedTfsTeamProjectCollection();
                var store = tfs.GetService <WorkItemStore>();
                WorkItemConfigurationItemImportExport.Import(this.Logger, task, true, store, teamProjectsWithCategories, options);
            };
            worker.RunWorkerCompleted += (sender, e) =>
            {
                if (e.Error != null)
                {
                    Logger.Log("An unexpected exception occurred while importing work item categories", e.Error);
                    task.SetError(e.Error);
                    task.SetComplete("An unexpected exception occurred");
                }
                else
                {
                    task.SetComplete(task.IsError ? "Failed" : (task.IsWarning ? "Succeeded with warnings" : "Succeeded"));
                }
            };
            worker.RunWorkerAsync();
        }
コード例 #29
0
 internal static void AddXmlComment(CodeTypeMember member, string documentation, ImportOptions options)
 {
     IEnumerable<string> commentLines = XmlCommentsUtils.ParseAndReformatComment(documentation, options.Format, options.WrapLongLines);
     CodeCommentStatement[] commentStatements = commentLines.Select(s => new CodeCommentStatement(s, true)).ToArray();
     member.Comments.AddRange(commentStatements);
 }
コード例 #30
0
        public void Import(ImportOptions options, string scheduleFile = null)
        {
            try
            {
                switch (DataFormat)
                {
                case "json":
                    if (options.HasFlag(ImportOptions.AllSchedules))
                    {
                        Schedule[] newSch = null;
                        using (var stream = File.Open(SchedulesFile, FileMode.Open, FileAccess.Read))
                            using (var reader = new StreamReader(stream))
                                newSch = JsonConvert.DeserializeObject <Schedule[]>(reader.ReadToEnd());
                        if (newSch == null)
                        {
                            return;
                        }
                        Schedules.Clear();
                        foreach (var sch in newSch)
                        {
                            Schedules.Add(sch);
                        }
                    }
                    if (options.HasFlag(ImportOptions.MapData))
                    {
                        Map[] newMaps = null;
                        using (var stream = File.Open(MapDataFile, FileMode.Open, FileAccess.Read))
                            using (var reader = new StreamReader(stream))
                                newMaps = JsonConvert.DeserializeObject <Map[]>(reader.ReadToEnd());
                        if (newMaps == null)
                        {
                            return;
                        }
                        MapData.Clear();
                        foreach (var map in newMaps)
                        {
                            MapData.Add(map);
                        }
                    }
                    if (options.HasFlag(ImportOptions.Questions))
                    {
                        Question[] newQueries = null;
                        using (var stream = File.Open(QuestionsFile, FileMode.Open, FileAccess.Read))
                            using (var reader = new StreamReader(stream))
                                newQueries = JsonConvert.DeserializeObject <Question[]>(reader.ReadToEnd());
                        if (newQueries == null)
                        {
                            return;
                        }
                        Questions.Clear();
                        foreach (var query in newQueries)
                        {
                            Questions.Add(query);
                        }
                    }
                    if (options.HasFlag(ImportOptions.Activities))
                    {
                        Activity[] newAct = null;
                        using (var stream = File.Open(ActivitiesFile, FileMode.Open, FileAccess.Read))
                            using (var reader = new StreamReader(stream))
                                newAct = JsonConvert.DeserializeObject <Activity[]>(reader.ReadToEnd());
                        if (newAct == null)
                        {
                            return;
                        }
                        Activities.Clear();
                        foreach (var act in newAct)
                        {
                            Activities.Add(act);
                        }
                    }
                    break;

                case "csv":
                    if (options.HasFlag(ImportOptions.AllSchedules))
                    {
                        var newSch = Schedule.FromCsvMulti(DataDirectory, true);
                        Schedules.Clear();
                        foreach (var sch in newSch)
                        {
                            Schedules.Add(sch);
                        }
                    }
                    if (options == ImportOptions.SingleSchedule)
                    {
                        Schedules.Add(Schedule.FromCsv(scheduleFile));
                    }
                    if (options.HasFlag(ImportOptions.MapData))
                    {
                        var newMaps = Map.FromCsvMulti(MapDataFile, true);
                        MapData.Clear();
                        foreach (var map in newMaps)
                        {
                            MapData.Add(map);
                        }
                    }
                    if (options.HasFlag(ImportOptions.Questions))
                    {
                        var newQueries = Question.FromCsvMulti(QuestionsFile, true);
                        Questions.Clear();
                        foreach (var query in newQueries)
                        {
                            Questions.Add(query);
                        }
                    }
                    if (options.HasFlag(ImportOptions.Activities))
                    {
                        var newActs = Activity.FromCsvMulti(ActivitiesFile, true);
                        Activities.Clear();
                        foreach (var act in newActs)
                        {
                            Activities.Add(act);
                        }
                    }
                    break;
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                Console.WriteLine(ex.StackTrace);
            }
        }
コード例 #31
0
        public async Task Load()
        {
            var importOptions = new ImportOptions
            {
                AsyncCoroutineHelper = gameObject.GetComponent <AsyncCoroutineHelper>() ?? gameObject.AddComponent <AsyncCoroutineHelper>(),
                ExternalDataLoader   = null,
            };

            GLTFSceneImporter sceneImporter = null;

            try
            {
                Factory = Factory ?? ScriptableObject.CreateInstance <DefaultImporterFactory>();

                if (UseStream)
                {
                    string fullPath;
                    if (AppendStreamingAssets)
                    {
                        // Path.Combine treats paths that start with the separator character
                        // as absolute paths, ignoring the first path passed in. This removes
                        // that character to properly handle a filename written with it.
                        fullPath = Path.Combine(Application.streamingAssetsPath, GLTFUri.TrimStart(new[] { Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar }));
                    }
                    else
                    {
                        fullPath = GLTFUri;
                    }
                    string directoryPath = URIHelper.GetDirectoryName(fullPath);
                    importOptions.ExternalDataLoader = new FileLoader(directoryPath);
                    sceneImporter = Factory.CreateSceneImporter(
                        Path.GetFileName(GLTFUri),
                        importOptions
                        );
                }
                else
                {
                    string directoryPath = URIHelper.GetDirectoryName(GLTFUri);
                    importOptions.ExternalDataLoader = new WebRequestLoader(directoryPath);

                    sceneImporter = Factory.CreateSceneImporter(
                        URIHelper.GetFileFromUri(new Uri(GLTFUri)),
                        importOptions
                        );
                }

                sceneImporter.SceneParent      = gameObject.transform;
                sceneImporter.Collider         = Collider;
                sceneImporter.MaximumLod       = MaximumLod;
                sceneImporter.Timeout          = Timeout;
                sceneImporter.IsMultithreaded  = Multithreaded;
                sceneImporter.CustomShaderName = shaderOverride ? shaderOverride.name : null;

                if (MaterialsOnly)
                {
                    var mat = await sceneImporter.LoadMaterialAsync(0);

                    var cube = GameObject.CreatePrimitive(PrimitiveType.Cube);
                    cube.transform.SetParent(gameObject.transform);
                    var renderer = cube.GetComponent <Renderer>();
                    renderer.sharedMaterial = mat;
                }
                else
                {
                    await sceneImporter.LoadSceneAsync();
                }

                // Override the shaders on all materials if a shader is provided
                if (shaderOverride != null)
                {
                    Renderer[] renderers = gameObject.GetComponentsInChildren <Renderer>();
                    foreach (Renderer renderer in renderers)
                    {
                        renderer.sharedMaterial.shader = shaderOverride;
                    }
                }

                LastLoadedScene = sceneImporter.LastLoadedScene;

                Animations = sceneImporter.LastLoadedScene.GetComponents <Animation>();

                if (PlayAnimationOnLoad && Animations.Any())
                {
                    Animations.FirstOrDefault().Play();
                }
            }
            finally
            {
                if (importOptions.ExternalDataLoader != null)
                {
                    sceneImporter?.Dispose();
                    sceneImporter = null;
                    importOptions.ExternalDataLoader = null;
                }
            }
        }
コード例 #32
0
        private void NotifyUsers(ImportOptions options, int num, int num2, int num3, int num4, string pathToEmailReport)
        {
            try
            {
            Sitecore.Data.Database master = Sitecore.Modules.EmailCampaign.Util.GetContentDb();

            MediaCreatorOptions md = new MediaCreatorOptions();

            md.Destination = @"/sitecore/media library/Files/" + Sitecore.Configuration.Settings.GetSetting("RecipientImporterExt.PathToEmailReport", "/temp")+"/" + Path.GetFileNameWithoutExtension(pathToEmailReport);    // Set options
            md.Database = master;   // Set options
            MediaItem mediaItem = null;
            using (new SecurityDisabler())   // Use the SecurityDisabler object to override the security settings
            {
                // Create Media in database from file
                mediaItem = MediaManager.Creator.CreateFromFile(pathToEmailReport, md);
            }

            Sitecore.Data.Items.Item itemToSend = master.GetItem(Sitecore.Configuration.Settings.GetSetting("RecipientImporterExt.MessagePath", "/sitecore/content/Home/Email Campaign/Messages/Service Messages/Self-Service Subscription/Subscription Notification"));
            MessageItem messageItem = Sitecore.Modules.EmailCampaign.Factory.GetMessage(itemToSend);

            messageItem.Body = string.Format("Recipients imported: {0} <br/> E-mail addresses already exist: {1} <br/> E-mail addresses not provided: {2} <br/> Users not imported as required fields not available: {3}"
                                            + " <br/> You can check report file with the failed records here: {4}. <br/> Import finished at " + DateTime.Now.ToString(@"d/M/yyyy hh:mm:ss tt"), num, num2, num3, num4, pathToEmailReport);
            messageItem.Subject = "User import from " + Path.GetFileNameWithoutExtension(options.Filename) + " finished.";
            if (mediaItem != null)
            {
                messageItem.Attachments.Add(mediaItem);
            }
            SendingManager sendingManager = new SendingManager(messageItem);

            ListString usernamesToSend = new ListString(Sitecore.Configuration.Settings.GetSetting("RecipientImporterExt.SendTo", "sitecore\\admin"), ',');
            if (usernamesToSend.Count == 0)
            {
                Log.Info("RecipientImporterExt debug info: no users configured to send email to. Email will be sent only to the context user.", this);
                //  return result;
            }
            else
            {
                foreach (string nameString in usernamesToSend)
                {
                    Contact contactToSend = Sitecore.Modules.EmailCampaign.Factory.GetContactFromName(nameString);
                    if (contactToSend != null)
                    {
                        Log.Info("RecipientImporterExt debug info: Sending notification about the import to " + contactToSend.Profile.Email, this);
                        sendingManager.SendStandardMessage(contactToSend);
                    }
                }
            }

            User user = Sitecore.Context.User;
            if (user != null && !usernamesToSend.Contains(user.Name))
            {
                string username = user.Name;
                Contact contactToSend = Sitecore.Modules.EmailCampaign.Factory.GetContactFromName(username);
                if (contactToSend != null)
                {
                    Log.Info("RecipientImporterExt debug info: Sending notification about the import to " + username, this);
                    sendingManager.SendStandardMessage(contactToSend);
                }
            }
            }
            catch (Exception e)
            {

            Logging.LogError(e);
            }
        }
コード例 #33
0
    IEnumerator DownloadFiles(Entry entry, string serverURL, List <string> filenames, List <string> fileStorageIDs, ImportOptions importOptions)
    {
        for (int i = 0; i < filenames.Count; ++i)
        {
            // Check for invalid files
            if (string.IsNullOrEmpty(filenames[i]) || string.IsNullOrEmpty(fileStorageIDs[i]))
            {
                continue;
            }

            // Create a new request
            UnityWebRequest www = UnityWebRequest.Get(serverURL + "&file=" + fileStorageIDs[i]);

            Debug.Log("Downloading file " + filenames[i] + " (" + fileStorageIDs[i] + ")...");

            // Yield for the request
            yield return(www.SendWebRequest());

            // Wait for the request to finish
            while (!www.isDone)
            {
                yield return(null);
            }

            // Check for errors
            if (www.isNetworkError)
            {
                Debug.Log(www.error);
            }
            else
            {
                // Parse response
                byte[] bytes = www.downloadHandler.data;

                // Handle repsonse
                System.IO.File.WriteAllBytes(Application.persistentDataPath + "/" + filenames[i], bytes);

                Debug.Log("File " + filenames[i] + " (" + fileStorageIDs[i] + ") downloaded and stored in " + Application.persistentDataPath);
            }

            // Cleanup
            www.disposeDownloadHandlerOnDispose = true;
            www.disposeUploadHandlerOnDispose   = true;
            www.Dispose();
            www = null;
        }

        // Instantiate model
        StartCoroutine(InstantiateModel(entry, filenames, importOptions));
        yield return(null);
    }
コード例 #34
0
        public override async Task ImportAsync(IConfiguration configuration, ImportOptions options, IDataImportResult result)
        {
            await this.ValidateModelsAsync(configuration, result);

            await base.ImportAsync(configuration, options, result);
        }
コード例 #35
0
        static bool LoadFBX(ImportContext context, string virtualFileName, out List <MeshData> geometries)
        {
            geometries = null;

            var settings = context.settings;

            ImportFBX.LoadNativeLibrary();

            FbxManager    manager  = null;
            FbxIOSettings setting  = null;
            FbxImporter   importer = null;
            FbxScene      scene    = null;

            try
            {
                manager = FbxManager.Create();
                setting = FbxIOSettings.Create(manager, "IOSRoot");
                manager.SetIOSettings(setting);

                importer = FbxImporter.Create(manager, "");
                var realFileName = VirtualPathUtility.GetRealPathByVirtual(virtualFileName);
                //VirtualFileStream stream = null;
                //ToDo : FromStream
                bool status;
                if (!string.IsNullOrEmpty(realFileName) && File.Exists(realFileName))
                {
                    status = importer.Initialize(realFileName, -1, setting);
                }
                else
                {
                    return(false);
                    //throw new NotImplementedException();
                    //ToDo : ....
                    //stream = VirtualFile.Open( settings.virtualFileName );
                    //FbxStream fbxStream = null;
                    //SWIGTYPE_p_void streamData = null;

                    //status = impoter.Initialize( fbxStream, streamData, -1, setting );
                }

                if (!status)
                {
                    return(false);
                }

                scene  = FbxScene.Create(manager, "scene1");
                status = importer.Import(scene);
                if (!status)
                {
                    return(false);
                }

                //convert axis
                if (context.settings.component.ForceFrontXAxis)
                {
                    //Через такой конструктор не получится создать такие же оси как EPreDefinedAxisSystem.eMax - Front Axis имеет обратное направление, а направление задать нельзя.
                    //new FbxAxisSystem( FbxAxisSystem.EUpVector.eZAxis, FbxAxisSystem.EFrontVector.eParityOdd, FbxAxisSystem.ECoordSystem.eRightHanded );
                    //FromFBX Docs:
                    //The enum values ParityEven and ParityOdd denote the first one and the second one of the remain two axes in addition to the up axis.
                    //For example if the up axis is X, the remain two axes will be Y And Z, so the ParityEven is Y, and the ParityOdd is Z ;

                    //We desire to convert the scene from Y-Up to Z-Up. Using the predefined axis system: Max (UpVector = +Z, FrontVector = -Y, CoordSystem = +X (RightHanded))
                    var maxAxisSystem = new FbxAxisSystem(FbxAxisSystem.EPreDefinedAxisSystem.eMax);

                    if (!scene.GetGlobalSettings().GetAxisSystem().eq(maxAxisSystem))
                    {
                        maxAxisSystem.ConvertScene(scene);                           //No conversion will take place if the scene current axis system is equal to the new one. So condition can be removed.
                    }
                }

                //convert units
                if (!scene.GetGlobalSettings().GetSystemUnit().eq(FbxSystemUnit.m))
                {
                    FbxSystemUnit.m.ConvertScene(scene);
                }

                var additionalTransform = new Matrix4(settings.component.Rotation.Value.ToMatrix3() * Matrix3.FromScale(settings.component.Scale), settings.component.Position);

                var options = new ImportOptions
                {
                    NormalsOptions         = NormalsAndTangentsLoadOptions.FromFileIfPresentOrCalculate,
                    TangentsOptions        = NormalsAndTangentsLoadOptions.FromFileIfPresentOrCalculate,
                    ImportPostProcessFlags = ImportPostProcessFlags.FixInfacingNormals
                };
                options.ImportPostProcessFlags |= ImportPostProcessFlags.SmoothNormals | ImportPostProcessFlags.SmoothTangents;
                if (context.settings.component.FlipUVs)
                {
                    options.ImportPostProcessFlags |= ImportPostProcessFlags.FlipUVs;
                }
                //if( importContext.settings.component.MergeMeshGeometries )
                //	options.ImportPostProcessFlags |= ImportPostProcessFlags.MergeGeometriesByMaterials;

                var sceneLoader = new SceneLoader();
                sceneLoader.Load(scene, manager, options, additionalTransform);

                geometries = sceneLoader.Geometries;
                //foreach( var geometry in sceneLoader.Geometries )
                //	ImportGeometry( context, destinationMesh, geometry );

                ////check is it a billboard
                //MeshGetIsBillboard( context, destinationMesh );

                //stream?.Dispose();
            }
            finally
            {
                //Особенности удаления.
                //Создается через функцию: impoter = FbxImporter.Create(manager, "");
                //В таких случаях(создание не через конструктор, а возврат указателя из функции) SWIG задает флажок что объект не владеет ссылкой, поэтому Dispose ничего не делает.
                //Хотя в SWIG можно задать в конфигурации: %newobject FbxImporter::Create; Тогда объект будет владеть ссылкой. Но все равно в С++ наследники FbxObject не имеют public destructor
                //поэтому в Dispose вставлен: throw new MethodAccessException("C++ destructor does not have public access"). Поэтому удалять только через Destroy.

                try { scene?.Destroy(); } catch { }
                try { importer?.Destroy(); } catch { }
                try { setting?.Destroy(); } catch { }
                try { manager?.Destroy(); } catch { }
            }

            return(true);
        }
コード例 #36
0
        /// <summary>
        /// Imports all objects from the given source.
        /// </summary>
        /// <param name="objSource">The source to load from.</param>
        /// <param name="importOptions">All options for import logic.</param>
        public async Task <IEnumerable <SceneObject> > ImportAsync(ResourceLink objSource, ImportOptions importOptions)
        {
            List <SceneObject> result = new List <SceneObject>();

            // Import all data
            ImportedModelContainer modelContainer = await GraphicsCore.Current.ImportersAndExporters
                                                    .ImportAsync(objSource, importOptions);

            // Append all data to the scene
            await this.ManipulateSceneAsync((manipulator) =>
            {
                // Add all resources first
                foreach (var actResourceInfo in modelContainer.ImportedResources)
                {
                    manipulator.AddResource(
                        actResourceInfo.ResourceFactory,
                        actResourceInfo.ResourceKey);
                }

                // Add all objects
                foreach (var actObject in modelContainer.Objects)
                {
                    manipulator.Add(actObject);
                    result.Add(actObject);
                }

                // Apply parent/child relationships
                foreach (var actDependencyInfo in modelContainer.ParentChildRelationships)
                {
                    manipulator.AddChild(
                        actDependencyInfo.Item1,
                        actDependencyInfo.Item2);
                }
            });

            return(result);
        }
コード例 #37
0
        public MDL0Node ShowDialog(string filePath)
        {
            _importOptions = BrawlLib.Properties.Settings.Default.ColladaImportOptions;
            propertyGrid1.SelectedObject = _importOptions;

            if (base.ShowDialog() == DialogResult.OK)
            {
                panel1.Visible = false;
                Height = 70;
                UseWaitCursor = true;
                Text = "Please wait...";
                Show();
                Update();
                MDL0Node model = ImportModel(filePath);
                BrawlLib.Properties.Settings.Default.Save();
                Close();
                _importOptions = new ImportOptions();
                return model;
            }
            _importOptions = new ImportOptions();
            return null;
        }
コード例 #38
0
        protected internal virtual async Task ImportAsyncScenarioTest(ImportOptions importOptions, IList <ClientModel> models, int savedChangesExpected, IServiceProvider serviceProvider)
        {
            if (importOptions == null)
            {
                throw new ArgumentNullException(nameof(importOptions));
            }

            if (models == null)
            {
                throw new ArgumentNullException(nameof(models));
            }

            if (serviceProvider == null)
            {
                throw new ArgumentNullException(nameof(serviceProvider));
            }

            using (var serviceScope = serviceProvider.CreateScope())
            {
                var clientStore = serviceScope.ServiceProvider.GetRequiredService <IClientStore>();
                var configurationDatabaseContext = serviceScope.ServiceProvider.GetRequiredService <IConfigurationDbContext>();

                var clientImporter = await this.CreateClientImporterAsync(configurationDatabaseContext, serviceScope.ServiceProvider);

                var result = new DataImportResult();
                await clientImporter.ImportAsync(models, importOptions, result);

                var savedChanges = await configurationDatabaseContext.SaveChangesAsync();

                Assert.IsFalse(result.Errors.Any());
                Assert.AreEqual(savedChangesExpected, savedChanges);

                foreach (var model in models)
                {
                    var client = await clientStore.FindClientByIdAsync(model.ClientId);

                    Assert.AreEqual(model.Description, client.Description);
                    Assert.AreEqual(model.AllowedGrantTypes.Count, client.AllowedGrantTypes.Count);
                    for (var i = 0; i < model.AllowedGrantTypes.Count; i++)
                    {
                        Assert.AreEqual(model.AllowedGrantTypes.ElementAt(i), client.AllowedGrantTypes.ElementAt(i));
                    }

                    Assert.AreEqual(model.ClientSecrets.Count, client.ClientSecrets.Count);
                    for (var i = 0; i < model.ClientSecrets.Count; i++)
                    {
                        Assert.AreEqual(model.ClientSecrets.ElementAt(i).Description, client.ClientSecrets.ElementAt(i).Description);
                        Assert.AreEqual(model.ClientSecrets.ElementAt(i).Expiration, client.ClientSecrets.ElementAt(i).Expiration);
                        Assert.AreEqual(model.ClientSecrets.ElementAt(i).Type, client.ClientSecrets.ElementAt(i).Type);
                        Assert.AreEqual(model.ClientSecrets.ElementAt(i).Value, client.ClientSecrets.ElementAt(i).Value);
                    }
                }
            }

            using (var serviceScope = serviceProvider.CreateScope())
            {
                var configurationDatabaseContext = serviceScope.ServiceProvider.GetRequiredService <IConfigurationDbContext>();

                Assert.AreEqual(configurationDatabaseContext.ClientClaims().Count(), models.SelectMany(client => client.Claims).Count());
                Assert.AreEqual(configurationDatabaseContext.ClientGrantTypes().Count(), models.SelectMany(client => client.AllowedGrantTypes).Count());
                Assert.AreEqual(configurationDatabaseContext.ClientIdentityProviderRestrictions().Count(), models.SelectMany(client => client.IdentityProviderRestrictions).Count());
                Assert.AreEqual(configurationDatabaseContext.ClientPostLogoutRedirectUris().Count(), models.SelectMany(client => client.PostLogoutRedirectUris).Count());
                Assert.AreEqual(configurationDatabaseContext.ClientProperties().Count(), models.SelectMany(client => client.Properties).Count());
                Assert.AreEqual(configurationDatabaseContext.ClientRedirectUris().Count(), models.SelectMany(client => client.RedirectUris).Count());
                Assert.AreEqual(configurationDatabaseContext.ClientSecrets().Count(), models.SelectMany(client => client.ClientSecrets).Count());
                Assert.AreEqual(configurationDatabaseContext.ClientScopes().Count(), models.SelectMany(client => client.AllowedScopes).Count());
            }
        }
コード例 #39
0
        // Sitecore.Modules.EmailCampaign.Core.RecipientImporter
        public override string PerformImport(ImportOptions options)
        {
            Assert.ArgumentNotNull(options, "options");
              int num = 0;
              int num2 = 0;
              int num3 = 0;
              int num4 = 0;
              string result;

              string emailReport = Sitecore.Configuration.Settings.GetSetting("RecipientImporterExt.PathToEmailReport", "/temp")
            + "/ProblemRecordsFor_" + Path.GetFileNameWithoutExtension(options.Filename)
            + "_" + DateTime.Now.ToString("s").Replace(":", string.Empty) + ".csv";

              string pathToEmailReport = FileUtil.MapPath(emailReport);
              StreamWriter streamWriter = new StreamWriter(pathToEmailReport);

              using (CsvFile csvFile = new CsvFile(options.Filename))
              {
            try
            {
              List<string> list = csvFile.ReadLine();
              streamWriter.WriteLine(string.Join(",", list.ToArray()));
              int emailColumnIndex = this.GetEmailColumnIndex(options, list);
              if (emailColumnIndex < 0)
              {
            result = string.Empty;
            return result;
              }
              List<string> list2 = csvFile.ReadLine();
              while (list2 != null)
              {
            CsvRowsProcessed++;

            try
            {
                using (new EventDisabler())
                {
                    bool flag = false;
                    if (list.Count < list2.Count)
                    {
                        num4++;
                        Log.Info(string.Format("RecipientImporterExt debug info: Invalid row {0}", string.Join(",", list2.ToArray())), this);
                        streamWriter.WriteLine(string.Join(",", list2.ToArray()));
                        list2 = csvFile.ReadLine();
                    }
                    else
                    {
                        string text = list2[emailColumnIndex];
                        Log.Info(string.Format("RecipientImporterExt debug info: Processing the {0} record ...", text), this);
                        if (!Util.IsValidEmail(text))
                        {
                            text = this.TryFindEmail(text);
                            if (string.IsNullOrEmpty(text))
                            {
                                num3++;
                                Log.Info(string.Format("RecipientImporterExt debug info:  Invalid email {0}", text), this);
                                streamWriter.WriteLine(string.Join(",", list2.ToArray()));
                                list2 = csvFile.ReadLine();
                                continue;
                            }
                        }
                        string text2 = options.DomainName + "\\" + Util.AddressToUserName(text);
                        Contact contactFromName;
                        if (User.Exists(text2))
                        {
                            if (options.ConflictOption == ImportOptions.ConflictOptions.SkipUser)
                            {
                                this.AddUserToRoles(options, text2);
                                num2++;
                                Log.Info(string.Format("RecipientImporterExt debug info:  Record is skipped due to SkipUser setting ...", text), this);
                                streamWriter.WriteLine(string.Join(",", list2.ToArray()));
                                list2 = csvFile.ReadLine();
                                continue;
                            }
                            flag = (options.ConflictOption == ImportOptions.ConflictOptions.KeepProperties);
                            contactFromName = Factory.GetContactFromName(text2);
                        }
                        else
                        {
                            MembershipUser membershipUser = Membership.CreateUser(text2, text2);
                            membershipUser.ResetPassword();
                            contactFromName = Factory.GetContactFromName(text2);
                            contactFromName.Profile.ProfileItemId = options.Root.Settings.SubscriberProfile;
                            // contactFromName.Profile.Save(); - fix to decrease the number of events in EventQueue
                        }
                        if (!flag)
                        {
                            contactFromName.Profile.Email = text;
                            contactFromName.Profile["IsAnonymousSubscriber"] = "true";
                        }
                        foreach (string current in options.MappedProperties.Keys)
                        {
                            for (int i = 0; i < list.Count; i++)
                            {
                                if (options.MappedProperties[current].Equals(list[i]))
                                {
                                    if (!flag || string.IsNullOrEmpty(contactFromName.Profile[current]))
                                    {
                                        contactFromName.Profile[current] = list2[i];
                                    }
                                    break;
                                }
                            }
                        }
                        contactFromName.Profile.Save();
                        this.AddUserToRoles(options, text2);
                        num++;
                        list2 = csvFile.ReadLine();
                    }
                }
            }
            catch (Exception e)
            {
              Log.Info(string.Format("RecipientImporterExt debug info:  row cannot be processed. {0}", string.Join(",", list2.ToArray())), this);
              streamWriter.WriteLine(string.Join(",", list2.ToArray()));
              list2 = csvFile.ReadLine();
              Logging.LogError(e);
            }
              }
              //Need to clear UsersInRole and AccessResult cache, because events were disabled
              Event.RaiseEvent("roles:relationsRemoved", new object[] { "dummyRoleName" });
            }
            catch (Exception e)
            {
              Logging.LogError(e);
            }
            finally
            {
              streamWriter.Close();
            }
              }
              result = string.Concat(new object[]
            {
            num,  "|",
            num2, "|",
            num3, "|",
            num4
            });

               NotifyUsers(options, num, num2, num3, num4, pathToEmailReport);

              return result;
        }
コード例 #40
0
ファイル: ZenonCom.cs プロジェクト: COPA-DATA/zenonLogicAPI
 /// <summary>
 /// Imports all zenon Logic projects which are stored in <see cref="LogicProjects"/> into zenon.
 /// </summary>
 /// <param name="reloadZenonProject">Specifies if the current zenon project shall be reloaded after the import.</param>
 /// <param name="options">Specifies options on how to import the project into zenon.</param>
 public void ImportLogicProjectsIntoZenon(bool reloadZenonProject = true, ImportOptions options = ImportOptions.Default)
 {
     ImportLogicProjectsIntoZenon(LogicProjects, reloadZenonProject, options);
 }
コード例 #41
0
ファイル: ImportHandler.cs プロジェクト: jncc/topcat
 string GetErrorFilePath(ImportOptions options)
 {
     string directory = Path.GetDirectoryName(options.File);
     string filename = Path.GetFileNameWithoutExtension(options.File);
     return Path.Combine(directory, filename + ".errors.txt");
 }
コード例 #42
0
ファイル: ImportStatement.cs プロジェクト: rytmis/lesson.net
 public ImportStatement(Expression url, ImportOptions options, IEnumerable <MediaQuery> mediaQueries)
 {
     this.options      = options;
     this.mediaQueries = mediaQueries.ToList();
     Url = url;
 }
コード例 #43
0
ファイル: Configuration.cs プロジェクト: JXPrime/soddi
        private void ParseArguments(string[] args)
        {
            List<string> unparsed = new List<string>();

            for (int i = 0; i < args.Length; i++)
            {
                string value = null;
                string arg = args[i].Trim();
                if (arg.IndexOf(":") > -1)
                {
                    value = arg.Substring(arg.IndexOf(":") + 1).Trim('"', '\'');
                    arg = arg.Substring(0, arg.IndexOf(":"));
                }
                switch (arg.ToLowerInvariant())
                {
                    case "source":
                        Source = value;
                        break;
                    case "target":
                        Target = value;
                        Provider = DbProviders.ParseArg(value);
                        break;
                    case "batch":
                        int batchSize;
                        if (int.TryParse(value, out batchSize))
                        {
                            BatchSize = batchSize;
                        }
                        break;
                    case "indices":
                        Options = Options | ImportOptions.Indices;
                        break;
                    case "fulltext":
                        Options = Options | ImportOptions.FullText;
                        break;
                    case "split":
                        Options = Options | ImportOptions.Split;
                        break;
                    case "gui":
                        Options = Options | ImportOptions.GUI;
                        break;
                    case "foreignkeys":
                        Options = Options | ImportOptions.ForeignKeys;
                        break;
                    default:
                        unparsed.Add(args[i].Trim());
                        break;
                }
            }

            // unparsed args MUST be sites
            // if no sites specified, get them all
            if (unparsed.Count == 0 && !string.IsNullOrEmpty(Source))
            {
                unparsed = GetAllSites(Source);
            }

            Targets = GetTargets(Source, unparsed);
        }
コード例 #44
0
 public VertexShadedGltfImporter(Material templateMaterial, string gltfFileName, ImportOptions options)
     : base(gltfFileName, options)
 {
     _templateMaterial = templateMaterial;
     IsMultithreaded   = true;
 }
コード例 #45
0
ファイル: Import.cs プロジェクト: r2i-sitecore/dotless
 public Import(Url path, Value features, ImportOptions option)
     : this((Node)path, features, option)
 {
     OriginalPath = path;
     Path = path.GetUnadjustedUrl();
 }
コード例 #46
0
 public VertexShadedGltfImporter(Material templateMaterial, GLTFRoot root, Stream stream, ImportOptions options)
     : base(root, stream, options)
 {
     _templateMaterial = templateMaterial;
     IsMultithreaded   = true;
 }
コード例 #47
0
        protected virtual bool SecurityDomainCompleted()
        {
            if (string.IsNullOrEmpty(this.DomainInput.Value))
            {
                SheerResponse.Alert(EcmTexts.Localize("You need to select a domain first.", new object[0]), new string[0]);
                return false;
            }
            ImportOptions options = new ImportOptions
            {
                Filename = FileUtil.MapPath("/temp/" + FileUtil.GetFileName(this.Filename.Value)),
                MappedProperties = this.MappedProperties,
                Root = this.Root,
                DomainName = this.DomainInput.Value
            };
            string str = Context.ClientPage.ClientRequest.Form[this.SkipUser.Name];
            if (string.IsNullOrEmpty(str) || str.Equals(this.SkipUser.Value))
            {
                options.ConflictOption = ImportOptions.ConflictOptions.SkipUser;
            }
            else
            {
                options.ConflictOption = str.Equals(this.OverwriteProperties.Value) ? ImportOptions.ConflictOptions.OverwriteProperties : ImportOptions.ConflictOptions.KeepProperties;
            }
            List<string> roles = new List<string>();
            try
            {
                List<Sitecore.Security.Accounts.Role> roleList = RecipientList.OptInList.Roles;
                foreach (Sitecore.Security.Accounts.Role roleToAssign in roleList)
                {
                    roles.Add(roleToAssign.Name);
                }
            }
            catch (Exception exception)
            {
                SheerResponse.Alert(exception.Message, new string[0]);
                return false;
            }

            options.Roles = roles.ToArray();
            JobHelper.StartJob("Import Users", "PerformImport", CoreFactory.Instance.GetRecipientImporter(), new object[] { options });
            this.CheckImport();
            return true;
        }
コード例 #48
0
        protected virtual bool SecurityDomainCompleted()
        {
            if (string.IsNullOrEmpty(this.DomainInput.Value))
            {
                SheerResponse.Alert(EcmTexts.Localize("You need to select a domain first.", new object[0]), new string[0]);
                return false;
            }
            ImportOptions options = new ImportOptions
            {
                Filename = FileUtil.MapPath("/temp/" + FileUtil.GetFileName(this.Filename.Value)),
                MappedProperties = this.MappedProperties,
                Root = this.Root,
                DomainName = this.DomainInput.Value
            };
            string str = Context.ClientPage.ClientRequest.Form[this.SkipUser.Name];
            if (string.IsNullOrEmpty(str) || str.Equals(this.SkipUser.Value))
            {
                options.ConflictOption = ImportOptions.ConflictOptions.SkipUser;
            }
            else
            {
                options.ConflictOption = str.Equals(this.OverwriteProperties.Value) ? ImportOptions.ConflictOptions.OverwriteProperties : ImportOptions.ConflictOptions.KeepProperties;
            }
            List<string> roles = new List<string>();
            try
            {
                string rolename = this.DomainInput.Value + "\\" + this.RecipientListName.Value;
                using (new SecurityDisabler())
                {
                    System.Web.Security.Roles.CreateRole(rolename);
                    Item listsContainerRoot = Root.GetRecipientListContainerItem();
                    if (listsContainerRoot != null)
                    {
                        TargetAudience ta = TargetAudienceSource.Create(this.RecipientListName.Value, listsContainerRoot, rolename, null);
                        if (ta == null)
                        {
                            return false;
                        }
                    }
                }
                roles.Add(rolename);
            }
            catch (Exception exception)
            {
                SheerResponse.Alert(exception.Message, new string[0]);
                return false;
            }

            options.Roles = roles.ToArray();
            JobHelper.StartJob("Import Users", "PerformImport", CoreFactory.Instance.GetRecipientImporter(), new object[] { options });
            this.CheckImport();
            return true;
        }
コード例 #49
0
 // Sitecore.Modules.EmailCampaign.Core.RecipientImporter
 private void AddUserToRoles(ImportOptions options, string userName)
 {
     string[] assignedRoles = Roles.GetRolesForUser(userName);
       List<string> list = (
       from role in options.Roles
       where !assignedRoles.Any(r => r == role)
       select role).ToList<string>();
       if (list.Count > 0)
       {
     Roles.AddUserToRoles(userName, list.ToArray());
       }
 }
コード例 #50
0
ファイル: Importer.cs プロジェクト: naga-work/dotless
 private bool IsOptionSet(ImportOptions options, ImportOptions test)
 {
     return((options & test) == test);
 }
コード例 #51
0
        // Sitecore.Modules.EmailCampaign.Core.RecipientImporter
        public override string PerformImport(ImportOptions options)
        {
            Assert.ArgumentNotNull(options, "options");
              int num = 0;
              int num2 = 0;
              int num3 = 0;
              int num4 = 0;
              string result;

              string emailReport = Sitecore.Configuration.Settings.GetSetting("RecipientImporterExt.PathToEmailReport", "/temp")
            + "/ProblemRecordsFor_" + Path.GetFileNameWithoutExtension(options.Filename)
            + "_" + DateTime.Now.ToString("s").Replace(":", string.Empty) + ".csv";

              string pathToEmailReport = FileUtil.MapPath(emailReport);
              StreamWriter streamWriter = new StreamWriter(pathToEmailReport);

              using (CsvFile csvFile = new CsvFile(options.Filename))
              {
            try
            {
              List<string> list = csvFile.ReadLine();
              streamWriter.WriteLine(string.Join(",", list.ToArray()));
              int emailColumnIndex = this.GetEmailColumnIndex(options, list);
              if (emailColumnIndex < 0)
              {
            result = string.Empty;
            return result;
              }
              List<string> list2 = csvFile.ReadLine();
              List<List<string>> listOfEntries = new List<List<string>>();

              while (list2 != null)
              {
              listOfEntries.Add(list2);
              csvFile.ReadLine();
              }

              Parallel.ForEach<List<string>>(listOfEntries, item => Process(item, streamWriter));
              while (list2 != null)
              {

              }
            }
            catch (Exception e)
            {
              Logging.LogError(e);
            }
            finally
            {
              streamWriter.Close();
            }
              }
              result = string.Concat(new object[]
            {
            num,  "|",
            num2, "|",
            num3, "|",
            num4
            });

              try
              {
            Sitecore.Data.Database master = Sitecore.Configuration.Factory.GetDatabase("master");
            Sitecore.Data.Items.Item itemToSend = master.GetItem(Sitecore.Configuration.Settings.GetSetting("RecipientImporterExt.MessagePath", "/sitecore/content/Home/Email Campaign/Messages/Service Messages/Self-Service Subscription/Subscription Notification"));
            MessageItem messageItem = Sitecore.Modules.EmailCampaign.Factory.GetMessage(itemToSend);
            //var report = new MediaItem();
            //messageItem.Attachments.Add(
            messageItem.Body = string.Format("Recipients imported: {0} <br/> E-mail addresses already exist: {1} <br/> E-mail addresses not provided: {2} <br/> Users not imported as required fields not available: {3}"
                                        + " <br/> You can check report file with the failed records here: {4}. <br/> Import finished at " + DateTime.Now.ToString(@"d/M/yyyy hh:mm:ss tt"), num, num2, num3, num4, pathToEmailReport);
            messageItem.Subject = "User import from "+Path.GetFileNameWithoutExtension(options.Filename)+" finished." ;
            SendingManager sendingManager = new SendingManager(messageItem);

            ListString usernamesToSend = new ListString(Sitecore.Configuration.Settings.GetSetting("RecipientImporterExt.SendTo", "sitecore\\admin"), ',');
            if (usernamesToSend.Count == 0)
            {
            Log.Info("RecipientImporterExt debug info: no users to send email to ", this);
            return result;
            }
            foreach (string nameString in usernamesToSend)
            {
            Contact contactToSend = Sitecore.Modules.EmailCampaign.Factory.GetContactFromName(nameString);
            if (contactToSend != null)
            {
                Log.Info("RecipientImporterExt debug info: Sending notification about the import to " + contactToSend.Profile.Email, this);
                sendingManager.SendStandardMessage(contactToSend);
            }
            }

            //User user = Sitecore.Context.User;
            //if (user != null)
            //{
            //    string username = user.Name;
            //    Log.Info("------------contactToSend2: " + username, this);
            //    sendingManager.SendStandardMessage(Sitecore.Modules.EmailCampaign.Factory.GetContactFromName(username));
            //}
              }
              catch (Exception e)
              {

            Logging.LogError(e);
              }

              return result;
        }
コード例 #52
0
        public void TestCustomCollection4()
        {
            var options = new ImportOptions();

            options.ReferencedCollectionTypes.Add(typeof(LinkedList <>));

            var ccu = WsdlHelper.Import(customCollectionsMetadata, options);

            var type = ccu.FindType("MyCollection");

            Assert.That(type, Is.Not.Null, "#1a");
            Assert.That(type.BaseTypes.Count, Is.EqualTo(1), "#2a");

            var baseType = type.BaseTypes[0];

            Assert.That(baseType.BaseType, Is.EqualTo("System.Collections.Generic.LinkedList`1"), "#3a");
            Assert.That(baseType.TypeArguments.Count, Is.EqualTo(1), "#4a");
            Assert.That(baseType.TypeArguments[0].BaseType, Is.EqualTo("System.String"), "#5a");

            var attr = type.FindAttribute("System.Runtime.Serialization.CollectionDataContractAttribute");

            Assert.That(attr, Is.Not.Null, "#6a");

            var nameArg = attr.FindArgument("Name");

            Assert.That(nameArg, Is.Not.Null, "#7a");
            Assert.That(((CodePrimitiveExpression)nameArg.Value).Value, Is.EqualTo("MyCollection"), "#8a");

            var nsArg = attr.FindArgument("Namespace");

            Assert.That(nsArg, Is.Not.Null, "#9a");
            Assert.That(((CodePrimitiveExpression)nsArg.Value).Value, Is.EqualTo("http://schemas.datacontract.org/2004/07/TestWCF.Model"), "#10a");

            var itemArg = attr.FindArgument("ItemName");

            Assert.That(itemArg, Is.Not.Null);
            Assert.That(((CodePrimitiveExpression)itemArg.Value).Value, Is.EqualTo("string"), "#11a");

            type = ccu.FindType("MyCollectionOfdouble");
            Assert.That(type, Is.Not.Null, "#1b");
            Assert.That(type.BaseTypes.Count, Is.EqualTo(1), "#2b");

            baseType = type.BaseTypes[0];
            Assert.That(baseType.BaseType, Is.EqualTo("System.Collections.Generic.LinkedList`1"), "#3b");
            Assert.That(baseType.TypeArguments.Count, Is.EqualTo(1), "#4b");
            Assert.That(baseType.TypeArguments[0].BaseType, Is.EqualTo("System.Double"), "#5b");

            attr = type.FindAttribute("System.Runtime.Serialization.CollectionDataContractAttribute");
            Assert.That(attr, Is.Not.Null, "#6b");

            nameArg = attr.FindArgument("Name");
            Assert.That(nameArg, Is.Not.Null, "#7b");
            Assert.That(((CodePrimitiveExpression)nameArg.Value).Value, Is.EqualTo("MyCollectionOfdouble"), "#8b");

            nsArg = attr.FindArgument("Namespace");
            Assert.That(nsArg, Is.Not.Null, "#9b");
            Assert.That(((CodePrimitiveExpression)nsArg.Value).Value, Is.EqualTo("http://schemas.datacontract.org/2004/07/TestWCF.Model"), "#10b");

            itemArg = attr.FindArgument("ItemName");
            Assert.That(itemArg, Is.Not.Null);
            Assert.That(((CodePrimitiveExpression)itemArg.Value).Value, Is.EqualTo("double"), "#11b");
        }
コード例 #53
0
ファイル: Importer.cs プロジェクト: marpstar/dotless
 private bool IsOptionSet(ImportOptions options, ImportOptions test)
 {
     return (options & test) == test;
 }
コード例 #54
0
 public WordReader(ImportOptions settings, string sourceLanguage, string targetLanguage)
 {
     _settings       = settings;
     _sourceLanguage = sourceLanguage;
     _targetLanguage = targetLanguage;
 }
コード例 #55
0
 public Import Import(Quoted path, Value features, ImportOptions option, NodeLocation location)
 {
   return new Import(path, features, option) { Location = location };
 }
コード例 #56
0
    /// <summary>
    /// Uploads the file.
    /// </summary>
    public void UploadFile()
    {
        if (uplFile.UploadedFiles.Count == 0)
            return;

        lblFileRequired.Visible = false;
        lblRequiredMsg.Visible = false;
        try
        {
            switch (txtConfirmUpload.Value)
            {
                case "F":
                    uplFile.UploadedFiles.Clear();
                    break;
                case "O":
                    //elected to overwrite existing uploaded file
                    ImportManager importManager = GetImportManager();
                    importManager.SourceFileName = uplFile.UploadedFiles[0].FileName;
                    importManager.ImportMaps.Clear();
                    ImportOptions options = new ImportOptions();
                    importManager.Options = options;
                    Page.Session["importManager"] = importManager;
                    txtConfirmUpload.Value = "T";
                    UploadFileEx();
                    break;
                case "T":
                    UploadFileEx();
                    break;
            }
        }
        catch (Exception ex)
        {
            string sSlxErrorId = null;
            var sMsg = ErrorHelper.GetClientErrorHtmlMessage(ex, ref sSlxErrorId);
            if (!string.IsNullOrEmpty(sSlxErrorId))
            {
                log.Error(ErrorHelper.AppendSlxErrorId("The call to StepSelectFile.UploadFile() failed", sSlxErrorId),
                          ex);
            }
            DialogService.ShowHtmlMessage(sMsg, ErrorHelper.IsDevelopmentContext() ? 600 : -1,
                                          ErrorHelper.IsDevelopmentContext() ? 800 : -1);
        }
    }