public void GetIncomeMoveOrderNotifications() { Client.Tracer = null; var docs = Client.GetIncomeDocuments(new DocFilter { DocType = 601, DocStatus = DocStatusEnum.PROCESSED_DOCUMENT, ProcessedDateFrom = DateTime.Today.AddDays(-200), }, 0, 400); foreach (var d in docs.Documents) { var xml = Client.GetDocumentText(d.DocumentID); var md = XmlSerializationHelper.Deserialize(xml); Assert.NotNull(md.Move_Order_Notification); if (md.Move_Order_Notification.Order_Details.IsNullOrEmpty()) { continue; } var od = md.Move_Order_Notification.Order_Details; if (od.Where(o => o.Sscc_Detail != null).Any() && od.Where(o => o.Sgtin != null).Any()) { WriteLine("==== Move order with SGTINs and SSCCs ======="); WriteLine(xml); } } }
private void LoadZones() { var openDialog = new OpenFileDialog(); var path = string.Format(Application.StartupPath); openDialog.InitialDirectory = path; openDialog.FilterIndex = 0; if (openDialog.ShowDialog() != DialogResult.OK) { return; } var zoneFilename = openDialog.FileName; Logger.AddDebugText(rtbDebug, $@"Nav file loaded = {zoneFilename}"); try { Zones = XmlSerializationHelper.Deserialize <List <Zones> >(zoneFilename) ?? new List <Zones>(); openDialog.Dispose(); Logger.AddDebugText(rtbDebug, $@"Added {Zones.Count.ToString()} Zones"); foreach (var item in Zones) { mapLB.Items.Add(item.Name); } } catch (Exception ex) { Logger.AddDebugText(rtbDebug, $@"LoadZones error {ex}"); } }
public void XmlDeserializeDocument601() { // из ЛК загружен документ схемы 601 с кодом 3ad8d361-0044-48fc-b0ee-aeed97df3f8e var doc = XmlSerializationHelper.Deserialize(Doc601xml); var mo = doc.Move_Order_Notification; Assert.NotNull(mo); Assert.AreEqual("00000000104494", mo.Subject_Id); // типография в Могойтуй Assert.AreEqual("00000000104453", mo.Receiver_Id); // автомойка в пгт Яблоновский Assert.NotNull(mo.Order_Details); Assert.AreEqual(2, mo.Order_Details.Count); var sgtin = mo.Order_Details[0]; Assert.AreEqual("507540413987451234567894123", sgtin.Sgtin); Assert.IsNull(sgtin.Sscc_Detail); var sscc = mo.Order_Details[1]; Assert.IsNull(sscc.Sgtin); Assert.IsNotNull(sscc.Sscc_Detail); Assert.AreEqual(1, sscc.Sscc_Detail.Detail.Count); var ssccSgtin = sscc.Sscc_Detail.Detail[0]; Assert.IsNotNull(ssccSgtin); Assert.AreEqual("50754041398745", ssccSgtin.Gtin); }
/// <summary> /// Gets the genetic progress instance. /// </summary> /// <returns>Genetic progress singleton</returns> public static GeneticProgress GetGeneticProgressInstance() { if (instance == null) { lock (Lock) { if (instance == null) { if (File.Exists(Filepath)) { try { instance = XmlSerializationHelper.Deserialize <GeneticProgress>(Filepath); } catch (Exception ex) { //If there is a problem with the progress file, just make a new one instance = new GeneticProgress(); instance.Serialize(Filepath); } } else { //create new file and save it instance = new GeneticProgress(); instance.Serialize(Filepath); } } } } return(instance); }
/// <summary> /// The get import data. /// </summary> /// <param name="xmlFilePath"> /// The xml file path. /// </param> /// <returns> /// The <see cref="Zags_VNov"/>. /// </returns> public virtual Zags_VNov GetImportData(string xmlFilePath) { XmlSchema schema; // зачитываем из ресурсов xsd var resourceName = string.Format("rt.srz.business.exchange.import.zags.Implementation.xsd.{0}", XsdResourceName); var myAssembly = Assembly.GetExecutingAssembly(); using (var schemaStream = myAssembly.GetManifestResourceStream(resourceName)) { schema = XmlSchema.Read(schemaStream, null); } // проверяем документ на соответствие var settings = new XmlReaderSettings(); settings.Schemas.Add(schema); settings.ValidationType = ValidationType.Schema; settings.ValidationEventHandler += ValidationHandler; var reader = XmlReader.Create(xmlFilePath, settings); var obj = new TTypeXmlObj(); obj = (TTypeXmlObj)XmlSerializationHelper.Deserialize(obj, reader); return(Convert(obj)); }
public void XmlDeserializationTest() { var docXml = @"<?xml version=""1.0"" encoding=""utf-8""?> <documents xmlns:xsd=""http://www.w3.org/2001/XMLSchema"" xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" version=""1.34""> <register_end_packing action_id=""311""> <subject_id>00000000100930</subject_id> <operation_date>2020-04-08T16:14:05.8168969+03:00</operation_date> <order_type>1</order_type> <series_number>100000001</series_number> <expiration_date>22.08.2020</expiration_date> <gtin>11170012610151</gtin> <signs> <sgtin>07091900400001TRANSF2000021</sgtin> </signs> </register_end_packing> </documents>"; var doc = XmlSerializationHelper.Deserialize(docXml); Assert.NotNull(doc); Assert.NotNull(doc.Register_End_Packing); Assert.AreEqual("11170012610151", doc.Register_End_Packing.Gtin); Assert.AreEqual(1, doc.Register_End_Packing.Signs.Count); Assert.AreEqual("07091900400001TRANSF2000021", doc.Register_End_Packing.Signs[0]); }
/// <summary> /// Loads the zones. /// </summary> public void LoadZones() { OpenFileDialog OpenDialog = new OpenFileDialog(); string PATH = (string.Format(Application.StartupPath + "\\Documents\\")); OpenDialog.InitialDirectory = PATH; OpenDialog.FilterIndex = 0; if (OpenDialog.ShowDialog() == DialogResult.OK) { Tasks.RandomPathTask.Options.Zones.Clear(); string ZoneFilename = OpenDialog.FileName; Logger.AddDebugText(Tc.rtbDebug, string.Format(@"Nav file loaded = {0}", ZoneFilename)); try { Tasks.RandomPathTask.Options.Zones = XmlSerializationHelper.Deserialize <List <Zones> >(ZoneFilename) ?? new List <Zones>(); OpenDialog.Dispose(); Logger.AddDebugText(Tc.rtbDebug, string.Format(@"Added {0} Zones", Tasks.RandomPathTask.Options.Zones.Count.ToString())); foreach (var item in Tasks.RandomPathTask.Options.Zones) { Tc.mapLB.Items.Add(item.id); } } catch (Exception ex) { Logger.AddDebugText(Tc.rtbDebug, string.Format(@"LoadZones error {0}", ex.ToString())); } } }
public void LoadPointsOfInterest() { OpenFileDialog OpenDialog = new OpenFileDialog(); Tc.PointsComboBox.Items.Clear(); string PATH = (string.Format(Application.StartupPath + "\\Documents\\Points of intrest")); OpenDialog.InitialDirectory = PATH; OpenDialog.FilterIndex = 0; if (OpenDialog.ShowDialog() == DialogResult.OK) { Navi.Reset(); Points.Clear(); string PointsFilename = OpenDialog.FileName; Logger.AddDebugText(Tc.rtbDebug, string.Format(@"Nav file loaded = {0}", PointsFilename)); try { Points = XmlSerializationHelper.Deserialize <List <PointsOfInterest> >(PointsFilename) ?? new List <PointsOfInterest>(); OpenDialog.Dispose(); foreach (var item in Points) { Tc.PointsComboBox.Items.Add(item.Name); } Logger.AddDebugText(Tc.rtbDebug, string.Format(@"Added {0} Points of interest", Points.Count.ToString())); Tc.PointsComboBox.SelectedIndex = 0; } catch (Exception ex) { Logger.AddDebugText(Tc.rtbDebug, string.Format(@"LoadWaypoints error {0}", ex.ToString())); } } }
public string ModifySingleApp(string valueToModify, CustomizationContextData context) { Tracer.TraceInfo("Single Resource only"); if (!DoesCustomizationApply(context)) { return(valueToModify); } // turn the input string into the single resource object // NB it's a string that happens to be an XML document, if you want to manipulate it in any // other way, feel free... var sRes = singleResourceSerializer.Deserialize(valueToModify); TraceResource(sRes); // Apply the customisation logic to this resource. if (FixupResourceForCallCenter(sRes)) { string newResDoc = singleResourceSerializer.Serialize(sRes); Tracer.TraceInfo("Returning modified resource doc: {0}", newResDoc); return(newResDoc); } // false return from the above indicates we want to discard this element. Tracer.TraceInfo("//BUGBUG Need to return empty element..."); // no work to do here...will fall through to revert to original return(valueToModify); }
/// <summary> /// The prepair xml. /// </summary> /// <param name="file"> /// The file. /// </param> /// <param name="cqtasks"> /// The cq tasks. /// </param> /// <param name="oid"> /// The oid. /// </param> /// <returns> /// The <see cref="int"/>. /// </returns> private int PrepairXml(FileInfo file, ConcurrentQueue <Organisation> cqtasks, Oid oid) { var packet = new Packet(); packet = (Packet)XmlSerializationHelper.Deserialize(file.FullName, packet); PrepairList(packet, cqtasks, oid); return(cqtasks.Count); }
public void XmlSerializeDocument701() { // получили 601 => создали на его основе 701 var doc601 = XmlSerializationHelper.Deserialize(Doc601xml); var doc701 = CreateDocument701(doc601); var xml = XmlSerializationHelper.Serialize(doc701, " Подтверждение из Автомойки "); WriteLine(xml); }
/// <summary> /// Initializes a new instance of the <see cref="NavTask"/> class. /// </summary> /// <param name="Character">The character.</param> public NavTask(Character Character) : base(Character) { Options = XmlSerializationHelper.Deserialize <Options>(FileName) ?? new Options(); TS = new Taskstate(Character, Options); TS.Stopped += Stop; Engine = new StateEngine(); InitializeStateEngine(); }
protected void btnEncrypt_Click(object sender, EventArgs e) { ZlList obj = new ZlList(); XmlSerializer serializer = new XmlSerializer(typeof(ZlList)); using (FileStream fs = new FileStream(@"c:\Projects\PolicyDistributionPoint\ExchangeTask\063131RS01002.xml", FileMode.Open, FileAccess.Read)) { obj = (ZlList)serializer.Deserialize(fs); } XmlSerializationHelper.Deserialize(@"c:\Projects\PolicyDistributionPoint\ExchangeTask\063131RS01002.xml", obj); // Encryption(true); }
public void XmlSerializationHelperSetsXsdSchemaVersionIfNotSpecified() { var doc = new Documents(); Assert.True(string.IsNullOrWhiteSpace(doc.Version)); var xml = XmlSerializationHelper.Serialize(doc); doc = XmlSerializationHelper.Deserialize(xml); Assert.False(string.IsNullOrWhiteSpace(doc.Version)); Assert.AreEqual(XmlSerializationHelper.DocumentSchemaVersion, doc.Version); }
public override object GetValue(FunctionContextContainer contextContainer, Type type) { Verify.ArgumentNotNull(contextContainer, "contextContainer"); Verify.ArgumentNotNull(type, "type"); if (_attribute != null) { return(XmlSerializationHelper.Deserialize(_attribute, type)); } return(ValueTypeConverter.Convert(_constantValue, type)); }
public string Modify(string valueToModify, CustomizationContextData context) { // For this example, we're going to alter resources if the user in question is a member of // the 'Callcenter Users' group. Tracer.TraceInfo("Resource SDK Enumeration customisation"); Tracer.TraceInfo(context.ToString()); try { if (!DoesCustomizationApply(context)) { return(valueToModify); } // we have a full list of enumerated resources Tracer.TraceInfo("Full Resource List"); var resources = resourcesSerializer.Deserialize(valueToModify); var editres = new List <resourceType>(); // Accumulate resultant resources in list foreach (resourceType r in resources.resource) { Tracer.TraceInfo("Evaluating Resource... "); TraceResource(r); // apply our customisation logic to this resource // only preserve resources in the list is we get a true return from the customisation method if (FixupResourceForCallCenter(r)) { editres.Add(r); } } // Back to array to include in resources object. resources.resource = editres.ToArray(); // Re-serialise into string string newDoc = resourcesSerializer.Serialize(resources); // Return modified XML document for further use. return(newDoc); } catch (Exception outer) { Tracer.TraceInfo("Exception in customization: {0}" + outer); // Revert to pre-customisation enumeration value. return(valueToModify); } }
/// <summary> /// The read configuration. /// </summary> /// <returns> /// The <see cref="ConfigData"/>. /// </returns> /// <exception cref="ApplicationException"> /// </exception> public ConfigData ReadConfiguration() { try { return(XmlSerializationHelper.Deserialize <ConfigData>(EnvirenmentHelper.ConfigFilePath)); } catch (Exception exception) { if (exception is FileNotFoundException || exception is ApplicationException) { throw; } throw new ApplicationException("Unexpected error occured.", exception); } }
public string Modify(string valueToModify, CustomizationContextData context) { // Example: we set the ClientTabletOS Access Condition in the InputModifer CustomizeAccessCondiitions // example, but this would equally apply to any externally set access condition. // // The presence of this Session Customization point is to provide consistent control for scenarios // where access to resources is dynamically controlled. As well as limiting visibility to resource // enumeration, block the clients 'view' of any active sessions for such apps which may have been established // in a permitted context. if (!HasAccessCondition(context, "ClientTabletOS")) { // No changes required as context not applicable return(valueToModify); } Tracer.TraceInfo("Session filtering customization applies"); var sessions = serializer.Deserialize(valueToModify); var resultantList = new List <sessionType>(); foreach (sessionType s in sessions.sessions) { TraceSession(s); // Having NT in the resource internal name used as shorthand for 'No Tablets'in this example // Note: limited info on the apps in the target session is available here so either use an explicit // list of apps or have some encoding in the available data. if (!s.initialapp.Contains("NT")) { resultantList.Add(s); } } sessions.sessions = resultantList.ToArray(); string newSessions = serializer.Serialize(sessions); if (newSessions == null) { Tracer.TraceInfo("Failure to reform session document, revert to original"); return(valueToModify); } Tracer.TraceInfo("Resultant Session String: {0}", newSessions); return(newSessions); }
/// <summary> /// Gets simple parameter value from it's markup. /// </summary> /// <returns></returns> public static object GetParameterValue(XElement parameterNode, ParameterProfile parameterProfile) { List <XElement> parameterElements = parameterNode.Elements(ParameterValueElementXName).ToList(); if (parameterElements.Any()) { return(parameterElements.Select(element => element.Attribute("value").Value).ToList()); } var valueAttr = parameterNode.Attribute("value"); if (valueAttr != null) { try { return(XmlSerializationHelper.Deserialize(valueAttr, parameterProfile.Type)); } catch (Exception ex) { Log.LogError(LogTitle, ex); return(parameterProfile.GetDefaultValue()); } } if (parameterNode.Elements().Any()) { Type paramType = parameterProfile.Type; if (paramType.IsSubclassOf(typeof(XContainer)) || (paramType.IsLazyGenericType() && paramType.GetGenericArguments()[0].IsSubclassOf(typeof(XContainer)))) { return(ValueTypeConverter.Convert(parameterNode.Elements().First(), parameterProfile.Type)); } throw new NotImplementedException("Not supported type of function parameter element node: '{0}'".FormatWith(paramType.FullName)); } return(parameterProfile.GetDefaultValue()); }
static void Main(string[] args) { string baseUri = "http://localhost:8000/"; string city = "Poznań"; string specialization = "Neurology"; string visitor = "Adrian Karalus"; //TimeSlotsRepository timeSlotsRepo = new TimeSlotsRepository(); //DoctorsRepository doctorsRepo = new DoctorsRepository(); //foreach (var doc in doctorsRepo.GetAll()) //{ // for (int i = 0; i < 10; i++) // { // timeSlotsRepo.Add(doc.Id, DateTime.Now.AddHours(i)); // timeSlotsRepo.Save(); // } //} //var response = WebHelper.GetWebResponseString(baseUri + "Doctorsxml", WebMethod.GET); //var doctors = XmlSerializationHelper.Deserialize<DoctorModel[]>(response); //doctorsRepo.Save(); var response = WebHelper.Get(baseUri + string.Format("DoctorsXML/{0}/{1}", specialization, city)); var doctors = XmlSerializationHelper.Deserialize <DoctorModel[]>(response); var doctor = doctors.First(d => d.TimeSlots.Any(ts => string.IsNullOrEmpty(ts.Visitor))); var freeTimeSlot = doctor.TimeSlots.First(ts => string.IsNullOrEmpty(ts.Visitor)); var uri = baseUri + string.Format("DoctorXML/{0}/TimeSlot/{1}", doctor.Id, freeTimeSlot.Id); var postResponse = WebHelper.Post(uri, visitor); Console.ReadKey(); }
/// <summary> /// Gets the winning genome instance. /// </summary> /// <returns>Return the winning genome instance</returns> public static WinningGenome GetWinningGenomeInstance() { if (instance == null) { lock (Lock) { if (instance == null) { if (File.Exists(filepath)) { instance = XmlSerializationHelper.Deserialize <WinningGenome>(filepath); } else { //create new file and save it instance = new WinningGenome(); instance.Serialize(filepath); } } } } return(instance); }
/// <summary> /// Обработка /// </summary> /// <param name="file"> /// Путь к файлу загрузки /// </param> /// <param name="context"> /// The context. /// </param> /// <returns> /// был ли обработан пакет /// </returns> public override bool Processing(FileInfo file, IJobExecutionContext context) { var logger = LogManager.GetCurrentClassLogger(); var conceptManager = ObjectFactory.GetInstance <IConceptCacheManager>(); // Попытка десериализации файла и создание батча var operList = new OPListType(); Batch batch; try { // Десериализация operList = XmlSerializationHelper.Deserialize(file.FullName, operList) as OPListType; // Создание батча batch = CreateBatch(operList); } catch (Exception ex) { // Ошибка десериализации либо создания бачта logger.Error(ex.Message, ex); throw; } // Вычисляем код ПВП var splittedFileName = batch.FileName.Split(new[] { '_' }); if (splittedFileName.Length == 3) { } // Создаем экспортер для файлов ответа и стартуем батч var repExp = ObjectFactory.GetInstance <IExporterBatchFactory <REPListType, REPType> >().GetExporter(Exporters.SmoRepExporter); repExp.FileName = batch.FileName.Replace("i", "p"); // Меняем префикс в имени файла ответа repExp.Number = batch.Number; repExp.PeriodId = batch.Period.Id; repExp.SenderId = batch.Receiver.Id; repExp.ReceiverId = batch.Sender.Id; repExp.BeginBatch(); // Создаем экспортер для файлов ответа c протоколом ФЛК и стартуем батч var flkRepExp = ObjectFactory.GetInstance <IExporterBatchFactory <PFLKType, PRType> >().GetExporter(Exporters.SmoFlkExporter); flkRepExp.FileName = batch.FileName.Replace("i", "f"); // Меняем префикс в имени файла ответа flkRepExp.Number = batch.Number; flkRepExp.PeriodId = batch.Period.Id; flkRepExp.SenderId = batch.Receiver.Id; flkRepExp.ReceiverId = batch.Sender.Id; flkRepExp.BeginBatch(); // Проход по записям, маппинг и сохранение заявления bool goodAnswer; if (operList != null) { foreach (var op in operList.OP) { Statement statement = null; try { // Маппинг statement = MapStatement(op); // Сохраняем заявление // Создаем Message var message = new Message(); message.Batch = batch; message.IsCommit = true; message.IsError = false; message.Type = conceptManager.GetById(TransactionCode.K); ObjectFactory.GetInstance <ISessionFactory>().GetCurrentSession().Save(message); // Создаем MessageStatement var messageStat = new MessageStatement(); messageStat.Statement = statement; messageStat.Message = message; messageStat.Version = statement.Version; messageStat.Type = conceptManager.GetById(MessageStatementType.MainStatement); ObjectFactory.GetInstance <ISessionFactory>().GetCurrentSession().Save(messageStat); // Сбрасываем изменения в БД ObjectFactory.GetInstance <ISessionFactory>().GetCurrentSession().Flush(); goodAnswer = true; } catch (LogicalControlException ex) { // ошибка ФЛК logger.Info(ex.Message, ex); logger.Info(op); logger.Info(statement); goodAnswer = false; // Пишем ошибки ФЛК в ответ foreach (var err in ex.LogicalControlExceptions) { // Пишем ошибки ФЛК в ответ var flkAnswer = new PRType(); flkAnswer.N_REC = op.N_REC; flkAnswer.OSHIB = err.Info.Code; flkAnswer.COMMENT = err.Message; flkRepExp.AddNode(flkAnswer); } } catch (Exception ex) { logger.Error(ex.Message, ex); logger.Error(op); logger.Error(statement); goodAnswer = false; } // Пишем ответ var answer = new REPType(); answer.N_REC = op.N_REC; answer.ID = op.ID; answer.CODE_ERP = goodAnswer ? CodeConfirm.AA : CodeConfirm.CA; repExp.AddNode(answer); } } // Коммитим батч ответа repExp.CommitBatch(); // Коммитим батч ответа ФЛК flkRepExp.CommitBatch(); return(true); }
/// <summary> /// Обработка /// </summary> /// <param name="file"> /// Путь к файлу загрузки /// </param> /// <param name="context"> /// The context. /// </param> /// <returns> /// был ли обработан пакет /// </returns> public override bool Processing(FileInfo file, IJobExecutionContext context) { var logger = LogManager.GetCurrentClassLogger(); // Попытка десериализации файла var personErp = new PersonErp(); try { // Десериализация personErp = XmlSerializationHelper.Deserialize(file.FullName, personErp) as PersonErp; } catch (Exception ex) { // Ошибка десериализации либо создания бачта logger.Error(ex.Message, ex); throw; } // Получаем идентификатор батча var batchId = Guid.Empty; if (personErp != null && personErp.BeginPacket != null) { Guid.TryParse(personErp.BeginPacket.Identificator, out batchId); } if (batchId == Guid.Empty) { logger.Error("Не верный идентификатор пакета. Имя файла: " + file.FullName); return(false); } var session = ObjectFactory.GetInstance <ISessionFactory>().GetCurrentSession(); if (personErp == null || personErp.AckList == null) { return(false); } // Парсим ошибки ФЛК от шлюза foreach (var ack in personErp.AckList) { var messageId = Guid.Empty; Guid.TryParse(ack.Msa.ReferenceIdentificator, out messageId); // Получаем ссылку на заявление var statement = session.QueryOver <Statement>() .JoinQueryOver <MessageStatement>(s => s.MessageStatements) .Where(ms => ms.Message.Id == messageId) .List() .FirstOrDefault(); if (statement == null) { logger.Error("Отсутствует заявление"); return(false); } // Удаляем предыдущие ошибки var oldErrors = session.QueryOver <Error>() .Where(x => x.Statement.Id == statement.Id && x.Application.Id == ExchangeSubjectType.Erz) .List(); foreach (var oldError in oldErrors) { session.Delete(oldError); } session.Flush(); // Пишем ошибки в Errors var wasError = false; foreach (var uprErr in personErp.AckList.FirstOrDefault().ErrList) { // Пропускаем предупреждения if (uprErr.LevelSeriously != "E") { continue; } // Создаем запись в БД var error = new Error(); error.Statement = statement; error.Application = ObjectFactory.GetInstance <IConceptCacheManager>().GetById(ExchangeSubjectType.Erz); error.Code = uprErr.ErrorCodeApp.MessageCode; error.Message1 = uprErr.ErrorCodeApp.MessageDescription; error.Repl = "Ошибки ФЛК шлюза РС"; session.Save(error); // Взводим флаг ошибки wasError = true; } if (wasError) { // Меняем статус заявления на отклонено statement.Status = ObjectFactory.GetInstance <IConceptCacheManager>().GetById(StatusStatement.Cancelled); session.Save(statement); // Пишем ошибку в сообщение var message = ObjectFactory.GetInstance <IMessageManager>().GetById(messageId); if (message != null) { message.IsError = true; session.Save(message); } } // Чистим сессию session.Flush(); } return(true); }
/// <summary> /// Loads the settings. /// </summary> /// <param name="File">The file.</param> public void LoadSettings(string File) { Options = XmlSerializationHelper.Deserialize <Options>(File) ?? new Options(); }
//Load XML public static void Load() { Config = XmlSerializationHelper.Deserialize <config>(InterProcessCom.ConfigPath); }
/// <summary> /// Обработка /// </summary> /// <param name="file"> /// Путь к файлу загрузки /// </param> /// <param name="context"> /// The context. /// </param> /// <returns> /// был ли обработан пакет /// </returns> public override bool Processing(FileInfo file, IJobExecutionContext context) { var logger = LogManager.GetCurrentClassLogger(); var conceptManager = ObjectFactory.GetInstance <IConceptCacheManager>(); // Попытка десериализации файла и создание батча var recList = new RECListType(); Batch batch = null; try { // Десериализация recList = XmlSerializationHelper.Deserialize(file.FullName, recList) as RECListType; // Создание батча // batch = CreateBatch(recList); } catch (Exception ex) { // Ошибка десериализации logger.Error(ex.Message, ex); throw; } // Проход по записям, маппинг и сохранение заявления if (recList != null) { foreach (var rec in recList.REC) { Statement statement = null; try { // Маппинг statement = MapStatement(rec); // Сохраняем заявление // ObjectFactory.GetInstance<IStatementManager>().ReplicateStatement(statement, GetPdpCodeFromFileName(batch.FileName)); // Создаем Message var message = new Message(); message.Batch = batch; message.IsCommit = true; message.IsError = false; message.Type = conceptManager.GetById(TransactionCode.K); ObjectFactory.GetInstance <ISessionFactory>().GetCurrentSession().Save(message); // Создаем MessageStatement var messageStat = new MessageStatement(); messageStat.Statement = statement; messageStat.Message = message; messageStat.Version = statement.Version; messageStat.Type = conceptManager.GetById(MessageStatementType.MainStatement); ObjectFactory.GetInstance <ISessionFactory>().GetCurrentSession().Save(messageStat); // Сбрасываем изменения в БД ObjectFactory.GetInstance <ISessionFactory>().GetCurrentSession().Flush(); } catch (LogicalControlException ex) { // ошибка ФЛК logger.Info(ex.Message, ex); logger.Info(rec); logger.Info(statement); } catch (Exception ex) { logger.Error(ex.Message, ex); logger.Error(rec); logger.Error(statement); } } } return(true); }
private void Button_Click(object sender, RoutedEventArgs e) { IntPtr hModule; StartButton.IsEnabled = false; //Serialize configuration XML. var eradstyle = XmlSerializationHelper.Deserialize <config>("config.xml"); //Make a List of ffxiv process IDs for later use. var pidList = Process.GetProcessesByName("ffxiv").Select(p => p.Id).ToList(); //Check if we found any ffxiv processes running. if (!pidList.Any()) { MessageBox.Show("No FFXIV process is active."); StartButton.IsEnabled = true; return; } //Set our current pid. var pid = pidList[ProcessListBox.SelectedIndex]; //Get handle for the selected ffxiv process. var hProc = _mapper.OpenHan(0x001F0FFF, pid); //Check if the CLR is already loaded into the selected process. if (Process.GetProcessById(pid).Modules.Cast <ProcessModule>().Any(mod => mod.ModuleName == "clr.dll")) { hModule = eradstyle.MemInfo.First(id => id.ID == pid).hModule; } //CLR not loaded. Map new instance of the CLR, into the ffxiv process. else { hModule = _mapper.Inject(Properties.Resources.Link, hProc); if (hModule == IntPtr.Zero) { MessageBox.Show("Something blocked Bolter from loading, Check any Virus Scanners, or Windows Restrictions"); StartButton.IsEnabled = true; return; } } var mainNamespace = MainNamespaceOfPlugin(PluginsBox.SelectedItem.ToString()); var pInfo = new PassInfo { DomainName = mainNamespace, FilePath = string.Format("{0}\\{1}.dll", Directory.GetCurrentDirectory(), PluginsBox.SelectedItem), Raw = 0, InterProcClass = string.Format("{0}.InterProcessCom", mainNamespace) }; var ppInfo = Marshal.AllocHGlobal(Marshal.SizeOf(typeof(PassInfo))); Marshal.StructureToPtr(pInfo, ppInfo, true); // Allocate memory in ffxiv to hold the parameters struct. var pathPtr = _mapper.AllocMem(hProc, (uint)Marshal.SizeOf(typeof(PassInfo)), 0x1000 | 0x2000, 0x04); SigScan.WriteProcessMemory(hProc, pathPtr, ppInfo, (uint)Marshal.SizeOf(typeof(PassInfo)), new UIntPtr()); Marshal.FreeHGlobal(ppInfo); // Get pointer for the Load Assembly function, inside our unmanaged CLR host DLL. var routinePtr = _mapper.GetFuncPointer(hProc, hModule, "LoadIt"); // Remove old pids eradstyle.MemInfo.RemoveAll(pe => !pidList.Contains(pe.ID) || pe.ID == pid); // Add current pid. eradstyle.MemInfo.Add(new PastProcess { ID = pid, hModule = hModule }); // Save configuration. XmlSerializationHelper.Serialize("config.xml", eradstyle); // Create remote thread in the selected ffxiv process starting at the Load Assembly routine. var ntThread = _mapper.CreateThread(hProc, routinePtr, pathPtr); // Wait for completion or 2000ms. _mapper.WaitForEvent(ntThread, 2000); // Close handles. _mapper.CloseHan(ntThread); _mapper.CloseHan(hProc); StartButton.IsEnabled = true; }
/// <summary> /// Instantiates new GatherHelper class, and loads our Waypoints /// </summary> public GatherHelper() { var filepath = InterProcessCom.ConfigPath.Replace("config.xml", "waypoints.xml"); _Waypoints = !File.Exists(filepath) ? new Waypoints() : XmlSerializationHelper.Deserialize <Waypoints>(filepath); }
//Handler for loading the XML private void Load_XML(object sender, RoutedEventArgs e) { Config = XmlSerializationHelper.Deserialize <config>(InterProcessCom.ConfigPath); ConfigWrapper.RefreshAreaBox(AreaPOS_Box); }
public void Reload() { XmlSerializationHelper.Serialize(InterProcessCom.ConfigPath.Replace("config.xml", "waypoints.xml"), _Waypoints); _Waypoints = XmlSerializationHelper.Deserialize <Waypoints>(InterProcessCom.ConfigPath.Replace("config.xml", "waypoints.xml")); }