System.Xml.XmlDocument.LoadXml(string)

Here are the examples of the csharp api System.Xml.XmlDocument.LoadXml(string) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

936 Examples 7

19 View Source File : DotNetToJScript.cs
License : MIT License
Project Creator : 1y0n

static string CreateScriptlet(string script, string script_name, bool register_script, Guid clsid)
        {
            XmlDoreplacedent doc = new XmlDoreplacedent();
            doc.LoadXml(Global_Var.scriptlet_template);
            XmlWriterSettings settings = new XmlWriterSettings();
            settings.Indent = true;
            settings.NewLineOnAttributes = true;
            settings.Encoding = new UTF8Encoding(false);

            XmlElement reg_node = (XmlElement)doc.SelectSingleNode("/package/component/registration");
            XmlNode root_node = register_script ? reg_node : doc.SelectSingleNode("/package/component");
            XmlNode script_node = root_node.AppendChild(doc.CreateElement("script"));
            script_node.Attributes.Append(doc.CreateAttribute("language")).Value = script_name;
            script_node.AppendChild(doc.CreateCDataSection(script));
            if (clsid != Guid.Empty)
            {
                reg_node.SetAttribute("clreplacedid", clsid.ToString("B"));
            }

            using (MemoryStream stm = new MemoryStream())
            {
                using (XmlWriter writer = XmlWriter.Create(stm, settings))
                {
                    doc.Save(writer);
                }
                return Encoding.UTF8.GetString(stm.ToArray());
            }
        }

19 View Source File : FauxDeployCMAgent.cs
License : GNU General Public License v3.0
Project Creator : 1RedOne

public static void SendDiscovery(string CMServerName, string clientName, string domainName, string SiteCode,
            string CertPath, SecureString preplaced, SmsClientId clientId, ILog log, bool enumerateAndAddCustomDdr = false)
        {
            using (MessageCertificateX509Volatile certificate = new MessageCertificateX509Volatile(CertPath, preplaced))

            {
                //X509Certificate2 thisCert = new X509Certificate2(CertPath, preplaced);

                log.Info($"Got SMSID from registration of: {clientId}");

                // create base DDR Message
                ConfigMgrDataDiscoveryRecordMessage ddrMessage = new ConfigMgrDataDiscoveryRecordMessage
                {
                    // Add necessary discovery data
                    SmsId = clientId,
                    ADSiteName = "Default-First-Site-Name", //Changed from 'My-AD-SiteName
                    SiteCode = SiteCode,
                    DomainName = domainName,
                    NetBiosName = clientName
                };

                ddrMessage.Discover();
                // Add our certificate for message signing
                ddrMessage.AddCertificateToMessage(certificate, CertificatePurposes.Signing);
                ddrMessage.AddCertificateToMessage(certificate, CertificatePurposes.Encryption);
                ddrMessage.Settings.HostName = CMServerName;
                ddrMessage.Settings.Compression = MessageCompression.Zlib;
                ddrMessage.Settings.ReplyCompression = MessageCompression.Zlib;
                Debug.WriteLine("Sending [" + ddrMessage.DdrInstances.Count + "] instances of Discovery data to CM");
                if (enumerateAndAddCustomDdr)
                {
                    //see current value for the DDR message
                    var OSSetting = ddrMessage.DdrInstances.OfType<InventoryInstance>().Where(m => m.Clreplaced == "CCM_DiscoveryData");

                    ////retrieve actual setting
                    string osCaption = (from x in new ManagementObjectSearcher("SELECT Caption FROM Win32_OperatingSystem").Get().Cast<ManagementObject>()
                                        select x.GetPropertyValue("Caption")).FirstOrDefault().ToString();

                    XmlDoreplacedent xmlDoc = new XmlDoreplacedent();

                    ////retrieve reported value
                    xmlDoc.LoadXml(ddrMessage.DdrInstances.OfType<InventoryInstance>().FirstOrDefault(m => m.Clreplaced == "CCM_DiscoveryData")?.InstanceDataXml.ToString());

                    ////Set OS to correct setting
                    xmlDoc.SelectSingleNode("/CCM_DiscoveryData/PlatformID").InnerText = "Microsoft Windows NT Server 10.0";

                    ////Remove the instance
                    ddrMessage.DdrInstances.Remove(ddrMessage.DdrInstances.OfType<InventoryInstance>().FirstOrDefault(m => m.Clreplaced == "CCM_DiscoveryData"));

                    CMFauxStatusViewClreplacedesFixedOSRecord FixedOSRecord = new CMFauxStatusViewClreplacedesFixedOSRecord
                    {
                        PlatformId = osCaption
                    };
                    InventoryInstance instance = new InventoryInstance(FixedOSRecord);

                    ////Add new instance
                    ddrMessage.DdrInstances.Add(instance);
                }

                ddrMessage.SendMessage(Sender);

                ConfigMgrHardwareInventoryMessage hinvMessage = new ConfigMgrHardwareInventoryMessage();
                hinvMessage.Settings.HostName = CMServerName;
                hinvMessage.SmsId = clientId;
                hinvMessage.Settings.Compression = MessageCompression.Zlib;
                hinvMessage.Settings.ReplyCompression = MessageCompression.Zlib;
                //hinvMessage.Settings.Security.EncryptMessage = true;
                hinvMessage.Discover();

                var Clreplacedes = CMFauxStatusViewClreplacedes.GetWMIClreplacedes();
                foreach (string Clreplaced in Clreplacedes)
                {
                    try { hinvMessage.AddInstancesToInventory(WmiClreplacedToInventoryReportInstance.WmiClreplacedToInventoryInstances(@"root\cimv2", Clreplaced)); }
                    catch { log.Info($"!!!Adding clreplaced : [{Clreplaced}] :( not found on this system"); }
                }

                var SMSClreplacedes = new List<string> { "SMS_Processor", "CCM_System", "SMS_LogicalDisk" };
                foreach (string Clreplaced in SMSClreplacedes)
                {
                    log.Info($"---Adding clreplaced : [{Clreplaced}]");
                    try { hinvMessage.AddInstancesToInventory(WmiClreplacedToInventoryReportInstance.WmiClreplacedToInventoryInstances(@"root\cimv2\sms", Clreplaced)); }
                    catch { log.Info($"!!!Adding clreplaced : [{Clreplaced}] :( not found on this system"); }
                }

                hinvMessage.AddCertificateToMessage(certificate, CertificatePurposes.Signing | CertificatePurposes.Encryption);
                hinvMessage.Validate(Sender);
                hinvMessage.SendMessage(Sender);
            };
        }

19 View Source File : GameXMLUtils.cs
License : Apache License 2.0
Project Creator : AantCoder

public T FromXml<T>(string dataXML)
            where T : new()
        {
            lock (SuncObj)
            {
                XmlDoreplacedent xmlDoreplacedent = new XmlDoreplacedent();
                xmlDoreplacedent.LoadXml(dataXML);
                Scribe.loader.curXmlParent = xmlDoreplacedent.DoreplacedentElement;
                Scribe.mode = LoadSaveMode.LoadingVars;
                try
                {
                    /*
                    bool flag = typeof(T).IsValueType || typeof(Name).IsreplacedignableFrom(typeof(T));
                    if (!flag)
                    {
                        Scribe.loader.crossRefs.RegisterForCrossRefResolve(exposable);
                    }*/
                    FromXmlIsActive = true;
                    Scribe.EnterNode(rootElementName);
                    var thing = new T();
                    Scribe_Deep.Look<T>(ref thing, "saveable", new object[0]);

                    // Scribe.loader.crossRefs.ResolveAllCrossReferences()

                    return thing;
                }
                finally
                {
                    try
                    {
                        //Finish()
                        Scribe.loader.FinalizeLoading();
                    }
                    finally
                    {
                        FromXmlIsActive = false;
                    }
                }
            }
        }

