Exemple #1
0
        public FolderIdModel RemoveFolder(string folder_id, string ticket = "")
        {
            FolderIdModel model = new FolderIdModel();

            if (string.IsNullOrEmpty(ticket))
            {
                //return ApiHelper.JsonError(400, new string[] { "error" });
                model.errors = ApiHelper.JsonError(400, new string[] { "error" });
                return(model);
            }

            if (folder_id.Contains("^") || folder_id.Contains("@"))
            {
                model.errors = ApiHelper.JsonError(400, new string[] { "folder not exist" });
                return(model);
            }

            string ret = ApiHelper.FindFolderById(folder_id, PathHelper.GetRepoPath());

            if (ret == null)
            {
                //return ApiHelper.JsonError(400, new string[] { "folder not exist" });
                model.errors = ApiHelper.JsonError(400, new string[] { "folder not exist" });
                return(model);
            }
            else
            {
                Command.RemoveFolder(ret);
                model.folder_id = folder_id;
                SVNManager.SaveChanges();

                return(model);
            }
        }
        private Diff GetRevisionDiff(string pathForComparer, int revision)
        {
            Diff diff = new Diff();

            SVNManager.GetInfo((res) =>
            {
                int currentRevision = 0;
                string[] splits     = res.Split(new string[] { "\n" }, System.StringSplitOptions.RemoveEmptyEntries);
                foreach (string s in splits)
                {
                    if (s.StartsWith("Last Changed Rev: ", StringComparison.Ordinal))
                    {
                        currentRevision = int.Parse(s.Replace("Last Changed Rev: ", ""));
                    }
                    if (s.StartsWith("Revision:", StringComparison.Ordinal))
                    {
                        currentRevision = int.Parse(s.Replace("Revision: ", ""));
                    }
                }

                SVNManager.GetFileInRevision(revision, pathForComparer.Replace("\\", "/").Replace(PathHelper.GetRepoPath().Replace("\\", "/") + "/", ""), (cont) =>
                {
                    diff.current   = IOFile.ReadAllText(pathForComparer);
                    diff.requested = cont;
                });
            });

            return(diff);
        }
        public HistorySwitchVersion SetLastversion(string scenario_id, string ticket = "", string topic_id = "")
        {
            HistorySwitchVersion model = new HistorySwitchVersion();

            string folder = ApiHelper.FindFolderById(scenario_id, PathHelper.GetRepoPath());

            if (folder == null)
            {
                model.errors = ApiHelper.JsonError(400, new string[] { "scenario not exist" });
                return(model);
            }
            ;

            string topicInfoFile = string.Empty;

            if (!string.IsNullOrEmpty(topic_id))
            {
                List <TopicModel> topics = ApiHelper.GetTopicsOrigin(scenario_id);
                foreach (TopicModel t in topics)
                {
                    if (t.index.ToString() == topic_id)
                    {
                        folder        = t.vmpPath;
                        topicInfoFile = t.infoPath;
                        break;
                    }
                }
            }

            SVNManager.RevertToLastVersion("./", (res) =>
            {
                model.message = res;
            });
            return(model);
        }
Exemple #4
0
        private static void GenerateXMLFromDirectory(string path, string writeTo, string title)
        {
            //path = Path.Combine(UsersHelper.GetUserFolder(), UsersHelper.GetToolsFolder(), path);

            DirectoryInfo info = new DirectoryInfo(path);

            FileInfo[] files    = info.GetFiles().OrderBy(p => p.LastWriteTime).ToArray();
            string     xmlMask  = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\r\n<topic>\r\n<title>{0}</title>\r\n{1}\r\n</topic>";
            string     xmlParts = "";

            foreach (FileInfo file in files)
            {
                string fileName = Path.GetFileName(file.FullName);
                if (fileName != "dita_pub_00001.xml" && Path.GetExtension(file.FullName).Contains("xml"))
                {
                    string[] lines = File.ReadAllLines(file.FullName);
                    for (int i = 2; i < lines.Length; i++)
                    {
                        xmlParts += lines[i] + "\r\n";
                    }
                }
            }

            string result = string.Format(xmlMask, title, xmlParts);

            File.WriteAllText(writeTo, result, System.Text.Encoding.UTF8);

            SVNManager.AddFile(writeTo, (res) => { SVNManager.Commit("Generate xml files", (com) => { }); });
        }
        public HistoryScenarioVersion SetScenarioVersion(string scenario_id, string version_number, string ticket = "", string topic_id = "")
        {
            HistoryScenarioVersion model = new HistoryScenarioVersion();
            string folder = ApiHelper.FindFolderById(scenario_id, PathHelper.GetRepoPath());

            if (folder == null)
            {
                model.errors = ApiHelper.JsonError(400, new string[] { "scenario not exist" });
                return(model);
            }

            string topicInfoFile = string.Empty;

            if (!string.IsNullOrEmpty(topic_id))
            {
                List <TopicModel> topics = ApiHelper.GetTopicsOrigin(scenario_id);
                foreach (TopicModel t in topics)
                {
                    if (t.index.ToString() == topic_id)
                    {
                        folder        = t.vmpPath;
                        topicInfoFile = t.infoPath;
                        break;
                    }
                }
            }

            int version = int.Parse(version_number);

            SVNManager.RevertToRevision(version, folder, (res) =>
            {
                try
                {
                    List <TopicObject> topics = ApiHelper.GetTopics(scenario_id);
                    topics = topics.OrderBy(t => t.id).ToList();

                    string ret       = ApiHelper.FindFolderById(scenario_id, PathHelper.GetRepoPath());
                    string folderr   = new DirectoryInfo(ret).Name;
                    DescModel modell = JsonConvert.DeserializeObject <DescModel>(IOFile.ReadAllText(Path.Combine(ret, folderr + ".info")));
                    model.topics     = topics;
                    model.scenario   = modell;
                }
                catch
                {
                }

                if (string.IsNullOrEmpty(topicInfoFile))
                {
                    SVNManager.RevertToRevision(version, topicInfoFile, (r) => { });
                }

                model.current_version = version;
                model.message         = res;
            });
            return(model);
        }
