Exemple #1
0
        public HttpResponseMessage Get(HttpRequestMessage request)
        {
            IEnumerable <KeyValuePair <string, string> > keyValues = request.GetQueryNameValuePairs();
            XElement element = new XmlService(keyValues).Get();

            return(CreateHttpResponseMessage(element, request));
        }
Exemple #2
0
        public ActionResult UploadXml(HttpPostedFileBase SourceFile)
        {
            XmlImportResults result = new XmlImportResults();

            try
            {
                if (SourceFile == null || SourceFile.ContentLength < 1 || SourceFile.FileName.IsEmpty())
                {
                    throw new ArgumentNullException("SourceFile", "No source file selected!");
                }

                result = XmlService.UploadXml(SourceFile.FileName, SourceFile.InputStream);
            }
            catch (Exception e)
            {
                if (result == null)
                {
                    result = new XmlImportResults();
                }
                result.ErrorMessage = e.Message;
                result.Success      = false;
            }


            return(View("Index", result));
        }
Exemple #3
0
        public void Validate_StateUnderTest_ExpectedBehavior()
        {
            // Arrange
            var service        = new XmlService();
            var pathToXsdFiles = Path.Combine(Directory.GetCurrentDirectory(), "TestingInfrastructure", "Files", "Xsd");
            var xsdFiles       = Directory.GetFiles(pathToXsdFiles);
            var xsds           = new List <string>();

            foreach (var xsdFile in xsdFiles)
            {
                File.Exists(xsdFile).Should().BeTrue();
                var xsd = File.ReadAllText(xsdFile);
                xsds.Add(xsd);
            }

            var pathToXmlFile = Path.Combine(Directory.GetCurrentDirectory(), "TestingInfrastructure", "Files", "Xml", "Invoice1.xml");

            File.Exists(pathToXmlFile).Should().BeTrue();
            var xml = File.ReadAllText(pathToXmlFile);

            // Act
            var result = service.Validate(xml, xsds.ToArray());

            // Assert
            result.Should().BeNullOrEmpty();
        }
Exemple #4
0
        public void OnGet()
        {
            var xmlService = new XmlService(_env);

            Posts = xmlService.RetrievePosts();
            Posts.Reverse();
        }
        private void OnCmdSpeichern()
        {
            // TODO: Add your Code here

            var metadataItem = new MetadataItem(_bezeichnung, _erfassungsdatum, _typItems[0], _stichwoerter);

            // überprüfen ob die Pflichtfelder ausgefüllt worden sind:
            if (!requiredFields())
            {
                MessageBox.Show("Es müssen alle Pflichtfelder ausgefüllt werden!");
                return;
            }
            var documentLibrary = new DocumentLibrary();
            var xmlService      = new XmlService();

            // File Speichern:
            documentLibrary.SaveFileInFolder(this._filePath, ".pdf");
            metadataItem.FilePath = documentLibrary.FilePath;

            // MetadatenXmlFile erstellen, speichern und in eine Liste speichern:
            var guid      = documentLibrary.CreateDmsSaveFileName(this._filePath, ".xml");
            var serialXml = xmlService.CreateXmlWithMetadataItem(metadataItem);

            xmlService.SaveXml(serialXml, guid);


            _navigateBack();
        }
        private ObservableCollection <ICampaign> GetCampaignList()
        {
            ObservableCollection <ICampaign> result = new ObservableCollection <ICampaign>();

            string campaignDirectory = "Campaign";

            if (Directory.Exists(campaignDirectory))
            {
                List <string> dirs = new List <string>(Directory.EnumerateDirectories(campaignDirectory));
                foreach (var dir in dirs)
                {
                    IEnumerable <string> files = Directory.EnumerateFiles(dir);
                    string campaignFilePath    = string.Concat(dir, "\\Campaign.txt");
                    if (files.Contains(campaignFilePath))
                    {
                        ICampaign campaign = XmlService <Campaign> .ReadXml(campaignFilePath);

                        if (campaign != null)
                        {
                            while (result.Select(x => x.Name).Contains(campaign.Name))
                            {
                                string.Concat(campaign.Name, "1");
                            }
                            result.Add(campaign);
                        }
                    }
                }
            }
            else
            {
                // RAF
            }
            return(result);
        }