19 View Source File : XmlMessageParser.cs
License : MIT License
Project Creator : ABN-SFLookupTechnicalSupport

private static XmlDoreplacedent LoadXml(string xml) {
         XmlDoreplacedent XmlDoc = new XmlDoreplacedent();
         try {
            XmlDoc.LoadXml(xml);
         }
         catch {
            throw;
         }
         return XmlDoc;
      }

19 View Source File : DataBuilder.cs
License : MIT License
Project Creator : abvogel

public void AppendData(String DataXML, String SchemaXML)
        {
            var _dataXml = new XmlDoreplacedent();
            _dataXml.LoadXml(DataXML);

            var _schemaXml = new XmlDoreplacedent();
            _schemaXml.LoadXml(SchemaXML);

            this.AppendData(_dataXml, _schemaXml);
        }

19 View Source File : DataBuilder.cs
License : MIT License
Project Creator : abvogel

public XmlDoreplacedent BuildContentTypesXML()
        {
            String contentType = "<?xml version=\"1.0\" encoding=\"utf-8\"?><Types xmlns=\"http://schemas.openxmlformats.org/package/2006/content-types\"><Default Extension=\"xml\" ContentType=\"application/octet-stream\" /></Types>";
            XmlDoreplacedent content = new XmlDoreplacedent();
            content.LoadXml(contentType);
            return content;
        }

19 View Source File : DataBuilder.cs
License : MIT License
Project Creator : abvogel

private bool HasManyToManyAttribute(string fetchXml)
        {
            XmlDoreplacedent xml = new XmlDoreplacedent();
            xml.LoadXml(fetchXml);

            if (xml.SelectSingleNode("fetch/enreplacedy/link-enreplacedy[@intersect='true']//attribute") != null)
            {
                return true;
            }

            return false;
        }

19 View Source File : DataBuilder.cs
License : MIT License
Project Creator : abvogel

private string GetFirstLinkEnreplacedyName(string fetchXml)
        {
            XmlDoreplacedent xml = new XmlDoreplacedent();
            xml.LoadXml(fetchXml);

            return xml.SelectSingleNode("fetch/enreplacedy/link-enreplacedy[@intersect='true']/@name").Value;
        }

19 View Source File : Import-CrmDataPackage.cs
License : MIT License
Project Creator : abvogel

