public static string Serialize(object oObject, bool Indent = false) { System.Xml.Serialization.XmlSerializer oXmlSerializer = null; System.Text.StringBuilder oStringBuilder = null; System.Xml.XmlWriter oXmlWriter = null; string sXML = null; System.Xml.XmlWriterSettings oXmlWriterSettings = null; System.Xml.Serialization.XmlSerializerNamespaces oXmlSerializerNamespaces = null; // ----------------------------------------------------------------------------------------------------------------------- // Lage XML // ----------------------------------------------------------------------------------------------------------------------- oStringBuilder = new System.Text.StringBuilder(); oXmlSerializer = new System.Xml.Serialization.XmlSerializer(oObject.GetType()); oXmlWriterSettings = new System.Xml.XmlWriterSettings(); oXmlWriterSettings.OmitXmlDeclaration = true; oXmlWriterSettings.Indent = Indent; oXmlWriter = System.Xml.XmlWriter.Create(new System.IO.StringWriter(oStringBuilder), oXmlWriterSettings); oXmlSerializerNamespaces = new System.Xml.Serialization.XmlSerializerNamespaces(); oXmlSerializerNamespaces.Add(string.Empty, string.Empty); oXmlSerializer.Serialize(oXmlWriter, oObject, oXmlSerializerNamespaces); oXmlWriter.Close(); sXML = oStringBuilder.ToString(); return sXML; }
/// <summary> /// Serialize an object into XML /// </summary> /// <param name="serializableObject">Object that can be serialized</param> /// <returns>Serial XML representation</returns> public static string ToXml(this object serializableObject) { string ret = ""; Type serializableObjectType = serializableObject.GetType(); using (System.IO.StringWriter output = new System.IO.StringWriter(new System.Text.StringBuilder())) { System.Xml.Serialization.XmlSerializer s = new System.Xml.Serialization.XmlSerializer(serializableObjectType); System.Xml.Serialization.XmlSerializerNamespaces xsn = new System.Xml.Serialization.XmlSerializerNamespaces(); xsn.Add("", ""); // get a list of the xml type attributes so that we can clean up the xml. In other words. remove extra namespace text. object[] attributes = serializableObjectType.GetCustomAttributes(typeof(System.Xml.Serialization.XmlTypeAttribute), false); if (attributes != null) { System.Xml.Serialization.XmlTypeAttribute xta; for (int i = 0; i < attributes.Length; i++) { xta = (System.Xml.Serialization.XmlTypeAttribute)attributes[i]; //xsn.Add("ns" + 1, xta.Namespace); } } s.Serialize(output, serializableObject, xsn); ret = output.ToString().Replace("utf-16", "utf-8").Trim(); } return ret; }
/// <summary> /// Full constructor. /// </summary> /// <param name="serializer">A pre-configured <see cref="System.Xml.Serialization.XmlSerializer"/> used to serialised property values.</param> /// <exception cref="System.ArgumentNullException">Thrown if <paramref name="serializer"/> is null.</exception> public XmlPropertyRenderer(System.Xml.Serialization.XmlSerializer serializer) { #if CONTRACTS_ONLY BaitExceptionHelper.Throw(); #else if (serializer == null) { throw new ArgumentNullException(nameof(serializer)); } _Serialiser = serializer; _EmptyNamespaces = new System.Xml.Serialization.XmlSerializerNamespaces(); _EmptyNamespaces.Add(String.Empty, String.Empty); #endif }
///xmlファイルの保存 private void xmlSave() { using (System.IO.FileStream FW = new System.IO.FileStream(@"setting.xml", System.IO.FileMode.Create)) { using (System.IO.StreamWriter sw = new System.IO.StreamWriter(FW, Encoding.UTF8)) { System.Xml.Serialization.XmlSerializerNamespaces xsn = new System.Xml.Serialization.XmlSerializerNamespaces(); xsn.Add(string.Empty, string.Empty); System.Xml.Serialization.XmlSerializer xs = new System.Xml.Serialization.XmlSerializer(typeof(setting)); xs.Serialize(sw, Xset); sw.Flush(); } } }
static void LoadConfig() { configFileName = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Speed.xml"); if (File.Exists(configFileName)) { var s = new System.Xml.Serialization.XmlSerializer(typeof(ConfigFile)); var ns = new System.Xml.Serialization.XmlSerializerNamespaces(); ns.Add("", ""); using (System.IO.StreamReader reader = new StreamReader(configFileName)) Config = (ConfigFile)s.Deserialize(reader); } else { Config = new ConfigFile(); } }
static void SaveConfig() { if (File.Exists(configFileName)) { File.SetAttributes(configFileName, FileAttributes.Normal); } var s = new System.Xml.Serialization.XmlSerializer(typeof(ConfigFile)); var ns = new System.Xml.Serialization.XmlSerializerNamespaces(); ns.Add("", ""); using (System.IO.StreamWriter writer = System.IO.File.CreateText(configFileName)) { s.Serialize(writer, Config, ns); writer.Close(); } }
private void _reportListBox_DoubleClick(object sender, EventArgs e) { object reportItem = _reportListBox.SelectedItem; if (reportItem != null) { using (System.IO.StringWriter stringWriter = new System.IO.StringWriter()) { //Create our own namespaces for the output System.Xml.Serialization.XmlSerializerNamespaces ns = new System.Xml.Serialization.XmlSerializerNamespaces(); ns.Add("", ""); System.Xml.Serialization.XmlSerializer x = new System.Xml.Serialization.XmlSerializer(reportItem.GetType()); x.Serialize(stringWriter, reportItem, ns); MessageBox.Show(this, stringWriter.ToString(), reportItem.GetType().ToString()); } } }
/// <summary> /// 对象进行序列化生成XML /// </summary> /// <typeparam name="T">需要序列化的对象类型</typeparam> /// <param name="obj">需要序列化的对象</param> /// <returns>序列化后的XML</returns> public static string SerilizeObject <T>(T obj) { if (obj == null) { return(""); } string ret = ""; using (MemoryStream stream = new MemoryStream()) { try { ret = ""; System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(typeof(T)); XmlWriterSettings s = new XmlWriterSettings(); s.Encoding = Encoding.UTF8; s.OmitXmlDeclaration = true; //s.NamespaceHandling = NamespaceHandling.OmitDuplicates; //s.Indent = true; using (XmlWriter binaryWriter = XmlWriter.Create(stream, s)) { System.Xml.Serialization.XmlSerializerNamespaces ns = new System.Xml.Serialization.XmlSerializerNamespaces(); ns.Add("", ""); serializer.Serialize(binaryWriter, obj, ns); binaryWriter.Flush(); } ret = Encoding.UTF8.GetString(stream.ToArray()); } catch (Exception ex) { Console.WriteLine("SerilizeAnObject Exception: {0}", ex.Message); } finally { stream.Close(); stream.Dispose(); } } return(ret); }
/// <summary> /// Initializes a new instance of the <see cref="ExperimentFactoryReader"/> class. /// </summary> /// <param name="library">The library.</param> /// <param name="experimentLocationRoot">The experiment location root - it can be null in case the experiment belongs to composite component.</param> public ExperimentFactoryReader(Components.IComponentsLibrary library, IEnumerable<IPackageReference> references, string experimentLocationRoot) { if (library == null) throw new ArgumentNullException("library"); m_library = library.GetPackageAwareLibrary(references); m_experimentLocationRoot = experimentLocationRoot; //Create our own namespaces for the output var ns = new System.Xml.Serialization.XmlSerializerNamespaces(); //Add an empty namespace and empty value ns.Add("", ""); m_nodeSerializer = TraceLab.Core.Serialization.XmlSerializerFactory.GetSerializer(typeof(SerializedVertexData), null); m_nodeSerializerWithSize = TraceLab.Core.Serialization.XmlSerializerFactory.GetSerializer(typeof(SerializedVertexDataWithSize), null); }
private static void SaveFile(Osm osm, string path) { var serializer = new System.Xml.Serialization.XmlSerializer(typeof(Osm)); var settings = new System.Xml.XmlWriterSettings(); settings.OmitXmlDeclaration = true; settings.Indent = false; settings.NewLineChars = string.Empty; var emptyNamespace = new System.Xml.Serialization.XmlSerializerNamespaces(); emptyNamespace.Add(string.Empty, string.Empty); using (var resultStream = new FileStream(path, FileMode.Create)) using (var stringWriter = System.Xml.XmlWriter.Create(resultStream, settings)) { serializer.Serialize(stringWriter, osm, emptyNamespace); } }
private string ToOuterXML <T>(T TModel) { string xmlData = String.Empty; System.Xml.Serialization.XmlSerializerNamespaces EmptyNameSpace = new System.Xml.Serialization.XmlSerializerNamespaces(); EmptyNameSpace.Add("", ""); var xmlSerializer = new System.Xml.Serialization.XmlSerializer(typeof(T)); var memoryStream = new System.IO.MemoryStream(); var xmlWriter = new System.Xml.XmlTextWriter(memoryStream, System.Text.Encoding.Default); xmlSerializer.Serialize(xmlWriter, TModel, EmptyNameSpace); memoryStream = (System.IO.MemoryStream)xmlWriter.BaseStream; //xmlData = UTF8ByteArrayToString(memoryStream.ToArray()); xmlData = System.Text.Encoding.Default.GetString(memoryStream.ToArray()); return(xmlData); }
/// <summary> /// XMLファイル書出し /// </summary> /// <typeparam name="T">クラス</typeparam> /// <param name="src">シリアライズ化するクラス</param> /// <param name="savePath">保存パス</param> /// <returns>成功:True/失敗:False</returns> public static Boolean Save <T>(T src, String savePath) where T : class { try { var ns = new System.Xml.Serialization.XmlSerializerNamespaces(); ns.Add(String.Empty, String.Empty); // 読み込み用オブジェ作成 var serializer = new System.Xml.Serialization.XmlSerializer(typeof(T)); // 書き込み using (var sw = new StreamWriter(savePath, FILE_OVERWRITE, new UTF8Encoding(false))) { serializer.Serialize(sw, src, ns); } } catch (Exception) { return(false); } return(true); }
public static string ToXml(object obj) { using (var writer = new System.IO.StringWriter()) { var settings = new System.Xml.XmlWriterSettings(); settings.OmitXmlDeclaration = true; settings.Indent = true; settings.IndentChars = "\t"; var xmlWriter = System.Xml.XmlWriter.Create(writer, settings); var ns = new System.Xml.Serialization.XmlSerializerNamespaces(); ns.Add(string.Empty, "http://www.w3.org/2001/XMLSchema-instance"); ns.Add(string.Empty, "http://www.w3.org/2001/XMLSchema"); var serializer = new System.Xml.Serialization.XmlSerializer(obj.GetType()); serializer.Serialize(xmlWriter, obj, ns); return(writer.ToString()); } }
public void Save() { List <Trigger> list = _sortedlist.Values.ToList(); try { System.Xml.Serialization.XmlSerializerNamespaces ns = new System.Xml.Serialization.XmlSerializerNamespaces(); ns.Add(String.Empty, String.Empty); using (System.IO.TextWriter writer = new System.IO.StreamWriter(_filepath)) { System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(typeof(List <Trigger>)); serializer.Serialize(writer, list, ns); } }catch (Exception e) { System.Diagnostics.Debug.WriteLine(e.ToString()); } }
/// <summary> /// Initializes a new instance of the <see cref="ExperimentFactoryReader"/> class. /// </summary> /// <param name="library">The library.</param> /// <param name="experimentLocationRoot">The experiment location root - it can be null in case the experiment belongs to composite component.</param> public ExperimentFactoryReader(Components.IComponentsLibrary library, IEnumerable <IPackageReference> references, string experimentLocationRoot) { if (library == null) { throw new ArgumentNullException("library"); } m_library = library.GetPackageAwareLibrary(references); m_experimentLocationRoot = experimentLocationRoot; //Create our own namespaces for the output var ns = new System.Xml.Serialization.XmlSerializerNamespaces(); //Add an empty namespace and empty value ns.Add("", ""); m_nodeSerializer = TraceLab.Core.Serialization.XmlSerializerFactory.GetSerializer(typeof(SerializedVertexData), null); m_nodeSerializerWithSize = TraceLab.Core.Serialization.XmlSerializerFactory.GetSerializer(typeof(SerializedVertexDataWithSize), null); }
public static void SerializeToXml <T>(T ThisTypeInstance, System.IO.TextWriter tw) { if (ThisTypeInstance == null) { throw new NullReferenceException("ThisTypeInstance"); } System.Xml.Serialization.XmlSerializerNamespaces ns = GetSerializerNamespaces(ThisTypeInstance.GetType()); System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(ThisTypeInstance.GetType()); using (System.IO.TextWriter twTextWriter = tw) { // serializer.Serialize(twTextWriter, ThisTypeInstance); serializer.Serialize(twTextWriter, ThisTypeInstance, ns); twTextWriter.Close(); } // End Using twTextWriter serializer = null; } // End Sub SerializeToXml
} // End Function SerializeToXml public static System.Xml.Serialization.XmlSerializerNamespaces GetSerializerNamespaces(System.Type t) { System.Xml.Serialization.XmlSerializerNamespaces ns = new System.Xml.Serialization.XmlSerializerNamespaces(); object[] attribs = t.GetCustomAttributes(typeof(System.Xml.Serialization.XmlRootAttribute), false); bool hasXmlRootAttribute = attribs.Length > 0; if (hasXmlRootAttribute) { System.Xml.Serialization.XmlRootAttribute xa = (System.Xml.Serialization.XmlRootAttribute)(attribs[0]); string nameSpace = xa.Namespace; ns.Add("", xa.Namespace); } else { ns.Add("", ""); } return(ns); }
/// <summary> /// 将 obj 序列化成 xml /// </summary> /// <param name="obj"></param> /// <returns></returns> public static string Serialize(this object obj) { System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(obj.GetType()); System.IO.Stream stream = new System.IO.MemoryStream(); //此部分是为了去除默认命名空间xmlns:xsd和xmlns:xsi @chuchur 2014年1月11日 20:07:39 System.Xml.Serialization.XmlSerializerNamespaces ns = new System.Xml.Serialization.XmlSerializerNamespaces(); ns.Add("", ""); // System.Xml.XmlTextWriter xtWriter = new System.Xml.XmlTextWriter(stream, System.Text.Encoding.UTF8); serializer.Serialize(xtWriter, obj, ns); xtWriter.Flush(); stream.Seek(0, System.IO.SeekOrigin.Begin); using (System.IO.StreamReader reader = new System.IO.StreamReader(stream, System.Text.Encoding.UTF8)) { string result = reader.ReadToEnd(); reader.Close(); return(result); } }
/// <summary> /// Serialize a Object to XML by using the Stream. /// </summary> /// <typeparam name="T">Type of the given Object</typeparam> /// <param name="objectToWrite">Object to be serialized</param> /// <param name="stream">Stream - object for Serializing</param> /// <returns>Returns True if the Serializing was OK. Returns false if the Serializing fails</returns> public bool WriteXmlToStream <T>(T objectToWrite, Stream stream) { XmlWriterSettings xmlSettings = SetXmlWriterSettings(); System.Xml.Serialization.XmlSerializer serializer = null; try { serializer = GetXmlSerializer(typeof(T)); using (XmlWriter writer = XmlWriter.Create(stream, xmlSettings)) { if (this.EmptyNamespaces) { var xmlns = new System.Xml.Serialization.XmlSerializerNamespaces(); xmlns.Add(string.Empty, string.Empty); serializer.Serialize(writer, objectToWrite, xmlns); } else { serializer.Serialize(writer, objectToWrite); } } //set Stream to the top position stream.Position = 0; return(true); } catch (Exception ex) { this.LastError = BuildLastErrorString(ex); OnLogEvent(ex.ToString()); return(false); } finally { UnMapEvents(serializer); } }
/// <summary> /// /// </summary> /// <typeparam name="T"></typeparam> /// <param name="type"></param> /// <returns></returns> public static string ToXmlString <T>(this T type) { try { System.Xml.Serialization.XmlSerializer xs = new System.Xml.Serialization.XmlSerializer(type.GetType()); System.Xml.Serialization.XmlSerializerNamespaces ns = new System.Xml.Serialization.XmlSerializerNamespaces(); ns.Add("", "http://www.portalfiscal.inf.br/nfe"); using (StringWriter sw = new StringWriter()) { using (XmlWriter value = XmlWriter.Create(sw)) { xs.Serialize(value, type, ns); return(sw.ToString()); } } } catch (Exception ex) { return("Exception - " + ex.ToString()); } }
/// <summary> /// Serialize object to XML. /// <para> /// Object class must implement IXmlSerializable interface. /// </para> /// <code> /// string xml = Energy.Base.Xml.Serialize(myObject, "Root", "org.example.xns"); /// </code> /// </summary> /// <param name="data">Object to serialize</param> /// <param name="root">Root element</param> /// <param name="space">Namespace</param> /// <param name="error">Serialization error message. Empty when no error.</param> /// <returns>XML string</returns> public static string Serialize(object data, string root, string space, out string error) { error = ""; string xml = null; try { lock (_XmlLock) { System.Xml.Serialization.XmlRootAttribute xra = new System.Xml.Serialization.XmlRootAttribute(root); xra.Namespace = space; System.Xml.Serialization.XmlSerializer xs = new System.Xml.Serialization.XmlSerializer(data.GetType(), xra); StringBuilder sb = new StringBuilder(); XmlWriterSettings xws = new XmlWriterSettings() { OmitXmlDeclaration = true }; xws.Indent = true; System.Xml.Serialization.XmlSerializerNamespaces ns = new System.Xml.Serialization.XmlSerializerNamespaces(); ns.Add("", space); XmlWriter xw = XmlWriter.Create(sb, xws); xs.Serialize(xw, data, ns); xml = sb.ToString(); } } catch (Exception x) { if (null != x.InnerException) { error = x.InnerException.Message; } else { error = x.Message; } Energy.Core.Bug.Catch(x); } return(xml); }
public static string Serialize <T>(T targetObject, bool includeXmlDeclaration) { var writerSettings = new System.Xml.XmlWriterSettings(); writerSettings.OmitXmlDeclaration = !includeXmlDeclaration; writerSettings.Indent = true; writerSettings.Encoding = System.Text.Encoding.ASCII; var sb = new System.Text.StringBuilder(); using (var writer = System.Xml.XmlWriter.Create(sb, writerSettings)) { // Clear the default namespace declarations var ns = new System.Xml.Serialization.XmlSerializerNamespaces(); ns.Add(string.Empty, string.Empty); var serializer = new System.Xml.Serialization.XmlSerializer(targetObject.GetType()); serializer.Serialize(writer, targetObject, ns); } return(sb.ToString()); }
public static string ToXml(Object objToXml, bool includeNameSpace) { string buffer; System.IO.StringWriter stWriter = null; try { stWriter = new System.IO.StringWriter(); var xmlSerializer = new System.Xml.Serialization.XmlSerializer(objToXml.GetType()); if (!includeNameSpace) { var xs = new System.Xml.Serialization.XmlSerializerNamespaces(); //To remove namespace and any other inline information tag xs.Add("", ""); xmlSerializer.Serialize(stWriter, objToXml, xs); } else { xmlSerializer.Serialize(stWriter, objToXml); } buffer = stWriter.ToString(); } catch (Exception Ex) { throw Ex; } finally { if (stWriter != null) { stWriter.Close(); } } return(buffer); }
/// <summary> /// Write a given Object to the given XML-File /// </summary> /// <typeparam name="T">Type of the Object to be serialized</typeparam> /// <param name="objectToWrite">Object to be written</param> /// <returns>Return True on Success. Returns false on fail</returns> public bool WriteXmlFile <T>(T objectToWrite) { XmlWriterSettings xmlSettings = SetXmlWriterSettings(); System.Xml.Serialization.XmlSerializer serializer = null; try { serializer = GetXmlSerializer(typeof(T)); using (XmlWriter writer = XmlWriter.Create(this.ConfigurationFileName, xmlSettings)) { if (this.EmptyNamespaces) { var xmlns = new System.Xml.Serialization.XmlSerializerNamespaces(); xmlns.Add(string.Empty, string.Empty); serializer.Serialize(writer, objectToWrite, xmlns); } else { serializer.Serialize(writer, objectToWrite); } } return(true); } catch (Exception ex) { this.LastError = BuildLastErrorString(ex); OnLogEvent($@"{this.ConfigurationFileName}:{ex.Message}"); return(false); } finally { UnMapEvents(serializer); } }
// Changes for NGT-3035 private static XmlNode SerializeObjectToXmlNode(Object obj) { if (obj == null) { throw new ArgumentNullException("Argument cannot be null"); } XmlNode resultNode = null; System.Xml.Serialization.XmlSerializer xmlSerializer = new System.Xml.Serialization.XmlSerializer(obj.GetType()); System.Xml.Serialization.XmlSerializerNamespaces ns = new System.Xml.Serialization.XmlSerializerNamespaces(); ns.Add("", ""); using (MemoryStream memoryStream = new MemoryStream()) { try { xmlSerializer.Serialize(memoryStream, obj, ns); } catch (InvalidOperationException) { return(null); } memoryStream.Position = 0; XmlDocument doc = new XmlDocument(); // Fix for Xml external entity injection violation in fortify report XmlReaderSettings settings = new XmlReaderSettings(); settings.DtdProcessing = DtdProcessing.Prohibit; settings.XmlResolver = null; XmlReader reader = XmlReader.Create(memoryStream, settings); doc.Load(reader); resultNode = doc.DocumentElement; } return(resultNode); }
public void SearchForCiscoIPPhone(string directory) { CicsoIPPhoneInputType input = new CicsoIPPhoneInputType(); try { input.Prompt = "Entrer un critère de recherche"; input.Title = "Recherche répertoire"; input.InputItem = new CiscoIPPhoneInputItemType[3]; input.InputItem[1] = new CiscoIPPhoneInputItemType(); input.InputItem[1].DefaultValue = " "; input.InputItem[1].DisplayName = "Prénom"; input.InputItem[1].InputFlags = "A"; input.InputItem[1].QueryStringParam = "givenName"; input.InputItem[0] = new CiscoIPPhoneInputItemType(); input.InputItem[0].DefaultValue = " "; input.InputItem[0].DisplayName = "Nom"; input.InputItem[0].InputFlags = "A"; input.InputItem[0].QueryStringParam = "sn"; input.InputItem[2] = new CiscoIPPhoneInputItemType(); input.InputItem[2].DefaultValue = " "; input.InputItem[2].DisplayName = "Numéro de tél"; input.InputItem[2].InputFlags = "T"; input.InputItem[2].QueryStringParam = "telephonenumber"; input.URL = this.Context.Request.Url.AbsoluteUri.Substring(0, this.Context.Request.Url.AbsoluteUri.LastIndexOf("/") + 1) + "GetResultsForCiscoIPPhone?directory=" + System.Web.HttpUtility.UrlEncode(directory) + "&pos=0"; //return input; CicsoIPPhoneInputTypeSerializer xml = new CicsoIPPhoneInputTypeSerializer(); System.Xml.XmlWriterSettings settings = new System.Xml.XmlWriterSettings(); ; settings.Encoding = System.Text.Encoding.UTF8; System.IO.MemoryStream ms = new System.IO.MemoryStream(); System.Xml.XmlWriter xw = System.Xml.XmlWriter.Create(ms, settings); System.Xml.Serialization.XmlSerializerNamespaces xmlnsEmpty = new System.Xml.Serialization.XmlSerializerNamespaces(); xmlnsEmpty.Add("", ""); xml.Serialize(xw, input, xmlnsEmpty); ms.Position = 0; this.Context.Response.ContentType = "text/xml"; this.Context.Response.ContentEncoding = System.Text.Encoding.UTF8; this.Context.Response.Write(GetStringFromStream(ms)); //ms.Flush(); //ms.Close(); } catch (Exception e) { log.Error("Unable to build Cisco Ipphone Input Type: " + e.Message); this.Context.Response.Redirect(this.Context.Request.Url.AbsoluteUri.Substring(0, this.Context.Request.Url.AbsoluteUri.LastIndexOf("/") + 1) + "Error?error=" + System.Web.HttpUtility.UrlEncode(e.Message), false); //return input; } }
public void GetResultsForCiscoIPPhone(string directory, string givenName, string sn, string telephonenumber, string pos) { string gn = "givenName"; string name = "sn"; string tel = "telephonenumber"; string filter = ""; CiscoIPPhoneDirectoryType dir = new CiscoIPPhoneDirectoryType(); List<CiscoIPPhoneDirectoryEntryType> entry = new List<CiscoIPPhoneDirectoryEntryType>(); try { dir.Title = "Recherche répertoire"; foreach (DirectoryType dt in Global.directoryConfiguration) { if (dt.name == directory) { if (dt.Item is SqlDatasourceType) { SqlDatasourceType sdt = dt.Item as SqlDatasourceType; if (sdt.ipphonefilter != null) { gn = sdt.ipphonefilter.firstnamemap; name = sdt.ipphonefilter.lastnamemap; tel = sdt.ipphonefilter.telephonenumbermap; } } else if (dt.Item is LdapDatasourceType) { LdapDatasourceType ldt = dt.Item as LdapDatasourceType; if (ldt.ipphonefilter != null) { gn = ldt.ipphonefilter.firstnamemap; name = ldt.ipphonefilter.lastnamemap; tel = ldt.ipphonefilter.telephonenumbermap; } } else if (dt.Item is CiscoDatasourceType) { CiscoDatasourceType cdt = dt.Item as CiscoDatasourceType; if (cdt.ipphonefilter != null) { gn = cdt.ipphonefilter.firstnamemap; name = cdt.ipphonefilter.lastnamemap; tel = cdt.ipphonefilter.telephonenumbermap; } } filter = gn + " LIKE '" + givenName.Trim() + "*' AND " + name + " LIKE '" + sn.Trim() + "*' AND " + tel + " LIKE '" + telephonenumber.Trim() + "*'"; } } DataTable results = null; int identityCol = 0; int telephoneCol = 0; foreach (DirectoryType dt in Global.directoryConfiguration) { if (dt.name == directory) { FieldFormatter[] ffs = null; if (dt.Item is SqlDatasourceType) { ffs = ((SqlDatasourceType)dt.Item).fieldFormatters; } else if (dt.Item is LdapDatasourceType) { ffs = ((LdapDatasourceType)dt.Item).fieldFormatters; } else if (dt.Item is CiscoDatasourceType) { ffs = ((CiscoDatasourceType)dt.Item).fieldFormatters; } int cpt = 0; foreach (FieldFormatter ff in ffs) { if (ff.fieldType == FieldType.Identity) { identityCol = cpt; } if (ff.fieldType == FieldType.Telephone) { telephoneCol = cpt; } cpt++; } break; } } if (HttpRuntime.Cache.Get(directory + "_" + filter) != null) { results = (DataTable)HttpRuntime.Cache.Get(directory + "_" + filter); } else { if (HttpRuntime.Cache.Get(directory) != null) { DataSet fromCache = (DataSet)HttpRuntime.Cache.Get(directory); DataView dv = null; try { if (fromCache != null) { dv = fromCache.Tables[0].AsDataView(); dv.RowFilter = filter; DataTable calcTable = dv.ToTable("CalcTable"); foreach (DirectoryType dt in Global.directoryConfiguration) { if (dt.name == directory) { FieldFormatter[] ffs = null; List<string> cols = new List<string>(); if (dt.Item is SqlDatasourceType) { ffs = ((SqlDatasourceType)dt.Item).fieldFormatters; } else if (dt.Item is LdapDatasourceType) { ffs = ((LdapDatasourceType)dt.Item).fieldFormatters; } else if (dt.Item is CiscoDatasourceType) { ffs = ((CiscoDatasourceType)dt.Item).fieldFormatters; } foreach (FieldFormatter ff in ffs) { cols.Add(ff.fieldName); if (!calcTable.Columns.Contains(ff.fieldName)) { DataColumn dc = new DataColumn(); dc.DataType = typeof(string); dc.ColumnName = ff.fieldName; dc.Expression = ff.value; calcTable.Columns.Add(dc); } } DataView sortedView = calcTable.AsDataView(); if (cols.Count > 0) { sortedView.Sort = cols[identityCol]; } results = sortedView.ToTable("Results", false, cols.ToArray()); dv = results.AsDataView(); dv.RowFilter = results.Columns[telephoneCol].ColumnName + " <> ''"; results = dv.ToTable(); HttpRuntime.Cache.Insert(directory + "_" + filter, results, null, DateTime.Now.AddMinutes(Double.Parse(System.Web.Configuration.WebConfigurationManager.AppSettings.Get("DMDRefreshTimer"))), System.Web.Caching.Cache.NoSlidingExpiration, System.Web.Caching.CacheItemPriority.Normal, null); break; } } } else { log.Debug("Cache is null, no data to retreive..."); } } catch (Exception e) { log.Error("Error while searching: " + e.Message); } } } if (results.Rows.Count > 0) { if ((Int32.Parse(pos) + 32) >= results.Rows.Count) { dir.Prompt = "Enreg. " + (Int32.Parse(pos) + 1).ToString() + " à " + results.Rows.Count.ToString() + " sur " + results.Rows.Count.ToString(); dir.SoftKey = new CiscoIPPhoneSoftKeyType[4]; dir.SoftKey[0] = new CiscoIPPhoneSoftKeyType(); dir.SoftKey[0].Name = "Compos."; dir.SoftKey[0].URL = "SoftKey:Dial"; dir.SoftKey[0].URLDown = ""; dir.SoftKey[0].Postion = 1; dir.SoftKey[0].PostionSpecified = true; dir.SoftKey[1] = new CiscoIPPhoneSoftKeyType(); dir.SoftKey[1].Name = "EditNum."; dir.SoftKey[1].URL = "SoftKey:EditDial"; dir.SoftKey[1].URLDown = ""; dir.SoftKey[1].Postion = 2; dir.SoftKey[1].PostionSpecified = true; dir.SoftKey[2] = new CiscoIPPhoneSoftKeyType(); dir.SoftKey[2].Name = "Quitter"; dir.SoftKey[2].URL = "SoftKey:Exit"; dir.SoftKey[2].URLDown = ""; dir.SoftKey[2].Postion = 3; dir.SoftKey[2].PostionSpecified = true; dir.SoftKey[3] = new CiscoIPPhoneSoftKeyType(); dir.SoftKey[3].Name = "Recher."; dir.SoftKey[3].URL = this.Context.Request.Url.AbsoluteUri.Substring(0, this.Context.Request.Url.AbsoluteUri.LastIndexOf("/") + 1) + "SearchForCiscoIPPhone?directory=" + System.Web.HttpUtility.UrlEncode(directory); dir.SoftKey[3].URLDown = ""; dir.SoftKey[3].Postion = 4; dir.SoftKey[3].PostionSpecified = true; } else { dir.Prompt = "Enreg. " + (Int32.Parse(pos) + 1).ToString() + " à " + (Int32.Parse(pos) + 32).ToString() + " sur " + results.Rows.Count.ToString(); this.Context.Response.AddHeader("Refresh", ";url=" + this.Context.Request.Url.AbsoluteUri.Substring(0, this.Context.Request.Url.AbsoluteUri.LastIndexOf("/") + 1) + "GetResultsForCiscoIPPhone?directory=" + System.Web.HttpUtility.UrlEncode(directory) + "&givenName=" +System.Web.HttpUtility.UrlEncode(givenName)+ "&sn=" +System.Web.HttpUtility.UrlEncode(sn)+ "&telephonenumber=" +System.Web.HttpUtility.UrlEncode(telephonenumber)+ "&pos=" + System.Web.HttpUtility.UrlEncode((Int32.Parse(pos) + 32).ToString())); dir.SoftKey = new CiscoIPPhoneSoftKeyType[5]; dir.SoftKey[0] = new CiscoIPPhoneSoftKeyType(); dir.SoftKey[0].Name = "Compos."; dir.SoftKey[0].URL = "SoftKey:Dial"; dir.SoftKey[0].URLDown = ""; dir.SoftKey[0].Postion = 1; dir.SoftKey[0].PostionSpecified = true; dir.SoftKey[1] = new CiscoIPPhoneSoftKeyType(); dir.SoftKey[1].Name = "EditNum."; dir.SoftKey[1].URL = "SoftKey:EditDial"; dir.SoftKey[1].URLDown = ""; dir.SoftKey[1].Postion = 2; dir.SoftKey[1].PostionSpecified = true; dir.SoftKey[2] = new CiscoIPPhoneSoftKeyType(); dir.SoftKey[2].Name = "Quitter"; dir.SoftKey[2].URL = "SoftKey:Exit"; dir.SoftKey[2].URLDown = ""; dir.SoftKey[2].Postion = 3; dir.SoftKey[2].PostionSpecified = true; dir.SoftKey[3] = new CiscoIPPhoneSoftKeyType(); dir.SoftKey[3].Name = "Suivant"; dir.SoftKey[3].URL = "SoftKey:Update"; dir.SoftKey[3].URLDown = ""; dir.SoftKey[3].Postion = 4; dir.SoftKey[3].PostionSpecified = true; dir.SoftKey[4] = new CiscoIPPhoneSoftKeyType(); dir.SoftKey[4].Name = "Recher."; dir.SoftKey[4].URL = this.Context.Request.Url.AbsoluteUri.Substring(0, this.Context.Request.Url.AbsoluteUri.LastIndexOf("/") + 1) + "SearchForCiscoIPPhone?directory=" + System.Web.HttpUtility.UrlEncode(directory); dir.SoftKey[4].URLDown = ""; dir.SoftKey[4].Postion = 5; dir.SoftKey[4].PostionSpecified = true; } for (int cptRow = Int32.Parse(pos); cptRow <= Int32.Parse(pos) + 31; cptRow++) { if (cptRow < results.Rows.Count) { CiscoIPPhoneDirectoryEntryType dirEntry = new CiscoIPPhoneDirectoryEntryType(); dirEntry.Name = (string)results.Rows[cptRow][identityCol]; dirEntry.Telephone = (string)results.Rows[cptRow][telephoneCol]; entry.Add(dirEntry); } else { break; } } } else { dir.Prompt = "Pas d'enregistrement trouvé"; dir.SoftKey = new CiscoIPPhoneSoftKeyType[2]; dir.SoftKey[0] = new CiscoIPPhoneSoftKeyType(); dir.SoftKey[0].Name = "Quitter"; dir.SoftKey[0].URL = "SoftKey:Exit"; dir.SoftKey[0].URLDown = ""; dir.SoftKey[0].Postion = 3; dir.SoftKey[0].PostionSpecified = true; dir.SoftKey[1] = new CiscoIPPhoneSoftKeyType(); dir.SoftKey[1].Name = "Recher."; dir.SoftKey[1].URL = this.Context.Request.Url.AbsoluteUri.Substring(0, this.Context.Request.Url.AbsoluteUri.LastIndexOf("/") + 1) + "SearchForCiscoIPPhone?directory=" + System.Web.HttpUtility.UrlEncode(directory); dir.SoftKey[1].URLDown = ""; dir.SoftKey[1].Postion = 1; dir.SoftKey[1].PostionSpecified = true; } dir.DirectoryEntry = entry.ToArray(); //return dir; CiscoIPPhoneDirectoryTypeSerializer xml = new CiscoIPPhoneDirectoryTypeSerializer(); System.Xml.XmlWriterSettings settings = new System.Xml.XmlWriterSettings(); ; settings.Encoding = System.Text.Encoding.UTF8; System.IO.MemoryStream ms = new System.IO.MemoryStream(); System.Xml.XmlWriter xw = System.Xml.XmlWriter.Create(ms, settings); System.Xml.Serialization.XmlSerializerNamespaces xmlnsEmpty = new System.Xml.Serialization.XmlSerializerNamespaces(); xmlnsEmpty.Add("", ""); xml.Serialize(xw, dir, xmlnsEmpty); ms.Position = 0; this.Context.Response.ContentType = "text/xml"; this.Context.Response.ContentEncoding = System.Text.Encoding.UTF8; this.Context.Response.Write(GetStringFromStream(ms)); } catch (Exception e) { log.Error("Unable to build Cisco Ipphone Directory Type: " + e.Message); this.Context.Response.Redirect(this.Context.Request.Url.AbsoluteUri.Substring(0, this.Context.Request.Url.AbsoluteUri.LastIndexOf("/") + 1) + "Error?error=" + System.Web.HttpUtility.UrlEncode(e.Message), false); //return dir; } }
public void Error(string error) { CiscoIPPhoneTextType er = new CiscoIPPhoneTextType(); er.Prompt = "Erreur"; er.Title = "La requête a échouée"; er.Text = error; er.SoftKey = new CiscoIPPhoneSoftKeyType[1]; er.SoftKey[0] = new CiscoIPPhoneSoftKeyType(); er.SoftKey[0].Name = "Quitter"; er.SoftKey[0].Postion = 3; er.SoftKey[0].PostionSpecified = true; er.SoftKey[0].URL = "SoftKey:Exit"; er.SoftKey[0].URLDown = ""; //return er; CiscoIPPhoneTextTypeSerializer xml = new CiscoIPPhoneTextTypeSerializer(); System.Xml.XmlWriterSettings settings = new System.Xml.XmlWriterSettings(); ; settings.Encoding = System.Text.Encoding.UTF8; System.IO.MemoryStream ms = new System.IO.MemoryStream(); System.Xml.XmlWriter xw = System.Xml.XmlWriter.Create(ms, settings); System.Xml.Serialization.XmlSerializerNamespaces xmlnsEmpty = new System.Xml.Serialization.XmlSerializerNamespaces(); xmlnsEmpty.Add("", ""); xml.Serialize(xw, er, xmlnsEmpty); ms.Position = 0; this.Context.Response.ContentType = "text/xml"; this.Context.Response.ContentEncoding = System.Text.Encoding.UTF8; this.Context.Response.Write(GetStringFromStream(ms)); }
public static void Do() { string accountName = "enosg"; string sharedKey = "oooo+ps!"; bool useHTTPS = true; string contName = "testsas"; SharedAccessSignatureACL queueACL = new SharedAccessSignatureACL(); queueACL.SignedIdentifier = new List <SignedIdentifier>(); queueACL.SignedIdentifier.Add(new SignedIdentifier() { Id = "sisisisisisisvvv", AccessPolicy = new AccessPolicy() { Start = DateTime.Now.AddYears(-1), Expiry = DateTime.Now.AddYears(1), Permission = "rwd" } }); queueACL.SignedIdentifier.Add(new SignedIdentifier() { Id = "secondsigid", AccessPolicy = new AccessPolicy() { Start = DateTime.Now.AddYears(-10), Expiry = DateTime.Now.AddYears(10), Permission = "rwdl" } }); System.Xml.Serialization.XmlSerializer ser = new System.Xml.Serialization.XmlSerializer(queueACL.GetType()); // use this two lines to get rid of those useless namespaces :). System.Xml.Serialization.XmlSerializerNamespaces namespaces = new System.Xml.Serialization.XmlSerializerNamespaces(); namespaces.Add(string.Empty, string.Empty); using (System.IO.FileStream fs = new System.IO.FileStream("C:\\temp\\QueueACL.xml", System.IO.FileMode.Create, System.IO.FileAccess.Write, System.IO.FileShare.Read)) { ser.Serialize(fs, queueACL, namespaces); } using (System.IO.FileStream fs = new System.IO.FileStream("C:\\temp\\QueueACL.xml", System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.Read)) { queueACL = (SharedAccessSignatureACL)ser.Deserialize(fs); } var result = InternalMethods.SetContainerACL(accountName, sharedKey, useHTTPS, contName, null, queueACL, ITPCfSQL.Azure.Enumerations.ContainerPublicReadAccess.Blob); //return; AzureBlobService abs = new AzureBlobService(accountName, sharedKey, useHTTPS); List <Container> lConts = abs.ListContainers(); if (lConts.FirstOrDefault(item => item.Name == contName) == null) { abs.CreateContainer("testsas", ITPCfSQL.Azure.Enumerations.ContainerPublicReadAccess.Blob); lConts = abs.ListContainers(); } Container cTest = lConts.First(item => item.Name == contName); ContainerPublicReadAccess containerPublicAccess; var output = InternalMethods.GetContainerACL(accountName, sharedKey, useHTTPS, contName, out containerPublicAccess); }
public Models.acumuladoresCreditoConsulta acumuladoresCreditoIndicativaWeb(Models.imputacionCreditoConsulta data) { try { //Limpieza codigo strings Functions.CheckStringFields(ref data); } catch (Exception ex) { log.Info(ex.Message); } log.Info(ServiceLogName + " - Ingreso"); log.Debug(ServiceLogName + " - Seteando variables de contexto."); string usuarioProxy = Settings.GetAppSettings("Settings:Proxy:User"); string passwdProxy = Settings.GetAppSettings("Settings:Proxy:Password"); string urlProxy = Settings.GetAppSettings("Settings:Proxy:Url"); string domainProxy = Settings.GetAppSettings("Settings:Proxy:Domain"); string usuarioWS = Settings.GetAppSettings("Settings:Service:User"); string passwdWS = Settings.GetAppSettings("Settings:Service:Password"); string digitalMark = Settings.GetAppSettings("Settings:Credential:DigitalMark"); string WSAction = Settings.GetAppSettings("Settings:Service:Action"); string WSEndpoint = Settings.GetAppSettings("Settings:Service:Endpoint"); #region Consulta Servicio Gestion Claves //string passwdWS = string.Empty; //bool gestionClavesSuccess = true; //string gestionClavesMessage = string.Empty; //try //{ // log.Info("Inicio Servicio Gestion Claves"); // string gestionClavesEndpoint = ConfigurationManager.AppSettings["GClaves_Endpoint"]; // _gestionService.Endpoint.Address = new EndpointAddress(gestionClavesEndpoint); // string gcUser = ConfigurationManager.AppSettings["GCLaves_USU"]; // string gcPass = ConfigurationManager.AppSettings["GCLaves_PSW"]; // string key = ConfigurationManager.AppSettings["GClaves_EsidifPass"]; // log.Info("Invocando al metodo ConsultarKey"); // string resultGC = _gestionService.ConsultarKey(gcUser, gcPass, key); // if (!string.IsNullOrEmpty(resultGC) && resultGC.Length > 0) // { // log.Info("Invocacion a Gestion Claves Correcta"); // passwdWS = resultGC; // } // else // { // throw new Exception("El valor devuelto esta vacio"); // } //} //catch (Exception ex) //{ // gestionClavesSuccess = false; // gestionClavesMessage = ex.Message; // log.Info("Fallo la invocacion a Gestion Claves: " + ex.Message); //} //if (!gestionClavesSuccess) //{ // throw new Exception(gestionClavesMessage); //} #endregion log.Debug(ServiceLogName + " - Seteando PROXY."); WebProxy proxy = Functions.CreateProxy(usuarioProxy, passwdProxy, urlProxy, domainProxy); log.Debug(ServiceLogName + " - Cargando certificado X509."); NetworkCredential credential = new NetworkCredential(usuarioWS, passwdWS); CredentialCache credentialCache = new CredentialCache(); credentialCache.Add(new Uri(WSEndpoint), "NTLM", credential); log.Debug(ServiceLogName + " - IGNORA_ERROR_CERTI = true."); ServicePointManager.ServerCertificateValidationCallback += RemoteCertificateValidationCallback; log.Debug(ServiceLogName + " - Certificado X509 cargado exitosamente."); log.Debug(ServiceLogName + " - Creando Bean"); var envelope = new Envelope(); envelope.Header = new Header("UsernameToken-1", usuarioWS, passwdWS, WSEndpoint, WSAction); envelope.Body = new XmlAnything <IBody>(data); System.Xml.Serialization.XmlSerializerNamespaces xmlnsSoap = new System.Xml.Serialization.XmlSerializerNamespaces(); xmlnsSoap.Add("soapenv", "http://schemas.xmlsoap.org/soap/envelope/"); xmlnsSoap.Add("web", "http://webService.imputacionesPresupuestarias.esidif.mecon.gov.ar"); xmlnsSoap.Add("wsse", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd"); xmlnsSoap.Add("wsu", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd"); xmlnsSoap.Add("wsa", "http://www.w3.org/2005/08/addressing"); log.Debug(ServiceLogName + " - Mapeando a objeto XML."); string msgRequest = Functions.SerializeObjectToString(envelope, xmlnsSoap); string msgResponse = string.Empty; log.Debug(ServiceLogName + " - Armando header de autenticacion"); HttpWebRequest request = WebRequest.Create(WSEndpoint) as HttpWebRequest; request.Headers.Add("SOAPAction", WSAction); request.ContentType = "text/xml;charset=\"utf-8\""; request.Accept = "text/xml"; request.Method = WebRequestMethods.Http.Post; request.KeepAlive = true; request.PreAuthenticate = true; request.AuthenticationLevel = AuthenticationLevel.MutualAuthRequested; request.Proxy = proxy; request.Credentials = credentialCache; request.ClientCertificates.Add(Functions.GetClientCertificate(digitalMark)); using (Stream stm = request.GetRequestStream()) { using (StreamWriter stmw = new StreamWriter(stm)) { stmw.Write(msgRequest); } } log.Info("Consulta Servicio - ESIDIF : " + Environment.NewLine + Functions.ParseXml(msgRequest)); WebResponse response = request.GetResponse(); using (StreamReader reader = new StreamReader(response.GetResponseStream())) { msgResponse = reader.ReadToEnd(); } log.Info("Respuesta ESIDIF - Servicio : " + Environment.NewLine + Functions.ParseXml(msgResponse)); var resp = Functions.DeserializeXMLString <Models.acumuladoresCreditoConsulta>(msgResponse); return(resp); }
public static EntityFile Load(string filename) { EntityFile file = new EntityFile(); var s = new System.Xml.Serialization.XmlSerializer(typeof(EntityFile)); var ns = new System.Xml.Serialization.XmlSerializerNamespaces(); ns.Add("", ""); using (System.IO.StreamReader reader = new StreamReader(filename)) { file = (EntityFile)s.Deserialize(reader); } return file; }
public static void Do() { string accountName = "enosg"; string sharedKey = "oooo+ps!"; bool useHTTPS = true; string contName = "testsas"; SharedAccessSignatureACL queueACL = new SharedAccessSignatureACL(); queueACL.SignedIdentifier = new List<SignedIdentifier>(); queueACL.SignedIdentifier.Add(new SignedIdentifier() { Id = "sisisisisisisvvv", AccessPolicy = new AccessPolicy() { Start = DateTime.Now.AddYears(-1), Expiry = DateTime.Now.AddYears(1), Permission = "rwd" } }); queueACL.SignedIdentifier.Add(new SignedIdentifier() { Id = "secondsigid", AccessPolicy = new AccessPolicy() { Start = DateTime.Now.AddYears(-10), Expiry = DateTime.Now.AddYears(10), Permission = "rwdl" } }); System.Xml.Serialization.XmlSerializer ser = new System.Xml.Serialization.XmlSerializer(queueACL.GetType()); // use this two lines to get rid of those useless namespaces :). System.Xml.Serialization.XmlSerializerNamespaces namespaces = new System.Xml.Serialization.XmlSerializerNamespaces(); namespaces.Add(string.Empty, string.Empty); using (System.IO.FileStream fs = new System.IO.FileStream("C:\\temp\\QueueACL.xml", System.IO.FileMode.Create, System.IO.FileAccess.Write, System.IO.FileShare.Read)) { ser.Serialize(fs, queueACL, namespaces); } using (System.IO.FileStream fs = new System.IO.FileStream("C:\\temp\\QueueACL.xml", System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.Read)) { queueACL = (SharedAccessSignatureACL)ser.Deserialize(fs); } var result = InternalMethods.SetContainerACL(accountName, sharedKey, useHTTPS, contName, null, queueACL, ITPCfSQL.Azure.Enumerations.ContainerPublicReadAccess.Blob); //return; AzureBlobService abs = new AzureBlobService(accountName, sharedKey, useHTTPS); List<Container> lConts = abs.ListContainers(); if (lConts.FirstOrDefault(item => item.Name == contName) == null) { abs.CreateContainer("testsas", ITPCfSQL.Azure.Enumerations.ContainerPublicReadAccess.Blob); lConts = abs.ListContainers(); } Container cTest = lConts.First(item => item.Name == contName); ContainerPublicReadAccess containerPublicAccess; var output = InternalMethods.GetContainerACL(accountName, sharedKey, useHTTPS, contName, out containerPublicAccess); }
private void SerializeObjectToXML(System.Xml.XmlWriter reportDataStream, System.Xml.XmlWriterSettings writerSettings, object o) { System.Xml.Serialization.XmlSerializer ser = new System.Xml.Serialization.XmlSerializer(o.GetType()); System.Xml.Serialization.XmlSerializerNamespaces ns = new System.Xml.Serialization.XmlSerializerNamespaces(); ns.Add("", ""); System.Xml.XmlWriter xmlWriter = System.Xml.XmlWriter.Create(reportDataStream, writerSettings); ser.Serialize(xmlWriter, o, ns); }
public void Execute(ESRI.ArcGIS.esriSystem.IArray paramvalues, ESRI.ArcGIS.esriSystem.ITrackCancel TrackCancel, ESRI.ArcGIS.Geoprocessing.IGPEnvironmentManager envMgr, ESRI.ArcGIS.Geodatabase.IGPMessages message) { try { IGPUtilities3 execute_Utilities = new GPUtilitiesClass(); if (TrackCancel == null) { TrackCancel = new CancelTrackerClass(); } IGPParameter inputFeatureDatasetParameter = paramvalues.get_Element(in_featureDatasetParameterNumber) as IGPParameter; IGPValue inputFeatureDatasetGPValue = execute_Utilities.UnpackGPValue(inputFeatureDatasetParameter); IGPValue outputOSMFileGPValue = execute_Utilities.UnpackGPValue(paramvalues.get_Element(out_osmFileLocationParameterNumber)); // get the name of the feature dataset int fdDemlimiterPosition = inputFeatureDatasetGPValue.GetAsText().LastIndexOf("\\"); string nameOfFeatureDataset = inputFeatureDatasetGPValue.GetAsText().Substring(fdDemlimiterPosition + 1); XmlWriterSettings settings = new XmlWriterSettings(); settings.Indent = true; System.Xml.XmlWriter xmlWriter = null; try { xmlWriter = XmlWriter.Create(outputOSMFileGPValue.GetAsText(), settings); } catch (Exception ex) { message.AddError(120021, ex.Message); return; } xmlWriter.WriteStartDocument(); xmlWriter.WriteStartElement("osm"); // start the osm root node xmlWriter.WriteAttributeString("version", "0.6"); // add the version attribute xmlWriter.WriteAttributeString("generator", "ArcGIS Editor for OpenStreetMap"); // add the generator attribute // write all the nodes // use a feature search cursor to loop through all the known points and write them out as osm node IFeatureClassContainer osmFeatureClasses = execute_Utilities.OpenDataset(inputFeatureDatasetGPValue) as IFeatureClassContainer; if (osmFeatureClasses == null) { message.AddError(120022, string.Format(resourceManager.GetString("GPTools_NullPointerParameterType"), inputFeatureDatasetParameter.Name)); return; } IFeatureClass osmPointFeatureClass = osmFeatureClasses.get_ClassByName(nameOfFeatureDataset + "_osm_pt"); if (osmPointFeatureClass == null) { message.AddError(120023, string.Format(resourceManager.GetString("GPTools_OSMGPExport2OSM_no_pointfeatureclass"), nameOfFeatureDataset + "_osm_pt")); return; } // check the extension of the point feature class to determine its version int internalOSMExtensionVersion = osmPointFeatureClass.OSMExtensionVersion(); IFeatureCursor searchCursor = null; System.Xml.Serialization.XmlSerializerNamespaces xmlnsEmpty = new System.Xml.Serialization.XmlSerializerNamespaces(); xmlnsEmpty.Add("", ""); message.AddMessage(resourceManager.GetString("GPTools_OSMGPExport2OSM_exporting_pts_msg")); int pointCounter = 0; string nodesExportedMessage = String.Empty; // collect the indices for the point feature class once int pointOSMIDFieldIndex = osmPointFeatureClass.Fields.FindField("OSMID"); int pointChangesetFieldIndex = osmPointFeatureClass.Fields.FindField("osmchangeset"); int pointVersionFieldIndex = osmPointFeatureClass.Fields.FindField("osmversion"); int pointUIDFieldIndex = osmPointFeatureClass.Fields.FindField("osmuid"); int pointUserFieldIndex = osmPointFeatureClass.Fields.FindField("osmuser"); int pointTimeStampFieldIndex = osmPointFeatureClass.Fields.FindField("osmtimestamp"); int pointVisibleFieldIndex = osmPointFeatureClass.Fields.FindField("osmvisible"); int pointTagsFieldIndex = osmPointFeatureClass.Fields.FindField("osmTags"); using (ComReleaser comReleaser = new ComReleaser()) { searchCursor = osmPointFeatureClass.Search(null, false); comReleaser.ManageLifetime(searchCursor); System.Xml.Serialization.XmlSerializer pointSerializer = new System.Xml.Serialization.XmlSerializer(typeof(node)); IFeature currentFeature = searchCursor.NextFeature(); IWorkspace pointWorkspace = ((IDataset)osmPointFeatureClass).Workspace; while (currentFeature != null) { if (TrackCancel.Continue() == true) { // convert the found point feature into a osm node representation to store into the OSM XML file node osmNode = ConvertPointFeatureToOSMNode(currentFeature, pointWorkspace, pointTagsFieldIndex, pointOSMIDFieldIndex, pointChangesetFieldIndex, pointVersionFieldIndex, pointUIDFieldIndex, pointUserFieldIndex, pointTimeStampFieldIndex, pointVisibleFieldIndex, internalOSMExtensionVersion); pointSerializer.Serialize(xmlWriter, osmNode, xmlnsEmpty); // increase the point counter to later status report pointCounter++; currentFeature = searchCursor.NextFeature(); } else { // properly close the document xmlWriter.WriteEndElement(); // closing the osm root element xmlWriter.WriteEndDocument(); // finishing the document xmlWriter.Close(); // closing the document // report the number of elements loader so far nodesExportedMessage = String.Format(resourceManager.GetString("GPTools_OSMGPExport2OSM_pts_exported_msg"), pointCounter); message.AddMessage(nodesExportedMessage); return; } } } nodesExportedMessage = String.Format(resourceManager.GetString("GPTools_OSMGPExport2OSM_pts_exported_msg"), pointCounter); message.AddMessage(nodesExportedMessage); // next loop through the line and polygon feature classes to export those features as ways // in case we encounter a multi-part geometry, store it in a relation collection that will be serialized when exporting the relations table IFeatureClass osmLineFeatureClass = osmFeatureClasses.get_ClassByName(nameOfFeatureDataset + "_osm_ln"); if (osmLineFeatureClass == null) { message.AddError(120023, string.Format(resourceManager.GetString("GPTools_OSMGPExport2OSM_no_linefeatureclass"), nameOfFeatureDataset + "_osm_ln")); return; } message.AddMessage(resourceManager.GetString("GPTools_OSMGPExport2OSM_exporting_ways_msg")); // as we are looping through the line and polygon feature classes let's collect the multi-part features separately // as they are considered relations in the OSM world List<relation> multiPartElements = new List<relation>(); System.Xml.Serialization.XmlSerializer waySerializer = new System.Xml.Serialization.XmlSerializer(typeof(way)); int lineCounter = 0; int relationCounter = 0; string waysExportedMessage = String.Empty; using (ComReleaser comReleaser = new ComReleaser()) { searchCursor = osmLineFeatureClass.Search(null, false); comReleaser.ManageLifetime(searchCursor); IFeature currentFeature = searchCursor.NextFeature(); // collect the indices for the point feature class once int lineOSMIDFieldIndex = osmLineFeatureClass.Fields.FindField("OSMID"); int lineChangesetFieldIndex = osmLineFeatureClass.Fields.FindField("osmchangeset"); int lineVersionFieldIndex = osmLineFeatureClass.Fields.FindField("osmversion"); int lineUIDFieldIndex = osmLineFeatureClass.Fields.FindField("osmuid"); int lineUserFieldIndex = osmLineFeatureClass.Fields.FindField("osmuser"); int lineTimeStampFieldIndex = osmLineFeatureClass.Fields.FindField("osmtimestamp"); int lineVisibleFieldIndex = osmLineFeatureClass.Fields.FindField("osmvisible"); int lineTagsFieldIndex = osmLineFeatureClass.Fields.FindField("osmTags"); int lineMembersFieldIndex = osmLineFeatureClass.Fields.FindField("osmMembers"); IWorkspace lineWorkspace = ((IDataset)osmLineFeatureClass).Workspace; while (currentFeature != null) { if (TrackCancel.Continue() == false) { // properly close the document xmlWriter.WriteEndElement(); // closing the osm root element xmlWriter.WriteEndDocument(); // finishing the document xmlWriter.Close(); // closing the document // report the number of elements loaded so far waysExportedMessage = String.Format(resourceManager.GetString("GPTools_OSMGPExport2OSM_ways_exported_msg"), lineCounter); message.AddMessage(waysExportedMessage); return; } //test if the feature geometry has multiple parts IGeometryCollection geometryCollection = currentFeature.Shape as IGeometryCollection; if (geometryCollection != null) { if (geometryCollection.GeometryCount == 1) { // convert the found polyline feature into a osm way representation to store into the OSM XML file way osmWay = ConvertFeatureToOSMWay(currentFeature, lineWorkspace, osmPointFeatureClass, pointOSMIDFieldIndex, lineTagsFieldIndex, lineOSMIDFieldIndex, lineChangesetFieldIndex, lineVersionFieldIndex, lineUIDFieldIndex, lineUserFieldIndex, lineTimeStampFieldIndex, lineVisibleFieldIndex, internalOSMExtensionVersion); waySerializer.Serialize(xmlWriter, osmWay, xmlnsEmpty); // increase the line counter for later status report lineCounter++; } else { relation osmRelation = ConvertRowToOSMRelation((IRow)currentFeature, lineWorkspace, lineTagsFieldIndex, lineOSMIDFieldIndex, lineChangesetFieldIndex, lineVersionFieldIndex, lineUIDFieldIndex, lineUserFieldIndex, lineTimeStampFieldIndex, lineVisibleFieldIndex, lineMembersFieldIndex, internalOSMExtensionVersion); multiPartElements.Add(osmRelation); // increase the line counter for later status report relationCounter++; } } currentFeature = searchCursor.NextFeature(); } } IFeatureClass osmPolygonFeatureClass = osmFeatureClasses.get_ClassByName(nameOfFeatureDataset + "_osm_ply"); IFeatureWorkspace commonWorkspace = ((IDataset)osmPolygonFeatureClass).Workspace as IFeatureWorkspace; if (osmPolygonFeatureClass == null) { message.AddError(120024, string.Format(resourceManager.GetString("GPTools_OSMGPExport2OSM_no_polygonfeatureclass"), nameOfFeatureDataset + "_osm_ply")); return; } using (ComReleaser comReleaser = new ComReleaser()) { searchCursor = osmPolygonFeatureClass.Search(null, false); comReleaser.ManageLifetime(searchCursor); IFeature currentFeature = searchCursor.NextFeature(); // collect the indices for the point feature class once int polygonOSMIDFieldIndex = osmPolygonFeatureClass.Fields.FindField("OSMID"); int polygonChangesetFieldIndex = osmPolygonFeatureClass.Fields.FindField("osmchangeset"); int polygonVersionFieldIndex = osmPolygonFeatureClass.Fields.FindField("osmversion"); int polygonUIDFieldIndex = osmPolygonFeatureClass.Fields.FindField("osmuid"); int polygonUserFieldIndex = osmPolygonFeatureClass.Fields.FindField("osmuser"); int polygonTimeStampFieldIndex = osmPolygonFeatureClass.Fields.FindField("osmtimestamp"); int polygonVisibleFieldIndex = osmPolygonFeatureClass.Fields.FindField("osmvisible"); int polygonTagsFieldIndex = osmPolygonFeatureClass.Fields.FindField("osmTags"); int polygonMembersFieldIndex = osmPolygonFeatureClass.Fields.FindField("osmMembers"); IWorkspace polygonWorkspace = ((IDataset)osmPolygonFeatureClass).Workspace; while (currentFeature != null) { if (TrackCancel.Continue() == false) { // properly close the document xmlWriter.WriteEndElement(); // closing the osm root element xmlWriter.WriteEndDocument(); // finishing the document xmlWriter.Close(); // closing the document // report the number of elements loaded so far waysExportedMessage = String.Format(resourceManager.GetString("GPTools_OSMGPExport2OSM_ways_exported_msg"), lineCounter); message.AddMessage(waysExportedMessage); message.AddAbort(resourceManager.GetString("GPTools_toolabort")); return; } //test if the feature geometry has multiple parts IGeometryCollection geometryCollection = currentFeature.Shape as IGeometryCollection; if (geometryCollection != null) { if (geometryCollection.GeometryCount == 1) { // convert the found polyline feature into a osm way representation to store into the OSM XML file way osmWay = ConvertFeatureToOSMWay(currentFeature, polygonWorkspace, osmPointFeatureClass, pointOSMIDFieldIndex, polygonTagsFieldIndex, polygonOSMIDFieldIndex, polygonChangesetFieldIndex, polygonVersionFieldIndex, polygonUIDFieldIndex, polygonUserFieldIndex, polygonTimeStampFieldIndex, polygonVisibleFieldIndex, internalOSMExtensionVersion); waySerializer.Serialize(xmlWriter, osmWay, xmlnsEmpty); // increase the line counter for later status report lineCounter++; } else { relation osmRelation = ConvertRowToOSMRelation((IRow)currentFeature, polygonWorkspace, polygonTagsFieldIndex, polygonOSMIDFieldIndex, polygonChangesetFieldIndex, polygonVersionFieldIndex, polygonUIDFieldIndex, polygonUserFieldIndex, polygonTimeStampFieldIndex, polygonVisibleFieldIndex, polygonMembersFieldIndex, internalOSMExtensionVersion); multiPartElements.Add(osmRelation); // increase the line counter for later status report relationCounter++; } } currentFeature = searchCursor.NextFeature(); } } waysExportedMessage = String.Format(resourceManager.GetString("GPTools_OSMGPExport2OSM_ways_exported_msg"), lineCounter); message.AddMessage(waysExportedMessage); // now let's go through the relation table message.AddMessage(resourceManager.GetString("GPTools_OSMGPExport2OSM_exporting_relations_msg")); ITable relationTable = commonWorkspace.OpenTable(nameOfFeatureDataset + "_osm_relation"); if (relationTable == null) { message.AddError(120025, String.Format(resourceManager.GetString("GPTools_OSMGPExport2OSM_no_relationTable"), nameOfFeatureDataset + "_osm_relation")); return; } System.Xml.Serialization.XmlSerializer relationSerializer = new System.Xml.Serialization.XmlSerializer(typeof(relation)); string relationsExportedMessage = String.Empty; using (ComReleaser comReleaser = new ComReleaser()) { ICursor rowCursor = relationTable.Search(null, false); comReleaser.ManageLifetime(rowCursor); IRow currentRow = rowCursor.NextRow(); // collect the indices for the relation table once int relationOSMIDFieldIndex = relationTable.Fields.FindField("OSMID"); int relationChangesetFieldIndex = relationTable.Fields.FindField("osmchangeset"); int relationVersionFieldIndex = relationTable.Fields.FindField("osmversion"); int relationUIDFieldIndex = relationTable.Fields.FindField("osmuid"); int relationUserFieldIndex = relationTable.Fields.FindField("osmuser"); int relationTimeStampFieldIndex = relationTable.Fields.FindField("osmtimestamp"); int relationVisibleFieldIndex = relationTable.Fields.FindField("osmvisible"); int relationTagsFieldIndex = relationTable.Fields.FindField("osmTags"); int relationMembersFieldIndex = relationTable.Fields.FindField("osmMembers"); IWorkspace polygonWorkspace = ((IDataset)osmPolygonFeatureClass).Workspace; while (currentRow != null) { if (TrackCancel.Continue() == false) { // properly close the document xmlWriter.WriteEndElement(); // closing the osm root element xmlWriter.WriteEndDocument(); // finishing the document xmlWriter.Close(); // closing the document // report the number of elements loaded so far relationsExportedMessage = String.Format(resourceManager.GetString("GPTools_OSMGPExport2OSM_relations_exported_msg"), relationCounter); message.AddMessage(relationsExportedMessage); message.AddAbort(resourceManager.GetString("GPTools_toolabort")); return; } relation osmRelation = ConvertRowToOSMRelation(currentRow, (IWorkspace)commonWorkspace, relationTagsFieldIndex, relationOSMIDFieldIndex, relationChangesetFieldIndex, relationVersionFieldIndex, relationUIDFieldIndex, relationUserFieldIndex, relationTimeStampFieldIndex, relationVisibleFieldIndex, relationMembersFieldIndex, internalOSMExtensionVersion); relationSerializer.Serialize(xmlWriter, osmRelation, xmlnsEmpty); // increase the line counter for later status report relationCounter++; currentRow = rowCursor.NextRow(); } } // lastly let's serialize the collected multipart-geometries back into relation elements foreach (relation currentRelation in multiPartElements) { if (TrackCancel.Continue() == false) { // properly close the document xmlWriter.WriteEndElement(); // closing the osm root element xmlWriter.WriteEndDocument(); // finishing the document xmlWriter.Close(); // closing the document // report the number of elements loaded so far relationsExportedMessage = String.Format(resourceManager.GetString("GPTools_OSMGPExport2OSM_relations_exported_msg"), relationCounter); message.AddMessage(relationsExportedMessage); return; } relationSerializer.Serialize(xmlWriter, currentRelation, xmlnsEmpty); relationCounter++; } relationsExportedMessage = String.Format(resourceManager.GetString("GPTools_OSMGPExport2OSM_relations_exported_msg"), relationCounter); message.AddMessage(relationsExportedMessage); xmlWriter.WriteEndElement(); // closing the osm root element xmlWriter.WriteEndDocument(); // finishing the document xmlWriter.Close(); // closing the document } catch (Exception ex) { message.AddError(120026, ex.Message); } }
private void AddRunHistory(WebRequest Request, string RequestHeader, string RequestBody, HttpWebResponse Response, string JsonResponse) { int maxHistoryCount = 30; // Keep only 30 history. while (runHistory.RunInfo.Count >= maxHistoryCount) { runHistory.RunInfo.RemoveAt(0); } string statusCode; string headers; if (Response == null) { statusCode = "Error"; headers = ""; } else { statusCode = Response.StatusCode.ToString(); headers = Response.Headers.ToString(); } RunInformation newRunInfo = new RunInformation { ExecutionID = DateTime.UtcNow.ToString("yyyyMMddHHmmssfff"), RequestUrl = Request.RequestUri.ToString(), RequestMethod = Request.Method, RequestHeader = RequestHeader, RequestCompleteHeader = Request.Headers.ToString(), RequestBody = RequestBody, ResponseStatusCode = statusCode, ResponseHeader = headers, ResponseBody = JsonResponse }; // Add new history. runHistory.RunInfo.Add(newRunInfo); // Update the listbox. listBox_RunHistory.Items.Clear(); for (int i = runHistory.RunInfo.Count - 1; i >= 0; i--) { listBox_RunHistory.Items.Add(runHistory.RunInfo[i]); } // Save the file. try { FileStream stream = new FileStream(Path.Combine(Application.StartupPath, "RunHistory.xml"), FileMode.Create); using (StreamWriter writer = new StreamWriter(stream, Encoding.UTF8)) { // Serialize System.Xml.Serialization.XmlSerializerNamespaces nameSpace = new System.Xml.Serialization.XmlSerializerNamespaces(); nameSpace.Add(string.Empty, string.Empty); System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(typeof(RunHistory)); serializer.Serialize(writer, runHistory, nameSpace); writer.Flush(); } } catch (Exception ex) { MessageBox.Show("The run history file could not be saved." + Environment.NewLine + Environment.NewLine + ex.Message, "Office365APIEditor"); } }
/// <summary> /// Обработка входящих /// </summary> public void PrepareInputFolder() { if (!CheckSession()) Authorization(); var res = DocPackList(); foreach (var pack in res["d"]["СписокПакетовДокументов"]["d"]) { SBiSKonvert sk = new SBiSKonvert(); sk.Дата = pack[1]; sk.Номер = pack[2]; sk.Отправитель.ИНН = pack[3]; sk.Отправитель.КПП = pack[4]; sk.Отправитель.Название = pack[5]; sk.Получатель.ИНН = pack[6]; sk.Получатель.КПП = pack[7]; sk.Получатель.Название = pack[8]; //sk.Примечание = pack[9]; sk.ТипДокумента = pack[9]; var docs = GetDocListInPack(pack[0]); foreach (var doc in docs["d"]["СписокДокументов"]["d"]) { if (doc[6] == "Нет") { string HRName = GetDocument(doc[0], pack[0])["ИмяФайла"]; if (System.IO.Path.GetExtension(doc[1]) == ".xml") { HRName = GetHumanReadebleDocument(doc[0], pack[0])["ИмяФайла"]; } else Console.WriteLine("Не ХМЛ"); sk.Вложения.Add(new SBiSKonverAtta { ИдентификаторДокумента = doc[0], ИмяФайла = doc[1], Название = doc[3], Версия = doc[2], Выгружен = doc[5], Служебный = doc[6], ЧислоПодписей = doc[7], ТипДокумента = doc[8],Человечный =HRName }); } } string baseDir = System.IO.Path.Combine(Settings.WorkDir, pack[0]); string fullPath = System.IO.Path.Combine(baseDir, "KONVERT.xml"); System.Xml.Serialization.XmlSerializer ser = new System.Xml.Serialization.XmlSerializer(typeof(SBiSKonvert)); System.Xml.Serialization.XmlSerializerNamespaces namespaces = new System.Xml.Serialization.XmlSerializerNamespaces(); namespaces.Add(string.Empty, string.Empty); System.IO.TextWriter writer = new System.IO.StreamWriter(fullPath); ser.Serialize(writer, sk, namespaces); writer.Close(); } }
public void Execute(ESRI.ArcGIS.esriSystem.IArray paramvalues, ESRI.ArcGIS.esriSystem.ITrackCancel TrackCancel, ESRI.ArcGIS.Geoprocessing.IGPEnvironmentManager envMgr, ESRI.ArcGIS.Geodatabase.IGPMessages message) { try { IGPUtilities3 execute_Utilities = new GPUtilitiesClass(); if (TrackCancel == null) { TrackCancel = new CancelTrackerClass(); } IGPParameter inputFeatureDatasetParameter = paramvalues.get_Element(in_featureDatasetParameterNumber) as IGPParameter; IGPValue inputFeatureDatasetGPValue = execute_Utilities.UnpackGPValue(inputFeatureDatasetParameter); IGPValue outputOSMFileGPValue = execute_Utilities.UnpackGPValue(paramvalues.get_Element(out_osmFileLocationParameterNumber)); // get the name of the feature dataset int fdDemlimiterPosition = inputFeatureDatasetGPValue.GetAsText().LastIndexOf("\\"); string nameOfFeatureDataset = inputFeatureDatasetGPValue.GetAsText().Substring(fdDemlimiterPosition + 1); XmlWriterSettings settings = new XmlWriterSettings(); settings.Indent = true; System.Xml.XmlWriter xmlWriter = null; try { xmlWriter = XmlWriter.Create(outputOSMFileGPValue.GetAsText(), settings); } catch (Exception ex) { message.AddError(120021, ex.Message); return; } xmlWriter.WriteStartDocument(); xmlWriter.WriteStartElement("osm"); // start the osm root node xmlWriter.WriteAttributeString("version", "0.6"); // add the version attribute xmlWriter.WriteAttributeString("generator", "ArcGIS Editor for OpenStreetMap"); // add the generator attribute // write all the nodes // use a feature search cursor to loop through all the known points and write them out as osm node IFeatureClassContainer osmFeatureClasses = execute_Utilities.OpenDataset(inputFeatureDatasetGPValue) as IFeatureClassContainer; if (osmFeatureClasses == null) { message.AddError(120022, string.Format(resourceManager.GetString("GPTools_NullPointerParameterType"), inputFeatureDatasetParameter.Name)); return; } IFeatureClass osmPointFeatureClass = osmFeatureClasses.get_ClassByName(nameOfFeatureDataset + "_osm_pt"); if (osmPointFeatureClass == null) { message.AddError(120023, string.Format(resourceManager.GetString("GPTools_OSMGPExport2OSM_no_pointfeatureclass"), nameOfFeatureDataset + "_osm_pt")); return; } // check the extension of the point feature class to determine its version int internalOSMExtensionVersion = osmPointFeatureClass.OSMExtensionVersion(); IFeatureCursor searchCursor = null; System.Xml.Serialization.XmlSerializerNamespaces xmlnsEmpty = new System.Xml.Serialization.XmlSerializerNamespaces(); xmlnsEmpty.Add("", ""); message.AddMessage(resourceManager.GetString("GPTools_OSMGPExport2OSM_exporting_pts_msg")); int pointCounter = 0; string nodesExportedMessage = String.Empty; // collect the indices for the point feature class once int pointOSMIDFieldIndex = osmPointFeatureClass.Fields.FindField("OSMID"); int pointChangesetFieldIndex = osmPointFeatureClass.Fields.FindField("osmchangeset"); int pointVersionFieldIndex = osmPointFeatureClass.Fields.FindField("osmversion"); int pointUIDFieldIndex = osmPointFeatureClass.Fields.FindField("osmuid"); int pointUserFieldIndex = osmPointFeatureClass.Fields.FindField("osmuser"); int pointTimeStampFieldIndex = osmPointFeatureClass.Fields.FindField("osmtimestamp"); int pointVisibleFieldIndex = osmPointFeatureClass.Fields.FindField("osmvisible"); int pointTagsFieldIndex = osmPointFeatureClass.Fields.FindField("osmTags"); using (ComReleaser comReleaser = new ComReleaser()) { searchCursor = osmPointFeatureClass.Search(null, false); comReleaser.ManageLifetime(searchCursor); System.Xml.Serialization.XmlSerializer pointSerializer = new System.Xml.Serialization.XmlSerializer(typeof(node)); IFeature currentFeature = searchCursor.NextFeature(); IWorkspace pointWorkspace = ((IDataset)osmPointFeatureClass).Workspace; while (currentFeature != null) { if (TrackCancel.Continue() == true) { // convert the found point feature into a osm node representation to store into the OSM XML file node osmNode = ConvertPointFeatureToOSMNode(currentFeature, pointWorkspace, pointTagsFieldIndex, pointOSMIDFieldIndex, pointChangesetFieldIndex, pointVersionFieldIndex, pointUIDFieldIndex, pointUserFieldIndex, pointTimeStampFieldIndex, pointVisibleFieldIndex, internalOSMExtensionVersion); pointSerializer.Serialize(xmlWriter, osmNode, xmlnsEmpty); // increase the point counter to later status report pointCounter++; currentFeature = searchCursor.NextFeature(); } else { // properly close the document xmlWriter.WriteEndElement(); // closing the osm root element xmlWriter.WriteEndDocument(); // finishing the document xmlWriter.Close(); // closing the document // report the number of elements loader so far nodesExportedMessage = String.Format(resourceManager.GetString("GPTools_OSMGPExport2OSM_pts_exported_msg"), pointCounter); message.AddMessage(nodesExportedMessage); return; } } } nodesExportedMessage = String.Format(resourceManager.GetString("GPTools_OSMGPExport2OSM_pts_exported_msg"), pointCounter); message.AddMessage(nodesExportedMessage); // next loop through the line and polygon feature classes to export those features as ways // in case we encounter a multi-part geometry, store it in a relation collection that will be serialized when exporting the relations table IFeatureClass osmLineFeatureClass = osmFeatureClasses.get_ClassByName(nameOfFeatureDataset + "_osm_ln"); if (osmLineFeatureClass == null) { message.AddError(120023, string.Format(resourceManager.GetString("GPTools_OSMGPExport2OSM_no_linefeatureclass"), nameOfFeatureDataset + "_osm_ln")); return; } message.AddMessage(resourceManager.GetString("GPTools_OSMGPExport2OSM_exporting_ways_msg")); // as we are looping through the line and polygon feature classes let's collect the multi-part features separately // as they are considered relations in the OSM world List<relation> multiPartElements = new List<relation>(); System.Xml.Serialization.XmlSerializer waySerializer = new System.Xml.Serialization.XmlSerializer(typeof(way)); int lineCounter = 0; int relationCounter = 0; string waysExportedMessage = String.Empty; using (ComReleaser comReleaser = new ComReleaser()) { searchCursor = osmLineFeatureClass.Search(null, false); comReleaser.ManageLifetime(searchCursor); IFeature currentFeature = searchCursor.NextFeature(); // collect the indices for the point feature class once int lineOSMIDFieldIndex = osmLineFeatureClass.Fields.FindField("OSMID"); int lineChangesetFieldIndex = osmLineFeatureClass.Fields.FindField("osmchangeset"); int lineVersionFieldIndex = osmLineFeatureClass.Fields.FindField("osmversion"); int lineUIDFieldIndex = osmLineFeatureClass.Fields.FindField("osmuid"); int lineUserFieldIndex = osmLineFeatureClass.Fields.FindField("osmuser"); int lineTimeStampFieldIndex = osmLineFeatureClass.Fields.FindField("osmtimestamp"); int lineVisibleFieldIndex = osmLineFeatureClass.Fields.FindField("osmvisible"); int lineTagsFieldIndex = osmLineFeatureClass.Fields.FindField("osmTags"); int lineMembersFieldIndex = osmLineFeatureClass.Fields.FindField("osmMembers"); IWorkspace lineWorkspace = ((IDataset)osmLineFeatureClass).Workspace; while (currentFeature != null) { if (TrackCancel.Continue() == false) { // properly close the document xmlWriter.WriteEndElement(); // closing the osm root element xmlWriter.WriteEndDocument(); // finishing the document xmlWriter.Close(); // closing the document // report the number of elements loaded so far waysExportedMessage = String.Format(resourceManager.GetString("GPTools_OSMGPExport2OSM_ways_exported_msg"), lineCounter); message.AddMessage(waysExportedMessage); return; } //test if the feature geometry has multiple parts IGeometryCollection geometryCollection = currentFeature.Shape as IGeometryCollection; if (geometryCollection != null) { if (geometryCollection.GeometryCount == 1) { // convert the found polyline feature into a osm way representation to store into the OSM XML file way osmWay = ConvertFeatureToOSMWay(currentFeature, lineWorkspace, osmPointFeatureClass, pointOSMIDFieldIndex, lineTagsFieldIndex, lineOSMIDFieldIndex, lineChangesetFieldIndex, lineVersionFieldIndex, lineUIDFieldIndex, lineUserFieldIndex, lineTimeStampFieldIndex, lineVisibleFieldIndex, internalOSMExtensionVersion); waySerializer.Serialize(xmlWriter, osmWay, xmlnsEmpty); // increase the line counter for later status report lineCounter++; } else { relation osmRelation = ConvertRowToOSMRelation((IRow)currentFeature, lineWorkspace, lineTagsFieldIndex, lineOSMIDFieldIndex, lineChangesetFieldIndex, lineVersionFieldIndex, lineUIDFieldIndex, lineUserFieldIndex, lineTimeStampFieldIndex, lineVisibleFieldIndex, lineMembersFieldIndex, internalOSMExtensionVersion); multiPartElements.Add(osmRelation); // increase the line counter for later status report relationCounter++; } } currentFeature = searchCursor.NextFeature(); } } IFeatureClass osmPolygonFeatureClass = osmFeatureClasses.get_ClassByName(nameOfFeatureDataset + "_osm_ply"); IFeatureWorkspace commonWorkspace = ((IDataset)osmPolygonFeatureClass).Workspace as IFeatureWorkspace; if (osmPolygonFeatureClass == null) { message.AddError(120024, string.Format(resourceManager.GetString("GPTools_OSMGPExport2OSM_no_polygonfeatureclass"), nameOfFeatureDataset + "_osm_ply")); return; } using (ComReleaser comReleaser = new ComReleaser()) { searchCursor = osmPolygonFeatureClass.Search(null, false); comReleaser.ManageLifetime(searchCursor); IFeature currentFeature = searchCursor.NextFeature(); // collect the indices for the point feature class once int polygonOSMIDFieldIndex = osmPolygonFeatureClass.Fields.FindField("OSMID"); int polygonChangesetFieldIndex = osmPolygonFeatureClass.Fields.FindField("osmchangeset"); int polygonVersionFieldIndex = osmPolygonFeatureClass.Fields.FindField("osmversion"); int polygonUIDFieldIndex = osmPolygonFeatureClass.Fields.FindField("osmuid"); int polygonUserFieldIndex = osmPolygonFeatureClass.Fields.FindField("osmuser"); int polygonTimeStampFieldIndex = osmPolygonFeatureClass.Fields.FindField("osmtimestamp"); int polygonVisibleFieldIndex = osmPolygonFeatureClass.Fields.FindField("osmvisible"); int polygonTagsFieldIndex = osmPolygonFeatureClass.Fields.FindField("osmTags"); int polygonMembersFieldIndex = osmPolygonFeatureClass.Fields.FindField("osmMembers"); IWorkspace polygonWorkspace = ((IDataset)osmPolygonFeatureClass).Workspace; while (currentFeature != null) { if (TrackCancel.Continue() == false) { // properly close the document xmlWriter.WriteEndElement(); // closing the osm root element xmlWriter.WriteEndDocument(); // finishing the document xmlWriter.Close(); // closing the document // report the number of elements loaded so far waysExportedMessage = String.Format(resourceManager.GetString("GPTools_OSMGPExport2OSM_ways_exported_msg"), lineCounter); message.AddMessage(waysExportedMessage); message.AddAbort(resourceManager.GetString("GPTools_toolabort")); return; } //test if the feature geometry has multiple parts IGeometryCollection geometryCollection = currentFeature.Shape as IGeometryCollection; if (geometryCollection != null) { if (geometryCollection.GeometryCount == 1) { // convert the found polyline feature into a osm way representation to store into the OSM XML file way osmWay = ConvertFeatureToOSMWay(currentFeature, polygonWorkspace, osmPointFeatureClass, pointOSMIDFieldIndex, polygonTagsFieldIndex, polygonOSMIDFieldIndex, polygonChangesetFieldIndex, polygonVersionFieldIndex, polygonUIDFieldIndex, polygonUserFieldIndex, polygonTimeStampFieldIndex, polygonVisibleFieldIndex, internalOSMExtensionVersion); waySerializer.Serialize(xmlWriter, osmWay, xmlnsEmpty); // increase the line counter for later status report lineCounter++; } else { relation osmRelation = ConvertRowToOSMRelation((IRow)currentFeature, polygonWorkspace, polygonTagsFieldIndex, polygonOSMIDFieldIndex, polygonChangesetFieldIndex, polygonVersionFieldIndex, polygonUIDFieldIndex, polygonUserFieldIndex, polygonTimeStampFieldIndex, polygonVisibleFieldIndex, polygonMembersFieldIndex, internalOSMExtensionVersion); multiPartElements.Add(osmRelation); // increase the line counter for later status report relationCounter++; } } currentFeature = searchCursor.NextFeature(); } } waysExportedMessage = String.Format(resourceManager.GetString("GPTools_OSMGPExport2OSM_ways_exported_msg"), lineCounter); message.AddMessage(waysExportedMessage); // now let's go through the relation table message.AddMessage(resourceManager.GetString("GPTools_OSMGPExport2OSM_exporting_relations_msg")); ITable relationTable = commonWorkspace.OpenTable(nameOfFeatureDataset + "_osm_relation"); if (relationTable == null) { message.AddError(120025, String.Format(resourceManager.GetString("GPTools_OSMGPExport2OSM_no_relationTable"), nameOfFeatureDataset + "_osm_relation")); return; } System.Xml.Serialization.XmlSerializer relationSerializer = new System.Xml.Serialization.XmlSerializer(typeof(relation)); string relationsExportedMessage = String.Empty; using (ComReleaser comReleaser = new ComReleaser()) { ICursor rowCursor = relationTable.Search(null, false); comReleaser.ManageLifetime(rowCursor); IRow currentRow = rowCursor.NextRow(); // collect the indices for the relation table once int relationOSMIDFieldIndex = relationTable.Fields.FindField("OSMID"); int relationChangesetFieldIndex = relationTable.Fields.FindField("osmchangeset"); int relationVersionFieldIndex = relationTable.Fields.FindField("osmversion"); int relationUIDFieldIndex = relationTable.Fields.FindField("osmuid"); int relationUserFieldIndex = relationTable.Fields.FindField("osmuser"); int relationTimeStampFieldIndex = relationTable.Fields.FindField("osmtimestamp"); int relationVisibleFieldIndex = relationTable.Fields.FindField("osmvisible"); int relationTagsFieldIndex = relationTable.Fields.FindField("osmTags"); int relationMembersFieldIndex = relationTable.Fields.FindField("osmMembers"); IWorkspace polygonWorkspace = ((IDataset)osmPolygonFeatureClass).Workspace; while (currentRow != null) { if (TrackCancel.Continue() == false) { // properly close the document xmlWriter.WriteEndElement(); // closing the osm root element xmlWriter.WriteEndDocument(); // finishing the document xmlWriter.Close(); // closing the document // report the number of elements loaded so far relationsExportedMessage = String.Format(resourceManager.GetString("GPTools_OSMGPExport2OSM_relations_exported_msg"), relationCounter); message.AddMessage(relationsExportedMessage); message.AddAbort(resourceManager.GetString("GPTools_toolabort")); return; } relation osmRelation = ConvertRowToOSMRelation(currentRow, (IWorkspace)commonWorkspace, relationTagsFieldIndex, relationOSMIDFieldIndex, relationChangesetFieldIndex, relationVersionFieldIndex, relationUIDFieldIndex, relationUserFieldIndex, relationTimeStampFieldIndex, relationVisibleFieldIndex, relationMembersFieldIndex, internalOSMExtensionVersion); relationSerializer.Serialize(xmlWriter, osmRelation, xmlnsEmpty); // increase the line counter for later status report relationCounter++; currentRow = rowCursor.NextRow(); } } // lastly let's serialize the collected multipart-geometries back into relation elements foreach (relation currentRelation in multiPartElements) { if (TrackCancel.Continue() == false) { // properly close the document xmlWriter.WriteEndElement(); // closing the osm root element xmlWriter.WriteEndDocument(); // finishing the document xmlWriter.Close(); // closing the document // report the number of elements loaded so far relationsExportedMessage = String.Format(resourceManager.GetString("GPTools_OSMGPExport2OSM_relations_exported_msg"), relationCounter); message.AddMessage(relationsExportedMessage); return; } relationSerializer.Serialize(xmlWriter, currentRelation, xmlnsEmpty); relationCounter++; } relationsExportedMessage = String.Format(resourceManager.GetString("GPTools_OSMGPExport2OSM_relations_exported_msg"), relationCounter); message.AddMessage(relationsExportedMessage); xmlWriter.WriteEndElement(); // closing the osm root element xmlWriter.WriteEndDocument(); // finishing the document xmlWriter.Close(); // closing the document } catch (Exception ex) { message.AddError(11111, ex.StackTrace); message.AddError(120026, ex.Message); } }
static XmlStreamingDeserializer() { ns = new System.Xml.Serialization.XmlSerializerNamespaces(); ns.Add("", ""); }
public void Save(string filename) { var s = new System.Xml.Serialization.XmlSerializer(this.GetType()); var ns = new System.Xml.Serialization.XmlSerializerNamespaces(); ns.Add("", ""); using (System.IO.StreamWriter writer = System.IO.File.CreateText(filename)) { s.Serialize(writer, this, ns); writer.Close(); } }
public void GetDirectoriesForCiscoIPPhone() { CiscoIPPhoneMenuType menu = new CiscoIPPhoneMenuType(); menu.Prompt = "Sélectionner un répertoire"; menu.Title = "Répertoires"; try { List<CiscoIPPhoneMenuItemType> menus = new List<CiscoIPPhoneMenuItemType>(); foreach (DirectoryType dt in Global.directoryConfiguration) { CiscoIPPhoneMenuItemType menuitem = null; bool isIPPhoneCompliant = false; if (dt.Item is SqlDatasourceType) { SqlDatasourceType sdt = dt.Item as SqlDatasourceType; if (sdt.ipphonefilter != null) { isIPPhoneCompliant = true; } } else if (dt.Item is LdapDatasourceType) { LdapDatasourceType ldt = dt.Item as LdapDatasourceType; if (ldt.ipphonefilter != null) { isIPPhoneCompliant = true; } } else if (dt.Item is CiscoDatasourceType) { CiscoDatasourceType cdt = dt.Item as CiscoDatasourceType; if (cdt.ipphonefilter != null) { isIPPhoneCompliant = true; } } if (isIPPhoneCompliant) { menuitem = new CiscoIPPhoneMenuItemType(); menuitem.Name = dt.name; menuitem.URL = this.Context.Request.Url.AbsoluteUri.Substring(0, this.Context.Request.Url.AbsoluteUri.LastIndexOf("/") + 1) + "SearchForCiscoIPPhone?directory=" + System.Web.HttpUtility.UrlEncode(dt.name); menus.Add(menuitem); } } if (menus.Count > 0) { menu.MenuItem = menus.ToArray(); } else { this.Context.Response.Redirect(this.Context.Request.Url.AbsoluteUri.Substring(0, this.Context.Request.Url.AbsoluteUri.LastIndexOf("/") + 1) + "Error?error=" + System.Web.HttpUtility.UrlEncode("No ipphone directories finded"), false); //return menu; } //return menu; CiscoIPPhoneMenuTypeSerializer xml = new CiscoIPPhoneMenuTypeSerializer(); System.Xml.XmlWriterSettings settings = new System.Xml.XmlWriterSettings();; settings.Encoding = System.Text.Encoding.UTF8; System.IO.MemoryStream ms = new System.IO.MemoryStream(); System.Xml.XmlWriter xw = System.Xml.XmlWriter.Create(ms, settings); System.Xml.Serialization.XmlSerializerNamespaces xmlnsEmpty = new System.Xml.Serialization.XmlSerializerNamespaces(); xmlnsEmpty.Add("", ""); xml.Serialize(xw, menu, xmlnsEmpty); ms.Position = 0; this.Context.Response.ContentType = "text/xml"; this.Context.Response.ContentEncoding = System.Text.Encoding.UTF8; this.Context.Response.Write(GetStringFromStream(ms)); //xw.Flush(); //xw.Close(); } catch (Exception e) { log.Error("Unable get directories: " + e.Message); this.Context.Response.Redirect(this.Context.Request.Url.AbsoluteUri.Substring(0, this.Context.Request.Url.AbsoluteUri.LastIndexOf("/") + 1) + "Error?error=" + System.Web.HttpUtility.UrlEncode(e.Message), false); //return menu; } }
public void SendReport(CrashReportDetails crashReport) { // Convert ReportItems to EmailBody string emailBody = ""; using (System.IO.StringWriter stringWriter = new System.IO.StringWriter()) { System.Xml.Serialization.XmlSerializerNamespaces ns = new System.Xml.Serialization.XmlSerializerNamespaces(); ns.Add("", ""); System.Xml.Serialization.XmlSerializer x = new System.Xml.Serialization.XmlSerializer(crashReport.GetType(), crashReport.GetItemTypes()); x.Serialize(stringWriter, crashReport, ns); emailBody = stringWriter.ToString(); } using (MailMessage msg = new MailMessage()) { msg.From = new MailAddress(EmailFromAddress); foreach (string s in EmailToAddress.Split(";".ToCharArray())) { msg.To.Add(s); } if (String.IsNullOrEmpty(EmailSubject)) msg.Subject = Application.ProductName + " - Error Report"; else msg.Subject = EmailSubject; msg.Body = emailBody; SmtpClient smtp = null; if (String.IsNullOrEmpty(EmailHost)) { smtp = new SmtpClient(); } else { if (EmailPort == 0) smtp = new SmtpClient(EmailHost); else smtp = new SmtpClient(EmailHost, EmailPort); } if (String.IsNullOrEmpty(EmailUsername) && String.IsNullOrEmpty(EmailPassword)) smtp.UseDefaultCredentials = true; else smtp.Credentials = new System.Net.NetworkCredential(EmailUsername, EmailPassword); smtp.EnableSsl = EmailSSL; smtp.Send(msg); } }
public void Save() { List<Trigger> list = _sortedlist.Values.ToList(); try { System.Xml.Serialization.XmlSerializerNamespaces ns = new System.Xml.Serialization.XmlSerializerNamespaces(); ns.Add(String.Empty, String.Empty); using (System.IO.TextWriter writer = new System.IO.StreamWriter(_filepath)) { System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(typeof(List<Trigger>)); serializer.Serialize(writer, list,ns); } }catch(Exception e) { System.Diagnostics.Debug.WriteLine(e.ToString()); } }
private void _reportListBox_DoubleClick(object sender, EventArgs e) { object reportItem = _reportListBox.SelectedItem; if (reportItem != null) { using (System.IO.StringWriter stringWriter = new System.IO.StringWriter()) { //Create our own namespaces for the output System.Xml.Serialization.XmlSerializerNamespaces ns = new System.Xml.Serialization.XmlSerializerNamespaces(); ns.Add("", ""); System.Xml.Serialization.XmlSerializer x = new System.Xml.Serialization.XmlSerializer(reportItem.GetType()); x.Serialize(stringWriter, reportItem, ns); MessageBox.Show(this, stringWriter.ToString(), reportItem.GetType().ToString()); } } }
// Changes for NGT-3035 private static XmlNode SerializeObjectToXmlNode(Object obj) { if (obj == null) throw new ArgumentNullException("Argument cannot be null"); XmlNode resultNode = null; System.Xml.Serialization.XmlSerializer xmlSerializer = new System.Xml.Serialization.XmlSerializer(obj.GetType()); System.Xml.Serialization.XmlSerializerNamespaces ns = new System.Xml.Serialization.XmlSerializerNamespaces(); ns.Add("", ""); using (MemoryStream memoryStream = new MemoryStream()) { try { xmlSerializer.Serialize(memoryStream, obj, ns); } catch (InvalidOperationException) { return null; } memoryStream.Position = 0; XmlDocument doc = new XmlDocument(); doc.Load(memoryStream); resultNode = doc.DocumentElement; } return resultNode; }
public void SendReport(CrashReportDetails crashReport) { // Create xml file containing reportItems string prettyXml = ""; using (System.IO.StringWriter stringWriter = new System.IO.StringWriter()) { System.Xml.Serialization.XmlSerializerNamespaces ns = new System.Xml.Serialization.XmlSerializerNamespaces(); ns.Add("", ""); System.Xml.Serialization.XmlSerializer x = new System.Xml.Serialization.XmlSerializer(crashReport.GetType(), crashReport.GetItemTypes()); x.Serialize(stringWriter, crashReport, ns); prettyXml = stringWriter.ToString(); } using (System.IO.StreamWriter streamWriter = new System.IO.StreamWriter(new System.IO.MemoryStream())) { streamWriter.WriteLine(prettyXml); streamWriter.Flush(); streamWriter.BaseStream.Position = 0; ZipStore.AddStream(System.IO.Compression.ZipStorer.Compression.Deflate, "crashrpt.xml", streamWriter.BaseStream, DateTime.Now, ""); } ZipStore.Close(); ZipStream.Position = 0; // Upload File HttpUploadFile(HttpUrl, ZipStream, FileParamName, FileName, "application/x-zip-compressed", HttpParams); }
public void Serialize(System.IO.Stream stream, object o, System.Xml.Serialization.XmlSerializerNamespaces namespaces) { }
public void Serialize(System.Xml.XmlWriter xmlWriter, object o, System.Xml.Serialization.XmlSerializerNamespaces namespaces) { }
public XmlSerializerNamespaces(System.Xml.Serialization.XmlSerializerNamespaces namespaces) { }
public XmlSerializationWriter1() { xsn = new System.Xml.Serialization.XmlSerializerNamespaces(); xsn.Add("", ""); }