Exemple #7
0
 public Program(XmlService xmlService, PlayerService playerService, CoachService coachService, TeamService teamService)
 {
     _xmlService    = xmlService;
     _playerService = playerService;
     _coachService  = coachService;
     _teamService   = teamService;
 }
        public void ProcessTextTest_ReturnsModel_IsRequestSuccessful_IsFalse()
        {
            //arrange
            string      inText                 = "Hi somebody, here is my expenses claim <expense><total>1024.01</total></expense>. Thanks!";
            string      xmlString              = "<expense><total>1024.01</total></expense>";
            var         textValidationService  = new TextValidationService();
            var         xmlService             = new XmlService();
            int         openingBracketPosition = textValidationService.GetOpeningBracketPosition(inText);
            int         closingBracketPosition = textValidationService.GetClosingBracketPosition(inText);
            XmlDocument xmlDoc                 = xmlService.BuildXmlDocumentFromString(xmlString);
            var         responseModel          = new ApiResponseModel();

            mockTextValidationService.Setup(p => p.GetOpeningBracketPosition(inText)).Returns(openingBracketPosition);
            mockTextValidationService.Setup(p => p.GetClosingBracketPosition(inText)).Returns(closingBracketPosition);
            mockXmlService.Setup(p => p.IsRecognisedElement(It.IsAny <string>())).Returns(true);
            mockXmlService.Setup(p => p.BuildXmlDocumentFromString(It.IsAny <string>())).Returns(xmlDoc);
            mockXmlService.Setup(p => p.BuildExpenseClaimModelFromXmlDocument(xmlDoc)).Returns((ExpenseClaimModel)null);

            //act
            var result = importService.ProcessText(inText);

            //assert
            Assert.IsNotNull(result);
            Assert.IsFalse(result.IsRequestSuccessful);
            Assert.IsTrue(result.GstCost == 0);
            Assert.IsTrue(result.TotalExcludingGst == 0);
            Assert.IsTrue(!string.IsNullOrEmpty(result.ErrorMessage));
            Assert.AreEqual(result.ErrorMessage, "Could not build based response from the XML provided.");
        }
        public override void SaveToXml(object o = null)
        {
            try
            {
                base.SaveToXml();
                if (SelectedItem != null)
                {
                    SaveFileDialog sfd = new SaveFileDialog
                    {
                        FileName         = $"{SelectedItem.OrderHeader.OrderNumber}",
                        FilterIndex      = 0,
                        Filter           = "XML-файл (*.xml)|*.xml|Текстовый файл (*.txt)|*.txt",
                        InitialDirectory = "C:\\"
                    };
                    bool saveResultOk = sfd.ShowDialog().Value;
                    if (saveResultOk)
                    {
                        XmlService <DocumentOrder> .Serialize(SelectedItem, sfd.FileName);
                    }
                    Refresh();
                }
            }
            catch (Exception ex)
            {
                Utilites.Error(ex);
            }

            base.SaveToXml(o);
        }
