/// <summary> /// Default ctor /// </summary> internal XName(string localName, XNamespace @namespace) { this.localName = localName; this.@namespace = @namespace; hashCode = localName.GetHashCode() ^ @namespace.GetHashCode(); }
/// <summary> /// Changes the namespace of the root element and all descendants with the same namespace to the new namespace. /// </summary> /// <param name="root">The root.</param> /// <param name="newNamespace">The new namespace.</param> public static void ChangeNamespaceTo(this XElement root, XNamespace newNamespace) { XName xmlns = "xmlns"; XNamespace origionalNamespace = root.Name.Namespace; foreach (XElement element in root.DescendantsAndSelf()) { if (element.Name.Namespace == origionalNamespace) { element.SetAttributeValue(xmlns, newNamespace.NamespaceName); element.Name = newNamespace + element.Name.LocalName; } } }
public static XElement ToXElement(this ManifestMetadata metadata, XNamespace ns) { var elem = new XElement(ns + "metadata"); if (metadata.MinClientVersionString != null) { elem.SetAttributeValue("minClientVersion", metadata.MinClientVersionString); } elem.Add(new XElement(ns + "id", metadata.Id)); // OCTOPUS: Use original version string AddElementIfNotNull(elem, ns, "version", metadata.Version?.ToString()); AddElementIfNotNull(elem, ns, "title", metadata.Title); AddElementIfNotNull(elem, ns, "authors", metadata.Authors, authors => string.Join(",", authors)); AddElementIfNotNull(elem, ns, "owners", metadata.Owners, owners => string.Join(",", owners)); elem.Add(new XElement(ns + "requireLicenseAcceptance", metadata.RequireLicenseAcceptance)); if (metadata.DevelopmentDependency) { elem.Add(new XElement(ns + "developmentDependency", metadata.DevelopmentDependency)); } AddElementIfNotNull(elem, ns, "licenseUrl", metadata.LicenseUrl); AddElementIfNotNull(elem, ns, "projectUrl", metadata.ProjectUrl); AddElementIfNotNull(elem, ns, "iconUrl", metadata.IconUrl); AddElementIfNotNull(elem, ns, "description", metadata.Description); AddElementIfNotNull(elem, ns, "summary", metadata.Summary); AddElementIfNotNull(elem, ns, "releaseNotes", metadata.ReleaseNotes); AddElementIfNotNull(elem, ns, "copyright", metadata.Copyright); AddElementIfNotNull(elem, ns, "language", metadata.Language); AddElementIfNotNull(elem, ns, "tags", metadata.Tags); if (metadata.Serviceable) { elem.Add(new XElement(ns + "serviceable", metadata.Serviceable)); } if (metadata.PackageTypes != null && metadata.PackageTypes.Any()) { elem.Add(GetXElementFromManifestPackageTypes(ns, metadata.PackageTypes)); } elem.Add(GetXElementFromGroupableItemSets( ns, metadata.DependencyGroups, set => set.TargetFramework.IsSpecificFramework || set.Packages.Any(dependency => dependency.Exclude.Count > 0 || dependency.Include.Count > 0), set => set.TargetFramework.IsSpecificFramework ? set.TargetFramework.GetFrameworkString() : null, set => set.Packages, GetXElementFromPackageDependency, Dependencies, TargetFramework)); elem.Add(GetXElementFromGroupableItemSets( ns, metadata.PackageAssemblyReferences, set => set.TargetFramework?.IsSpecificFramework == true, set => set.TargetFramework?.GetFrameworkString(), set => set.References, GetXElementFromPackageReference, References, TargetFramework)); elem.Add(GetXElementFromFrameworkAssemblies(ns, metadata.FrameworkReferences)); elem.Add(GetXElementFromManifestContentFiles(ns, metadata.ContentFiles)); return(elem); }
public object GetRss(string url, int count, int cacheDuration) { var feed = Services.Get <ICache>().Get(CACHE_KEY + url) as XElement; if (feed == null) { // We have failed to load the RSS before. So, let's not try again. if (string.Empty == (Services.Get <ICache>().Get(CACHE_KEY + url) as string)) { return(null); } try { HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest; request.Timeout = 15000; using (WebResponse response = request.GetResponse()) { using (XmlTextReader reader = new XmlTextReader(new StreamReader(response.GetResponseStream(), true))) { feed = XElement.Load(reader); } } if (feed == null) { return(null); } Services.Get <ICache>().Add(CACHE_KEY + url, feed, TimeSpan.FromMinutes(15)); } catch (Exception x) { Debug.WriteLine(x.ToString()); // Let's remember that we failed to load this RSS feed and we will not try to load it again // in next 15 mins Services.Get <ICache>().Add(CACHE_KEY + url, string.Empty, TimeSpan.FromMinutes(15)); return(null); } } XNamespace ns = "http://www.w3.org/2005/Atom"; // see if RSS or Atom try { // RSS if (feed.Element("channel") != null) { return((from item in feed.Element("channel").Elements("item") select new RssItem { Title = StripTags(item.Element("title").Value, 200), Link = item.Element("link").Value, Description = StripTags(item.Element("description").Value, 200) }).Take(count)); } // Atom else if (feed.Element(ns + "entry") != null) { return((from item in feed.Elements(ns + "entry") select new RssItem { Title = StripTags(item.Element(ns + "title").Value, 200), Link = item.Element(ns + "link").Attribute("href").Value, Description = StripTags(item.Element(ns + "content").Value, 200) }).Take(count)); } // Invalid else { return(null); } } finally { this.CacheResponse(Context, cacheDuration); } }
/// <summary> /// Gets the Open Search XML for the current site. You can customize the contents of this XML here. See /// http://www.hanselman.com/blog/CommentView.aspx?guid=50cc95b1-c043-451f-9bc2-696dc564766d /// http://www.opensearch.org /// </summary> /// <returns>The Open Search XML for the current site.</returns> public string GetOpenSearchXml() { // Short name must be less than or equal to 16 characters. string shortName = "Search"; string description = $"Search the {this.appSettings.Value.SiteTitle} Site"; // The link to the search page with the query string set to 'searchTerms' which gets replaced with a user // defined query. string searchUrl = this.urlHelper.AbsoluteRouteUrl( HomeControllerRoute.GetSearch, new { query = "{searchTerms}" }); // The link to the page with the search form on it. The home page has the search form on it. string searchFormUrl = this.urlHelper.AbsoluteRouteUrl(HomeControllerRoute.GetIndex); // The link to the favicon.ico file for the site. string favicon16Url = this.urlHelper.AbsoluteContent("~/favicon.ico"); // The link to the favicon.png file for the site. string favicon32Url = this.urlHelper.AbsoluteContent("~/img/icons/favicon-32x32.png"); // The link to the favicon.png file for the site. string favicon96Url = this.urlHelper.AbsoluteContent("~/img/icons/favicon-96x96.png"); XNamespace ns = "http://a9.com/-/spec/opensearch/1.1"; XDocument document = new XDocument( new XElement( ns + "OpenSearchDescription", new XElement(ns + "ShortName", shortName), new XElement(ns + "Description", description), new XElement( ns + "Url", new XAttribute("type", "text/html"), new XAttribute("method", "get"), new XAttribute("template", searchUrl)), // Search results can also be returned as RSS. Here, our start index is zero for the first result. // new XElement(ns + "Url", // new XAttribute("type", "application/rss+xml"), // new XAttribute("indexOffset", "0"), // new XAttribute("rel", "results"), // new XAttribute("template", "http://example.com/?q={searchTerms}&start={startIndex?}&format=rss")), // Search suggestions can also be returned as JSON. // new XElement(ns + "Url", // new XAttribute("type", "application/json"), // new XAttribute("indexOffset", "0"), // new XAttribute("rel", "suggestions"), // new XAttribute("template", "http://example.com/suggest?q={searchTerms}")), new XElement( ns + "Image", favicon16Url, new XAttribute("height", "16"), new XAttribute("width", "16"), new XAttribute("type", "image/x-icon")), new XElement( ns + "Image", favicon32Url, new XAttribute("height", "32"), new XAttribute("width", "32"), new XAttribute("type", "image/png")), new XElement( ns + "Image", favicon96Url, new XAttribute("height", "96"), new XAttribute("width", "96"), new XAttribute("type", "image/png")), new XElement(ns + "InputEncoding", "UTF-8"), new XElement(ns + "SearchForm", searchFormUrl))); return(document.ToString(Encoding.UTF8)); }
public void CheckStructsInList() { StartService(typeof(StructService)); var wsdl = GetWsdl(); StopServer(); var root = XElement.Parse(wsdl); var elementsWithEmptyName = GetElements(root, _xmlSchema + "element").Where(x => x.Attribute("name")?.Value == string.Empty); elementsWithEmptyName.ShouldBeEmpty(); var elementsWithEmptyType = GetElements(root, _xmlSchema + "element").Where(x => x.Attribute("type")?.Value == "xs:"); elementsWithEmptyType.ShouldBeEmpty(); var structTypeElement = GetElements(root, _xmlSchema + "complexType").Single(x => x.Attribute("name")?.Value == "AnyStruct"); var annotationNode = structTypeElement.Descendants(_xmlSchema + "annotation").SingleOrDefault(); var isValueTypeElement = annotationNode.Descendants(_xmlSchema + "appinfo").Descendants(XNamespace.Get("http://schemas.microsoft.com/2003/10/Serialization/") + "IsValueType").SingleOrDefault(); Assert.IsNotNull(isValueTypeElement); Assert.AreEqual("true", isValueTypeElement.Value); Assert.IsNotNull(annotationNode); }
/// <summary> /// Fills the XML solid work. /// </summary> /// <returns></returns> public static XDocument FillXMLSolidWork(string standard, string name, bool isSteel, IList <ExportPropertyGeneral> properties) { XDocument xml = new XDocument(new XDeclaration("1.0", "Unicode", "yes"), null); XNamespace ns = "http://www.solidworks.com/sldmaterials"; XNamespace c1 = "http://www.solidworks.com/sldmaterials"; XNamespace c2 = "http://www.w3.org/2001/XMLSchema-instance"; XNamespace c3 = "http://www.solidworks.com/sldcolorwatch"; XElement mstns1 = new XElement(ns + "materials"); mstns1.SetAttributeValue(XNamespace.Xmlns + "mstns", c1); mstns1.SetAttributeValue(XNamespace.Xmlns + "msdata", "urn:schemas-microsoft-com:xml-msdata"); mstns1.SetAttributeValue(XNamespace.Xmlns + "xsi", c2); mstns1.SetAttributeValue(XNamespace.Xmlns + "sldcolorswatch", c3); XElement curves = new XElement("curves"); curves.SetAttributeValue("id", "curve0"); XElement point = new XElement("point"); point.SetAttributeValue("x", "1.0"); point.SetAttributeValue("y", "1.0"); curves.Add(point); point = new XElement("point"); point.SetAttributeValue("x", "2.0"); point.SetAttributeValue("y", "1.0"); curves.Add(point); point = new XElement("point"); point.SetAttributeValue("x", "3.0"); point.SetAttributeValue("y", "1.0"); curves.Add(point); XElement classification = new XElement("classification"); if (isSteel) { classification.SetAttributeValue(NAME, "steel"); } else { classification.SetAttributeValue(NAME, "nonferrous"); } XElement material = new XElement("material"); material.SetAttributeValue(NAME, name + " " + standard); XElement shaders = new XElement("shaders"); XElement cgShaders = new XElement("cgshader"); cgShaders.SetAttributeValue(NAME, "Steel AISI 304"); shaders.Add(cgShaders); XElement pwShaders = new XElement("pwshader"); pwShaders.SetAttributeValue(NAME, "Stainless Steel"); shaders.Add(pwShaders); XElement swtexture = new XElement("swtexture"); swtexture.SetAttributeValue("path", "images\\textures\\metal\\cast\\cast_fine.jpg"); shaders.Add(swtexture); material.Add(shaders); XElement swatchColor = new XElement("swatchcolor"); swatchColor.SetAttributeValue("RGB", "c0c0c0"); XNamespace c4 = "http://www.solidworks.com/sldcolorwatch"; XElement sldcolorswatch = new XElement(c4 + "Optical"); sldcolorswatch.SetAttributeValue("Ambient", "1.000000"); sldcolorswatch.SetAttributeValue("Transparency", "0.000000"); sldcolorswatch.SetAttributeValue("Diffuse", "1.000000"); sldcolorswatch.SetAttributeValue("Specularity", "1.000000"); sldcolorswatch.SetAttributeValue("Shininess", "0.310000"); sldcolorswatch.SetAttributeValue("Emission", "0.000000"); swatchColor.Add(sldcolorswatch); material.Add(swatchColor); XElement xhatch = new XElement("xhatch"); xhatch.SetAttributeValue(NAME, "ANSI32 (Steel)"); xhatch.SetAttributeValue("angle", "0.0"); xhatch.SetAttributeValue("scale", "1.0"); material.Add(xhatch); XElement physicalproperties = new XElement("physicalproperties"); CreateXMLPropertyElement(properties, physicalproperties, "EX", PropertyTypeEnum.PhysicalModulusOfElasticity); CreateXMLPropertyElement(properties, physicalproperties, "EY", PropertyTypeEnum.PhysicalModulusOfElasticity); CreateXMLPropertyElement(properties, physicalproperties, "EZ", PropertyTypeEnum.PhysicalModulusOfElasticity); CreateXMLPropertyElement(properties, physicalproperties, "NUXY", PropertyTypeEnum.PhysicalPoissonCoefficient); CreateXMLPropertyElement(properties, physicalproperties, "ALPX", PropertyTypeEnum.PhysicalMeanCoeffThermalExpansion); CreateXMLPropertyElement(properties, physicalproperties, "DENS", PropertyTypeEnum.PhysicalDensity); CreateXMLPropertyElement(properties, physicalproperties, "KX", PropertyTypeEnum.PhysicalThermalConductivity); CreateXMLPropertyElement(properties, physicalproperties, "KY", PropertyTypeEnum.PhysicalThermalConductivity); CreateXMLPropertyElement(properties, physicalproperties, "C", PropertyTypeEnum.PhysicalSpecificThermalCapacity); CreateXMLPropertyElement(properties, physicalproperties, "SIGXT", PropertyTypeEnum.MechanicalTensile); CreateXMLPropertyElement(properties, physicalproperties, "SIGYLD", PropertyTypeEnum.MechanicalYield); material.Add(physicalproperties); mstns1.Add(curves); classification.Add(material); mstns1.Add(classification); xml.Add(mstns1); return(xml); }
static void Main(string[] args) { string result = ""; string address = "http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml"; List <CurrencyType> currencies = new List <CurrencyType>(); DataClasses1DataContext ctx = new DataClasses1DataContext(); try // faire écriture BDD, reste fonctionnel { // Requête web HttpWebRequest request = WebRequest.Create(address) as HttpWebRequest; // Réponse using (HttpWebResponse response = request.GetResponse() as HttpWebResponse) { StreamReader reader = new StreamReader(response.GetResponseStream()); // Récupération résultat result = reader.ReadToEnd(); } XDocument doc = XDocument.Parse(result); XNamespace ns = "http://www.ecb.int/vocabulary/2002-08-01/eurofxref"; //XML mis à jour à 4h pm CET == 17h France currencies = doc.Descendants(ns + "Cube") .Where(c => c.Attribute("currency") != null) .Select(c => new CurrencyType { Name = (string)c.Attribute("currency"), Value = (float)c.Attribute("rate"), }) .ToList(); foreach (CurrencyType c in currencies) // pour chaque taux, on met à jour la BDD s'il y a internet { var query = from rate in ctx.Rates where rate.Name == c.Name select rate; int count = 0; foreach (Rates rate in query) { count++; } if (count != 0) //si le taux existe déjà, on le met à jour dans la BDD { // Mettre à jour le taux foreach (Rates rate in query) { rate.Value = c.Value; rate.Last = DateTime.Now; } try { ctx.SubmitChanges(); } catch (Exception e) { Console.WriteLine(e); } } else //Sinon, on crée l'entrée dans la BDD { ctx.Rates.InsertOnSubmit(new Rates() //insertion des taux { Name = c.Name, Value = c.Value, Last = DateTime.Today, }); ctx.SubmitChanges(); } } foreach (var item in ctx.Rates) //écriture pour vérifier entrée des nouveaux taux { Console.WriteLine(string.Format("La monnaie {0} a un taux de change de {1} ", item.Name, item.Value)); Console.ReadKey(); } } catch (WebException e) // faire la récupération dans la BDD si pas internet { Console.WriteLine("Il y a un problème avec votre connexion internet" + "\n\nException :" + e.Message); foreach (var item in ctx.Rates) { Console.WriteLine(string.Format("La monnaie {0} a un taux de change de {1} ", item.Name, item.Value)); Console.ReadKey(); } } }
/// <summary> /// Get Weather Warning from XML /// </summary> /// <param name="area">Area which you want to get weather warning</param> /// <param name="keySeparator">Key separtor which concatnate Meteorological office name and area name</param> /// <param name="ignoreIdList">These IDs will not be processed</param> /// <returns></returns> public Task <WeatherInfoContainer> GetWarnings(Dictionary <string, List <string> > area, string keySeparator, List <string> ignoreIdList) { SyndicationFeed feed = weatherInfoContainer.AtomFeeds[Resources.EXTRA]; IEnumerable <SyndicationItem> feedItemList = feed.Items; List <string> processedIdList = new List <string>(); Dictionary <string, List <Dictionary <string, string> > > result = new Dictionary <string, List <Dictionary <string, string> > >(); foreach (SyndicationItem item in feedItemList) { string id = item.Id; string authorName = item.Authors.First().Name; if (item.Title.Text == Resources.WARNING_TITLE && area.Keys.Contains(authorName) && !ignoreIdList.Contains(id)) { string url = item.Links.First().Uri.ToString(); XDocument xdoc = XDocument.Load(url); XNamespace xns = null; GetHeadAndBody(xdoc, out XElement xHead, out XElement xBody); //Get Item Elements based on Area dictionary Dictionary <string, List <XElement> > dicAreaItem = GetItemsFromArea(area, xBody, authorName); //Get ReportDate string strReportDateTime = GetChildText(xHead, "ReportDateTime"); //Create result Dictionary foreach (string areaName in dicAreaItem.Keys) { XElement xElemItemArea = dicAreaItem[areaName][0]; xns = xElemItemArea.Name.Namespace; IEnumerable <XElement> ieXElemKind = xElemItemArea.Elements(xns + "Kind"); var listDic = new List <Dictionary <string, string> >(); // Set the value of Name,Status and Addition for each Warning to dictionary list. foreach (XElement xKind in ieXElemKind) { var dicResultItem = new Dictionary <string, string>() { { "ReportDateTime", strReportDateTime } }; if (xKind.Elements(xns + "Name").Count() > 0) { dicResultItem["Name"] = xKind.Element(xns + "Name").Value; } if (xKind.Elements(xns + "Status").Count() > 0) { dicResultItem["Status"] = xKind.Element(xns + "Status").Value; } if (xKind.Elements(xns + "Addition").Count() > 0) { IEnumerable <XElement> ieXadd = xKind.Element(xns + "Addition").Elements(xns + "Note"); string notes = ""; foreach (XElement xAdd in ieXadd) { notes += (xAdd.Value + " "); } if (!String.IsNullOrEmpty(notes.Trim())) { dicResultItem["Addition"] = notes.Trim(); } } listDic.Add(dicResultItem); } result[item.Authors.First().Name + keySeparator + areaName] = listDic; } xdoc = null; processedIdList.Add(id); area.Remove(authorName); if (area.Count == 0) { break; } } } weatherInfoContainer.Result[Resources.GetWarning] = result; weatherInfoContainer.ProcessedID[Resources.GetWarning] = processedIdList; return(Task.FromResult(this.weatherInfoContainer)); }
private static IEnumerable <ProductInfo> GetProductsInfo(ApexSettings settings, bool checkForUpdates) { var productsInfo = new List <ProductInfo>(); //Get the currently installed products var installed = typeof(ProductManager).Assembly.GetCustomAttributes(typeof(ApexProductAttribute), true).Cast <ApexProductAttribute>(); foreach (var p in installed) { var info = new ProductInfo { name = p.name, installedVersion = string.IsNullOrEmpty(p.version) ? null : new Version(p.version), type = p.type }; info.iconInfo = GetIconPath(settings, info); info.changeLogPath = GetChangeLogPath(settings, info); productsInfo.Add(info); } //Check existence of product manifest var manifestPath = string.Concat(settings.dataFolder, "/Products.manifest"); bool checkedForUpdates = checkForUpdates || settings.timeToUpdate || (!File.Exists(manifestPath) && settings.allowAutomaticUpdateCheck); if (checkedForUpdates) { DownloadLatest(settings, manifestPath); } //Read the product manifest if (!File.Exists(manifestPath)) { return(productsInfo); } var installedLookup = productsInfo.ToDictionary(p => p.name, StringComparer.OrdinalIgnoreCase); try { var productsXml = XDocument.Load(manifestPath); XNamespace ns = productsXml.Root.Attribute("xmlns").Value; foreach (var p in productsXml.Root.Elements(ns + "Product")) { var productName = p.Element(ns + "name").Value; ProductInfo info; if (!installedLookup.TryGetValue(productName, out info)) { info = new ProductInfo(); productsInfo.Add(info); } var versionString = p.Element(ns + "version").Value; var patchString = p.Element(ns + "latestPatch").Value; info.name = productName; info.description = p.Element(ns + "description").Value; info.newestVersion = string.IsNullOrEmpty(versionString) ? null : new Version(versionString); info.latestPatch = string.IsNullOrEmpty(patchString) ? null : new Version(patchString); info.productUrl = p.Element(ns + "productUrl").Value; info.storeUrl = p.Element(ns + "storeUrl").Value; info.type = (ProductType)Enum.Parse(typeof(ProductType), p.Element(ns + "type").Value); info.iconInfo = GetIconPath(settings, info); } } catch { //Just eat this, it should not happen, but if it does we do not want to impact the users, and there is no way to recover so... } //Apply update knowledge to list if (checkedForUpdates) { MarkPendingUpdates(settings, productsInfo); EnsureIcons(settings, productsInfo); } return(productsInfo); }
// TODO: support .resx too - will need to know which to use if project includes both private string GetResourceFilePath() { var reswFiles = new List <string>(); // See also https://docs.microsoft.com/en-us/dotnet/api/microsoft.visualstudio.shell.interop.ivssolution.getprojectenum?view=visualstudiosdk-2017#Microsoft_VisualStudio_Shell_Interop_IVsSolution_GetProjectEnum_System_UInt32_System_Guid__Microsoft_VisualStudio_Shell_Interop_IEnumHierarchies__ void IterateProjItems(EnvDTE.ProjectItem projectItem) { var item = projectItem.ProjectItems.GetEnumerator(); while (item.MoveNext()) { if (item.Current is EnvDTE.ProjectItem projItem) { if (projItem.ProjectItems.Count > 0) { IterateProjItems(projItem); } else if (projItem.Name.EndsWith(".resw")) { reswFiles.Add(projItem.FileNames[0]); } } } } void IterateProject(EnvDTE.Project project) { var item = project.ProjectItems.GetEnumerator(); while (item.MoveNext()) { if (item.Current is EnvDTE.ProjectItem projItem) { IterateProjItems(projItem); } } } var proj = ProjectHelpers.Dte.Solution.GetProjectContainingFile(this.File); // For very large projects this can be very inefficient. When an issue, consider caching or querying the file system directly. IterateProject(proj); if (reswFiles.Count == 0) { RapidXamlPackage.Logger?.RecordInfo(StringRes.Info_NoResourceFileFound); return(null); } else if (reswFiles.Count == 1) { return(reswFiles.First()); } else { var langOfInterest = string.Empty; var neutralLang = proj.Properties.Item("NeutralResourcesLanguage").Value.ToString(); if (string.IsNullOrWhiteSpace(neutralLang)) { var xProj = XDocument.Load(proj.FileName); XNamespace xmlns = "http://schemas.microsoft.com/developer/msbuild/2003"; var defLang = xProj.Descendants(xmlns + "DefaultLanguage").FirstOrDefault(); if (defLang != null) { langOfInterest = defLang.Value; } } else { langOfInterest = neutralLang; } if (!string.IsNullOrWhiteSpace(langOfInterest)) { return(reswFiles.FirstOrDefault(f => f.IndexOf(langOfInterest, StringComparison.OrdinalIgnoreCase) > 0)); } else { // Find neutral language file to return // RegEx to match if lang identifier in path or file name return(reswFiles.FirstOrDefault(f => Regex.Matches(f, "([\\.][a-zA-Z]{2}-[a-zA-Z]{2}[\\.])").Count == 0)); } } }
protected void btnImport_Click(object sender, EventArgs e) { try { String Path = Server.MapPath("~/Archivos/CargaXml/"); string[] docXml = Directory.GetFiles(Path); foreach (var elemento in docXml) { string documento = elemento; FileStream docPath = new FileStream(documento, FileMode.Open, FileAccess.Read); string fileName = docPath.Name; if (!string.IsNullOrEmpty(fileName)) { string uuid = string.Empty; string folio = string.Empty; string serie = string.Empty; string fechaTimbrado = string.Empty; string tasa = string.Empty; string importeTotal = string.Empty; string rfc = string.Empty; string nombreRfc = string.Empty; string moneda = string.Empty; string tipoCambio = string.Empty; string rfcReceptor = string.Empty; string tipoComprobante = string.Empty; XNamespace ns = "http://www.sat.gob.mx/cfd/3"; XNamespace nd = "http://www.sat.gob.mx/TimbreFiscalDigital"; XDocument xDoc = XDocument.Load(fileName); if (xDoc.Root.Element(ns + "Complemento").Element(nd + "TimbreFiscalDigital").Attribute("UUID") != null) { uuid = xDoc.Root.Element(ns + "Complemento").Element(nd + "TimbreFiscalDigital").Attribute("UUID").Value; } if (xDoc.Root.Attribute("folio") != null) { folio = xDoc.Root.Attribute("folio").Value; } if (xDoc.Root.Attribute("serie") != null) { serie = xDoc.Root.Attribute("serie").Value; } if (xDoc.Root.Element(ns + "Complemento").Element(nd + "TimbreFiscalDigital").Attribute("FechaTimbrado") != null) { fechaTimbrado = xDoc.Root.Element(ns + "Complemento").Element(nd + "TimbreFiscalDigital").Attribute("FechaTimbrado").Value; } if (xDoc.Root.Element(ns + "Impuestos") != null) { if (xDoc.Root.Element(ns + "Impuestos").Element(ns + "Traslados") != null) { if (xDoc.Root.Element(ns + "Impuestos").Element(ns + "Traslados").Element(ns + "Traslado") != null) { if (xDoc.Root.Element(ns + "Impuestos").Element(ns + "Traslados").Element(ns + "Traslado").Attribute("tasa") != null) { tasa = xDoc.Root.Element(ns + "Impuestos").Element(ns + "Traslados").Element(ns + "Traslado").Attribute("tasa").Value; } } } } if (xDoc.Root.Attribute("total") != null) { importeTotal = xDoc.Root.Attribute("total").Value; } if (xDoc.Root.Element(ns + "Emisor").Attribute("rfc") != null) { rfc = xDoc.Root.Element(ns + "Emisor").Attribute("rfc").Value; } if (xDoc.Root.Element(ns + "Emisor").Attribute("nombre") != null) { nombreRfc = xDoc.Root.Element(ns + "Emisor").Attribute("nombre").Value; } if (xDoc.Root.Attribute("Moneda") != null) { moneda = xDoc.Root.Attribute("Moneda").Value; } if (xDoc.Root.Attribute("TipoCambio") != null) { tipoCambio = xDoc.Root.Attribute("TipoCambio").Value; } if (xDoc.Root.Element(ns + "Receptor").Attribute("rfc") != null) { rfcReceptor = xDoc.Root.Element(ns + "Receptor").Attribute("rfc").Value; } if (xDoc.Root.Attribute("tipoDeComprobante") != null) { tipoComprobante = xDoc.Root.Attribute("tipoDeComprobante").Value; } double tasaEnviar = 0; double d; if (tasa != string.Empty && Double.TryParse(tasa, out d)) { tasaEnviar = Convert.ToDouble(tasa); } if (nombreRfc == "") { nombreRfc = "Sin identificar"; } if (moneda == "") { moneda = "Sin identificar"; } set_insertaXmlTableAdapter set_insertaXml = new set_insertaXmlTableAdapter(); set_insertaXml.GetData(uuid, fechaTimbrado, folio, serie, Decimal.Parse(importeTotal), tasaEnviar, nombreRfc, rfc, DateTimeOffset.Parse(fechaTimbrado).DateTime, moneda, tipoCambio, rfcReceptor, tipoComprobante); } } this.ctrPopup1.Show(); this.GridView1.DataBind(); } catch (Exception) { throw; } }
private void Init(Uri locationUri) { try { Logger.Info("the Description Url is {0}", locationUri); BaseUrl = locationUri; var document = XDocument.Load(locationUri.AbsoluteUri); var xnm = new XmlNamespaceManager(new NameTable()); XNamespace n1 = "urn:ses-com:satip"; XNamespace n0 = "urn:schemas-upnp-org:device-1-0"; xnm.AddNamespace("root", n0.NamespaceName); xnm.AddNamespace("satip:", n1.NamespaceName); if (document.Root != null) { var deviceElement = document.Root.Element(n0 + "device"); _deviceDescription = document.Declaration + document.ToString(); Logger.Info("The Description has this Content \r\n{0}", _deviceDescription); if (deviceElement != null) { var devicetypeElement = deviceElement.Element(n0 + "deviceType"); if (devicetypeElement != null) { _deviceType = devicetypeElement.Value; } var friendlynameElement = deviceElement.Element(n0 + "friendlyName"); if (friendlynameElement != null) { _friendlyName = friendlynameElement.Value; } var manufactureElement = deviceElement.Element(n0 + "manufacturer"); if (manufactureElement != null) { _manufacturer = manufactureElement.Value; } var manufactureurlElement = deviceElement.Element(n0 + "manufacturerURL"); if (manufactureurlElement != null) { _manufacturerUrl = manufactureurlElement.Value; } var modeldescriptionElement = deviceElement.Element(n0 + "modelDescription"); if (modeldescriptionElement != null) { _modelDescription = modeldescriptionElement.Value; } var modelnameElement = deviceElement.Element(n0 + "modelName"); if (modelnameElement != null) { _modelName = modelnameElement.Value; } var modelnumberElement = deviceElement.Element(n0 + "modelNumber"); if (modelnumberElement != null) { _modelNumber = modelnumberElement.Value; } var modelurlElement = deviceElement.Element(n0 + "modelURL"); if (modelurlElement != null) { _modelUrl = modelurlElement.Value; } var serialnumberElement = deviceElement.Element(n0 + "serialNumber"); if (serialnumberElement != null) { _serialNumber = serialnumberElement.Value; } var uniquedevicenameElement = deviceElement.Element(n0 + "UDN"); if (uniquedevicenameElement != null) { _uniqueDeviceName = uniquedevicenameElement.Value; } var iconList = deviceElement.Element(n0 + "iconList"); if (iconList != null) { var icons = from query in iconList.Descendants(n0 + "icon") select new SatIpDeviceIcon { // Needed to change mimeType to mimetype. XML is case sensitive MimeType = (string)query.Element(n0 + "mimetype"), Url = (string)query.Element(n0 + "url"), Height = (int)query.Element(n0 + "height"), Width = (int)query.Element(n0 + "width"), Depth = (int)query.Element(n0 + "depth"), }; _iconList = icons.ToArray(); } var presentationUrlElement = deviceElement.Element(n0 + "presentationURL"); if (presentationUrlElement != null) { if (presentationUrlElement.Value.StartsWith("Http;//")) { _presentationUrl = presentationUrlElement.Value; } _presentationUrl = locationUri.Scheme + "://" + locationUri.Host; } if (presentationUrlElement == null) { _presentationUrl = locationUri.Scheme + "://" + locationUri.Host; } var capabilitiesElement = deviceElement.Element(n1 + "X_SATIPCAP"); if (capabilitiesElement != null) { _capabilities = capabilitiesElement.Value; if (capabilitiesElement.Value.Contains(',')) { string[] capabilities = capabilitiesElement.Value.Split(','); foreach (var capability in capabilities) { ReadCapability(capability); } } else { ReadCapability(capabilitiesElement.Value); } } else { _supportsDVBS = true; //ToDo Create only one Digital Recorder / Capture Instance here } var m3uElement = deviceElement.Element(n1 + "X_SATIPM3U"); if (m3uElement != null) { _m3u = locationUri.Scheme + "://" + locationUri.Host + ":" + locationUri.Port + m3uElement.Value; } } } } catch (Exception exception) { Logger.Error("It give a Problem with the Description {0}", exception); } }
static SpreadsheetDocumentManager() { ns = "http://schemas.openxmlformats.org/spreadsheetml/2006/main"; relationshipsns = "http://schemas.openxmlformats.org/officeDocument/2006/relationships"; }
public static XElement RemoveNamespaceAttributes(string[] inScopePrefixes, XNamespace[] inScopeNs, List <XAttribute> attributes, XElement e) { checked { if (e != null) { XAttribute nextAttribute; for (XAttribute xattribute = e.FirstAttribute; xattribute != null; xattribute = nextAttribute) { nextAttribute = xattribute.NextAttribute; if (xattribute.IsNamespaceDeclaration) { XNamespace xnamespace = xattribute.Annotation <XNamespace>(); string localName = xattribute.Name.LocalName; if (xnamespace != null) { if (inScopePrefixes != null && inScopeNs != null) { int num = inScopePrefixes.Length - 1; int num2 = 0; int num3 = num; int num4 = num2; XNamespace right; for (;;) { int num5 = num4; int num6 = num3; if (num5 > num6) { goto Block_8; } string value = inScopePrefixes[num4]; right = inScopeNs[num4]; if (localName.Equals(value)) { break; } num4++; } if (xnamespace == right) { xattribute.Remove(); } xattribute = null; Block_8 :; } if (xattribute != null) { if (attributes != null) { int num7 = attributes.Count - 1; int num8 = 0; int num9 = num7; int num10 = num8; XNamespace xnamespace2; for (;;) { int num11 = num10; int num6 = num9; if (num11 > num6) { goto Block_13; } XAttribute xattribute2 = attributes[num10]; string localName2 = xattribute2.Name.LocalName; xnamespace2 = xattribute2.Annotation <XNamespace>(); if (xnamespace2 != null && localName.Equals(localName2)) { break; } num10++; } if (xnamespace == xnamespace2) { xattribute.Remove(); } xattribute = null; Block_13 :; } if (xattribute != null) { xattribute.Remove(); attributes.Add(xattribute); } } } } } } return(e); } }
public void StartReadFile(Stream input) { ZipArchive z = new ZipArchive(input, ZipArchiveMode.Read); var worksheet = z.GetEntry("xl/worksheets/sheet1.xml"); var sharedString = z.GetEntry("xl/sharedStrings.xml"); // get shared string _sharedStrings = new List <string>(); // if there is no content the sharedStrings will be null if (sharedString != null) { using (var sr = sharedString.Open()) { XDocument xdoc = XDocument.Load(sr); _sharedStrings = ( from e in xdoc.Root.Elements() select e.Elements().First().Value ).ToList(); } } // get header using (var sr = worksheet.Open()) { XDocument xdoc = XDocument.Load(sr); // get element to first sheet data XNamespace xmlns = "http://schemas.openxmlformats.org/spreadsheetml/2006/main"; XElement sheetData = xdoc.Root.Element(xmlns + "sheetData"); _header = new List <string>(); _derivedData = new List <Dictionary <string, string> >(); // worksheet empty? if (!sheetData.Elements().Any()) { return; } // build header first var firstRow = sheetData.Elements().First(); // full of c foreach (var c in firstRow.Elements()) { // the c element, if have attribute t, will need to consult sharedStrings string val = c.Elements().First().Value; if (c.Attribute("t") != null) { _header.Add(_sharedStrings[Convert.ToInt32(val)]); } else { _header.Add(val); } } // build content now foreach (var row in sheetData.Elements()) { // skip row 1 if (row.Attribute("r").Value == "1") { continue; } Dictionary <string, string> rowData = new Dictionary <string, string>(); // the "c" elements each represent a column foreach (var c in row.Elements()) { var cellID = c.Attribute("r").Value; // e.g. H2 // each "c" element has a "v" element representing the value string val = c.Elements().First().Value; // a string? look up in shared string file if (c.Attribute("t") != null) { rowData.Add(_header[GetColumnIndex(cellID)], _sharedStrings[Convert.ToInt32(val)]); } else { // number rowData.Add(_header[GetColumnIndex(cellID)], val); } } _derivedData.Add(rowData); } } }
private async void RefreshCredentials() { if (refreshCredentialsButton.InvokeRequired) { refreshCredentialsButton.Invoke(new Action(RefreshCredentials)); return; } refreshCredentialsButton.Enabled = false; logTextBox.Text = string.Empty; errorPanel.Visible = false; profilesListBox.Items.Clear(); _profiles.Clear(); refereshTimer.Stop(); Action <string> log = m => logTextBox.AppendText($"{DateTime.Now}: {m} {Environment.NewLine}"); try { // Authenticate against ADFS with NTLM. var endpoint = $"{adfsUrlTextBox.Text}?loginToRp={loginToRPTextBox.Text}"; var handler = new HttpClientHandler { UseCookies = true, AllowAutoRedirect = true, ClientCertificateOptions = ClientCertificateOption.Automatic }; if (useCurrentUserCheckBox.Checked) { handler.UseDefaultCredentials = true; } else { handler.Credentials = new NetworkCredential(usernameTextBox.Text, passwordTextBox.Text); } var client = new HttpClient(handler); client.DefaultRequestHeaders.Add("User-Agent", "Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident/6.0)"); client.DefaultRequestHeaders.Add("Connection", "Keep-Alive"); client.DefaultRequestHeaders.ExpectContinue = false; log($"Logging in as '{usernameTextBox.Text}'..."); var response = await client.GetAsync(endpoint); string body; if (useCurrentUserCheckBox.Checked) { if (response.StatusCode != HttpStatusCode.OK) { throw new InvalidOperationException("Authentication failed."); } body = await response.Content.ReadAsStringAsync(); } else { if (response.StatusCode != HttpStatusCode.Unauthorized) { throw new InvalidOperationException("Invalid ADFS Url. " + $"Visit {endpoint} in your browser to verify."); } // Need to a second time for the Network Credentials to be send. // Don't know why, but it works (and I saw firefox doing same). response = await client.GetAsync(response.RequestMessage.RequestUri); response.EnsureSuccessStatusCode(); body = await response.Content.ReadAsStringAsync(); } // Get the base64 encoded SAML response from the respons body HTML. var parser = new HtmlParser(); var htmlDocument = parser.Parse(body); var form = htmlDocument.Forms[0]; var encodedSamlResponse = ((IHtmlInputElement)form .GetElementsByTagName("input") .SingleOrDefault(e => e.GetAttribute("name") == "SAMLResponse"))?.Value; if (encodedSamlResponse == null) { throw new InvalidOperationException("Authentication failed. Check username and password." + $"Visit {endpoint} in your browser to verify."); } log("...success."); // Extract the status code and Role Attributes from the SAML response. var samlResponse = Encoding.UTF8.GetString(Convert.FromBase64String(encodedSamlResponse)); XNamespace pr = "urn:oasis:names:tc:SAML:2.0:protocol"; XNamespace ast = "urn:oasis:names:tc:SAML:2.0:assertion"; var doc = XDocument.Parse(samlResponse); var status = doc.Element(pr + "Response").Element(pr + "Status"); var statusCode = status.Element(pr + "StatusCode").Attribute("Value"); var statusMessage = status.Element(pr + "StatusMessage"); log($"SAML Status code: {statusCode}; message: {statusMessage}."); var attStatement = doc .Element(pr + "Response") .Element(ast + "Assertion") .Element(ast + "AttributeStatement"); var roles = attStatement .Elements(ast + "Attribute") .First(a => a.Attribute("Name").Value == "https://aws.amazon.com/SAML/Attributes/Role") .Elements(ast + "AttributeValue") .Select(e => e.Value.Split(',')[1]) .ToArray(); log("ADFS Defined Roles: "); foreach (var role in roles) { log($" {role}"); } // For each role, call AWS AssumeRoleWithSAML and thus create // temporary credentials. var stsClient = new AmazonSecurityTokenServiceClient(new AnonymousAWSCredentials()); var assumedRoles = new List <AssumeRoleWithSAMLResponse>(); foreach (var roleArn in roles) { log($"Assuming role {roleArn}..."); var arnParts = roleArn.Split(':'); var account = arnParts[4]; var assumeRoleWithSamlRequest = new AssumeRoleWithSAMLRequest { SAMLAssertion = encodedSamlResponse, PrincipalArn = $"arn:aws:iam::{account}:saml-provider/{samlProviderNameTextBox.Text}", RoleArn = roleArn, DurationSeconds = 3600 }; try { var assumeRoleWithSamlResponse = await stsClient.AssumeRoleWithSAMLAsync(assumeRoleWithSamlRequest); log($" AccessKeyId: {assumeRoleWithSamlResponse.Credentials.AccessKeyId}"); log($" SecretAccessKey: {assumeRoleWithSamlResponse.Credentials.SecretAccessKey}"); log($" SessionToken: {assumeRoleWithSamlResponse.Credentials.SessionToken}"); log($" Expires: {assumeRoleWithSamlResponse.Credentials.Expiration}"); assumedRoles.Add(assumeRoleWithSamlResponse); } catch (Exception ex) { log(ex.ToString()); } } // Write the temporary credentials to a the credential file (ini format) var stringBuilder = new StringBuilder(); foreach (var assumedRole in assumedRoles) { var profile = assumedRole.AssumedRoleUser.Arn.Split(':')[5].Split('/')[1]; _profiles.Add( new Profile( profile, assumedRole.Credentials.AccessKeyId, assumedRole.Credentials.SecretAccessKey, assumedRole.Credentials.SessionToken)); stringBuilder.AppendLine($"[{profile}]"); stringBuilder.AppendLine($"aws_access_key_id={assumedRole.Credentials.AccessKeyId}"); stringBuilder.AppendLine($"aws_secret_access_key={assumedRole.Credentials.SecretAccessKey}"); stringBuilder.AppendLine($"aws_session_token={assumedRole.Credentials.SessionToken}"); stringBuilder.AppendLine(); } foreach (var profile in _profiles) { profilesListBox.Items.Add(profile); } var credentialDirectory = Path.GetDirectoryName(credentialFilePathTextBox.Text); Directory.CreateDirectory(credentialDirectory); File.WriteAllText(credentialFilePathTextBox.Text, stringBuilder.ToString()); log($"Credentials written to {credentialFilePathTextBox.Text}"); } catch (Exception ex) { log(ex.ToString()); errorPanel.Visible = true; } refreshCredentialsButton.Enabled = true; _startTime = DateTime.Now; refereshTimer.Start(); }
/// <summary> /// Get Weather Forecast from XML /// </summary> /// <param name="area">Area which you want to get weather forecast</param> /// <param name="keySeparator">Key separtor which concatnate Meteorological office name and area name</param> /// <returns></returns> /// public Task<Dictionary<string, Dictionary<string, string>>> GetForecast(Dictionary<string, List<string>> area, string keySeparator) public Task <WeatherInfoContainer> GetForecast(Dictionary <string, List <string> > area, string keySeparator) { SyndicationFeed feed = weatherInfoContainer.AtomFeeds[Resources.REGULAR]; IEnumerable <SyndicationItem> itemList = feed.Items; var result = new Dictionary <string, Dictionary <string, String> >(); // Iterate ATOM Feed Items foreach (SyndicationItem item in itemList) { string id = item.Id; string authorName = item.Authors.First().Name; if (item.Title.Text == Resources.FORECAST_TITLE && area.Keys.Contains(authorName)) { string url = item.Links.First().Uri.ToString(); XDocument xdoc = XDocument.Load(url); XNamespace xns = null; GetHeadAndBody(xdoc, out XElement xHead, out XElement xBody); //Get Item Element based on area dictionary Dictionary <string, List <XElement> > dicAreaItem = GetItemsFromArea(area, xBody, authorName); //Get ReportDate string strReportDateTime = GetChildText(xHead, "ReportDateTime"); //Iterate each area foreach (string areaName in dicAreaItem.Keys) { XElement xe = null; foreach (XElement xeitem in dicAreaItem[areaName]) { var lxns = xeitem.Name.Namespace; string itemType = xeitem.Element(lxns + "Kind").Element(lxns + "Property").Element(lxns + "Type").Value; if (itemType == "天気") { xe = xeitem; break; } } if (xe == null) { throw new FormatException("Cannot find item Tenki"); } xns = xe.Name.Namespace; //Get defenition of TimeDef XElement xTimeDefines = (XElement)xe.PreviousNode; IEnumerable <XElement> xeTimeDef = xTimeDefines.Elements(xns + "TimeDefine"); var dicTimeDef = new Dictionary <string, string>(); foreach (XElement xElemTimeDef in xeTimeDef) { string timeIdValue = xElemTimeDef.Attribute("timeId").Value; if (timeIdValue != null) { dicTimeDef[timeIdValue] = xElemTimeDef.Element(xns + "Name").Value; } } //Iterate Weather Forecast Part Elements IEnumerable <XElement> ieXElemWFPart = xe.Elements(xns + "Kind").First().Descendants(xns + "WeatherForecastPart"); var dicContent = new Dictionary <string, string>() { { "ReportDateTime", strReportDateTime } }; foreach (XElement xElemWFPart in ieXElemWFPart) { var attr = xElemWFPart.Attribute("refID"); if (attr != null && dicTimeDef.ContainsKey(attr.Value)) { XNamespace sxns = xElemWFPart.Name.Namespace; dicContent[dicTimeDef[attr.Value]] = xElemWFPart.Element(sxns + "Sentence").Value; } else { throw new FormatException("Cannot find attr."); } } result[item.Authors.First().Name + keySeparator + areaName] = dicContent; } xdoc = null; area.Remove(authorName); if (area.Count == 0) { break; } } } weatherInfoContainer.Result[Resources.GetForecast] = result; return(Task.FromResult(weatherInfoContainer)); }
private async Task <IEnumerable <VideoFeedItem> > ParseFeed(string rss) { return(await Task.Run(() => { var xdoc = XDocument.Parse(rss); var list = new List <VideoFeedItem>(); XNamespace media = "http://search.yahoo.com/mrss/"; XNamespace itunes = "http://www.itunes.com/dtds/podcast-1.0.dtd"; foreach (var item in xdoc.Descendants("item")) { try { bool foundTheMagicKeyword = false; foreach (var element in item.Elements()) { var keyword = "jaimehernandez".ToLowerInvariant(); if (element.Value.ToLowerInvariant().Contains(keyword)) { foundTheMagicKeyword = true; break; } } if (!foundTheMagicKeyword) { continue; } var mediaGroup = item.Element(media + "group"); if (mediaGroup == null) { continue; } List <VideoContentItem> videoUrls = new List <VideoContentItem>(); foreach (var mediaUrl in mediaGroup.Elements()) { var duration = mediaUrl.Attribute("duration").Value; var fileSize = mediaUrl.Attribute("fileSize").Value; var url = mediaUrl.Attribute("url").Value; videoUrls.Add(new VideoContentItem() { Duration = TimeSpan.FromSeconds(Convert.ToInt32(duration)), FileSize = long.Parse(fileSize), Url = url, } ); } var videoFeedItem = new VideoFeedItem { VideoUrls = videoUrls.OrderByDescending(url => url.FileSize).ToList(), Title = (string)item.Element("title"), Description = (string)item.Element(itunes + "summary")?.Value, Link = (string)item.Element("link"), PublishDate = (string)item.Element("pubDate"), Category = (string)item.Element("category"), ThumbnailUrl = (string)item.Element(media + "thumbnail")?.Attribute("url")?.Value }; list.Add(videoFeedItem); } catch (Exception) { Debug.WriteLine("Unable to parse rss for item"); } } return list; })); }
/// <summary> /// Get Typhoon Info from XML /// </summary> /// <param name="typhoonNumberList"></param> /// <param name="ignoreIdList"></param> /// <returns></returns> public Task <WeatherInfoContainer> GetTyphoonInfo(List <Int32> typhoonNumberList, List <string> ignoreIdList) { SyndicationFeed feed = weatherInfoContainer.AtomFeeds[Resources.EXTRA]; IEnumerable <SyndicationItem> itemList = feed.Items; List <string> processedIdList = new List <string>(); List <string> processedNumberStrList = new List <string>(); var result = new Dictionary <string, Dictionary <string, string> >(); foreach (SyndicationItem item in itemList) { string id = item.Id; string authorName = item.Authors.First().Name; if (item.Title.Text == Resources.TYPHOON_TITLE && !ignoreIdList.Contains(id)) { string url = item.Links.First().Uri.ToString(); XDocument xdoc = XDocument.Load(url); XNamespace xns = null; GetHeadAndBody(xdoc, out XElement xHead, out XElement xBody); //Get Title string strTitle = GetChildText(xHead, "Title"); //Get ReportDate string strReportDateTime = GetChildText(xHead, "ReportDateTime"); string numStr = Microsoft.VisualBasic.Strings.StrConv(System.Text.RegularExpressions.Regex.Match(strTitle, @"(?<=台風第)\d+(?=号)").Value, Microsoft.VisualBasic.VbStrConv.Narrow, 0x411); //Check if already processed if (!processedNumberStrList.Contains(numStr)) { if (typhoonNumberList.Count > 0) { if (!typhoonNumberList.Any(x => x == Int32.Parse(numStr))) { continue; } } string resultHeadlineString = ""; string resultCommentString = ""; var dictResultItem = new Dictionary <string, string>(); // Get Headline text xns = xHead.Name.Namespace; IEnumerable <XElement> xElemComment = xHead.Descendants(xns + "Headline"); foreach (XElement xe in xElemComment) { resultHeadlineString = xe.Element(xns + "Text").Value; } // Get Comment text xns = xBody.Name.Namespace; xElemComment = xBody.Descendants(xns + "Comment"); foreach (XElement xeComment in xElemComment) { var xElemText = xeComment.Descendants(xns + "Text"); foreach (XElement xeText in xElemText) { resultCommentString += xeText.Value; } } dictResultItem["ReportDateTime"] = strReportDateTime; dictResultItem["Comment"] = resultCommentString; dictResultItem["Headline"] = resultHeadlineString; result[numStr] = dictResultItem; processedIdList.Add(id); processedNumberStrList.Add(numStr); } } } weatherInfoContainer.Result[Resources.GetTyphoonInfo] = result; weatherInfoContainer.ProcessedID[Resources.GetTyphoonInfo] = processedIdList; return(Task.FromResult(weatherInfoContainer)); }
static void Main(string[] args) { XDocument doc = XDocument.Load(FILENAME); XNamespace defaultNs = ((XElement)doc.FirstNode).GetDefaultNamespace(); string ovsCTicketID = (string)doc.Descendants(defaultNs + "OVSCTicketID").FirstOrDefault(); }
Pattern FromXml(XElement node) { XNamespace rng = "http://relaxng.org/ns/structure/1.0"; if (node.Name.Namespace != rng) { throw new Exception(); } var children = node.Elements().Select(x => FromXml(x)); switch (node.Name.LocalName) { case "anyName": return(children.Count() > 0 ? And(AnyName(), children.First()) : AnyName()); case "nsName": return(children.Count() > 0 ? And(NsName(node.Attribute("ns").Value), children.First()) : NsName(node.Attribute("ns").Value)); case "name": return(Name(node.Attribute("ns").Value, node.Value)); case "except": return(Not(children.First())); case "element": return(Element(children.First(), children.Skip(1).First())); case "define": case "group": return(children.Aggregate(Group)); case "oneOrMore": return(OneOrMore(children.Aggregate(Group))); case "choice": return(children.Aggregate(Choice)); case "interleave": return(children.Aggregate(Interleave)); case "zeroOrMore": return(Optional(OneOrMore(children.Aggregate(Group)))); case "optional": return(Optional(children.Aggregate(Group))); case "value": case "text": case "data": case "list": return(Text()); case "ref": return(Ref(node.Attribute("name").Value)); case "empty": return(Empty()); case "notAllowed": return(NotAllowed()); case "attribute": if (node.Elements().First().Name.LocalName != "name") { throw new Exception("Only <name> is allowed as name class for Attributes"); } return(Attribute(node.Elements().First().Value, node.Elements().First().Attribute("ns").Value)); default: throw new Exception(); } }
public void CheckValueTypes() { StartService(typeof(ValueTypeService)); var wsdl = GetWsdl(); StopServer(); var root = XElement.Parse(wsdl); var elementsWithEmptyName = GetElements(root, _xmlSchema + "element").Where(x => x.Attribute("name")?.Value == string.Empty); elementsWithEmptyName.ShouldBeEmpty(); var elementsWithEmptyType = GetElements(root, _xmlSchema + "element").Where(x => x.Attribute("type")?.Value == "xs:"); elementsWithEmptyType.ShouldBeEmpty(); File.WriteAllText("test.wsdl", wsdl); var inputElement = GetElements(root, _xmlSchema + "complexType").Single(x => x.Attribute("name")?.Value == "AnyStructInput"); var inputAnnotation = inputElement.Descendants(_xmlSchema + "annotation").SingleOrDefault(); var inputIsValueType = inputAnnotation.Descendants(_xmlSchema + "appinfo").Descendants(XNamespace.Get("http://schemas.microsoft.com/2003/10/Serialization/") + "IsValueType").SingleOrDefault(); var outputElement = GetElements(root, _xmlSchema + "complexType").Single(x => x.Attribute("name")?.Value == "AnyStructOutput"); var outputAnnotation = outputElement.Descendants(_xmlSchema + "annotation").SingleOrDefault(); var outputIsValueType = outputAnnotation.Descendants(_xmlSchema + "appinfo").Descendants(XNamespace.Get("http://schemas.microsoft.com/2003/10/Serialization/") + "IsValueType").SingleOrDefault(); Assert.IsNotNull(inputIsValueType); Assert.AreEqual("true", inputIsValueType.Value); Assert.IsNotNull(inputAnnotation); Assert.IsNotNull(outputIsValueType); Assert.AreEqual("true", outputIsValueType.Value); Assert.IsNotNull(outputAnnotation); }
IXmlListAttributeConfiguration IXmlRootConfiguration <IXmlListAttributeConfiguration> .WithNamespace(XNamespace xNamespace) { WithNamespace(xNamespace); return(this); }
public override void OnApplyTemplate() { base.OnApplyTemplate(); if (Template != null) { ViewHost = Template.FindName("PART_ViewHost", this) as FrameworkElement; if (ViewHost != null) { ViewHost.InputBindings.Add(new KeyBinding() { Command = mainModel.OpenMainMenuCommand, Key = Key.F1 }); ViewHost.InputBindings.Add(new KeyBinding() { Command = mainModel.PrevFilterViewCommand, Key = Key.F2 }); ViewHost.InputBindings.Add(new KeyBinding() { Command = mainModel.NextFilterViewCommand, Key = Key.F3 }); ViewHost.InputBindings.Add(new KeyBinding() { Command = mainModel.OpenSearchCommand, Key = Key.Y }); ViewHost.InputBindings.Add(new KeyBinding() { Command = mainModel.ToggleFiltersCommand, Key = Key.F }); ViewHost.InputBindings.Add(new KeyBinding() { Command = mainModel.SwitchToDesktopCommand, Key = Key.F11 }); ViewHost.InputBindings.Add(new XInputBinding(mainModel.PrevFilterViewCommand, XInputButton.LeftShoulder)); ViewHost.InputBindings.Add(new XInputBinding(mainModel.NextFilterViewCommand, XInputButton.RightShoulder)); ViewHost.InputBindings.Add(new XInputBinding(mainModel.OpenSearchCommand, XInputButton.Y)); ViewHost.InputBindings.Add(new XInputBinding(mainModel.ToggleFiltersCommand, XInputButton.RightStick)); ViewHost.InputBindings.Add(new XInputBinding(mainModel.OpenMainMenuCommand, XInputButton.Back)); } MainHost = Template.FindName("PART_MainHost", this) as FrameworkElement; if (MainHost != null) { BindingTools.SetBinding(MainHost, FrameworkElement.WidthProperty, mainModel, nameof(FullscreenAppViewModel.ViewportWidth)); BindingTools.SetBinding(MainHost, FrameworkElement.HeightProperty, mainModel, nameof(FullscreenAppViewModel.ViewportHeight)); } AssignButtonWithCommand(ref ButtonProgramUpdate, "PART_ButtonProgramUpdate", mainModel.OpenUpdatesCommand); AssignButtonWithCommand(ref ButtonMainMenu, "PART_ButtonMainMenu", mainModel.OpenMainMenuCommand); AssignButtonWithCommand(ref ButtonNotifications, "PART_ButtonNotifications", mainModel.OpenNotificationsMenuCommand); if (ButtonProgramUpdate != null) { BindingTools.SetBinding(ButtonProgramUpdate, Button.VisibilityProperty, mainModel, nameof(mainModel.UpdatesAvailable), converter: new Converters.BooleanToVisibilityConverter()); } ImageBackground = Template.FindName("PART_ImageBackground", this) as FadeImage; if (ImageBackground != null) { SetBackgroundBinding(); SetBackgroundEffect(); } TextClock = Template.FindName("PART_TextClock", this) as TextBlock; if (TextClock != null) { BindingTools.SetBinding(TextClock, TextBlock.TextProperty, mainModel.CurrentTime, nameof(ObservableTime.Time)); BindingTools.SetBinding( TextClock, TextBlock.VisibilityProperty, mainModel.AppSettings.Fullscreen, nameof(FullscreenSettings.ShowClock), converter: new Converters.BooleanToVisibilityConverter()); } TextBatteryPercentage = Template.FindName("PART_TextBatteryPercentage", this) as TextBlock; if (TextBatteryPercentage != null) { BindingTools.SetBinding(TextBatteryPercentage, TextBlock.TextProperty, mainModel.PowerStatus, nameof(ObservablePowerStatus.PercentCharge), stringFormat: "{0}%"); BindingTools.SetBinding(TextBatteryPercentage, TextBlock.VisibilityProperty, mainModel.AppSettings.Fullscreen, nameof(FullscreenSettings.ShowBatteryPercentage), converter: new Converters.BooleanToVisibilityConverter()); } ElemBatteryStatus = Template.FindName("PART_ElemBatteryStatus", this) as FrameworkElement; if (ElemBatteryStatus != null) { BindingTools.SetBinding( ElemBatteryStatus, TextBlock.VisibilityProperty, mainModel.AppSettings.Fullscreen, nameof(FullscreenSettings.ShowBattery), converter: new Converters.BooleanToVisibilityConverter()); } TextProgressTooltip = Template.FindName("PART_TextProgressTooltip", this) as TextBlock; if (TextProgressTooltip != null) { BindingTools.SetBinding(TextProgressTooltip, TextBlock.TextProperty, mainModel, nameof(FullscreenAppViewModel.ProgressStatus)); BindingTools.SetBinding(TextProgressTooltip, TextBlock.VisibilityProperty, mainModel, nameof(FullscreenAppViewModel.ProgressActive), converter: new Converters.BooleanToVisibilityConverter()); } ElemProgressIndicator = Template.FindName("PART_ElemProgressIndicator", this) as FrameworkElement; if (ElemProgressIndicator != null) { BindingTools.SetBinding(ElemProgressIndicator, ToggleButton.VisibilityProperty, mainModel, nameof(FullscreenAppViewModel.ProgressActive), converter: new Converters.BooleanToVisibilityConverter()); } ElemExtraFilterActive = Template.FindName("PART_ElemExtraFilterActive", this) as FrameworkElement; if (ElemExtraFilterActive != null) { BindingTools.SetBinding(ElemExtraFilterActive, FrameworkElement.VisibilityProperty, mainModel, nameof(FullscreenAppViewModel.IsExtraFilterActive), converter: new Converters.BooleanToVisibilityConverter()); } ElemSearchActive = Template.FindName("PART_ElemSearchActive", this) as FrameworkElement; if (ElemSearchActive != null) { BindingTools.SetBinding(ElemSearchActive, FrameworkElement.VisibilityProperty, mainModel, nameof(FullscreenAppViewModel.IsSearchActive), converter: new Converters.BooleanToVisibilityConverter()); } ListGameItems = Template.FindName("PART_ListGameItems", this) as ListBox; if (ListGameItems != null) { XNamespace pns = "http://schemas.microsoft.com/winfx/2006/xaml/presentation"; ListGameItems.ItemsPanel = Xaml.FromString <ItemsPanelTemplate>(new XDocument( new XElement(pns + nameof(ItemsPanelTemplate), new XElement(pns + nameof(FullscreenTilePanel), new XAttribute(nameof(FullscreenTilePanel.Rows), "{Settings Fullscreen.Rows}"), new XAttribute(nameof(FullscreenTilePanel.Columns), "{Settings Fullscreen.Columns}"), new XAttribute(nameof(FullscreenTilePanel.UseHorizontalLayout), "{Settings Fullscreen.HorizontalLayout}"), new XAttribute(nameof(FullscreenTilePanel.ItemAspectRatio), "{Settings CoverAspectRatio}"), new XAttribute(nameof(FullscreenTilePanel.ItemSpacing), "{Settings FullscreenItemSpacing}"))) ).ToString()); ListGameItems.ItemTemplate = Xaml.FromString <DataTemplate>(new XDocument( new XElement(pns + nameof(DataTemplate), new XElement(pns + nameof(GameListItem), new XAttribute(nameof(GameListItem.Style), "{StaticResource ListGameItemTemplate}"))) ).ToString()); ListGameItems.SetResourceReference(ListBoxEx.ItemContainerStyleProperty, "ListGameItemStyle"); BindingTools.SetBinding(ListGameItems, ListBox.VisibilityProperty, mainModel, nameof(FullscreenAppViewModel.GameListVisible), converter: new Converters.BooleanToVisibilityConverter()); BindingTools.SetBinding(ListGameItems, ListBox.SelectedItemProperty, mainModel, nameof(FullscreenAppViewModel.SelectedGame), BindingMode.TwoWay); BindingTools.SetBinding(ListGameItems, ListBox.ItemsSourceProperty, mainModel, $"{nameof(FullscreenAppViewModel.GamesView)}.{nameof(FullscreenCollectionView.CollectionView)}"); BindingTools.SetBinding(ListGameItems, FocusBahaviors.FocusBindingProperty, mainModel, nameof(mainModel.GameListFocused)); } AssignButtonWithCommand(ref ButtonInstall, "PART_ButtonInstall", mainModel.ActivateSelectedCommand); if (ButtonInstall != null) { BindingTools.SetBinding( ButtonInstall, ButtonBase.VisibilityProperty, mainModel, $"{nameof(FullscreenAppViewModel.SelectedGame)}.{nameof(GamesCollectionViewEntry.IsInstalled)}", converter: new InvertedBooleanToVisibilityConverter(), fallBackValue: Visibility.Collapsed); } AssignButtonWithCommand(ref ButtonPlay, "PART_ButtonPlay", mainModel.ActivateSelectedCommand); if (ButtonPlay != null) { ButtonPlay.Command = mainModel.ActivateSelectedCommand; BindingTools.SetBinding( ButtonPlay, ButtonBase.VisibilityProperty, mainModel, $"{nameof(FullscreenAppViewModel.SelectedGame)}.{nameof(GamesCollectionViewEntry.IsInstalled)}", converter: new Converters.BooleanToVisibilityConverter(), fallBackValue: Visibility.Collapsed); } AssignButtonWithCommand(ref ButtonDetails, "PART_ButtonDetails", mainModel.ToggleGameDetailsCommand); if (ButtonDetails != null) { BindingTools.SetBinding( ButtonDetails, ButtonBase.VisibilityProperty, mainModel, nameof(FullscreenAppViewModel.GameDetailsButtonVisible), converter: new Converters.BooleanToVisibilityConverter()); } AssignButtonWithCommand(ref ButtonGameOptions, "PART_ButtonGameOptions", mainModel.OpenGameMenuCommand); if (ButtonGameOptions != null) { BindingTools.SetBinding( ButtonGameOptions, ButtonBase.VisibilityProperty, mainModel, nameof(FullscreenAppViewModel.GameDetailsButtonVisible), converter: new Converters.BooleanToVisibilityConverter()); ButtonGameOptions.SetResourceReference(ButtonEx.InputHintProperty, "ButtonPromptStart"); } AssignButtonWithCommand(ref ButtonSearch, "PART_ButtonSearch", mainModel.OpenSearchCommand); ButtonSearch?.SetResourceReference(ButtonEx.InputHintProperty, "ButtonPromptY"); AssignButtonWithCommand(ref ButtonFilter, "PART_ButtonFilter", mainModel.ToggleFiltersCommand); ButtonFilter?.SetResourceReference(ButtonEx.InputHintProperty, "ButtonPromptRS"); ElemFilters = Template.FindName("PART_ElemFilters", this) as FrameworkElement; if (ElemFilters != null) { BindingTools.SetBinding(ElemFilters, FrameworkElement.VisibilityProperty, mainModel, nameof(FullscreenAppViewModel.FilterPanelVisible), converter: new Converters.BooleanToVisibilityConverter()); } ElemFiltersAdditional = Template.FindName("PART_ElemFiltersAdditional", this) as FrameworkElement; if (ElemFiltersAdditional != null) { BindingTools.SetBinding(ElemFiltersAdditional, FrameworkElement.VisibilityProperty, mainModel, nameof(FullscreenAppViewModel.FilterAdditionalPanelVisible), converter: new Converters.BooleanToVisibilityConverter()); } ContentFilterItems = Template.FindName("PART_ContentFilterItems", this) as ContentControl; if (ContentFilterItems != null) { BindingTools.SetBinding(ContentFilterItems, ContentControl.VisibilityProperty, mainModel, nameof(FullscreenAppViewModel.SubFilterVisible), converter: new Converters.BooleanToVisibilityConverter()); BindingTools.SetBinding(ContentFilterItems, ContentControl.ContentProperty, mainModel, nameof(FullscreenAppViewModel.SubFilterControl)); } ElemGameDetails = Template.FindName("PART_ElemGameDetails", this) as FrameworkElement; if (ElemGameDetails != null) { BindingTools.SetBinding(ElemGameDetails, FrameworkElement.VisibilityProperty, mainModel, nameof(FullscreenAppViewModel.GameDetailsVisible), converter: new Converters.BooleanToVisibilityConverter()); BindingTools.SetBinding(ElemGameDetails, FrameworkElement.DataContextProperty, mainModel, nameof(FullscreenAppViewModel.SelectedGame)); } ElemGameStatus = Template.FindName("PART_ElemGameStatus", this) as FrameworkElement; if (ElemGameStatus != null) { BindingTools.SetBinding(ElemGameStatus, FrameworkElement.VisibilityProperty, mainModel, nameof(FullscreenAppViewModel.GameStatusVisible), converter: new Converters.BooleanToVisibilityConverter()); BindingTools.SetBinding(ElemGameStatus, FrameworkElement.DataContextProperty, mainModel, nameof(FullscreenAppViewModel.SelectedGame)); } SetListCommandBindings(); ControlTemplateTools.InitializePluginControls( mainModel.Extensions, Template, this, ApplicationMode.Fullscreen, mainModel, $"{nameof(FullscreenAppViewModel.SelectedGameDetails)}.{nameof(GameDetailsViewModel.Game)}.{nameof(GameDetailsViewModel.Game.Game)}"); } }
public IXmlListElementConfiguration WithNamespace(XNamespace xNamespace) { _target.XNamespace = xNamespace; return(this); }
private static XElement GetXElementFromPackageReference(XNamespace ns, string reference) { return(new XElement(ns + Reference, new XAttribute(File, reference))); }
public void VersionCodeTests(bool seperateApk, string abis, string versionCode, bool useLegacy, string versionCodePattern, string versionCodeProperties, bool shouldBuild, string expectedVersionCode) { var proj = new XamarinAndroidApplicationProject() { IsRelease = true, MinSdkVersion = null, }; proj.SetProperty("Foo", "1"); proj.SetProperty(proj.ReleaseProperties, KnownProperties.AndroidCreatePackagePerAbi, seperateApk); if (!string.IsNullOrEmpty(abis)) { proj.SetAndroidSupportedAbis(abis); } if (!string.IsNullOrEmpty(versionCodePattern)) { proj.SetProperty(proj.ReleaseProperties, "AndroidVersionCodePattern", versionCodePattern); } else { proj.RemoveProperty(proj.ReleaseProperties, "AndroidVersionCodePattern"); } if (!string.IsNullOrEmpty(versionCodeProperties)) { proj.SetProperty(proj.ReleaseProperties, "AndroidVersionCodeProperties", versionCodeProperties); } else { proj.RemoveProperty(proj.ReleaseProperties, "AndroidVersionCodeProperties"); } if (useLegacy) { proj.SetProperty(proj.ReleaseProperties, "AndroidUseLegacyVersionCode", true); } proj.AndroidManifest = proj.AndroidManifest.Replace("android:versionCode=\"1\"", $"android:versionCode=\"{versionCode}\""); using (var builder = CreateApkBuilder(Path.Combine("temp", TestName), false, false)) { builder.ThrowOnBuildFailure = false; Assert.AreEqual(shouldBuild, builder.Build(proj), shouldBuild ? "Build should have succeeded." : "Build should have failed."); if (!shouldBuild) { return; } var abiItems = seperateApk ? abis.Split(';') : new string[1]; var expectedItems = expectedVersionCode.Split(';'); XNamespace aNS = "http://schemas.android.com/apk/res/android"; Assert.AreEqual(abiItems.Length, expectedItems.Length, "abis parameter should have matching elements for expected"); for (int i = 0; i < abiItems.Length; i++) { var path = seperateApk ? Path.Combine("android", abiItems[i], "AndroidManifest.xml") : Path.Combine("android", "manifest", "AndroidManifest.xml"); var manifest = builder.Output.GetIntermediaryAsText(Root, path); var doc = XDocument.Parse(manifest); var nsResolver = new XmlNamespaceManager(new NameTable()); nsResolver.AddNamespace("android", "http://schemas.android.com/apk/res/android"); var m = doc.XPathSelectElement("/manifest") as XElement; Assert.IsNotNull(m, "no manifest element found"); var vc = m.Attribute(aNS + "versionCode"); Assert.IsNotNull(vc, "no versionCode attribute found"); StringAssert.AreEqualIgnoringCase(expectedItems[i], vc.Value, $"Version Code is incorrect. Found {vc.Value} expect {expectedItems[i]}"); } } }
private static XElement GetXElementFromGroupableItemSets <TSet, TItem>( XNamespace ns, IEnumerable <TSet> objectSets, Func <TSet, bool> isGroupable, Func <TSet, string> getGroupIdentifer, Func <TSet, IEnumerable <TItem> > getItems, Func <XNamespace, TItem, XElement> getXElementFromItem, string parentName, string identiferAttributeName) { if (objectSets == null || !objectSets.Any()) { return(null); } var groupableSets = new List <TSet>(); var ungroupableSets = new List <TSet>(); foreach (var set in objectSets) { if (isGroupable(set)) { groupableSets.Add(set); } else { ungroupableSets.Add(set); } } var childElements = new List <XElement>(); if (!groupableSets.Any()) { // none of the item sets are groupable, then flatten the items childElements.AddRange(objectSets.SelectMany(getItems).Select(item => getXElementFromItem(ns, item))); } else { // move the group with null target framework (if any) to the front just for nicer display in UI foreach (var set in ungroupableSets.Concat(groupableSets)) { var groupElem = new XElement( ns + Group, getItems(set).Select(item => getXElementFromItem(ns, item)).ToArray()); if (isGroupable(set)) { var groupIdentifier = getGroupIdentifer(set); if (groupIdentifier != null) { groupElem.SetAttributeValue(identiferAttributeName, groupIdentifier); } } childElements.Add(groupElem); } } return(new XElement(ns + parentName, childElements.ToArray())); }
public void MergeLibraryManifest() { byte [] classesJar; using (var stream = typeof(XamarinAndroidCommonProject).Assembly.GetManifestResourceStream("Xamarin.ProjectTools.Resources.Base.classes.jar")) { classesJar = new byte [stream.Length]; stream.Read(classesJar, 0, (int)stream.Length); } byte [] data; using (var ms = new MemoryStream()) { using (var zip = ZipArchive.Create(ms)) { zip.AddEntry("AndroidManifest.xml", @"<?xml version='1.0'?> <manifest xmlns:android='http://schemas.android.com/apk/res/android' package='com.xamarin.test'> <uses-sdk android:minSdkVersion='16'/> <permission android:name='${applicationId}.permission.C2D_MESSAGE' android:protectionLevel='signature' /> <application> <activity android:name='.signin.internal.SignInHubActivity' /> <provider android:authorities='${applicationId}.FacebookInitProvider' android:name='.internal.FacebookInitProvider' android:exported='false' /> <meta-data android:name='android.support.VERSION' android:value='25.4.0' /> <meta-data android:name='android.support.VERSION' android:value='25.4.0' /> </application> </manifest> ", encoding: System.Text.Encoding.UTF8); zip.CreateDirectory("res"); zip.AddEntry(classesJar, "classes.jar"); zip.AddEntry("R.txt", " ", encoding: System.Text.Encoding.UTF8); } data = ms.ToArray(); } var path = Path.Combine("temp", TestContext.CurrentContext.Test.Name); var lib = new XamarinAndroidBindingProject() { ProjectName = "Binding1", AndroidClassParser = "class-parse", Jars = { new AndroidItem.LibraryProjectZip("Jars\\foo.aar") { BinaryContent = () => data, } }, }; var proj = new XamarinAndroidApplicationProject() { PackageName = "com.xamarin.manifest", References = { new BuildItem.ProjectReference("..\\Binding1\\Binding1.csproj", lib.ProjectGuid) }, PackageReferences = { KnownPackages.SupportMediaCompat_27_0_2_1, KnownPackages.SupportFragment_27_0_2_1, KnownPackages.SupportCoreUtils_27_0_2_1, KnownPackages.SupportCoreUI_27_0_2_1, KnownPackages.SupportCompat_27_0_2_1, KnownPackages.AndroidSupportV4_27_0_2_1, KnownPackages.SupportV7AppCompat_27_0_2_1, }, }; proj.Sources.Add(new BuildItem.Source("TestActivity1.cs") { TextContent = () => @"using System; using System.Collections.Generic; using System.Linq; using System.Text; using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Views; using Android.Widget; using Android.Support.V4.App; using Android.Util; [Activity (Label = ""TestActivity1"")] [IntentFilter (new[]{Intent.ActionMain}, Categories = new[]{ ""com.xamarin.sample"" })] public class TestActivity1 : FragmentActivity { } " , }); proj.Sources.Add(new BuildItem.Source("TestActivity2.cs") { TextContent = () => @"using System; using System.Collections.Generic; using System.Linq; using System.Text; using Android.App; using Android.Content; using Android.OS; using Android.Runtime; using Android.Views; using Android.Widget; using Android.Support.V4.App; using Android.Util; [Activity (Label = ""TestActivity2"")] [IntentFilter (new[]{Intent.ActionMain}, Categories = new[]{ ""com.xamarin.sample"" })] public class TestActivity2 : FragmentActivity { } " , }); using (var libbuilder = CreateDllBuilder(Path.Combine(path, "Binding1"))) { Assert.IsTrue(libbuilder.Build(lib), "Build should have succeeded."); using (var builder = CreateApkBuilder(Path.Combine(path, "App1"))) { Assert.IsTrue(builder.Build(proj), "Build should have succeeded."); var manifest = builder.Output.GetIntermediaryAsText(Root, "android/AndroidManifest.xml"); Assert.IsTrue(manifest.Contains("com.xamarin.manifest.permission.C2D_MESSAGE"), "${applicationId}.permission.C2D_MESSAGE was not replaced with com.xamarin.manifest.permission.C2D_MESSAGE"); Assert.IsTrue(manifest.Contains("com.xamarin.test.signin.internal.SignInHubActivity"), ".signin.internal.SignInHubActivity was not replaced with com.xamarin.test.signin.internal.SignInHubActivity"); Assert.IsTrue(manifest.Contains("com.xamarin.manifest.FacebookInitProvider"), "${applicationId}.FacebookInitProvider was not replaced with com.xamarin.manifest.FacebookInitProvider"); Assert.IsTrue(manifest.Contains("com.xamarin.test.internal.FacebookInitProvider"), ".internal.FacebookInitProvider was not replaced with com.xamarin.test.internal.FacebookInitProvider"); Assert.AreEqual(manifest.IndexOf("meta-data", StringComparison.OrdinalIgnoreCase), manifest.LastIndexOf("meta-data", StringComparison.OrdinalIgnoreCase), "There should be only one meta-data element"); var doc = XDocument.Parse(manifest); var ns = XNamespace.Get("http://schemas.android.com/apk/res/android"); var activities = doc.Element("manifest")?.Element("application")?.Elements("activity"); var e = activities.FirstOrDefault(x => x.Attribute(ns.GetName("label"))?.Value == "TestActivity2"); Assert.IsNotNull(e, "Manifest should contain an activity for TestActivity2"); Assert.IsNotNull(e.Element("intent-filter"), "TestActivity2 should have an intent-filter"); Assert.IsNotNull(e.Element("intent-filter").Element("action"), "TestActivity2 should have an intent-filter/action"); } } }
public void AllActivityAttributeProperties([Values("legacy", "manifestmerger.jar")] string manifestMerger) { string expectedOutput = manifestMerger == "legacy" ? "android:allowEmbedded=\"true\" android:allowTaskReparenting=\"true\" android:alwaysRetainTaskState=\"true\" android:autoRemoveFromRecents=\"true\" android:banner=\"@drawable/icon\" android:clearTaskOnLaunch=\"true\" android:colorMode=\"hdr\" android:configChanges=\"mcc\" android:description=\"@string/app_name\" android:directBootAware=\"true\" android:documentLaunchMode=\"never\" android:enabled=\"true\" android:enableVrMode=\"foo\" android:excludeFromRecents=\"true\" android:exported=\"true\" android:finishOnCloseSystemDialogs=\"true\" android:finishOnTaskLaunch=\"true\" android:hardwareAccelerated=\"true\" android:icon=\"@drawable/icon\" android:immersive=\"true\" android:label=\"TestActivity\" android:launchMode=\"singleTop\" android:lockTaskMode=\"normal\" android:logo=\"@drawable/icon\" android:maxAspectRatio=\"1.2\" android:maxRecents=\"1\" android:multiprocess=\"true\" android:name=\"com.contoso.TestActivity\" android:noHistory=\"true\" android:parentActivityName=\"unnamedproject.unnamedproject.MainActivity\" android:permission=\"com.contoso.permission.TEST_ACTIVITY\" android:persistableMode=\"persistNever\" android:process=\"com.contoso.process.testactivity_process\" android:recreateOnConfigChanges=\"mcc\" android:relinquishTaskIdentity=\"true\" android:resizeableActivity=\"true\" android:resumeWhilePausing=\"true\" android:rotationAnimation=\"crossfade\" android:roundIcon=\"@drawable/icon\" android:screenOrientation=\"portrait\" android:showForAllUsers=\"true\" android:showOnLockScreen=\"true\" android:showWhenLocked=\"true\" android:singleUser=\"true\" android:stateNotNeeded=\"true\" android:supportsPictureInPicture=\"true\" android:taskAffinity=\"com.contoso\" android:theme=\"@android:style/Theme.Light\" android:turnScreenOn=\"true\" android:uiOptions=\"splitActionBarWhenNarrow\" android:visibleToInstantApps=\"true\" android:windowSoftInputMode=\"stateUnchanged|adjustUnspecified\"" : "android:name=\"com.contoso.TestActivity\" android:allowEmbedded=\"true\" android:allowTaskReparenting=\"true\" android:alwaysRetainTaskState=\"true\" android:autoRemoveFromRecents=\"true\" android:banner=\"@drawable/icon\" android:clearTaskOnLaunch=\"true\" android:colorMode=\"hdr\" android:configChanges=\"mcc\" android:description=\"@string/app_name\" android:directBootAware=\"true\" android:documentLaunchMode=\"never\" android:enableVrMode=\"foo\" android:enabled=\"true\" android:excludeFromRecents=\"true\" android:exported=\"true\" android:finishOnCloseSystemDialogs=\"true\" android:finishOnTaskLaunch=\"true\" android:hardwareAccelerated=\"true\" android:icon=\"@drawable/icon\" android:immersive=\"true\" android:label=\"TestActivity\" android:launchMode=\"singleTop\" android:lockTaskMode=\"normal\" android:logo=\"@drawable/icon\" android:maxAspectRatio=\"1.2\" android:maxRecents=\"1\" android:multiprocess=\"true\" android:noHistory=\"true\" android:parentActivityName=\"unnamedproject.unnamedproject.MainActivity\" android:permission=\"com.contoso.permission.TEST_ACTIVITY\" android:persistableMode=\"persistNever\" android:process=\"com.contoso.process.testactivity_process\" android:recreateOnConfigChanges=\"mcc\" android:relinquishTaskIdentity=\"true\" android:resizeableActivity=\"true\" android:resumeWhilePausing=\"true\" android:rotationAnimation=\"crossfade\" android:roundIcon=\"@drawable/icon\" android:screenOrientation=\"portrait\" android:showForAllUsers=\"true\" android:showOnLockScreen=\"true\" android:showWhenLocked=\"true\" android:singleUser=\"true\" android:stateNotNeeded=\"true\" android:supportsPictureInPicture=\"true\" android:taskAffinity=\"com.contoso\" android:theme=\"@android:style/Theme.Light\" android:turnScreenOn=\"true\" android:uiOptions=\"splitActionBarWhenNarrow\" android:visibleToInstantApps=\"true\" android:windowSoftInputMode=\"stateUnchanged|adjustUnspecified\""; var proj = new XamarinAndroidApplicationProject { ManifestMerger = manifestMerger, }; proj.Sources.Add(new BuildItem.Source("TestActivity.cs") { TextContent = () => @"using Android.App; using Android.Content.PM; using Android.Views; [Activity ( AllowEmbedded = true, AllowTaskReparenting = true, AlwaysRetainTaskState = true, AutoRemoveFromRecents = true, Banner = ""@drawable/icon"", ClearTaskOnLaunch = true, ColorMode = ""hdr"", ConfigurationChanges = ConfigChanges.Mcc, Description = ""@string/app_name"", DirectBootAware = true, DocumentLaunchMode = DocumentLaunchMode.Never, Enabled = true, EnableVrMode = ""foo"", ExcludeFromRecents = true, Exported = true, FinishOnCloseSystemDialogs = true, FinishOnTaskLaunch = true, HardwareAccelerated = true, Icon = ""@drawable/icon"", Immersive = true, Label = ""TestActivity"", LaunchMode = LaunchMode.SingleTop, LockTaskMode = ""normal"", Logo = ""@drawable/icon"", MaxAspectRatio = 1.2F, MaxRecents = 1, MultiProcess = true, Name = ""com.contoso.TestActivity"", NoHistory = true, ParentActivity = typeof (UnnamedProject.MainActivity), Permission = ""com.contoso.permission.TEST_ACTIVITY"", PersistableMode = ActivityPersistableMode.Never, Process = ""com.contoso.process.testactivity_process"", RecreateOnConfigChanges = ConfigChanges.Mcc, RelinquishTaskIdentity = true, ResizeableActivity = true, ResumeWhilePausing = true, RotationAnimation = WindowRotationAnimation.Crossfade, RoundIcon = ""@drawable/icon"", ScreenOrientation = ScreenOrientation.Portrait, ShowForAllUsers = true, ShowOnLockScreen = true, ShowWhenLocked = true, SingleUser = true, StateNotNeeded = true, SupportsPictureInPicture = true, TaskAffinity = ""com.contoso"", Theme = ""@android:style/Theme.Light"", TurnScreenOn = true, UiOptions = UiOptions.SplitActionBarWhenNarrow, VisibleToInstantApps = true, WindowSoftInputMode = Android.Views.SoftInput.StateUnchanged)] class TestActivity : Activity { }" }); using (ProjectBuilder builder = CreateDllBuilder(Path.Combine("temp", TestName))) { Assert.IsTrue(builder.Build(proj), "Build should have succeeded"); string manifest = builder.Output.GetIntermediaryAsText(Path.Combine("android", "AndroidManifest.xml")); var doc = XDocument.Parse(manifest); var ns = XNamespace.Get("http://schemas.android.com/apk/res/android"); IEnumerable <XElement> activities = doc.Element("manifest")?.Element("application")?.Elements("activity"); XElement e = activities.FirstOrDefault(x => x.Attribute(ns.GetName("label"))?.Value == "TestActivity"); Assert.IsNotNull(e, "Manifest should contain an activity labeled TestActivity"); Assert.AreEqual(expectedOutput, string.Join(" ", e.Attributes())); } }
private static async Task <AppxManifestSummary> FromManifest(Stream manifestStream, ReadMode mode) { var result = new AppxManifestSummary(); Logger.Debug("Loading XML file..."); var xmlDocument = await XDocument.LoadAsync(manifestStream, LoadOptions.None, CancellationToken.None).ConfigureAwait(false); var identity = AppxIdentityReader.GetIdentityFromPackageManifest(xmlDocument); result.Name = identity.Name; result.Version = identity.Version; result.Publisher = identity.Publisher; result.Architectures = identity.Architectures; XNamespace win10Namespace = "http://schemas.microsoft.com/appx/manifest/foundation/windows10"; XNamespace appxNamespace = "http://schemas.microsoft.com/appx/2010/manifest"; XNamespace uapNamespace = "http://schemas.microsoft.com/appx/manifest/uap/windows10"; XNamespace uap3Namespace = "http://schemas.microsoft.com/appx/manifest/uap/windows10/3"; var packageNode = xmlDocument.Element(win10Namespace + "Package") ?? xmlDocument.Element(appxNamespace + "Package"); if (packageNode == null) { throw new ArgumentException("The manifest file does not contain a valid root element (<Package />)."); } if ((mode & ReadMode.Properties) == ReadMode.Properties) { var propertiesNode = packageNode.Element(win10Namespace + "Properties") ?? packageNode.Element(appxNamespace + "Properties"); Logger.Trace("Executing XQuery /*[local-name()='Package']/*[local-name()='Properties'] for a single node..."); if (propertiesNode != null) { foreach (var subNode in propertiesNode.Elements()) { switch (subNode.Name.LocalName) { case "DisplayName": result.DisplayName = subNode.Value; break; case "PublisherDisplayName": result.DisplayPublisher = subNode.Value; break; case "Description": result.Description = subNode.Value; break; case "Logo": result.Logo = subNode.Value; break; case "Framework": result.IsFramework = bool.TryParse(subNode.Value, out var parsed) && parsed; break; } } } var applicationsNode = packageNode.Element(win10Namespace + "Applications") ?? packageNode.Element(appxNamespace + "Applications"); if (applicationsNode != null) { var applicationNode = applicationsNode.Elements(win10Namespace + "Application").Concat(applicationsNode.Elements(appxNamespace + "Application")); var visualElementsNode = applicationNode .SelectMany(e => e.Elements(win10Namespace + "VisualElements") .Concat(e.Elements(appxNamespace + "VisualElements")) .Concat(e.Elements(uap3Namespace + "VisualElements")) .Concat(e.Elements(uapNamespace + "VisualElements"))); var background = visualElementsNode.Select(node => node.Attribute("BackgroundColor")).FirstOrDefault(a => a != null); result.AccentColor = background?.Value ?? "Transparent"; } else { result.AccentColor = "Transparent"; } } if ((mode & ReadMode.Applications) == ReadMode.Applications) { result.PackageType = result.IsFramework ? MsixPackageType.Framework : 0; var applicationsNode = packageNode.Element(win10Namespace + "Applications") ?? packageNode.Element(appxNamespace + "Applications"); if (applicationsNode != null) { var applicationNode = applicationsNode.Elements(win10Namespace + "Application").Concat(applicationsNode.Elements(appxNamespace + "Application")); foreach (var subNode in applicationNode) { var entryPoint = subNode.Attribute("EntryPoint")?.Value; var executable = subNode.Attribute("Executable")?.Value; var startPage = subNode.Attribute("StartPage")?.Value; result.PackageType |= PackageTypeConverter.GetPackageTypeFrom(entryPoint, executable, startPage, result.IsFramework); } } } Logger.Debug("Manifest information parsed."); return(result); }