Exemple #6
0
        public void GetReposLogsTest()
        {
            var url            = @"file:///C:/users/leonardo.kobus/desktop/games/gamification/SVNExtension.UnitTest/bin/Debug/RepositorioNET";
            int initialRelease = 0;

            using (var manager = new SVNManager())
            {
                manager.Generate(url, initialRelease);
                Assert.IsTrue(Directory.GetFiles("SVNReports").Length > 0);
            }
            Assert.IsTrue(!Directory.Exists("SVNReports"));
        }
        public HistorySwitchVersion SetVersionRepo(string version_number, string ticket = "")
        {
            HistorySwitchVersion model = new HistorySwitchVersion();
            int version = int.Parse(version_number);

            SVNManager.RevertToRevision(version, "./", (res) =>
            {
                model.current_version = version;
                model.message         = res;
            });
            return(model);
        }
        public HistoryVersionsModel Test()
        {
            HistoryVersionsModel model = new HistoryVersionsModel();

            SVNManager.Changelist("**", (res) =>
            {
                SVNManager.Commit("update", (ress) =>
                {
                    SVNManager.UpdateLocalRepo((resss) =>
                    {
                        string s = resss;
                    });
                });
            });
            return(model);
        }
Exemple #9
0
        public void GetReposByOneRevisionAhed()
        {
            var url            = @"file:///C:/users/leonardo.kobus/desktop/games/gamification/SVNExtension.UnitTest/bin/Debug/RepositorioNET";
            int initialRelease = 2;

            using (var manager = new SVNManager())
            {
                var reader = new SVNReader(initialRelease);
                manager.Generate(url, initialRelease);

                foreach (var file in manager.Files)
                {
                    var users = reader.Read(file);
                    Assert.AreEqual(0, users.Count);
                }
            }
        }
        public void EditTopic(string scenarioFolder, bool uniqueId, string topicId)
        {
            string topicsFolder = Path.Combine(scenarioFolder, "topics");

            foreach (string t in Directory.GetFiles(topicsFolder))
            {
                TopicModel topic = JsonConvert.DeserializeObject <TopicModel>(File.ReadAllText(t));
                if (((!uniqueId && topic.index.ToString() == topicId) || (uniqueId && topic.unique_id == topicId)))
                {
                    RunCortona(topic, t, _settingsManager.GetRapidManualPath());

                    break;
                }
            }

            SVNManager.SaveChanges();
        }
Exemple #11
0
        public FolderModel CreateCategory([FromBody] ApiFormInput formData)
        {
            FolderModel result = new FolderModel();

            if (formData == null)
            {
                result.errors = ApiHelper.JsonError(400, new[] { "error" });
                return(result);
            }

            if (string.IsNullOrWhiteSpace(formData.name))
            {
                result.errors = ApiHelper.JsonError(400, new[] { "Incorrect name" });
                return(result);
            }

            if (string.IsNullOrWhiteSpace(formData.name))
            {
                result.errors = ApiHelper.JsonError(400, new string[] { "error" });
                return(result);
            }

            if (!_authenticationManager.CheckAccessToken(formData.ticket))
            {
                result.errors = ApiHelper.JsonError(400, new string[] { "wrong token" });
                return(result);
            }

            if (formData.name.Length > 50)
            {
                result.errors = ApiHelper.JsonError(400, new[] { "Name is too long" }); //TODO: change all instances to ReflektBaseController.CustomBadRequestResult<T>()
                return(result);
            }

            result = ApiHelper.CreateFolder("", formData.name);
            if (result.folder != null)
            {
                result.folder.modified_utc = Scenarios.ConvertToUnixTimestamp(DateTime.Now);
            }
            SVNManager.SaveChanges();
            return(result);
        }