Exemple #10
0
        private void OnCmdSpeichern()
        {
            try
            {
                if (OnCanSpeichern())
                {
                    XmlService.WriteXML(CreateMetadataItem(), _filePath);
                    if (IsRemoveFileEnabled)
                    {
                        File.Delete(_filePath);
                    }

                    _navigateBack();
                }
                else
                {
                    MessageBox.Show("Es müssen alle Pflichtfelder ausgefüllt werden!", "Pflichtfelder ausfüllen");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Speichern fehlgeschlagen: " + ex.Message, "Speichern fehlgeschlagen");
            }

        }
 public override void SaveToXml(object o = null)
 {
     try
     {
         if (EdiService.SelectedRelationship == null)
         {
             Utilites.Error("Необходимо выбрать клиента"); return;
         }
         base.SaveToXml();
         if (SelectedItem != null)
         {
             SaveFileDialog sfd = new SaveFileDialog
             {
                 FileName         = $"{SelectedItem.OrderResponseHeader.OrderResponseNumber}",
                 FilterIndex      = 0,
                 Filter           = "XML-файл (*.xml)|*.xml|Текстовый файл (*.txt)|*.txt",
                 InitialDirectory = "C:\\edi_docs\\ordrsp\\"
             };
             bool saveResultOk = sfd.ShowDialog().Value;
             if (saveResultOk)
             {
                 XmlService <DocumentOrderResponse> .Serialize(SelectedItem, sfd.FileName);
             }
             Refresh();
         }
     }
     catch (Exception ex)
     {
         Utilites.Error(ex);
     }
 }
Exemple #12
0
        /**
         * 加载语音分配策略
         **/
        private void LoadAssign()
        {
            string className = XmlService.getProperty("Assign", "classname");
            Type   type      = Type.GetType(className);

            ta = (TelAssign)Activator.CreateInstance(type);
        }
        /// <summary>
        /// Метод проверяет одинаковые ли пароли, совпадают ли секретные слова из файла и "Старое секретное слово"
        /// и сохраняет измененный пароль в xml.
        /// Закрывает текущее окно и создаёт новый mainwindow.
        /// </summary>
        /// <param name="args"></param>
        private void ChangePassword(object args)
        {
            XmlService xmlForSecret  = new XmlService();
            bool       compareSecret = xmlForSecret.CompareSecretWords(SecretWord);

            if (compareSecret)
            {
                if (FirstPassword == SecondPassword)
                {
                    new_password.Password      = FirstPassword;
                    new_password.NewSecretWord = NewSecretWord;
                    XmlService changePass = new XmlService();
                    changePass.SaveUserPasswordToXml(new_password);
                    MainWindow Main = new MainWindow();
                    foreach (Window window in App.Current.Windows)
                    {
                        if (window is ChangePasswordWindow)
                        {
                            window.Close();
                        }
                    }
                    Main.Show();
                }
                else
                {
                    MessageBox.Show("Пароли не совпадают!");
                }
            }
            else
            {
                MessageBox.Show("Секретное слово неверно.");
            }
        }
Exemple #14
0
        public bool IsUserValid()
        {
            if (!IsInputValid())
            {
                return(false);
            }

            if (this.EmailExists())
            {
                var encodedEmail = Convert.ToBase64String(Encoding.UTF8.GetBytes(this.Email));
                var filePath     = Path.Combine(DatabaseDir, encodedEmail);
                filePath  = Path.ChangeExtension(filePath, "xml");
                this.User = XmlService.ReadFromXml <UserDto>(filePath);
                if (this.IsPassphraseMatch())
                {
                    return(true);
                }
                else
                {
                    this.WarningMessage = "Invalid passphrase";
                    return(false);
                }
            }
            else
            {
                this.WarningMessage = "Invalid email";
                return(false);
            }
        }
Exemple #15
0
        public HttpResponseMessage Create(XElement value, HttpRequestMessage request)
        {
            XmlService service = new XmlService(request.GetQueryNameValuePairs());

            service.Create(value, out XElement element);

            return(CreateHttpResponseMessage(element, request));
        }
        public MainWindow()
        {
            InitializeComponent();

            var xmlService = new XmlService();

            DataContext = new MainViewModel(new InvoiceService(xmlService), xmlService);
        }
Exemple #17
0
        public void CheckFileExists_FileNotExists_ReturnFalse()
        {
            var target = new XmlService();

            bool result = target.CheckFileExists("xxx");

            Assert.IsFalse(result);
        }
        public void TestReadXml()
        {
            MetadataItem item = XmlService.ReadXML(@"..\..\DMSTest\1cbed3d2-0d08-49ad-bd5d-0a1dfb57d499_Metadata.xml");

            Assert.IsNotNull(item);
            Assert.AreEqual("Joshua", item.Benutzer);
            Assert.AreEqual("Test Quittungen", item.Bezeichnung);
        }
            public void should_deserialize_when_file_exists()
            {
                Context();
                FileSystem.Setup(x => x.file_exists(It.IsAny <string>())).Returns(true);
                XmlService.Setup(x => x.deserialize <PackageFiles>(It.IsAny <string>())).Returns(new PackageFiles());

                because();
            }
Exemple #20
0
        public void ExtractExpenseMarkup_ForTextWithMissingTotal_Throws()
        {
            var logger         = new Mock <ILogger <XmlService> >();
            var xmlService     = new XmlService(logger.Object);
            var expenseService = GetMockedService(xmlService);

            Assert.ThrowsException <TotalMissingException>(() => expenseService.Object.ExtractExpenseMarkup(Resources.TextWithMissingTotal));
        }
Exemple #21
0
        public void CheckFileExists_FileExists_ReturnTrue()
        {
            var target = new XmlService();

            bool result = target.CheckFileExists(filePath);

            Assert.IsTrue(result);
        }
        /// <summary>
        /// Общий метод для всех способов открытия файла списка.
        /// </summary>
        /// <param name="file">Файл списка, который требуется открыть.</param>
        /// <param name="askSelectAction">Требуется ли запрашивать выбор действия.</param>
        private async void OpenList(StorageFile file, bool askSelectAction = true)
        {
            if (file == null)
            {
                return;
            }

            List <ListWordModel> data = new List <ListWordModel>();

            try
            {
                data = new XmlService().ReadList(await FileIO.ReadTextAsync(file), !askSelectAction);
                if (data == null)
                {
                    return;
                }
            }
            catch (Exception ex)
            {
                Messages.OpenFileError(ex.Message);
                return;
            }

            if (askSelectAction && WordList.Count > 0)
            {
                MessageDialogResult result = await Messages.SelectOperationWithLoadedListFileAsync();

                switch (result)
                {
                case MessageDialogResult.Yes:
                    WordList.Clear();
                    new AppHelper().AddFileToMRU(file); break;

                case MessageDialogResult.No: break;

                case MessageDialogResult.Cancel: return;
                }
            }
            else
            {
                WordList.Clear();
            }

            ListFile = file;

            ObservableCollection <ListWordViewModel> readed
                = new ObservableCollection <ListWordViewModel>(data?.Select(e => new ListWordViewModel(e)));

            foreach (ListWordViewModel item in readed)
            {
                WordList.Add(item);
            }

            for (int i = 0; i < WordList.Count; i++)
            {
                WordList[i].ID = (ushort)i;
            }
        }
 public List<MappedFieldModel> AddMappedField(string uuid, MappedFieldModel data)
 {
     var service = new XmlService();
     var mappedFields = GetMappedFields(uuid);
     mappedFields.Add(data);
     var dataAsString = service.Serialize<List<MappedFieldModel>>(mappedFields);
     this.UpdateImportSettings(uuid, new NameValueCollection { { "MappedFields", dataAsString } });
     return mappedFields;
 }
Exemple #24
0
        public IActionResult Requests()
        {
            var xmlPath = $"{_hostingEnvironment.WebRootPath}/xml/requests.xml";
            var logs    = XmlService.Deserialize <RequestLogs>(xmlPath) ?? new RequestLogs {
                Logs = new List <RequestLog>()
            };

            return(View(logs.Logs));
        }
Exemple #25
0
        public void LoadXml_Test()
        {
            var target = new XmlService();

            var result = target.LoadXml(filePath);

            Assert.IsNotNull(result);
            Assert.AreEqual(3, result.Count);
        }
Exemple #26
0
        static void Main()
        {
            System.Windows.Forms.Application.EnableVisualStyles();
            AppDomain.CurrentDomain.UnhandledException += (args, e) => Log.Debug(e.ExceptionObject.ToString());

            var baseDir     = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location) ?? Directory.GetCurrentDirectory();
            var profilesDir = Path.Combine(baseDir, "JitProfiles");

            if (!Directory.Exists(profilesDir))
            {
                Directory.CreateDirectory(profilesDir);
            }

            var dbcdir = Path.Combine(baseDir, "DBC");

            if (!Directory.Exists(dbcdir))
            {
                Directory.CreateDirectory(dbcdir);
            }

            ProfileOptimization.SetProfileRoot(profilesDir);
            ProfileOptimization.StartProfile("JitProfile.jpf");

            FontCollection.Initialize();
            Settings.KeyBindings.Initialize();
            XmlService.Initialize();

            var window  = new EditorWindow();
            var context = new GxContext(window.DrawTarget);

            context.InitContext();

            // TODO: move all shader initializations somehwere?
            context.InitShaders();

            WorldFrame.Instance.Initialize(window.DrawTarget, context);
            WorldFrame.Instance.OnResize((int)window.RenderSize.Width, (int)window.RenderSize.Height);

            var wnd = new MainWindow {
                elementHost1 = { Child = window }
            };

            wnd.Show();
            var isClosed = false;

            wnd.FormClosing += (sender, args) => isClosed = true;

            while (isClosed == false)
            {
                context.BeginFrame();
                WorldFrame.Instance.OnFrame();
                context.EndFrame();
                System.Windows.Forms.Application.DoEvents();
            }

            WorldFrame.Instance.Shutdown();
        }