protected override void ProcessRecord()
        {
            try
            {
                CrmDataPackage package = new CrmDataPackage();
                using (ZipFile zip = new ZipFile())
                {
                    var zipData = ZipFile.Read(ZipPath);
                    foreach (ZipEntry entry in zipData.Entries)
                    {
                        XmlDoreplacedent Xml = new XmlDoreplacedent();
                        using (var ms = new MemoryStream())
                        {
                            entry.Extract(ms);
                            ms.Position = 0;
                            var sr = new StreamReader(ms);
                            var myStr = sr.ReadToEnd();
                            Xml.LoadXml(myStr);
                        }
                        switch(entry.FileName)
                        {
                            case "data.xml":
                                package.Data = Xml;
                                break;
                            case "data_schema.xml":
                                package.Schema = Xml;
                                break;
                            default:
                                package.ContentTypes = Xml;
                                break;
                        }
                    }

                    base.WriteObject(package);
                }
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }

19 View Source File : DataBuilder.cs
License : MIT License
Project Creator : abvogel

public void RemoveData(String DataXML, String SchemaXML)
        {
            var _dataXml = new XmlDoreplacedent();
            _dataXml.LoadXml(DataXML);

            var _schemaXml = new XmlDoreplacedent();
            _schemaXml.LoadXml(SchemaXML);

            RemoveData(_dataXml, _schemaXml);
        }

19 View Source File : EpubBuilder.cs
License : GNU General Public License v3.0
Project Creator : Aeroblast

void SetCover()//等KindlePosToUri不再使用后 关系到xhtml相关变量
        {
            if (azw3.mobi_header.extMeta.id_value.ContainsKey(201))
            {
                string cover;
                int off = (int)azw3.mobi_header.extMeta.id_value[201];//CoverOffset
                if (azw3.mobi_header.first_res_index + off < azw3.section_count)
                    if (azw3.sections[azw3.mobi_header.first_res_index + off].type == "Image")
                    {
                        cover_name = AddImage(off, "Cover");

                        if (NeedCreateCoverDoreplacedent())
                        {
                            Log.log("[Info]Adding a cover doreplacedent.");

                            string t = File.ReadAllText("template\\template_cover.txt");
                            var (w, h) = Util.GetImageSize(imgs[img_names.IndexOf(cover_name)]);
                            cover = t.Replace("{❕image}", cover_name).Replace("{❕w}", w.ToString()).Replace("{❕h}", h.ToString());

                            string coverDoreplacedentName = "cover.xhtml";
                            if (renameXhtmlWithId)
                            {
                                var id = azw3.resc.spine.GetElementsByTagName("itemref")[0].Attributes.GetNamedItem("idref").Value;
                                coverDoreplacedentName = id + ".xhtml";
                            }
                            xhtml_names.Insert(0, coverDoreplacedentName);
                            XmlDoreplacedent cover_ = new XmlDoreplacedent();
                            cover_.LoadXml(cover);
                            xhtmls.Insert(0, cover_);
                            extraCoverDocAdded = true;
                        }

                    }
                return;
            }
            //if (azw3.mobi_header.extMeta.id_string.ContainsKey(129)){}
            Log.log("[Warn]No Cover!");
        }

19 View Source File : TocManage.cs
License : MIT License
Project Creator : Aeroblast

public static void Parse2()
        {
            var f = Program.epub.toc.GetFile() as TextEpubFileEntry;
            tocPath = f.fullName;
            XmlDoreplacedent xml = new XmlDoreplacedent();
            xml.LoadXml(f.text);
            var root = xml.GetElementsByTagName("navMap")[0];
            tocTree = new TocItem();
            tocTree.children = new List<TocItem>();
            Parse2Helper(root, tocTree);

        }

19 View Source File : TocManage.cs
License : MIT License
Project Creator : Aeroblast

public static void Parse3()
        {
            if (Program.epub.toc.mediaType == "application/x-dtbncx+xml")
            {
                Parse2(); return;
            }
            var f = Program.epub.toc.GetFile() as TextEpubFileEntry;

            tocPath = f.fullName;
            XmlDoreplacedent xml = new XmlDoreplacedent();
            xml.LoadXml(f.text);
            var navs = xml.GetElementsByTagName("nav");
            foreach (XmlElement nav in navs)
            {
                if (nav.GetAttribute("epub:type") == "toc")
                {
                    tocTree = new TocItem();
                    tocTree.children = new List<TocItem>();
                    var root = nav.GetElementsByTagName("ol")[0];
                    Parse3Helper(root, tocTree);
                    return;
                }
            }
            //We have <nav>, but no epub:type is toc, so last try:
            if (navs.Count > 0)
            {
                var nav = navs[0] as XmlElement;
                tocTree = new TocItem();
                tocTree.children = new List<TocItem>();
                var root = nav.GetElementsByTagName("ol")[0];
                Parse3Helper(root, tocTree);
            }
        }

19 View Source File : XmlHelper.cs
License : MIT License
Project Creator : afaniuolo

public static List<string> GetXmlElementNames(string fieldValue)
		{
			List<string> elementNames = new List<string>();
			XmlDoreplacedent xmlDoreplacedent = new XmlDoreplacedent();
			fieldValue = SanitizeFieldValue(fieldValue);
			try
			{
				xmlDoreplacedent.LoadXml(AddParentNodeAndEncodeElementValue(fieldValue));

				foreach (XmlNode childNode in xmlDoreplacedent.ChildNodes.Item(0).ChildNodes)
				{
					elementNames.Add(childNode.Name);
				}
			}
			catch (Exception e)
			{
				Console.WriteLine();
				Console.WriteLine("XmlHelper - GetXmlElementNames - Failed to parse Xml value - Value = " + fieldValue);
				Console.WriteLine(e);
				Console.WriteLine();
				Console.WriteLine("See logs for more details in the logs folder.");
				Console.WriteLine();
				throw;
			}

			return elementNames;
		}

19 View Source File : XmlHelper.cs
License : MIT License
Project Creator : afaniuolo

public static string StripHtml(string fieldValue)
		{
			if (!string.IsNullOrEmpty(fieldValue))
			{
				XmlDoreplacedent xmlDoreplacedent = new XmlDoreplacedent();
				fieldValue = SanitizeFieldValue(fieldValue);
				try
				{
					xmlDoreplacedent.LoadXml(AddParentNodeAndEncodeElementValue(fieldValue));
					return xmlDoreplacedent.InnerText;
				}
				catch (Exception e)
				{
					Console.WriteLine();
					Console.WriteLine("XmlHelper - StripHtml - Failed to parse Xml value - Value = " + fieldValue);
					Console.WriteLine(e);
					Console.WriteLine();
				}
				
			}
			return fieldValue;
		}

19 View Source File : XmlHelper.cs
License : MIT License
Project Creator : afaniuolo

public static string GetXmlElementValue(string fieldValue, string elementName, bool throwOnError = false)
		{
			if (!string.IsNullOrEmpty(fieldValue) && !string.IsNullOrEmpty(elementName))
			{
				XmlDoreplacedent xmlDoreplacedent = new XmlDoreplacedent();
				fieldValue = SanitizeFieldValue(fieldValue);
				try
				{
					xmlDoreplacedent.LoadXml(AddParentNodeAndEncodeElementValue(fieldValue));

					XmlNodeList elementsByTagName = xmlDoreplacedent.GetElementsByTagName(elementName);

					if (elementsByTagName.Count > 0)
					{
						var element = elementsByTagName.Item(0);
						return element?.InnerXml;
					}
				}
				catch (Exception e)
				{
					Console.WriteLine();
					Console.WriteLine("XmlHelper - GetXmlElementValue - Failed to parse Xml value - Value = " + fieldValue);
					Console.WriteLine(e);
					Console.WriteLine();
					if (throwOnError)
					{
						Console.WriteLine("See logs for more details in the logs folder.");
						Console.WriteLine();
						throw;
					}
				}			
			}
			return string.Empty;
		}

19 View Source File : XmlHelper.cs
License : MIT License
Project Creator : afaniuolo

public static XmlNode GetXmlElementNode(string fieldValue, string elementName, bool throwOnError = false)
		{
			if (!string.IsNullOrEmpty(fieldValue) && !string.IsNullOrEmpty(elementName))
			{
				XmlDoreplacedent xmlDoreplacedent = new XmlDoreplacedent();
				fieldValue = SanitizeFieldValue(fieldValue);
				try
				{
					xmlDoreplacedent.LoadXml(AddParentNodeAndEncodeElementValue(fieldValue));

					XmlNodeList elementsByTagName = xmlDoreplacedent.GetElementsByTagName(elementName);

					if (elementsByTagName.Count > 0)
					{
						return elementsByTagName.Item(0);
					}
				}
				catch (Exception e)
				{
					Console.WriteLine();
					Console.WriteLine("XmlHelper - GetXmlElementNode - Failed to parse Xml value - Value = " + fieldValue);
					Console.WriteLine(e);
					Console.WriteLine();
					if (throwOnError)
					{
						Console.WriteLine("See logs for more details in the logs folder.");
						Console.WriteLine();
						throw;
					}
				}			
			}
			return null;
		}

19 View Source File : XmlHelper.cs
License : MIT License
Project Creator : afaniuolo

public static XmlNodeList GetXmlElementNodeList(string fieldValue, string elementName, bool throwOnError = false)
		{
			if (!string.IsNullOrEmpty(fieldValue) && !string.IsNullOrEmpty(elementName))
			{
				XmlDoreplacedent xmlDoreplacedent = new XmlDoreplacedent();
				fieldValue = SanitizeFieldValue(fieldValue);
				try
				{
					xmlDoreplacedent.LoadXml(AddParentNodeAndEncodeElementValue(fieldValue));

					XmlNodeList elementsByTagName = xmlDoreplacedent.GetElementsByTagName(elementName);

					if (elementsByTagName.Count > 0)
					{
						return elementsByTagName;
					}
				}
				catch (Exception e)
				{
					Console.WriteLine();
					Console.WriteLine("XmlHelper - GetXmlElementNodeList - Failed to parse Xml value - Value = " + fieldValue);
					Console.WriteLine(e);
					Console.WriteLine();
					if (throwOnError)
					{
						Console.WriteLine("See logs for more details in the logs folder.");
						Console.WriteLine();
						throw;
					}
				}				
			}
			return null;
		}

19 View Source File : RSA.cs
License : GNU General Public License v3.0
Project Creator : aiportal

public static string SignXml(string xml, string keyName = null)
		{
			XmlDoreplacedent doc = new XmlDoreplacedent();
			doc.LoadXml(xml);
			RsaSign(doc, KeyStorage.GetPrivateKey(keyName));
			return doc.OuterXml;
		}

19 View Source File : RSA.cs
License : GNU General Public License v3.0
Project Creator : aiportal

public static bool VerifyXml(string xml, string keyName = null)
		{
			XmlDoreplacedent doc = new XmlDoreplacedent();
			doc.LoadXml(xml);
			return RsaVerify(doc, KeyStorage.GetPublicKey(keyName));
		}

19 View Source File : ConfigurationBase.cs
License : GNU General Public License v3.0
Project Creator : aiportal

public void SaveConfiguration(string filename)
		{
			try
			{
				Dictionary<string, object> dic = this.GetConfigurations();
				XmlDoreplacedent doc = new XmlDoreplacedent();
				doc.LoadXml(string.Format(@"<{0}></{0}>", ROOT_ELEMENT));
				foreach (string key in dic.Keys)
				{
					var node = doc.CreateElement(key);
					node.InnerText = DataConverter.Serilize(dic[key]);
					doc.DoreplacedentElement.AppendChild(node);
				}

				string xml;
				using (StringWriter sw = new StringWriter())
				using (XmlTextWriter tw = new XmlTextWriter(sw))
				{
					doc.WriteTo(tw);
					xml = sw.GetStringBuilder().ToString();
				}

				byte[] bs = Convert.FromBase64String(Encryption.Encrypt(xml));
				File.WriteAllBytes(filename, bs);
			}
			catch (Exception ex) { TraceLogger.Instance.WriteException(ex); throw; }
		}

19 View Source File : Serialization.cs
License : GNU General Public License v3.0
Project Creator : aiportal

public static T FromXml<T>(string xml)
			where T : new()
		{
			T result = new T();
			System.Xml.XmlDoreplacedent doc = new System.Xml.XmlDoreplacedent();
			doc.LoadXml(xml);

			if (doc.HasChildNodes)
			{
				PropertyInfo[] props = typeof(T).GetProperties(BindingFlags.Instance | BindingFlags.Public);
				foreach (var p in props)
				{
					var node = doc.DoreplacedentElement[p.Name];
					if (node != null)
						p.SetValue(result, Convert.ChangeType(node.InnerText, p.PropertyType), null);
				}
			}
			return result;
		}

19 View Source File : ConfigurationBase.cs
License : GNU General Public License v3.0
Project Creator : aiportal

public void LoadConfiguration(string filename)
		{
			try
			{
				byte[] bs = File.ReadAllBytes(filename);
				string xml = Encryption.Decrypt(Convert.ToBase64String(bs));

				XmlDoreplacedent doc = new XmlDoreplacedent();
				doc.LoadXml(xml);
				XmlNode root = doc.SelectSingleNode(ROOT_ELEMENT);

				Dictionary<string, object> dic = new Dictionary<string, object>();
				for (int i = 0; i < root.ChildNodes.Count; ++i)
					dic[root.ChildNodes[i].Name] = root.ChildNodes[i].InnerText;

				this.SetConfigurations(dic);
			}
			catch (Exception ex) { TraceLogger.Instance.WriteException(ex); throw; }
		}

19 View Source File : Serialization.cs
License : GNU General Public License v3.0
Project Creator : aiportal

public static string ToXml(object obj, string rootElement = null)
		{
			System.Xml.XmlDoreplacedent doc = new System.Xml.XmlDoreplacedent();
			doc.LoadXml(string.Format(@"<{0}></{0}>", obj.GetType().Name));

			PropertyInfo[] props = obj.GetType().GetProperties(BindingFlags.Instance | BindingFlags.Public);
			foreach (var p in props)
			{
				var node = doc.CreateElement(p.Name);
				node.InnerText = Convert.ToString(p.GetValue(obj, null));
				doc.DoreplacedentElement.AppendChild(node);
			}
			return doc.OuterXml;
		}

19 View Source File : ConfigurationBase.cs
License : GNU General Public License v3.0
Project Creator : aiportal

public void SaveConfiguration(string filename)
		{
			try
			{
				Dictionary<string, object> dic = this.GetConfigurations();
				XmlDoreplacedent doc = new XmlDoreplacedent();
				doc.LoadXml(string.Format(@"<{0}></{0}>", ROOT_ELEMENT));
				foreach (string key in dic.Keys)
				{
					var node = doc.CreateElement(key);
					node.InnerText = DataConverter.Serialize(dic[key]);
					doc.DoreplacedentElement.AppendChild(node);
				}

				string xml;
				using (StringWriter sw = new StringWriter())
				using (XmlTextWriter tw = new XmlTextWriter(sw))
				{
					doc.WriteTo(tw);
					xml = sw.GetStringBuilder().ToString();
				}

				byte[] bs = Convert.FromBase64String(Encryption.Encrypt(xml));
				File.WriteAllBytes(filename, bs);
			}
			catch (Exception ex) { TraceLogger.Instance.WriteException(ex); throw; }
		}

19 View Source File : LogsController.cs
License : MIT License
Project Creator : akasarto

private LogEntryViewModel BuildLogEntryViewModel(LogEnreplacedy enreplacedy)
		{
			var model = new LogEntryViewModel();

			if (enreplacedy != null)
			{
				model.InjectFrom(enreplacedy);

				if (!string.IsNullOrWhiteSpace(enreplacedy.Properties))
				{
					var xDoc = new XmlDoreplacedent();

					xDoc.LoadXml(enreplacedy.Properties);

					var nodes = xDoc.FirstChild.SelectNodes("property");

					foreach (XmlNode node in nodes)
					{
						model.Properties.Add(
							node.Attributes["key"].Value,
							node.InnerText
						);
					}
				}
			}

			return model;
		}

19 View Source File : RetrieveActivityBase.cs
License : MIT License
Project Creator : akaskela

protected List<Enreplacedy> RetrieveAnnotationEnreplacedy(CodeActivityContext context, ColumnSet noteColumns, int maxRecords = 1)
        {
            double miunutesOld = 0;
            List<Enreplacedy> returnValue = new List<Enreplacedy>();
            IWorkflowContext workflowContext = context.GetExtension<IWorkflowContext>();
            IOrganizationServiceFactory serviceFactory = context.GetExtension<IOrganizationServiceFactory>();
            IOrganizationService service = serviceFactory.CreateOrganizationService(workflowContext.InitiatingUserId);

            int? objectTypeCode = this.RetrieveEnreplacedyObjectTypeCode(workflowContext, service);
            if (objectTypeCode == null)
            {
                throw new ArgumentException($"Objecttypecode not found in metadata for enreplacedy {workflowContext.PrimaryEnreplacedyName}");
            }

            ExecuteFetchResponse fetchResponse = null;
            ExecuteFetchRequest request = new ExecuteFetchRequest();
            try
            {
                if (String.IsNullOrWhiteSpace(this.FileName.Get(context)))
                {
                    request.FetchXml =
                        [email protected]"<fetch version=""1.0"" output-format=""xml-platform"" mapping=""logical"" distinct=""false"" page=""1"" count=""{maxRecords}"">
                              <enreplacedy name=""annotation"">
                                <attribute name=""annotationid"" />
                                <attribute name=""createdon"" />
                                <filter type=""and"">
                                  <condition attribute=""isdoreplacedent"" operator=""eq"" value=""1"" />
                                  <condition attribute=""objectid"" operator=""eq"" value=""{workflowContext.PrimaryEnreplacedyId}"" />
                                  <condition attribute=""objecttypecode"" operator=""eq"" value=""{objectTypeCode.Value}"" />
                                </filter>
                                <order attribute=""createdon"" descending=""true"" />
                              </enreplacedy>
                            </fetch>";
                }
                else
                {
                    request.FetchXml =
                            [email protected]"<fetch version=""1.0"" output-format=""xml-platform"" mapping=""logical"" distinct=""false"" page=""1"" count=""{maxRecords}"">
                              <enreplacedy name=""annotation"">
                                <attribute name=""annotationid"" />
                                <attribute name=""createdon"" />
                                <filter type=""and"">
                                  <condition attribute=""filename"" operator=""like"" value=""%{this.FileName.Get(context)}%"" />
                                  <condition attribute=""isdoreplacedent"" operator=""eq"" value=""1"" />
                                  <condition attribute=""objectid"" operator=""eq"" value=""{workflowContext.PrimaryEnreplacedyId}"" />
                                  <condition attribute=""objecttypecode"" operator=""eq"" value=""{objectTypeCode.Value}"" />
                                </filter>
                                <order attribute=""createdon"" descending=""true"" />
                              </enreplacedy>
                            </fetch>";
                }

                fetchResponse = service.Execute(request) as ExecuteFetchResponse;

                XmlDoreplacedent queryResults = new XmlDoreplacedent();
                queryResults.LoadXml(fetchResponse.FetchXmlResult);
                int days = 0;
                int minutes = 0;
                for (int i = 0; i < queryResults["resultset"].ChildNodes.Count; i++)
                {
                    if (queryResults["resultset"].ChildNodes[i]["createdon"] != null && !String.IsNullOrWhiteSpace(queryResults["resultset"].ChildNodes[i]["createdon"].InnerText))
                    {
                        DateTime createdon = DateTime.Parse(queryResults["resultset"].ChildNodes[i]["createdon"].InnerText);
                        if (createdon.Kind == DateTimeKind.Local)
                        {
                            createdon = createdon.ToUniversalTime();
                        }
                        TimeSpan difference = DateTime.Now.ToUniversalTime() - createdon;
                        miunutesOld = difference.TotalMinutes;
                        switch (this.TimeSpanOption.Get(context).Value)
                        {
                            case 222540000:
                                minutes = this.TimeSpanValue.Get(context);
                                break;
                            case 222540001:
                                minutes = this.TimeSpanValue.Get(context) * 60;
                                break;
                            case 222540002:
                                days = this.TimeSpanValue.Get(context);
                                break;
                            case 222540003:
                                days = this.TimeSpanValue.Get(context) * 7;
                                break;
                            case 222540004:
                                days = this.TimeSpanValue.Get(context) * 365;
                                break;
                        }
                        TimeSpan allowedDifference = new TimeSpan(days, 0, minutes, 0);
                        if (difference <= allowedDifference)
                        {
                            returnValue.Add(service.Retrieve("annotation", Guid.Parse(queryResults["resultset"].ChildNodes[i]["annotationid"].InnerText), noteColumns));
                        }
                    }

                    if (returnValue.Count >= maxRecords)
                    {
                        break;
                    }
                }
            }
            catch (System.ServiceModel.FaultException<Microsoft.Xrm.Sdk.OrganizationServiceFault> ex)
            {
                throw new ArgumentException("There was an error executing the FetchXML. Message: " + ex.Message);
            }
            catch (Exception ex)
            {
                throw ex;
            }

            return returnValue;
        }

19 View Source File : WorkflowQueryBase.cs
License : MIT License
Project Creator : akaskela

protected List<ColumnInformation> BuildTableInformation(IOrganizationService service, string fetchXml, string layoutXml)
        {
            List<QueryAttribute> fetchXmlColumns = new List<QueryAttribute>();
            XmlDoreplacedent doc = new XmlDoreplacedent();
            doc.LoadXml(fetchXml);
            XmlNode enreplacedyNode = doc["fetch"]["enreplacedy"];

            string primaryEnreplacedy = enreplacedyNode.Attributes["name"].Value;
            this.RetrieveQueryAttributeRecursively(enreplacedyNode, fetchXmlColumns);

            List<QueryAttribute> layoutXmlColumns = new List<QueryAttribute>();
            if (!String.IsNullOrEmpty(layoutXml))
            {
                doc = new XmlDoreplacedent();
                doc.LoadXml(layoutXml);
                foreach (XmlNode cell in doc["grid"]["row"].ChildNodes)
                {
                    string columnPresentationValue = cell.Attributes["name"].Value;
                    if (columnPresentationValue.Contains("."))
                    {
                        layoutXmlColumns.Add(new QueryAttribute()
                        {
                            EnreplacedyAlias = columnPresentationValue.Split('.')[0],
                            Attribute = columnPresentationValue.Split('.')[1]
                        });
                    }
                    else
                    {
                        layoutXmlColumns.Add(new QueryAttribute() { Attribute = columnPresentationValue, EnreplacedyName = primaryEnreplacedy });
                    }
                }
                foreach (QueryAttribute attribute in layoutXmlColumns.Where(qa => !String.IsNullOrWhiteSpace(qa.EnreplacedyAlias)))
                {
                    QueryAttribute attributeFromFetch = fetchXmlColumns.FirstOrDefault(f => f.EnreplacedyAlias == attribute.EnreplacedyAlias);
                    if (attributeFromFetch != null)
                    {
                        attribute.EnreplacedyName = attributeFromFetch.EnreplacedyName;
                    }
                }
            }

            List<string> distintEnreplacedyNames = layoutXmlColumns.Select(lo => lo.EnreplacedyName).Union(fetchXmlColumns.Select(f => f.EnreplacedyName)).Distinct().ToList();
            foreach (string enreplacedyName in distintEnreplacedyNames)
            {
                Microsoft.Xrm.Sdk.Messages.RetrieveEnreplacedyRequest request = new Microsoft.Xrm.Sdk.Messages.RetrieveEnreplacedyRequest()
                {
                    EnreplacedyFilters = EnreplacedyFilters.Attributes,
                    LogicalName = enreplacedyName
                };
                Microsoft.Xrm.Sdk.Messages.RetrieveEnreplacedyResponse response = service.Execute(request) as Microsoft.Xrm.Sdk.Messages.RetrieveEnreplacedyResponse;
                EnreplacedyMetadata metadata = response.EnreplacedyMetadata;
                foreach (QueryAttribute queryAttribute in layoutXmlColumns.Union(fetchXmlColumns).Where(c => c.EnreplacedyName == enreplacedyName && !String.IsNullOrWhiteSpace(c.Attribute)))
                {
                    if (!String.IsNullOrWhiteSpace(queryAttribute.AttribueAlias))
                    {
                        queryAttribute.AttributeLabel = queryAttribute.AttribueAlias;
                    }
                    else
                    {
                        AttributeMetadata attributeMetadata = metadata.Attributes.FirstOrDefault(a => a.LogicalName == queryAttribute.Attribute);
                        Label displayLabel = attributeMetadata.DisplayName;
                        if (displayLabel != null && displayLabel.UserLocalizedLabel != null)
                        {
                            queryAttribute.AttributeLabel = displayLabel.UserLocalizedLabel.Label;
                        }
                    }
                }
            }

            List<ColumnInformation> returnColumns = new List<ColumnInformation>();
            List<QueryAttribute> toReturn = (layoutXmlColumns.Count > 0) ? layoutXmlColumns : fetchXmlColumns;
            foreach (QueryAttribute qa in toReturn)
            {
                ColumnInformation ci = new ColumnInformation();
                ci.Header = qa.AttributeLabel;
                if (!String.IsNullOrEmpty(qa.EnreplacedyAlias))
                {
                    ci.QueryResultAlias = String.Format("{0}.{1}", qa.EnreplacedyAlias, qa.Attribute);
                }
                else if (!String.IsNullOrEmpty(qa.AttribueAlias))
                {
                    ci.QueryResultAlias = qa.AttribueAlias;
                }
                else
                {
                    ci.QueryResultAlias = qa.Attribute;
                }
                returnColumns.Add(ci);
                returnColumns.Add(new ColumnInformation() { Header = String.Format(MetadataHeaderFormat, ci.Header, "RawValue") });
            }

            return returnColumns;
        }

19 View Source File : WorkflowQueryBase.cs
License : MIT License
Project Creator : akaskela

protected void LimitQueryToCurrentRecord(IOrganizationService service, ref string fetchXml, string enreplacedyName, Guid enreplacedyId)
        {
            Microsoft.Xrm.Sdk.Messages.RetrieveEnreplacedyRequest metadataRequest = new Microsoft.Xrm.Sdk.Messages.RetrieveEnreplacedyRequest() { LogicalName = enreplacedyName };
            Microsoft.Xrm.Sdk.Messages.RetrieveEnreplacedyResponse metadataResponse = service.Execute(metadataRequest) as Microsoft.Xrm.Sdk.Messages.RetrieveEnreplacedyResponse;
            if (metadataResponse == null)
            {
                return;
            }

            XmlDoreplacedent fetchXmlDoc = new XmlDoreplacedent();
            fetchXmlDoc.LoadXml(fetchXml);
            this.UpdateConditionRecursively(fetchXmlDoc, fetchXmlDoc.FirstChild, enreplacedyId, enreplacedyName, metadataResponse.EnreplacedyMetadata.PrimaryIdAttribute);
            fetchXml = fetchXmlDoc.OuterXml;
        }

19 View Source File : HelpDialog.xaml.cs
License : GNU Affero General Public License v3.0
Project Creator : akshinmustafayev

private void LoadXml(string helpitem)
        {
            XmlDoreplacedent doc = new XmlDoreplacedent();
            doc.LoadXml(CommonUtils.ReadreplacedemblyFile(@"EasyJob.Doreplacedentation.HelpDoreplacedentation.xml"));

            XmlNodeList nodeList = doc.SelectNodes("/items/item[name='" + helpitem + "']");

            HelpHeading.Text = nodeList[0]["heading"].InnerText;
            HelpUsed.Text = nodeList[0]["used"].InnerText;
            HelpDescription.Text = nodeList[0]["description"].InnerText;
            if (nodeList[0]["video"].InnerText != "" || nodeList[0]["video"].InnerText != null)
            {
                try
                {
                    HelpVideo.HorizontalAlignment = HorizontalAlignment.Stretch;
                    HelpVideo.VerticalAlignment = VerticalAlignment.Stretch;
                    HelpVideo.Stretch = Stretch.Fill;
                    HelpVideo.Volume = 0;
                    HelpVideo.Source = new Uri(@"Doreplacedentation\Videos\" + nodeList[0]["video"].InnerText, UriKind.Relative);
                    HelpVideo.Position = TimeSpan.FromSeconds(0);
                    HelpVideo.Play();
                }
                catch { }
            }
        }

19 View Source File : XmlUtility.cs
License : MIT License
Project Creator : AlenToma

public static object FromXml(this string xml, IRepository transaction = null)  
        {
            if (string.IsNullOrEmpty(xml))
                return null;
            var doc = new System.Xml.XmlDoreplacedent();
            doc.LoadXml(xml);
            var o = FromXml(doc.DoreplacedentElement);
            void LoadXmlIgnoreProperties(object item)
            {
                if (item is IList)
                {
                    foreach (var t in (IList)item)
                        LoadXmlIgnoreProperties(t);
                    return;
                }

                var type = item?.GetType().GetActualType();
                if (type == null)
                    return;
                if (!(item?.GetPrimaryKeyValue().ObjectIsNew() ?? true))
                {
                    var primaryId = item.GetPrimaryKeyValue();
                    foreach (var prop in DeepCloner.GetFastDeepClonerProperties(item.GetType()).Where(x => (x.ContainAttribute<XmlIgnore>() || !x.IsInternalType) && !x.ContainAttribute<ExcludeFromAbstract>() && x.CanRead))
                    {
                        var value = prop.GetValue(item);
                        if (prop.PropertyType == typeof(string) && string.IsNullOrEmpty(value?.ToString()))
                            value = string.Empty;
                        if (prop.IsInternalType && value == LightDataTableShared.ValueByType(prop.PropertyType)) // Value is default
                        {
                            var cmd = transaction.GetSqlCommand($"SELECT [{prop.GetPropertyName()}] FROM {type.TableName().GetName(transaction.DataBaseTypes)} WHERE [{item.GetPrimaryKey().GetPropertyName()}] = {Querys.GetValueByType(item.GetPrimaryKeyValue(), transaction.DataBaseTypes)}");
                            var data = transaction.ExecuteScalar(cmd);
                            if (data == null)
                                continue;
                            if (prop.ContainAttribute<DataEncode>())
                                data = new DataCipher(prop.GetCustomAttribute<DataEncode>().Key, prop.GetCustomAttribute<DataEncode>().KeySize).Decrypt(data.ToString());
                            else if (prop.ContainAttribute<ToBase64String>() && data.ToString().IsBase64String())
                                data = MethodHelper.DecodeStringFromBase64(data.ToString());

                            prop.SetValue(item, data.ConvertValue(prop.PropertyType));
                        }
                        else if (value != null) LoadXmlIgnoreProperties(value);
                    }

                }
            }
            if (transaction != null)
                LoadXmlIgnoreProperties(o);
            return o;

        }

19 View Source File : XmlUtility.cs
License : MIT License
Project Creator : AlenToma

public static T FromXml<T>(this string xml, IRepository transaction) where T : clreplaced
        {
            if (string.IsNullOrEmpty(xml))
                return (T)(new object());
            var doc = new System.Xml.XmlDoreplacedent();
            doc.LoadXml(xml);
            var o = (T)FromXml(doc.DoreplacedentElement);
            void LoadXmlIgnoreProperties(object item)
            {
                if (item is IList)
                {
                    foreach (var t in (IList)item)
                        LoadXmlIgnoreProperties(t);
                    return;
                }

                var type = item?.GetType().GetActualType();
                if (type == null)
                    return;
                if (!(item?.GetPrimaryKeyValue().ObjectIsNew() ?? true))
                {
                    var primaryId = item.GetPrimaryKeyValue();
                    foreach (var prop in DeepCloner.GetFastDeepClonerProperties(item.GetType()).Where(x => (x.ContainAttribute<XmlIgnore>() || !x.IsInternalType) && !x.ContainAttribute<ExcludeFromAbstract>() && x.CanRead))
                    {
                        var value = prop.GetValue(item);
                        if (prop.PropertyType == typeof(string) && string.IsNullOrEmpty(value?.ToString()))
                            value = string.Empty;
                        if (prop.IsInternalType && value == LightDataTableShared.ValueByType(prop.PropertyType)) // Value is default
                        {
                            var cmd = transaction.GetSqlCommand($"SELECT [{prop.GetPropertyName()}] FROM {type.TableName().GetName(transaction.DataBaseTypes)} WHERE [{item.GetPrimaryKey().GetPropertyName()}] = {Querys.GetValueByType(item.GetPrimaryKeyValue(), transaction.DataBaseTypes)}");
                            var data = transaction.ExecuteScalar(cmd);
                            if (data == null)
                                continue;
                            if (prop.ContainAttribute<DataEncode>())
                                data = new DataCipher(prop.GetCustomAttribute<DataEncode>().Key, prop.GetCustomAttribute<DataEncode>().KeySize).Decrypt(data.ToString());
                            else if (prop.ContainAttribute<ToBase64String>() && data.ToString().IsBase64String())
                                data = MethodHelper.DecodeStringFromBase64(data.ToString());

                            prop.SetValue(item, data.ConvertValue(prop.PropertyType));
                        }
                        else if (value != null) LoadXmlIgnoreProperties(value);
                    }

                }
            }
            if (transaction != null)
                LoadXmlIgnoreProperties(o);
            return o;

        }

19 View Source File : XmlUtility.cs
License : MIT License
Project Creator : AlenToma

public static string ToXml(this object o)
        {
            string xmlResult = "";
            ToXml(o, ref xmlResult);
            var xmlDoc = new System.Xml.XmlDoreplacedent();
            StringWriter sw = new StringWriter();
            xmlDoc.LoadXml(xmlResult);
            xmlDoc.Save(sw);
            return sw.ToString();
        }

19 View Source File : ClassTypeEditor.cs
License : GNU General Public License v3.0
Project Creator : alexgracianoarj

private void RefreshIdenreplacedyGeneratorParameters()
        {
            XmlDoreplacedent xmlGeneratorParameters = new XmlDoreplacedent();
            
            if (!string.IsNullOrEmpty(Shape.CompositeType.GeneratorParameters))
                xmlGeneratorParameters.LoadXml(Shape.CompositeType.GeneratorParameters);

            if (Shape.CompositeType.IdGenerator == "HiLo")
            {
                this.Height = pnlGeneratorParameters.Bottom + pnlGeneratorParameters.Margin.Bottom;
                
                CodeGenerator.HiLoIdenreplacedyGeneratorParameters hiLo = null;

                if(xmlGeneratorParameters.SelectSingleNode("//HiLoIdenreplacedyGeneratorParameters") != null)
                    hiLo = CodeGenerator.GeneratorParametersDeSerializer.Deserialize<CodeGenerator.HiLoIdenreplacedyGeneratorParameters>(Shape.CompositeType.GeneratorParameters);
                else
                {
                    Shape.CompositeType.GeneratorParameters = null;
                    hiLo = new CodeGenerator.HiLoIdenreplacedyGeneratorParameters();
                }

                prgGeneratorParameters.SelectedObject = hiLo;
            }
            else if (Shape.CompositeType.IdGenerator == "SeqHiLo")
            {
                this.Height = pnlGeneratorParameters.Bottom + pnlGeneratorParameters.Margin.Bottom;

                CodeGenerator.SeqHiLoIdenreplacedyGeneratorParameters seqHiLo = null;

                if (xmlGeneratorParameters.SelectSingleNode("//SeqHiLoIdenreplacedyGeneratorParameters") != null)
                    seqHiLo = CodeGenerator.GeneratorParametersDeSerializer.Deserialize<CodeGenerator.SeqHiLoIdenreplacedyGeneratorParameters>(Shape.CompositeType.GeneratorParameters);
                else
                {
                    Shape.CompositeType.GeneratorParameters = null;
                    seqHiLo = new CodeGenerator.SeqHiLoIdenreplacedyGeneratorParameters();
                }

                prgGeneratorParameters.SelectedObject = seqHiLo;
            }
            else if (Shape.CompositeType.IdGenerator == "Sequence")
            {
                this.Height = pnlGeneratorParameters.Bottom + pnlGeneratorParameters.Margin.Bottom;
                
                CodeGenerator.SequenceIdenreplacedyGeneratorParameters sequence = null;

                if (xmlGeneratorParameters.SelectSingleNode("//SequenceIdenreplacedyGeneratorParameters") != null)
                    sequence = CodeGenerator.GeneratorParametersDeSerializer.Deserialize<CodeGenerator.SequenceIdenreplacedyGeneratorParameters>(Shape.CompositeType.GeneratorParameters);
                else
                {
                    Shape.CompositeType.GeneratorParameters = null;
                    sequence = new CodeGenerator.SequenceIdenreplacedyGeneratorParameters();
                }

                prgGeneratorParameters.SelectedObject = sequence;
            }
            else if (Shape.CompositeType.IdGenerator == "UuidHex")
            {
                this.Height = pnlGeneratorParameters.Bottom + pnlGeneratorParameters.Margin.Bottom;

                CodeGenerator.UuidHexIdenreplacedyGeneratorParameters uuidHex = null;

                if (xmlGeneratorParameters.SelectSingleNode("//UuidHexIdenreplacedyGeneratorParameters") != null)
                    uuidHex = CodeGenerator.GeneratorParametersDeSerializer.Deserialize<CodeGenerator.UuidHexIdenreplacedyGeneratorParameters>(Shape.CompositeType.GeneratorParameters);
                else
                {
                    Shape.CompositeType.GeneratorParameters = null;
                    uuidHex = new CodeGenerator.UuidHexIdenreplacedyGeneratorParameters();
                }

                prgGeneratorParameters.SelectedObject = uuidHex;
            }
            else if (Shape.CompositeType.IdGenerator == "Foreign")
            {
                this.Height = pnlGeneratorParameters.Bottom + pnlGeneratorParameters.Margin.Bottom;

                CodeGenerator.ForeignIdenreplacedyGeneratorParameters foreign = null;

                if (xmlGeneratorParameters.SelectSingleNode("//ForeignIdenreplacedyGeneratorParameters") != null)
                    foreign = CodeGenerator.GeneratorParametersDeSerializer.Deserialize<CodeGenerator.ForeignIdenreplacedyGeneratorParameters>(Shape.CompositeType.GeneratorParameters);
                else
                {
                    Shape.CompositeType.GeneratorParameters = null;
                    foreign = new CodeGenerator.ForeignIdenreplacedyGeneratorParameters();
                }

                prgGeneratorParameters.SelectedObject = foreign;
            }
            else if (Shape.CompositeType.IdGenerator == "Custom")
            {
                this.Height = pnlGeneratorParameters.Bottom + pnlGeneratorParameters.Margin.Bottom;

                CodeGenerator.CustomIdenreplacedyGeneratorParameters custom = null;

                if (xmlGeneratorParameters.SelectSingleNode("//CustomIdenreplacedyGeneratorParameters") != null)
                    custom = CodeGenerator.GeneratorParametersDeSerializer.Deserialize<CodeGenerator.CustomIdenreplacedyGeneratorParameters>(Shape.CompositeType.GeneratorParameters);
                else
                {
                    Shape.CompositeType.GeneratorParameters = null;
                    custom = new CodeGenerator.CustomIdenreplacedyGeneratorParameters();
                }

                prgGeneratorParameters.SelectedObject = custom;
            }
            else
            {
                this.Height = pnlAdvancedOptions.Bottom + pnlAdvancedOptions.Margin.Bottom;
                Shape.CompositeType.GeneratorParameters = null;
            }
        }

19 View Source File : MainWindow.xaml.cs
License : MIT License
Project Creator : alexleen

private void Paste()
        {
            string text = Clipboard.GetText();

            try
            {
                XmlDoreplacedent doc = new XmlDoreplacedent();
                doc.LoadXml(text);
                XmlNode imported = mConfig.ConfigXml.ImportNode(doc.FirstChild, true);

                ModelCreateResult result = ModelFactory.TryCreate(imported, mConfig.Log4NetNode, out ModelBase model);

                if (result == ModelCreateResult.Success)
                {
                    OpenElementWindow(model, true);
                    return;
                }

                if (result == ModelCreateResult.UnknownAppender)
                {
                    mToastService.ShowError("Unrecognized appender.");
                    return;
                }
            }
            catch
            {
                // ignored
            }

            mToastService.ShowError("Unrecognized log4net element");
        }

19 View Source File : AditivityTest.cs
License : MIT License
Project Creator : alexleen

[TestCase("<logger />", true)]
        [TestCase("<logger aditivity=\"\" />", true)]
        [TestCase("<logger aditivity=\"FALSE\" />", false)]
        [TestCase("<logger aditivity=\"False\" />", false)]
        [TestCase("<logger aditivity=\"false\" />", false)]
        public void Load_ShouldLoadTheCorrectValue(string xml, bool expected)
        {
            XmlDoreplacedent xmlDoc = new XmlDoreplacedent();
            xmlDoc.LoadXml(xml);

            mSut.Load(xmlDoc.FirstChild);

            replacedert.AreEqual(expected, mSut.Value);
        }

19 View Source File : BackColorTest.cs
License : MIT License
Project Creator : alexleen

[TestCase("<backColor />", null)]
        [TestCase("<backColor value=\"\" />", null)]
        [TestCase("<backColor value=\"DarkBlue\" />", ConsoleColor.DarkBlue)]
        [TestCase("<backColor value=\"DarkRed\" />", ConsoleColor.DarkRed)]
        [TestCase("<backColor value=\"whatev\" />", null)]
        public void Load_ShouldLoadTheCorrectValue(string xml, ConsoleColor? expected)
        {
            XmlDoreplacedent xmlDoc = new XmlDoreplacedent();
            xmlDoc.LoadXml("<appender>\n" +
                           $"    {xml}\n" +
                           "</appender>");

            mSut.Load(xmlDoc.FirstChild);

            replacedert.AreEqual(expected, mSut.SelectedColor);
        }

19 View Source File : LayoutTest.cs
License : MIT License
Project Creator : alexleen

[Test]
        public void Save_ShouldSavePattern_WhenNotEqualToOriginal()
        {
            XmlDoreplacedent xmlDoc = new XmlDoreplacedent();
            xmlDoc.LoadXml("<appender>\r\n" +
                           "    <layout type=\"log4net.Layout.PatternLayout\">\r\n" +
                           "      <conversionPattern value=\"%date{HH:mm:ss:fff} %message%newline\" />\r\n" +
                           "    </layout>\r\n" +
                           "</appender>");

            mSut.Load(xmlDoc.FirstChild);

            mSut.Pattern = "%message%newline";

            mSut.Save(xmlDoc, xmlDoc.CreateElement("appender"));

            mHistoryManager.Received(1).Save(mSut.Pattern);
        }

19 View Source File : RollingStyleTest.cs
License : MIT License
Project Creator : alexleen

[TestCase(null)]
        [TestCase("<rollingStyle />")]
        [TestCase("<rollingStyle value=\"\" />")]
        [TestCase("<rollingStyle value=\"whatev\" />")]
        public void Load_ShouldNotLoadMode(string mode)
        {
            XmlDoreplacedent xmlDoc = new XmlDoreplacedent();
            xmlDoc.LoadXml("<appender type=\"log4net.Appender.RollingFileAppender\" name=\"rolling\">\n" +
                           $"    {mode}\n" +
                           "  </appender>");

            mSut.Load(xmlDoc.FirstChild);

            replacedert.AreEqual(RollingFileAppender.RollingMode.Composite, mSut.SelectedMode);
        }

19 View Source File : RollingStyleTest.cs
License : MIT License
Project Creator : alexleen

[Test]
        public void Load_ShouldLoadMode()
        {
            XmlDoreplacedent xmlDoc = new XmlDoreplacedent();
            xmlDoc.LoadXml("<appender type=\"log4net.Appender.RollingFileAppender\" name=\"rolling\">\n" +
                           "    <rollingStyle value=\"Date\" />\n" +
                           "  </appender>");

            mSut.Load(xmlDoc.FirstChild);

            replacedert.AreEqual(RollingFileAppender.RollingMode.Date, mSut.SelectedMode);
        }

19 View Source File : StringMatchTest.cs
License : MIT License
Project Creator : alexleen

[TestCase(null, null)]
        [TestCase("<stringToMatch />", null)]
        [TestCase("<stringToMatch value=\"\" />", null)]
        [TestCase("<stringToMatch value=\"str\" />", "str")]
        public void Load_ShouldLoadCorrectly(string xml, string expected)
        {
            XmlDoreplacedent xmlDoc = new XmlDoreplacedent();
            xmlDoc.LoadXml("<appender>\n" +
                           $"      {xml}\n" +
                           "</appender>");

            mSut.Load(xmlDoc.FirstChild);

            replacedert.AreEqual(expected, mSut.Value);
        }

19 View Source File : TargetTest.cs
License : MIT License
Project Creator : alexleen

[TestCase(null, ConsoleOut)]
        [TestCase("<target />", ConsoleOut)]
        [TestCase("<target value=\"\" />", ConsoleOut)]
        [TestCase("<target value=\"whatev\" />", ConsoleOut)]
        [TestCase("<target value=\"Console.Error\" />", ConsoleError)]
        public void Load_ShouldLoadCorrectly(string xml, string expected)
        {
            XmlDoreplacedent xmlDoc = new XmlDoreplacedent();
            xmlDoc.LoadXml("<appender>\n" +
                           $"      {xml}\n" +
                           "</appender>");

            mSut.Load(xmlDoc.FirstChild);

            replacedert.AreEqual(expected, mSut.SelectedItem);
        }

19 View Source File : ThresholdTest.cs
License : MIT License
Project Creator : alexleen

[TestCase("<threshold />", "")]
        [TestCase("<threshold value=\"\" />", "")]
        [TestCase("<threshold value=\"ALL\" />", "ALL")]
        [TestCase("<threshold value=\"All\" />", "ALL")]
        [TestCase("<threshold value=\"all\" />", "ALL")]
        public void Load_ShouldLoadTheCorrectValue(string xml, string expected)
        {
            XmlDoreplacedent xmlDoc = new XmlDoreplacedent();
            xmlDoc.LoadXml("<appender>\n" +
                           $"    {xml}\n" +
                           "</appender>");

            mSut.Load(xmlDoc.FirstChild);

            replacedert.AreEqual(expected, mSut.SelectedValue);
        }

19 View Source File : TypeAttributeTest.cs
License : MIT License
Project Creator : alexleen

[TestCase(null)]
        [TestCase("")]
        [TestCase("type=\"\"")]
        public void Load_ShouldNotLoadType_RegularCtor(string xml)
        {
            mSut = new TypeAttribute();

            XmlDoreplacedent xmlDoc = new XmlDoreplacedent();
            xmlDoc.LoadXml($"<appender name=\"ColoredConsoleAppender\" {xml}>\r\n" +
                           "</appender>");

            mSut.Load(xmlDoc.FirstChild);

            replacedert.IsNull(mSut.Value);
        }

19 View Source File : TypeAttributeTest.cs
License : MIT License
Project Creator : alexleen

[TestCase("type=\"\"")]
        [TestCase("")]
        public void Load_ShouldMaintainType_FromCtor(string type)
        {
            XmlDoreplacedent xmlDoc = new XmlDoreplacedent();
            xmlDoc.LoadXml($"<appender name=\"ColoredConsoleAppender\" {type}>\r\n" +
                           "</appender>");

            mSut.Load(xmlDoc.FirstChild);

            replacedert.AreEqual(AppenderDescriptor.Async.TypeNamespace, mSut.Value);
        }

19 View Source File : TypeAttributeTest.cs
License : MIT License
Project Creator : alexleen

[Test]
        public void Load_ShouldLoadCorrectType()
        {
            XmlDoreplacedent xmlDoc = new XmlDoreplacedent();
            xmlDoc.LoadXml("<appender name=\"ColoredConsoleAppender\" type=\"log4net.Appender.ColoredConsoleAppender\">\r\n" +
                           "</appender>");

            mSut.Load(xmlDoc.FirstChild);

            replacedert.AreEqual("log4net.Appender.ColoredConsoleAppender", mSut.Value);
        }

19 View Source File : ValueTest.cs
License : MIT License
Project Creator : alexleen

[TestCase(null)]
        [TestCase("")]
        [TestCase("value=\"\"")]
        public void Load_ShouldNotLoadValue(string xml)
        {
            XmlDoreplacedent xmlDoc = new XmlDoreplacedent();
            xmlDoc.LoadXml($"<appender name=\"ColoredConsoleAppender\" {xml}>\r\n" +
                           "</appender>");

            mSut.Load(xmlDoc.FirstChild);

            replacedert.IsNull(mSut.Value);
        }

19 View Source File : ValueTest.cs
License : MIT License
Project Creator : alexleen

[TestCase("value=\"\"")]
        [TestCase("")]
        public void Load_ShouldMaintainValue_FromCtor(string value)
        {
            XmlDoreplacedent xmlDoc = new XmlDoreplacedent();
            xmlDoc.LoadXml($"<appender name=\"ColoredConsoleAppender\" {value}>\r\n" +
                           "</appender>");

            mSut.Load(xmlDoc.FirstChild);

            replacedert.IsNull(mSut.Value);
        }

19 View Source File : ValueTest.cs
License : MIT License
Project Creator : alexleen

[Test]
        public void Load_ShouldLoadCorrectValue()
        {
            XmlDoreplacedent xmlDoc = new XmlDoreplacedent();
            xmlDoc.LoadXml("<appender name=\"ColoredConsoleAppender\" value=\"log4net.Appender.ColoredConsoleAppender\">\r\n" +
                           "</appender>");

            mSut.Load(xmlDoc.FirstChild);

            replacedert.AreEqual("log4net.Appender.ColoredConsoleAppender", mSut.Value);
        }

19 View Source File : ParamModelTest.cs
License : MIT License
Project Creator : alexleen

[TestCase(nameof(ParamModel.Name))]
        [TestCase(nameof(ParamModel.Type))]
        [TestCase(nameof(ParamModel.Value))]
        public void NodeSet_ShouldFireOnPropertyChanged(string propName)
        {
            bool fired = false;
            mSut.PropertyChanged += (sender, args) =>
                {
                    if (args.PropertyName == propName)
                    {
                        fired = true;
                    }
                };

            XmlDoreplacedent xmlDoc = new XmlDoreplacedent();
            xmlDoc.LoadXml("<param name=\"someName\" value=\"someValue\" type=\"someType\" />");

            mSut.Node = xmlDoc.FirstChild;

            replacedert.IsTrue(fired);
        }

See More Examples