Exemple #12
0
        private static void DraftTopic(string topic, string path)
        {
            string     pathToFolder = Path.Combine(path, "default", "projects");
            TopicModel topicModel   = JsonConvert.DeserializeObject <TopicModel>(File.ReadAllText(topic));

            topicModel.localization = "default";
            string vmbFile = topicModel.vmpPath.Replace(".vmp", ".vmb");

            if (File.Exists(vmbFile))
            {
                string unzipFolder = Path.Combine(pathToFolder, topicModel.name.Replace(" ", "_"));
                if (Directory.Exists(unzipFolder))
                {
                    foreach (string f in Directory.GetFiles(unzipFolder))
                    {
                        File.Delete(f);
                    }
                }

                if (!string.IsNullOrEmpty(topicModel.pathToZip) && File.Exists(topicModel.pathToZip))
                {
                    topicModel.pathToZip = topicModel.pathToZip.Replace("data\\", UsersHelper.GetToolsFolder() + "\\");
                    topicModel.pathToZip = topicModel.pathToZip.Replace("data/", UsersHelper.GetToolsFolder() + "/");
                    string toolsDir = PathHelper.GetUserProcessingFolder();
                    string pathOne  = Path.Combine(toolsDir, "input/resourceFolder").Replace("\\", "/");
                    string pathTwo  = Path.Combine(toolsDir, "input").Replace("\\", "/");
                    File.Copy(topicModel.pathToZip, Path.Combine(pathOne, Path.GetFileName(topicModel.pathToZip)).Replace("\\", "/"), true);
                    File.Copy(topicModel.pathToZip, Path.Combine(pathTwo, Path.GetFileName(topicModel.pathToZip)).Replace("\\", "/"), true);
                }

                Unzip(vmbFile, unzipFolder);
                ConvertToX3D(unzipFolder, Path.Combine(path, "default", "pub_draft"), topicModel.name + new Random().Next(1000, 9999), topicModel.type == "info", topicModel);
            }

            if (!string.IsNullOrEmpty(topicModel.pathToZip) && File.Exists(topicModel.pathToZip))
            {
                string fileCopy = topicModel.pathToZip.Replace("pub_in", "pub_draft");
                File.Copy(topicModel.pathToZip, fileCopy, true);
                SVNManager.AddFile(fileCopy.Replace(Path.Combine(UsersHelper.GetUserFolder(), UsersHelper.GetToolsFolder()) + "/", ""));
            }
        }
Exemple #13
0
        //public string CreateScenario(string folder_id, string name, string description, string ticket = "")
        public ScenarioModel CreateScenario(string folder_id, [FromBody] ApiFormInput formData)
        {
            if (formData == null)
            {
                ScenarioModel model = new ScenarioModel();
                model.errors = ApiHelper.JsonError(400, new string[] { "error" });
                return(model);
            }

            if (string.IsNullOrWhiteSpace(formData.name))
            {
                ScenarioModel model = new ScenarioModel();
                model.errors = ApiHelper.JsonError(400, new string[] { "Incorrect name" });
                return(model);
            }

            if (!_authenticationManager.CheckAccessToken(formData.ticket))
            {
                ScenarioModel model = new ScenarioModel();
                //return ApiHelper.JsonError(401, new string[] { "wrong token" });
                model.errors = ApiHelper.JsonError(400, new string[] { "wrong token" });
                return(model);
            }

            if (formData.name.Length > 50)
            {
                ScenarioModel model = new ScenarioModel();
                model.errors = ApiHelper.JsonError(400, new string[] { "Name are too long" });
                return(model);
            }

            ScenarioModel mod = ApiHelper.CreateScenarioModel(folder_id, formData.name, formData.description);

            if (mod.scenario != null)
            {
                mod.scenario.modified_utc = Scenarios.ConvertToUnixTimestamp(DateTime.Now);
            }

            SVNManager.SaveChanges();
            return(mod);
        }