Exemple #27
0
        private void InitializeConnections()
        {
            var xml = new XmlService();

            foreach (var connection in xml.GetIdAttributes())
            {
                ConnectionsModel.Connections.Add(connection);
            }
        }
            public void should_save_if_the_snapshot_is_not_null()
            {
                Context();
                files = new PackageFiles();

                because();

                XmlService.Verify(x => x.serialize(files, It.IsAny <string>()), Times.Once());
            }
            public void should_not_deserialize_if_file_does_not_exist()
            {
                Context();
                FileSystem.Setup(x => x.file_exists(It.IsAny <string>())).Returns(false);

                because();

                XmlService.Verify(x => x.deserialize <PackageFiles>(It.IsAny <string>()), Times.Never);
            }
            public void should_not_do_anything_if_the_snapshot_is_null()
            {
                Context();
                files = null;

                because();

                XmlService.Verify(x => x.serialize(files, It.IsAny <string>()), Times.Never);
            }
Exemple #31
0
        public void CreateXmlFile_Success()
        {
            var target = new XmlService();

            var path = Path.Combine(Environment.CurrentDirectory, "Resources", "tmp.xml");

            target.CreateXmlFile(path);

            Assert.IsTrue(File.Exists(path));
        }
        public List<MappedFieldModel> GetMappedFields(string uuid)
        {
            var service = new XmlService();
            var folder = GetImportSettingsFolder();
            var content = folder.CreateQuery().FirstOrDefault(a => a.UUID == uuid);
            var mappedFields = content.GetValue<string>("MappedFields");
            if (string.IsNullOrEmpty(mappedFields))
                return new List<MappedFieldModel>();

            var data = service.Deserialize<List<MappedFieldModel>>(mappedFields);
            return data;
        }
 public NameValueCollection GetSourceStructure(ImportSetting setting)
 {
     var sqlService = new SqlService();
     var xmlService = new XmlService();
     switch (setting.SourceType)
     {
         case SourceTypeEnum.XML:
             return xmlService.GetSourceStructure(setting);
         case SourceTypeEnum.SQL:
         case SourceTypeEnum.SQLQUERY:
             return sqlService.GetSourceStructure(setting);
     }
     return new NameValueCollection();
 }
        public List<NameValueCollection> GetDataToImport(ImportSetting importSetting)
        {
            var objectsToImport = new List<NameValueCollection>();
            var sqlService = new SqlService();
            var xmlService = new XmlService();
            var dataToImport = new List<NameValueCollection>();
            switch (importSetting.SourceType)
            {
                case SourceTypeEnum.XML:
                    dataToImport = xmlService.GetData(importSetting);
                    break;
                case SourceTypeEnum.SQL:
                case SourceTypeEnum.SQLQUERY:
                    dataToImport = sqlService.GetData(importSetting);
                    break;
            }

            foreach (var row in dataToImport)
            {
                var objectToImport = new NameValueCollection();
                foreach (var mappedField in importSetting.MappedFields)
                {
                    if (!string.IsNullOrEmpty(row[mappedField.SourceField]))
                    {
                        if (!mappedField.IsDefault)
                            objectToImport.Add(mappedField.KoobooField, row[mappedField.SourceField]);
                        else
                            objectToImport.Add(mappedField.KoobooField, mappedField.DefaultValue);
                    }
                }
                if (objectToImport.Count > 0)
                    objectsToImport.Add(objectToImport);
            }

            return objectsToImport;
        }
 public List<MappedFieldModel> RemoveMappedField(string uuid, MappedFieldModel data)
 {
     var service = new XmlService();
     var mappedFields = GetMappedFields(uuid);
     var elementToRemove = mappedFields.FirstOrDefault(a => a.KoobooField == data.KoobooField);
     if (elementToRemove != null)
     {
         mappedFields.Remove(elementToRemove);
         var dataAsString = service.Serialize<List<MappedFieldModel>>(mappedFields);
         UpdateImportSettings(uuid, new NameValueCollection {{"MappedFields", dataAsString}});
     }
     return mappedFields;
 }
 public void SetMappedFields(string uuid, List<MappedFieldModel> data)
 {
     var service = new XmlService();
     var dataAsString = service.Serialize<List<MappedFieldModel>>(data);
     this.UpdateImportSettings(uuid, new NameValueCollection { { "MappedFields", dataAsString } });
 }