private object NodeToValue(XmlNode node, Type valueType) { // сложный объект пусть сам себя разбирает if (typeof(IXmlSerializable).IsAssignableFrom(valueType)) { var doc = new XmlDocument(); doc.LoadXml(node.OuterXml); return(XmlDocumentConverter.ConvertTo(valueType, doc)); } // если ожидаем коллекцию if (typeof(IEnumerable).IsAssignableFrom(valueType) && valueType != typeof(string)) { var itemType = valueType.GetGenericArguments()[0]; // создаем коллекцию var res = (IList)Activator.CreateInstance(typeof(List <>).MakeGenericType(itemType)); foreach (XmlNode n in node.ChildNodes) { var internalValue = NodeToValue(n, itemType); res.Add(internalValue); } return(res); } return(node.Value); }
protected override void Execute(NativeActivityContext context) { var source = Source.Get(context); if (string.IsNullOrEmpty(source)) { throw new DeveloperException("Нет данных для десериализации"); } var xmlDoc = new XmlDocument(); xmlDoc.LoadXml(source); if (xmlDoc.DocumentElement == null) { throw new DeveloperException("Не верный формат исходных данных"); } var result = new List <T>(); foreach (XmlNode node in xmlDoc.DocumentElement.ChildNodes) { var doc = new XmlDocument(); doc.LoadXml(node.OuterXml); var obj = (T)XmlDocumentConverter.ConvertTo(typeof(T), doc); if (IsNew) { var editable = obj as IEditable; if (editable != null) { editable.AcceptChanges(true); } } result.Add(obj); } Result.Set(context, result); }
public void SimpleTest() { const int cnt = 5; using (var mgr = IoC.Instance.Resolve <IBPProcessManager>()) { string manageFlag = string.Empty; string manageParam = string.Empty; var xmlPos = new XmlDocument(); xmlPos.LoadXml("<TENTIWBPOSINPUT><IWBPOSID>-1</IWBPOSID><SKUID>54651</SKUID><IWBPOSCOUNT>0</IWBPOSCOUNT><REQUIREDSKUCOUNT>1</REQUIREDSKUCOUNT><TETYPECODE>EURO</TETYPECODE><SKU2TTEQUANTITY>10000</SKU2TTEQUANTITY><SKU2TTEHEIGHT /><QLFCODE_R>QLFNORMAL</QLFCODE_R><IWBPOSBLOCKING /><IWBPOSEXPIRYDATE /><PRODUCTCOUNTSKU>0</PRODUCTCOUNTSKU><PRODUCTCOUNT>1</PRODUCTCOUNT><ARTCODE>ETN010145</ARTCODE><ARTDESC>F3A-D</ARTDESC><ARTINPUTDATEMETHOD>DAY</ARTINPUTDATEMETHOD><MEASURECODE>шт</MEASURECODE><IWBPOSCOLOR /><IWBPOSTONE /><IWBPOSSIZE /><IWBPOSBATCH /><IWBPOSPRODUCTDATE /><IWBPOSSERIALNUMBER /><FACTORYID_R /><IWBPOSTE>EUROTO201412081020</IWBPOSTE><IWBPOSLOT /><IWBPOSQLFDETAILDESCL /><SKU2TTEQUANTITYMAX>10000</SKU2TTEQUANTITYMAX><IWBPOSINPUTBATCHCODE /><IWBPOSBOXNUMBER /><IWBPOSKITARTNAME /><IWBPOSOWNER /><REMAINCOUNT /><POSSKUID /><POSIWBPOSCOUNT /><POSPRODUCTCOUNT /><SKUNAME /><TETYPENAME /><ARTNAME /><MEASURESHORTNAME /><QLFNAME /><PRODUCTBLOCKINGNAME /><ARTINPUTDATEMETHODNAME /><VFACTORYNAME /><VOWNERCODE /></TENTIWBPOSINPUT>"); var posInput = XmlDocumentConverter.ConvertTo <IWBPosInput>(xmlPos); long totalElapsedMilliseconds = 0; for (int i = 0; i < cnt; i++) { var sw = new Stopwatch(); sw.Start(); var products = mgr.CreateProductByCargoIwb(ref manageFlag, ref manageParam, "OP_INPUT_PRD", posInput, "41D01001000000000", 6508); sw.Stop(); totalElapsedMilliseconds += sw.ElapsedMilliseconds; Debug.WriteLine("create {0} products in {1} ms", products == null ? 0 : products.Count, sw.ElapsedMilliseconds); } Debug.WriteLine("Total time is {0} ms ({1} per call)", totalElapsedMilliseconds, totalElapsedMilliseconds / cnt); } }
public void Test() { //var res = new OtherClass() //{ // Items = new SerializableDictionary<string, List<SomeClass>>() //}; var source = new SerializableDictionary <string, List <PMConfig> >(); source.Add("test1", new List <PMConfig> { new PMConfig() { ObjectName_r = "O1", MethodCode_r = "M1", ObjectEntitycode_R = "E1", PM2OperationCode_r = "OP1" } }); source.Add("test2", new List <PMConfig> { new PMConfig() { ObjectName_r = "O2", MethodCode_r = "M2", ObjectEntitycode_R = "E2", PM2OperationCode_r = "OP2" } }); //res.Items.Add("test1", new List<SomeClass> { new SomeClass() { A = "A1", B = "B1" } }); //res.Items.Add("test2", new List<SomeClass> { new SomeClass() { A = "A2", B = "B2" } }); var xmlDoc = XmlDocumentConverter.ConvertFrom(source); var target = XmlDocumentConverter.ConvertTo <SerializableDictionary <string, List <PMConfig> > >(xmlDoc); }
public PrintStreamConfig GetDefaultPrinter(string tListParams) { return(RunManualDbOperation(db => { var stm = string.Format("select {0}({1}) from dual", "PKGPRINTSTREAMCONFIG.getDefaultPrinter", tListParams); var resXml = db.SetCommand(stm, null).ExecuteScalar <XmlDocument>(); return resXml == null ? null : XmlDocumentConverter.ConvertTo <PrintStreamConfig>(resXml); })); }
public ReportRedefinition GetDefaultReport(string tListParams) { return(RunManualDbOperation(db => { var stm = string.Format("select {0}({1}) from dual", "pkgReportRedefinition.getDefaultReport", tListParams); var resXml = db.SetCommand(stm, null).ExecuteScalar <XmlDocument>(); return resXml == null ? null : XmlDocumentConverter.ConvertTo <ReportRedefinition>(resXml); })); }
public TestObject GetImageTestObject() { XmlDocument xmlDoc = null; using (var db = GetDbManager()) { xmlDoc = db.SetCommand("select spftstgetImage from dual").ExecuteScalar <XmlDocument>(); } return(XmlDocumentConverter.ConvertTo <TestObject>(xmlDoc)); }
protected T GetFromRequestBody <T>() where T : class { // TODO: use binding var xmlDoc = new XmlDocument(); xmlDoc.LoadXml(Request.Content.ReadAsStringAsync().Result); if (xmlDoc.DocumentElement == null) { Request.CreateResponse(HttpStatusCode.BadRequest); } return(XmlDocumentConverter.ConvertTo <T>(xmlDoc)); }
public virtual T Get(TKey key, string attrentity) { ClearStatistics(); var attr = XmlDocumentConverter.XmlDocFromString(attrentity); var xmlDoc = XmlGet(key, attr); if (xmlDoc == null) { return(null); } return(XmlDocumentConverter.ConvertTo <T>(xmlDoc)); }
private object GetValueFromNode(Node node, Type valueType) { if (valueType.IsValueType || (typeof(string) == valueType)) { // хитро определяем, что значения нет if (node.Nodes == null) { return(valueType.IsByRef ? null : Activator.CreateInstance(valueType)); } return(SerializationHelper.ConvertToTrueType(node.Value, valueType)); } if (typeof(IEnumerable).IsAssignableFrom(valueType) && valueType != typeof(XmlDocument) && !typeof(IDictionary).IsAssignableFrom(valueType)) { var itemType = valueType.IsGenericType ? valueType.GetGenericArguments()[0] : typeof(string); var listType = valueType.IsInterface ? typeof(List <>).MakeGenericType(itemType) : valueType; var list = (IList)Activator.CreateInstance(listType); foreach (var n in node.Nodes) { list.Add(GetValueFromNode(n, itemType)); } return(list); } // если сложный объект, то разбираем его сложно if (typeof(IXmlSerializable).IsAssignableFrom(valueType) && (node.Value != null || node.Nodes != null)) { if (node.Value != null) { using (var sr = new StringReader(node.Value)) using (var xmlReader = XmlReader.Create(sr)) return(XmlDocumentConverter.ConvertTo(valueType, xmlReader)); } } if (valueType == typeof(XmlDocument)) { if (string.IsNullOrEmpty(node.Value)) { return(null); } var doc = new XmlDocument(); doc.LoadXml(node.Value); return(doc); } return(node.Value); }
public HttpResponseMessage Post() { var uowFactory = IoC.Instance.Resolve <IUnitOfWorkFactory>(); using (var uow = uowFactory.Create(GetUnitOfWorkContext())) { try { var xmlDoc = GetRequestDocument(); using (var mgr = IoC.Instance.Resolve <IBaseManager <T> >()) { uow.BeginChanges(); mgr.SetUnitOfWork(uow, false); // определяем как работать с данными if (!xmlDoc.DocumentElement.Name.EqIgnoreCase("ITEMS")) { var obj = (T)XmlDocumentConverter.ConvertTo(typeof(T), xmlDoc); mgr.Insert(ref obj); uow.CommitChanges(); return(Request.CreateResponse(HttpStatusCode.Created, obj)); } else { var objList = new List <T>(); foreach (XmlNode node in xmlDoc.DocumentElement.ChildNodes) { var doc = new XmlDocument(); doc.LoadXml(node.OuterXml); var obj = (T)XmlDocumentConverter.ConvertTo(typeof(T), doc); objList.Add(obj); } var list = (IEnumerable <T>)objList; mgr.Insert(ref list); uow.CommitChanges(); return(Request.CreateResponse(HttpStatusCode.Created, EntityListResult(list))); } } } catch (Exception ex) { uow.RollbackChanges(); Log.Debug(ex); return(Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex)); } } }
public string ProcessApi(string action, string controller, object request) { if (string.IsNullOrEmpty(action)) { throw new ArgumentNullException("action"); } if (string.IsNullOrEmpty(controller)) { throw new ArgumentNullException("controller"); } var helper = new WebAPIHelper(_url); switch (action.ToUpper()) { case "POST": using (var ms = helper.Post <Stream>(controller, request)) { if (ms != null) { using (var reader = XmlReader.Create(ms)) { var responseXmlDoc = XmlDocumentConverter.ConvertTo <XmlDocument>(reader); if (responseXmlDoc != null) { return(responseXmlDoc.InnerXml); } } } } break; default: throw new NotImplementedException(string.Format("Action '{0}' is not Implemented", action)); } return(null); }
protected override void Execute(NativeActivityContext context) { var source = Source.Get(context); if (string.IsNullOrEmpty(source)) { throw new DeveloperException("Нет данных для десериализации"); } var xmlDoc = new XmlDocument(); xmlDoc.LoadXml(source); var result = (T)XmlDocumentConverter.ConvertTo(typeof(T), xmlDoc); if (IsNew) { var editable = result as IEditable; if (editable != null) { editable.AcceptChanges(true); } } Result.Set(context, result); }
public void SerializableListTest() { var source = new OtherClass() { Items = new SerializableDictionary <string, SerializableList <SomeClass> >() }; source.Items.Add("test1", new SerializableList <SomeClass> { new SomeClass() { A = "A1", B = "B1" } }); source.Items.Add("test2", new SerializableList <SomeClass> { new SomeClass() { A = "A2", B = "B2" } }); var xmlDoc = XmlDocumentConverter.ConvertFrom(source); var target = XmlDocumentConverter.ConvertTo <OtherClass>(xmlDoc); }
public T Post <T>(string controller, object request) where T : class { if (string.IsNullOrWhiteSpace(controller)) { throw new ArgumentException("controller"); } try { var policy = new RetryPolicy(new ErrorDetectionStrategy(), new FixedInterval(Settings.Default.RequestRetryCount, TimeSpan.FromSeconds(Settings.Default.RequestRetryIntervalInSeconds))); return(policy.ExecuteAction(() => { using (var wc = new CustomWebClient()) { wc.BaseAddress = _baseUri; wc.Headers[HttpRequestHeader.ContentType] = "text/xml"; wc.Credentials = WMSEnvironment.Instance.AuthenticatedUser.GetCredentials(); var buffer = Encoding.UTF8.GetBytes(XmlDocumentConverter.ConvertFrom(request).InnerXml); var resp = wc.UploadData(controller, "POST", buffer); if (typeof(WMSBusinessObject).IsAssignableFrom(typeof(T))) { using (var ms = new MemoryStream(resp)) using (var reader = XmlReader.Create(ms)) { return XmlDocumentConverter.ConvertTo <T>(reader); } } else if (typeof(T) == typeof(Stream)) { return new MemoryStream(resp) as T; } else { return (T)Convert.ChangeType(resp, typeof(T)); } } })); } catch (WebException ex) { if (ex.Status != WebExceptionStatus.ProtocolError) { throw; } var response = ex.Response as HttpWebResponse; if (response == null) { throw; } if (response.StatusCode != HttpStatusCode.InternalServerError && response.StatusCode != HttpStatusCode.Unauthorized) { throw; } using (var responseStream = response.GetResponseStream()) using (var reader = XmlReader.Create(responseStream)) { try { var err = XmlDocumentConverter.ConvertTo <HttpError>(reader); throw new Exception(err.ContainsKey("ExceptionMessage") ? string.Format("{0}: {1}", err["ExceptionType"], err["ExceptionMessage"]) : err.Message); } catch (XmlException) { throw new Exception("Could not deserialize error response."); } } } }
public T Get <T>(string controller, string action, NameValueCollection parameters) where T : class { if (string.IsNullOrWhiteSpace(controller)) { throw new ArgumentException("controller"); } try { var policy = new RetryPolicy(new ErrorDetectionStrategy(), new FixedInterval(Settings.Default.RequestRetryCount, TimeSpan.FromSeconds(Settings.Default.RequestRetryIntervalInSeconds))); return(policy.ExecuteAction(() => { using (var wc = new CustomWebClient()) { wc.BaseAddress = _baseUri; wc.Headers[HttpRequestHeader.ContentType] = "text/xml"; // если пользователь не авторизован - пробуем под анонимусом // такое возможно, если мы отрпавляем запросы еще до авторизации wc.Credentials = WMSEnvironment.Instance.AuthenticatedUser == null ? null : WMSEnvironment.Instance.AuthenticatedUser.GetCredentials(); wc.QueryString = parameters; //var buffer = Encoding.UTF8.GetBytes(XmlDocumentConverter.ConvertFrom(request).InnerXml); var url = string.IsNullOrEmpty(action) ? controller : string.Format("{0}/{1}", controller, action); var resp = wc.DownloadData(url); if (typeof(T) == typeof(Stream)) { return new MemoryStream(resp) as T; } using (var ms = new MemoryStream(resp)) using (var reader = XmlReader.Create(ms)) { return XmlDocumentConverter.ConvertTo <T>(reader); } } })); } catch (WebException ex) { if (ex.Status != WebExceptionStatus.ProtocolError) { throw; } var response = ex.Response as HttpWebResponse; if (response == null) { throw; } if (response.StatusCode != HttpStatusCode.InternalServerError) { throw; } using (var responseStream = response.GetResponseStream()) using (var reader = XmlReader.Create(responseStream)) { try { var err = XmlDocumentConverter.ConvertTo <HttpError>(reader); throw new Exception(err.ContainsKey("ExceptionMessage") ? string.Format("{0}: {1}", err["ExceptionType"], err["ExceptionMessage"]) : err.Message); } catch (XmlException) { throw new Exception("Could not deserialize error response."); } } } }
private static object NodeToValue(Node node, Type valueType) { //Передаем XmlDocument if (valueType == typeof(XmlDocument)) { if (node.Value == null) { return(null); } var doc = new XmlDocument(); doc.LoadXml(node.Value); return(doc); } // INFO: вынес отдельно от IXmlSerializable чтобы проверить приходит ли документ if (typeof(XmlDocument).IsAssignableFrom(valueType)) { if (node.Value == null) { return(null); } var doc = new XmlDocument(); doc.LoadXml(node.Value); return(XmlDocumentConverter.ConvertTo(valueType, doc)); } // сложный объект пусть сам себя разбирает if (typeof(IXmlSerializable).IsAssignableFrom(valueType)) { var doc = new XmlDocument(); if (node.Value != null) { doc.LoadXml(node.Value); } return(node.Value != null?XmlDocumentConverter.ConvertTo(valueType, doc) : null); } // если ожидаем коллекцию if (IsCollectionType(valueType)) { var itemType = valueType.GetGenericArguments()[0]; // создаем коллекцию var res = (IList)Activator.CreateInstance(typeof(List <>).MakeGenericType(itemType)); foreach (var n in node.Nodes) { var internalValue = NodeToValue(n, itemType); res.Add(internalValue); } return(res); } if (valueType.IsNullable() && node.Value == null) { return(null); } var universalResult = SerializationHelper.ConvertToTrueType(node.Value, valueType); if (universalResult != null) { return(universalResult); } return(node.Value); }
public virtual T Get(TKey key, string attrentity) { var xmlItem = GetXml(key, attrentity); return(XmlDocumentConverter.ConvertTo <T>(xmlItem)); }