Exemple #14
0
        public FolderModel CreateProduct(string folder_id, [FromBody] ApiFormInput formData)
        {
            FolderModel result = new FolderModel();

            if (formData == null)
            {
                result.errors = ApiHelper.JsonError(400, new[] { "error" });
                return(result);
            }

            if (string.IsNullOrWhiteSpace(formData.name))
            {
                result.errors = ApiHelper.JsonError(400, new[] { "Incorrect name" });
                return(result);
            }

            if (!_authenticationManager.CheckAccessToken(formData.ticket))
            {
                result.errors = ApiHelper.JsonError(400, new[] { "wrong token" });
                return(result);
            }

            if (formData.name.Length > 50)
            {
                result.errors = ApiHelper.JsonError(400, new[] { "Name are too long" });
                return(result);
            }

            result = ApiHelper.CreateFolder(folder_id, formData.name);

            if (result.folder != null)
            {
                result.folder.modified_utc = Scenarios.ConvertToUnixTimestamp(DateTime.Now);
            }

            SVNManager.SaveChanges();

            return(result);
        }
        private static void Setup(string pathToVmp,
                                  string topicPath,
                                  string appName,
                                  string webRootPath,
                                  TopicModel topic,
                                  Action onStart,
                                  Action <TopicModel, string, string> onExit)
        {
            Show(topicPath, pathToVmp, appName, webRootPath,
                 () =>
            {
                _logger.LogDebug("Starting Cortona, locking files in SVN");
                SVNManager.LockFile(pathToVmp.Replace(PathHelper.GetRepoPath(), ""));
                onStart?.Invoke();
            },
                 (sender, e) =>
            {
                _logger.LogDebug("Exit Cortona");
                SVNManager.UnlockFile(pathToVmp.Replace(PathHelper.GetRepoPath(), ""));

                onExit(topic, topicPath, pathToVmp);
            });
        }
        public TicketModel Post([FromBody] ApiFormInput formData)
        {
            if (formData == null)
            {
                return(new TicketModel
                {
                    Errors = ApiHelper.JsonError(400, new[] { "User credentials are incomplete" })
                });
            }

            if (string.IsNullOrWhiteSpace(formData.username) && string.IsNullOrWhiteSpace(formData.password))
            {
                return(new TicketModel
                {
                    Errors = ApiHelper.JsonError(400, new[] { "Invalid login or password" })
                });
            }

            if (!_authenticationManager.Authenticate(formData.username, formData.password, out var authToken, out var refreshToken))
            {
                return(new TicketModel
                {
                    Errors = ApiHelper.JsonError(400, new[] { "Invalid login or password" })
                });
            }

            var resulTicketModel = new TicketModel {
                Token = authToken, RefreshToken = refreshToken
            };

            var server = string.IsNullOrEmpty(formData.server) ? "localhost" : formData.server;

            SVNManager.Authorizate(server, formData.username, formData.password, _ => { });

            return(resulTicketModel);
        }
Exemple #17
0
        public void GetRepostLogByRevisionTest()
        {
            var url            = @"file:///C:/users/leonardo.kobus/desktop/games/gamification/SVNExtension.UnitTest/bin/Debug/RepositorioNET";
            int initialRelease = 0;

            using (var manager = new SVNManager())
            {
                manager.Generate(url, initialRelease);
                var reader = new SVNReader(initialRelease);
                foreach (var file in manager.Files)
                {
                    var users = reader.Read(file);
                    Assert.AreEqual(1, users.Count);

                    foreach (var user in users)
                    {
                        Assert.AreEqual(10, ((SVNModel)user.ExtensionPoint["SVNExtension"]).Add);
                        Assert.AreEqual(2, reader.CurrentRevision);
                        Assert.AreEqual(0, ((SVNModel)user.ExtensionPoint["SVNExtension"]).Deleted);
                        Assert.AreEqual(0, ((SVNModel)user.ExtensionPoint["SVNExtension"]).Modified);
                    }
                }
            }
        }
        public CommitModel Commit()
        {
            SVNManager.ResolveConflicts((conRes) =>
            {
                SVNManager.RemoveMissingFiles((r) =>
                {
                    SVNManager.Changelist("**", (res) =>
                    {
                        SVNManager.Commit("update", (ress) =>
                        {
                            SVNManager.UpdateLocalRepo((resss) =>
                            {
                                if (IOFile.Exists(Path.Combine(UsersHelper.GetUserFolder(), "missing.list")))
                                {
                                    IOFile.Delete(Path.Combine(UsersHelper.GetUserFolder(), "missing.list"));
                                }
                            });
                        });
                    });
                });
            });

            return(new CommitModel());
        }
Exemple #19
0
        public static void Publish(string path, Action <string> onResult)
        {
            onResultAction = onResult;
            string[] drafts = Directory.GetFiles(Path.Combine(path, "default", "pub_draft"));

            foreach (string s in Directory.GetFiles(Path.Combine(path, "default", "pub_out")))
            {
                if (!Path.GetExtension(s).Contains("html"))
                {
                    File.Delete(s);
                }
            }

            foreach (string s in drafts)
            {
                File.Copy(s, s.Replace("pub_draft", "pub_out"), true);
                File.Delete(s);
            }

            SVNManager.Commit("Save project", (res) =>
            {
                onResultAction("");
            });
        }
        public HistoryVersionsModel GetVersions(string scenario_id, string ticket = "", string topic_id = "")
        {
            HistoryVersionsModel model     = new HistoryVersionsModel();
            List <int>           revisions = new List <int>();

            string folder = ApiHelper.FindFolderById(scenario_id, PathHelper.GetRepoPath());

            if (folder == null)
            {
                model.errors = ApiHelper.JsonError(400, new string[] { "scenario not exist" });
                return(model);
            }

            string infoPath = Path.Combine(folder, new DirectoryInfo(folder).Name + ".info");

            if (!string.IsNullOrEmpty(topic_id))
            {
                List <TopicModel> topics = ApiHelper.GetTopicsOrigin(scenario_id);
                foreach (TopicModel t in topics)
                {
                    if (t.index.ToString() == topic_id)
                    {
                        infoPath = t.vmpPath;
                        break;
                    }
                }
            }

            model.versions = revisions;

            SVNManager.GetCurrentRevisionFile(infoPath, (res) =>
            {
                res = res.Replace("Revision:", "");
                res = res.Replace("\r\n", "");
                try
                {
                    model.current_version = int.Parse(res);
                }
                catch (Exception e)
                {
                }
            });

            SVNManager.GetAllRevisionsForFile(infoPath, (res) =>
            {
                res             = res.Replace("------------------------------------------------------------------------", "-_-_-");
                string[] splits = res.Split(new string[] { "-_-_-" }, StringSplitOptions.RemoveEmptyEntries);
                foreach (string s in splits)
                {
                    string[] revisionParts = s.Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries);
                    if (revisionParts.Length > 3)
                    {
                        try
                        {
                            int revisionNumber   = int.Parse(revisionParts[0].Replace("r", ""));
                            string[] timeAndDate = revisionParts[2].Split(new char[] { ' ' }, System.StringSplitOptions.RemoveEmptyEntries);
                            string revisionText  = $"{revisionNumber} - {timeAndDate[0]} {timeAndDate[1]}  {revisionParts[1]}";
                            revisions.Add(revisionNumber);
                        }
                        catch (Exception ex)
                        {
                        }
                    }
                }
                if (revisions != null && revisions.Count > 0)
                {
                    model.current_version = revisions[0];
                }
                model.versions = revisions;
            });

            return(model);
        }
Exemple #21
0
        //public string UpdateFolder(string folder_id, string folder, string ticket = "")
        public FolderModel UpdateFolder(string folder_id, [FromBody] ApiFormInput formData)
        {
            FolderModel result = new FolderModel();

            if (formData == null)
            {
                //return ApiHelper.JsonError(400, new string[] { "empty body" });
                result.errors = ApiHelper.JsonError(400, new string[] { "empty body" });
                return(result);
            }

            if (string.IsNullOrEmpty(formData.ticket))
            {
                //return ApiHelper.JsonError(400, new string[] { "error" });
                result.errors = ApiHelper.JsonError(400, new string[] { "error" });
                return(result);
            }

            if (string.IsNullOrEmpty(formData.folder.name))
            {
                result.errors = ApiHelper.JsonError(400, new string[] { "Incorrect name" });
                return(result);
            }

            if (string.IsNullOrEmpty(formData.folder.name))
            {
                result.errors = ApiHelper.JsonError(400, new string[] { "Folder name are empty" });
                return(result);
            }

            if (!_authenticationManager.CheckAccessToken(formData.ticket))
            {
                //return ApiHelper.JsonError(401, new string[] { "wrong token" });
                result.errors = ApiHelper.JsonError(400, new string[] { "wrong token" });
                return(result);
            }

            if (formData.folder.name.Length > 50)
            {
                result.errors = ApiHelper.JsonError(400, new string[] { "Name are too long" });
                return(result);
            }

            string ret = ApiHelper.FindFolderById(folder_id, PathHelper.GetRepoPath());

            if (ret == null)
            {
                //return ApiHelper.JsonError(400, new string[] { "folder not exist" });
                result.errors = ApiHelper.JsonError(400, new string[] { "folder not exist" });
                return(result);
            }

            try
            {
                string sc = formData.folder.name;
                if (sc != null)
                {
                    string        dir   = new DirectoryInfo(ret).Name;
                    CategoryModel model = JsonConvert.DeserializeObject <CategoryModel>(IOFile.ReadAllText(Path.Combine(ret, dir + ".info")));
                    model.title = sc;
                    string newModel = JsonConvert.SerializeObject(model);
                    IOFile.WriteAllText(Path.Combine(ret, dir + ".info"), newModel);
                    //PathHelper.RenameFolder(ret, dir, sc);
                    ret    = ApiHelper.FindFolderById(folder_id, PathHelper.GetRepoPath());
                    result = ApiHelper.GetFolderInfo(folder_id, Path.Combine(PathHelper.GetRepoPath(), ret));

                    string oldPath = new DirectoryInfo(ret).FullName.Replace("\\", "/");
                    //SVNManager.Rename(oldPath, oldPath.Replace(dir,sc));

                    SVNManager.SaveChanges();

                    return(result);
                }
            }
            catch (Exception e)
            {
                //return ApiHelper.JsonError(400, new string[] { "wrong folder object" });
                result.errors = ApiHelper.JsonError(400, new string[] { "wrong folder object" });
                return(result);
            }
            return(null);
        }
Exemple #22
0
        public ImportedScenarioModel Import(string folder_id, [FromBody] ApiFormInput formData)
        {
            ImportedScenarioModel model = new ImportedScenarioModel();

            if (!formData.local)
            {
                string fileName = formData.filename;
                string base64   = formData.file;

                formData.file = Path.Combine(PathHelper.GetViewerImagesFolder(), fileName);

                byte[] fileContent = ApiHelper.DecodeBase64(base64);
                IOFile.WriteAllBytes(formData.file, fileContent);
            }

            if (string.IsNullOrEmpty(formData.ticket))
            {
                model.errors = ApiHelper.JsonError(400, new string[] { "error" });
                return(model);
            }

            if (string.IsNullOrEmpty(formData.file))
            {
                model.errors = ApiHelper.JsonError(400, new string[] { "File is required" });
                return(model);
            }

            if (!PathHelper.CheckIfStringIsPathCompliant(Path.GetFileName(formData.file)))
            {
                model.errors = ApiHelper.JsonError(400, new[] { "Invalid file name provided" });
                return(model);
            }

            if (!_authenticationManager.CheckAccessToken(formData.ticket))
            {
                model.errors = ApiHelper.JsonError(400, new string[] { "wrong token" });
                return(model);
            }

            formData.file = formData.file.Replace("file:///", "");
            formData.file = formData.file.Replace("file://", "");
            string ret = ApiHelper.FindFolderById(folder_id, PathHelper.GetRepoPath());

            if (ret == null)
            {
                //return ApiHelper.JsonError(400, new string[] { "folder not exist" });
                model.errors = ApiHelper.JsonError(400, new string[] { "file not exist" });
                return(model);
            }
            if (!IOFile.Exists(formData.file))
            {
                //return ApiHelper.JsonError(400, new string[] { "file not exist" });
                model.errors = ApiHelper.JsonError(400, new string[] { "file not exist" });
                return(model);
            }

            if (!string.IsNullOrEmpty(ret))
            {
                ret = ret.Replace(PathHelper.GetRepoPath(), "").Replace("\\", "/");
                Exporter.Import(formData.file, ret, formData.overRide, (res) =>
                {
                    model = res;
                });
            }

            SVNManager.SaveChanges();
            return(model);
        }
Exemple #23
0
        private static void XSLTTransformation(string fromFolder, string copyTo)
        {
            string        path = PathHelper.GetUserProcessingFolder();
            DirectoryInfo dir  = new DirectoryInfo(path);

            path = dir.FullName.Replace("\\", "/");
            string aPath = Path.Combine(path, "xslt/a.xml").Replace("\\", "/");

            if (!Directory.Exists(Path.GetDirectoryName(aPath)))
            {
                Directory.CreateDirectory(Path.GetDirectoryName(aPath));
            }

            File.Copy(fromFolder, Path.Combine(path, "xslt/a.xml"), true);
            File.Copy(Path.Combine(path, "xslt/a.xml"), Path.Combine(path, "input/1_1.xml"), true);
            string command = "";

            var xsltConfigFileName = Path.Combine(path, "xslt.config");

            if (!File.Exists(xsltConfigFileName))
            {
                File.WriteAllText(xsltConfigFileName, JsonConvert.SerializeObject(new XsltConfigModel {
                    port = 9000, ticket = "ytrewq654321", url = "http://127.0.0.1"
                }));
            }

            string configContent = File.ReadAllText(xsltConfigFileName);

            var xspConfigFilePath = Path.Combine(path, "xsp.config");

            if (!File.Exists(xspConfigFilePath))
            {
                File.WriteAllText(xspConfigFilePath, JsonConvert.SerializeObject(new XSPConfigModel {
                    port = 0
                }));
            }
            string          xspContent = File.ReadAllText(Path.Combine(path, "xsp.config"));
            XsltConfigModel config     = JsonConvert.DeserializeObject <XsltConfigModel>(configContent);
            XsltConfigModel xspConfig  = JsonConvert.DeserializeObject <XsltConfigModel>(xspContent);
            string          fileNameWithoutExtension = Path.GetFileNameWithoutExtension(copyTo.Replace("\\", "/"));
            string          parameters = "id=" + fileNameWithoutExtension + " server_host={SERVER}:{PORT} ticket=" + config.ticket;

            CopyTo = copyTo;
            Action onFinish = () =>
            {
                foreach (string s in Directory.GetFiles(path))
                {
                    if (s.ToLower().Contains("b.xml"))
                    {
                        string textToReplace = File.ReadAllText(s);
                        while (textToReplace.Contains("res://res://"))
                        {
                            textToReplace = textToReplace.Replace("res://res://", "res://");
                        }
                        textToReplace = textToReplace.Replace("/document", "/viewer/document");
                        textToReplace = textToReplace.Replace(config.ticket, "{TICKET}");
                        File.WriteAllText(copyTo, textToReplace);
                        File.Copy(copyTo, Path.Combine(path, "input/1_1.xml"), true);
                        string repoPath = Path.Combine(UsersHelper.GetUserFolder(), UsersHelper.GetToolsFolder());
                        SVNManager.AddFile(copyTo.Replace(repoPath + "/", ""));
                    }
                }

                X3DTrans(copyTo);
            };

            Thread th = new Thread(new ThreadStart(() =>
            {
                command = "cd \"" + path + "\" & java -jar \"" + PathHelper.GetToolsPath() + "/saxon9he.jar\" \"" + path + "/xslt/a.xml\" \"" + PathHelper.GetToolsPath() + "/xslt/c.xsl\" " + parameters + " > \"" + path + "/b.xml\"";
                ProcessStartInfo processInfo;
                processInfo = new ProcessStartInfo("cmd.exe", "/C " + command);

                processInfo.CreateNoWindow         = true;
                processInfo.UseShellExecute        = false;
                processInfo.RedirectStandardOutput = true;
                processInfo.RedirectStandardError  = true;

                var process    = Process.Start(processInfo);
                string outputt = process.StandardOutput.ReadToEnd();
                string errors  = process.StandardError.ReadToEnd();

                if (!string.IsNullOrEmpty(errors))
                {
                    _logger.LogError($"Error executing command: \"{command}\". Message: '{errors}'");
                }

                process.WaitForExit();
                onFinish();
            }));

            th.Start();
        }
Exemple #24
0
        private static void X3DTrans(string copyTo)
        {
            string basePath = AppContext.BaseDirectory.Replace("\\", "/");

            string binaryToolsPath    = PathHelper.GetToolsPath();
            string userProcessingPath = PathHelper.GetUserProcessingFolder();

            string command = "cd \"" + userProcessingPath + "\" & \"" + binaryToolsPath + "/PublishEngineExecute.exe\" \"" + userProcessingPath + "/input\" \"" + userProcessingPath + "/input/resourceFolder\" -p XmlCompass -f";

            ProcessStartInfo processInfo;
            Action           onFinish = () =>
            {
                string   pathToFile = "";
                string[] files      = Directory.GetFiles(Path.Combine(userProcessingPath, "input/resourceFolder"));

                foreach (string fileName in files)
                {
                    if (fileName.ToLower().Contains("x3d") || fileName.ToLower().Contains("zip") || fileName.ToLower().Contains("rar"))
                    {
                        string copyFile = Path.Combine(copyTo.Replace(Path.GetFileName(copyTo), ""), Path.GetFileName(fileName));
                        File.Copy(fileName, copyFile, true);
                        string repoPath = Path.Combine(UsersHelper.GetUserFolder(), UsersHelper.GetToolsFolder());
                        SVNManager.AddFile(copyFile.Replace(repoPath + "/", ""));
                        pathToFile = copyFile;
                        if (fileName.ToLower().Contains("x3d"))
                        {
                            _logger.LogInformation($"Processing X3D file: '{fileName}'");

                            DirectoryInfo    dInfo      = new DirectoryInfo(binaryToolsPath);
                            string           newDPath   = dInfo.FullName.Replace("\\", "/");
                            string           x3dCommand = "cd \"" + PathHelper.GetUserProcessingFolder() + "\" & \"" + newDPath + "/remgeom.bat\" \"" + copyFile + "\" \"" + newDPath + "\"";
                            ProcessStartInfo processBat = new ProcessStartInfo("cmd.exe", "/C " + x3dCommand);

                            processBat.CreateNoWindow         = true;
                            processBat.UseShellExecute        = false;
                            processBat.RedirectStandardOutput = true;
                            processBat.RedirectStandardError  = true;
                            processBat.WorkingDirectory       = newDPath;

                            var    processB = Process.Start(processBat);
                            string outputt  = processB.StandardOutput.ReadToEnd();
                            string errors   = processB.StandardError.ReadToEnd();

                            if (!string.IsNullOrEmpty(errors))
                            {
                                _logger.LogError($"Error while performing X3D transformation: '{errors}' Command: {x3dCommand}");
                            }

                            processB.WaitForExit();
                        }
                    }
                }

                foreach (string s in Directory.GetFiles(Path.Combine(userProcessingPath, "input")))
                {
                    if (s.ToLower().Contains(".xml"))
                    {
                        string ditaText = File.ReadAllText(s);

                        File.WriteAllText(s, ditaText);
                        File.Copy(s, CopyTo, true);
                    }
                }

                OnFinishDrafting();

                onResultAction("");
            };

            processInfo = new ProcessStartInfo("cmd.exe", "/C " + command);
            processInfo.CreateNoWindow         = true;
            processInfo.UseShellExecute        = false;
            processInfo.RedirectStandardOutput = true;
            processInfo.RedirectStandardError  = true;

            var    process = Process.Start(processInfo);
            string output  = process.StandardOutput.ReadToEnd();
            string errorss = process.StandardError.ReadToEnd();

            if (!string.IsNullOrEmpty(errorss))
            {
                _logger.LogError($"Error '{errorss}' while executing command: {command} ");
            }

            process.WaitForExit();

            command = "cd \"" + userProcessingPath + "\" & \"" + binaryToolsPath + "/PublishEngineExecute.exe\" \"" + userProcessingPath + "/input\" \"" + userProcessingPath + "/input/resourceFolder\" -p Cortona –f";

            processInfo = new ProcessStartInfo("cmd.exe", "/C " + command);
            processInfo.CreateNoWindow         = false;
            processInfo.UseShellExecute        = false;
            processInfo.RedirectStandardOutput = true;
            processInfo.RedirectStandardError  = true;

            process = Process.Start(processInfo);
            output  = process.StandardOutput.ReadToEnd();
            errorss = process.StandardError.ReadToEnd();
            if (!string.IsNullOrEmpty(errorss))
            {
                _logger.LogError($"Error '{errorss}' while executing command: {command} ");
            }

            process.WaitForExit();
            onFinish();
        }
Exemple #25
0
        public ImportedTopicsModel ImportTopic(string scenario_id, [FromBody] ApiFormInput formData)
        {
            ImportedTopicsModel model = new ImportedTopicsModel();

            if (!formData.local)
            {
                string fileName = formData.filename;
                string base64   = formData.file;
                formData.file = Path.Combine(PathHelper.GetViewerImagesFolder(), fileName);
                byte[] fileContent = ApiHelper.DecodeBase64(base64);
                System.IO.File.WriteAllBytes(formData.file, fileContent);
            }

            if (string.IsNullOrEmpty(formData.ticket))
            {
                //return ApiHelper.JsonError(400, new string[] { "error" });
                model.errors = ApiHelper.JsonError(400, new string[] { "error" });
                return(model);
            }

            if (string.IsNullOrEmpty(formData.file))
            {
                model.errors = ApiHelper.JsonError(400, new string[] { "File is required" });
                return(model);
            }

            if (!_authenticationManager.CheckAccessToken(formData.ticket))
            {
                //return ApiHelper.JsonError(401, new string[] { "wrong token" });
                model.errors = ApiHelper.JsonError(400, new string[] { "wrong token" });
                return(model);
            }

            formData.file = formData.file.Replace("file:///", "");

            if (!System.IO.File.Exists(formData.file))
            {
                //return ApiHelper.JsonError(400, new string[] { "file not exist" });
                model.errors = ApiHelper.JsonError(400, new string[] { "file not exist" });
                return(model);
            }
            string ret = ApiHelper.FindFolderById(scenario_id, PathHelper.GetRepoPath());

            List <TopicObject> beforeImportTopics = ApiHelper.GetTopics(scenario_id);

            Exporter.ImportTopic(formData.file, ret, formData.overRide, (res) =>
            {
                List <TopicObject> topics = ApiHelper.GetTopics(scenario_id);
                topics = topics.OrderBy(t => t.id).ToList();
                List <TopicModel> orogintopics = ApiHelper.GetTopicsOrigin(scenario_id);
                List <int> ids = new List <int>();
                foreach (TopicObject obj in topics)
                {
                    int index = int.Parse(obj.id);
                    while (ids.Contains(index))
                    {
                        index += 1;
                    }
                    ids.Add(index);
                    obj.id = index.ToString();
                }

                ids.Clear();

                foreach (TopicModel obj in orogintopics)
                {
                    int index = obj.index;
                    while (ids.Contains(index))
                    {
                        index += 1;
                    }
                    obj.index = index;
                    ids.Add(index);
                    System.IO.File.WriteAllText(obj.infoPath, JsonConvert.SerializeObject(obj));
                }

                foreach (TopicObject lastObj in beforeImportTopics)
                {
                    topics.Remove(topics.Find(t => t.id == lastObj.id));
                }

                topics       = topics.OrderBy(t => t.id).ToList();
                model.topics = topics;
            });

            SVNManager.SaveChanges();

            return(model);
        }