Ejemplo n.º 1
16
    public static string MetaBuild()
    {
        var sb = new StringBuilder();

            sb.AppendLine("\\\\ hello");

            foreach (var proj in Directory.GetFiles(Directory.GetCurrentDirectory(), "*.*proj"))
            {
                sb.AppendLine("\\\\ file: " + proj);

                var xml = new XmlDocument();
                xml.Load(proj);
                var nm = new XmlNamespaceManager(xml.NameTable);
                nm.AddNamespace("x", "http://schemas.microsoft.com/developer/msbuild/2003");

                foreach (var reference in xml.SelectNodes(@"x:Project\x:ItemGroup\x:Reference"))
                {
                    sb.AppendLine("\\\\" + reference);
                }
                foreach (var reference in xml.SelectNodes(@"x:Project\x:ItemGroup\x:Reference"))
                {
                    sb.AppendLine("\\\\" + reference);
                }
            }
            return sb.ToString();
    }
Ejemplo n.º 2
1
  protected void GenerateAction_Click(object sender, EventArgs e)
  {
    XmlDocument doc = new XmlDocument();
    doc.LoadXml(Resources.MyResourceStrings.MyDocument);

    XmlNode TextNode;
    XmlNamespaceManager NsMgr = new XmlNamespaceManager(doc.NameTable);
    NsMgr.AddNamespace("ns1", "uri:AspNetPro20/Chapter16/Demo1");
    NsMgr.AddNamespace("w", "http://schemas.microsoft.com/office/word/2003/wordml");

    TextNode = doc.SelectSingleNode("//ns1:Firstname//w:p", NsMgr);
    TextNode.InnerXml = string.Format("<w:r><w:t>{0}</w:t></w:r>", TextFirstname.Text);

    TextNode = doc.SelectSingleNode("//ns1:Lastname//w:p", NsMgr);
    TextNode.InnerXml = string.Format("<w:r><w:t>{0}</w:t></w:r>", TextLastname.Text);

    TextNode = doc.SelectSingleNode("//ns1:Age//w:p", NsMgr);
    TextNode.InnerXml = string.Format("<w:r><w:t>{0}</w:t></w:r>", TextAge.Text);

    // Clear the response
    Response.Clear();
    Response.ContentType = "application/msword";
    Response.Write(doc.OuterXml);
    Response.End();
  }
 public static void DumpProjRefs(string projectFilename, string baseDirectory)
 {
     List<string> files = new List<string>();
     var stream = new MemoryStream(File.ReadAllBytes(projectFilename)); // cache file in memoty
     var document = XDocument.Load(stream);
     var xmlNamespaceManager = new XmlNamespaceManager(new NameTable());
     xmlNamespaceManager.AddNamespace("ns", namespaceName);
     IEnumerable<XElement> listOfSourceFiles = document.XPathSelectElements("/ns:Project/ns:ItemGroup/ns:ProjectReference[@Include]", xmlNamespaceManager);
     foreach (var el in listOfSourceFiles)
     {
         files.Add(el.Attribute("Include").Value);
     }
     string separator = new string(Path.DirectorySeparatorChar, 1);
     string projDir = (new FileInfo(projectFilename)).Directory.FullName;
     foreach (string relativeName in files)
     {
         var correctedRelativeName = relativeName.Replace("\\", separator);
         string fullFileName = Path.Combine(projDir, correctedRelativeName);
         fullFileName = new FileInfo(fullFileName).FullName;
         string shortName;
         if (fullFileName.StartsWith(baseDirectory, StringComparison.InvariantCulture))
         {
             shortName = fullFileName.Substring(baseDirectory.Length);
             if (shortName.StartsWith(separator, StringComparison.InvariantCulture))
             {
                 shortName = shortName.Substring(1);
             }
         }
         else
         {
             shortName = fullFileName;
         }
         Console.WriteLine(shortName);
     }
 }
Ejemplo n.º 4
0
    static void Main(string[] args)
    {
        if (args.Length > 0 && args[0] == "-refsonly")
            onlyRefs = true;

        var nsStr = "http://schemas.microsoft.com/developer/msbuild/2003";
        nsManager = new XmlNamespaceManager(new NameTable());
        nsManager.AddNamespace("p", nsStr);
        ns = nsStr;

        //FeatureSamples.Core
        var coreCsproj = @"Samples/FeatureSamples/Core/Urho.Samples.csproj";
        var coreDoc = XDocument.Load(coreCsproj);
        RemovePackagesConfig(coreDoc);
        ReplaceRef(coreDoc, "Urho", "{641886db-2c6c-4d33-88da-97bec0ec5f86}", @"..\..\..\Bindings\Urho.csproj");
        coreDoc.Save(coreCsproj);

        //FeatureSamples.Droid
        var droidCsproj = @"Samples/FeatureSamples/Android/Urho.Samples.Droid.csproj";
        var droidDoc = XDocument.Load(droidCsproj);
        RemovePackagesConfig(droidDoc);
        ReplaceRef(droidDoc, "Urho", "{f0c1189b-75f7-4bd8-b394-a23d5b03eff6}", @"..\..\..\Bindings\Urho.Droid.csproj");
        droidDoc.Save(droidCsproj);

        //FeatureSamples.iOS
        var iosCsproj = @"Samples/FeatureSamples/iOS/Urho.Samples.iOS.csproj";
        var iosDoc = XDocument.Load(iosCsproj);
        RemovePackagesConfig(iosDoc);
        ReplaceRef(iosDoc, "Urho", "{9ae80bd9-e1e2-41da-bb6f-712b35028bd9}", @"..\..\..\Bindings\Urho.iOS.csproj");
        iosDoc.Save(iosCsproj);

        //FeatureSamples.Mac
        var desktopCsproj = @"Samples/FeatureSamples/Mac/Urho.Samples.Mac.csproj";
        var desktopDoc = XDocument.Load(desktopCsproj);
        RemovePackagesConfig(desktopDoc);
        ReplaceRef(desktopDoc, "Urho", "{F0359D5E-D6D4-47D3-A9F0-5A97C31DC476}", @"..\..\..\Bindings\Urho.Desktop.csproj");
        RemoveTargets(desktopDoc);
        desktopDoc.Save(desktopCsproj);

        //FormsSample.Core
        var formsCoreCsproj = @"Samples/FormsSample/FormsSample/FormsSample.csproj";
        var formsCoreDoc = XDocument.Load(formsCoreCsproj);
        RemovePackagesConfig(formsCoreDoc);
        ReplaceRef(formsCoreDoc, "Urho.Forms", "{D599C47F-B9E0-4A58-82E8-6286E0442E8F}", @"..\..\..\Bindings\Urho.Forms.csproj");
        formsCoreDoc.Save(formsCoreCsproj);

        //FormsSample.Droid
        var formsDroidCsproj = @"Samples/FormsSample/FormsSample.Droid/FormsSample.Droid.csproj";
        var formsDroidDoc = XDocument.Load(formsDroidCsproj);
        RemovePackagesConfig(formsDroidDoc);
        ReplaceRef(formsDroidDoc, "Urho.Forms", "{8BAE491B-46F0-4A51-A456-D7A3B332BDC4}", @"..\..\..\Bindings\Urho.Forms.Droid.csproj");
        formsDroidDoc.Save(formsDroidCsproj);

        //FormsSample.iOS
        var formsIosCsproj = @"Samples/FormsSample/FormsSample.iOS/FormsSample.iOS.csproj";
        var formsIosDoc = XDocument.Load(formsIosCsproj);
        RemovePackagesConfig(formsIosDoc);
        ReplaceRef(formsIosDoc, "Urho.Forms", "{8F3352BA-BF6A-49F8-81D6-58D54B3EA72B}", @"..\..\..\Bindings\Urho.Forms.iOS.csproj");
        formsIosDoc.Save(formsIosCsproj);
    }
Ejemplo n.º 5
0
    protected void Page_Load(object sender, EventArgs e)
    {
        //Load document
        string booksFile = Server.MapPath("books.xml");

        XmlDocument document = new XmlDocument();
        document.Load(booksFile);
        XPathNavigator nav = document.CreateNavigator();

        //Add a namespace prefix that can be used in the XPath expression
        XmlNamespaceManager namespaceMgr = new XmlNamespaceManager(nav.NameTable);
        namespaceMgr.AddNamespace("b", "http://example.books.com");

        //All books whose price is not greater than 10.00
        foreach (XPathNavigator node in
            nav.Select("//b:book[not(b:price[. > 10.00])]/b:price",
            namespaceMgr))
        {
            Decimal price = (decimal)node.ValueAs(typeof(decimal));
            node.SetTypedValue(price * 1.2M);
            Response.Write(String.Format("Price raised from {0} to {1}<BR/>",
                price,
                node.ValueAs(typeof(decimal))));
        }
    }
	void ConfirmSettings() {
		XmlNode newAppendNode;
		XmlElement newAppendElement;
		XmlAttribute newAttribute;
		string xmlNamespace = "http://schemas.android.com/apk/res/android";

		PlayerSettings.bundleIdentifier = bundleIdentifier;
		xmlDoc.Load(rootPath + ANDROID_MANIFEST_PATH);
		XmlNamespaceManager nameSpaceMgr = new XmlNamespaceManager(xmlDoc.NameTable);
		nameSpaceMgr.AddNamespace ("android", xmlNamespace);

		// Xml Manifest node
		XmlNode manifestNode = xmlDoc.SelectSingleNode("descendant::manifest", nameSpaceMgr);
		XmlElement packageElement = (XmlElement)manifestNode;
		packageElement.SetAttribute("package", bundleIdentifier);

		// uses-sdk node
		XmlNode usesSdkNode = xmlDoc.SelectSingleNode("descendant::manifest/uses-sdk", nameSpaceMgr);
		if (usesSdkNode != null) {
			XmlElement minSdkElement = (XmlElement)usesSdkNode;
			minSdkElement.SetAttribute("android:minSdkVersion", "8");
		} else {
			newAppendElement = xmlDoc.CreateElement("uses-sdk");
			newAttribute = CreateXmlAttribute(xmlDoc, "android", "minSdkVersion", xmlNamespace, "8");
			newAppendElement.Attributes.Append(newAttribute);
			newAttribute = CreateXmlAttribute(xmlDoc, "android", "targetSdkVersion", xmlNamespace, "17");
			newAppendElement.Attributes.Append(newAttribute);
			newAppendNode = (XmlNode)newAppendElement;
			manifestNode.AppendChild(newAppendNode);
		}

		xmlDoc.Save(rootPath + ANDROID_MANIFEST_PATH);
	}
Ejemplo n.º 7
0
Archivo: client.cs Proyecto: mono/gert
	static int Main ()
	{
		try {
			FaultService svc = new FaultService ();
			svc.Url = "http://" + IPAddress.Loopback.ToString () + ":8081/FaultService.asmx";
			svc.Run ();
			return 1;
		} catch (SoapException ex) {
			if (ex.Actor != "Mono Web Service")
				return 2;
			if (ex.Code != SoapException.ServerFaultCode)
				return 3;
			if (ex.Detail == null)
				return 4;
			if (ex.Detail.LocalName != "detail")
				return 5;
			if (ex.Detail.NamespaceURI != string.Empty)
				return 6;

			XmlNamespaceManager nsMgr = new XmlNamespaceManager (ex.Detail.OwnerDocument.NameTable);
			nsMgr.AddNamespace ("se", "http://www.mono-project/System");

			XmlElement systemError = (XmlElement) ex.Detail.SelectSingleNode (
				"se:systemerror", nsMgr);
			if (systemError == null)
				return 7;
			if (ex.InnerException != null)
				return 8;
			if (ex.Message != "Failure processing request.")
				return 9;
			return 0;
		}
	}
Ejemplo n.º 8
0
    public void Adjust(string fileName)
    {
        try
        {
            string path = Path.GetDirectoryName(Application.dataPath+"..");
            if (File.Exists(path+"/"+fileName))
            {
                TextReader tx = new StreamReader(path+"/"+fileName);
                if (doc == null)
                    doc = new XmlDocument();
                doc.Load(tx);
                tx.Close();
                if (doc!=null && doc.DocumentElement!=null)
                {
                    string xmlns = doc.DocumentElement.Attributes["xmlns"].Value;
                    XmlNamespaceManager nsmgr = new XmlNamespaceManager(doc.NameTable);
                    nsmgr.AddNamespace("N",xmlns);

                    SetNode("TargetFrameworkVersion","v4.0", nsmgr);
                    // SetNode("DefineConstants","TRACE;UNITY_3_5_6;UNITY_3_5;UNITY_EDITOR;ENABLE_PROFILER;UNITY_STANDALONE_WIN;ENABLE_GENERICS;ENABLE_DUCK_TYPING;ENABLE_TERRAIN;ENABLE_MOVIES;ENABLE_WEBCAM;ENABLE_MICROPHONE;ENABLE_NETWORK;ENABLE_CLOTH;ENABLE_WWW;ENABLE_SUBSTANCE", nsmgr);

                    TextWriter txs = new StreamWriter(path+"/"+fileName);
                    doc.Save(txs);
                    txs.Close();
                }
            }
        }
        catch(System.Exception)
        {
        }
    }
Ejemplo n.º 9
0
    /// <summary>
    /// Creates a namespace manager needed for XML XPath queries
    /// </summary>
    /// <param name="prefix"></param>
    /// <returns></returns>
    public static XmlNamespaceManager CreateTableauXmlNamespaceManager(string prefix)
    {
        var msTable = new NameTable();
        var ns = new XmlNamespaceManager(msTable);
        ns.AddNamespace(prefix, "http://tableausoftware.com/api");

        return ns;
    }
 public AmazonSearchBookResult(XDocument lookupResult)
 {
     this.RawData = lookupResult;
     this._NameSpaceManager = new Lazy<XmlNamespaceManager>(() => {
         var nameTable = RawData.Root.CreateReader().NameTable;
         var nsmgr = new XmlNamespaceManager(nameTable);
         nsmgr.AddNamespace("ns", this.RawData.Root.Name.NamespaceName);
         return nsmgr;
     });
 }
Ejemplo n.º 11
0
    public List<FeedData> ReadData()
    {
        //Load the document
        XmlDocument doc = new XmlDocument();
        XmlNamespaceManager namespaces = new XmlNamespaceManager(doc.NameTable);
        namespaces.AddNamespace("ns", "urn:hl7-org:v3");
        doc.Load(_masterFile);

        var nodeList = doc.DocumentElement.SelectNodes("channel/item");

        foreach (XmlNode node in nodeList)
        {
            string title = node["title"]?.InnerText;
            string description = node["description"]?.InnerText;

            string link = string.Empty;
            string pubdate = string.Empty;

            if (node["link"] != null)
            {
                link = node["link"]?.InnerText;
            }
            else if (node["a10:link"] != null)
            {
                link = node["a10:link"].Attributes[0].InnerText;
                //link = node["a10:link"].InnerText;
            }

            if (node["pubDate"] != null)
            {
                pubdate = node["pubDate"].InnerText;
            }
            else if (node["a10:updated"] != null)
            {
                pubdate = node["a10:updated"].InnerText;
            }

            fdata = new FeedData();
            fdata.publishdate = Convert.ToDateTime(pubdate);
            fdata.link = link;
            fdata.title = title;
            if (Regex.Replace(description, "<[^>]*>", "").Length > 300)
            {
                fdata.description = Regex.Replace(description, "<[^>]*>", "").Substring(0, 299) + "...";
            }
            else
            {
                fdata.description = Regex.Replace(description, "<[^>]*>", "");
            }
            feedData.Add(fdata);
        }

        return feedData;

    }
Ejemplo n.º 12
0
            public bool IsValid()
            {
                bool status = false;

                XmlNamespaceManager manager = new XmlNamespaceManager(xmlDoc.NameTable);
                manager.AddNamespace("ds", SignedXml.XmlDsigNamespaceUrl);
                XmlNodeList nodeList = xmlDoc.SelectNodes("//ds:Signature", manager);

                SignedXml signedXml = new SignedXml(xmlDoc);
                signedXml.LoadXml((XmlElement)nodeList[0]);
                return signedXml.CheckSignature(certificate.cert, true);
            }
Ejemplo n.º 13
0
  public void Run ()
  {
    if (templateFile == null || templateFile.Length == 0 ||
	targetDir == null || targetDir.Length == 0)
      throw new ApplicationException ("Missing or invalid installation data");

    XmlDocument doc = new XmlDocument ();
    doc.Load (templateFile);
    nsmgr = new XmlNamespaceManager (doc.NameTable);
    nsmgr.AddNamespace ("def", "http://schemas.microsoft.com/developer/vstemplate/2005");
    
    ReadTemplateData (doc);
    InstallProject (doc);
  }
Ejemplo n.º 14
0
    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            XmlDocument docForecasts = LoadAllForecasts();

            XPathNavigator navigator = docForecasts.CreateNavigator();
            namespaceManager = new XmlNamespaceManager(navigator.NameTable);
            namespaceManager.AddNamespace("yweather", "http://xml.weather.yahoo.com/ns/rss/1.0");
            XmlNodeList channels = docForecasts.SelectNodes("/rss/channel");

            ForecastsView.DataSource = channels;
            ForecastsView.DataBind();
        }
        catch (Exception) { }
    }
Ejemplo n.º 15
0
 // perform the Amazon search with REST and return results as a DataTable
 public static DataTable GetAmazonDataWithRest()
 {
     // The response data table
     DataTable responseTable = GetResponseTable();
     // Compose the Amazon REST request URL
     string amazonRequest = string.Format("{0}&SubscriptionId={1}&Operation=ItemSearch&Keywords={2}&SearchIndex={3}&ResponseGroup={4}", BalloonShopConfiguration.AmazonRestUrl, BalloonShopConfiguration.SubscriptionId, BalloonShopConfiguration.SearchKeywords, BalloonShopConfiguration.SearchIndex, BalloonShopConfiguration.ResponseGroups);
     // If any problems occur, we prefer to send back empty result set
     // instead of throwing exception
     try
     {
       // Load the Amazon response
       XmlDocument responseXmlDoc = new XmlDocument();
       responseXmlDoc.Load(amazonRequest);
       // Prepare XML document for searching
       XmlNamespaceManager xnm = new XmlNamespaceManager
     (responseXmlDoc.NameTable);
       xnm.AddNamespace("amz", "http://webservices.amazon.com/AWSECommerceService/2005-10-05");
       // Get the list of Item nodes
       XmlNodeList itemNodes = responseXmlDoc.SelectNodes("/amz:ItemSearchResponse/amz:Items/amz:Item", xnm);
       // Copy node data to the DataTable
       foreach (XmlNode itemNode in itemNodes)
       {
     try
     {
       // Create a new datarow and populate it with data
       DataRow dataRow = responseTable.NewRow();
       dataRow["ASIN"] = itemNode["ASIN"].InnerText;
       dataRow["ProductName"] = itemNode["ItemAttributes"]["Title"].InnerText;
       dataRow["ProductImageUrl"] = itemNode["SmallImage"]["URL"].InnerText;
       dataRow["ProductPrice"] = itemNode["OfferSummary"]
     ["LowestNewPrice"]["FormattedPrice"].InnerText;
       // Add the row to the results table
       responseTable.Rows.Add(dataRow);
     }
     catch
     {
       // Ignore products with incomplete information
     }
       }
     }
     catch
     {
       // Ignore all possible errors
     }
     return responseTable;
 }
    private static void OnPostprocessAllAssets(string[] importedAssets, string[] deletedAssets, string[] movedAssets, string[] movedFromAssetPaths)
    {
        string slnFileContent;
        string utGuid;
        string slnGuid;
        string currentDir = Directory.GetCurrentDirectory ();
        string slnPath = Path.Combine (currentDir, SOLUTION_FILENAME);
        string utFullPath = Path.Combine (UNIT_TEST_PRJ_PATH, UNIT_TEST_PRJ_FILENAME);

        try {

            // check if project is already in the sln
            slnFileContent = File.ReadAllText (slnPath);
            Regex prjRegex = new Regex (UNIT_TEST_PRJ_FILENAME);
            if (prjRegex.IsMatch (slnFileContent))
                return;

            // get unit test project guid
            XmlDocument unitTestPrj = new XmlDocument ();
            unitTestPrj.LoadXml (File.ReadAllText (Path.Combine (currentDir, utFullPath)));
            XmlNamespaceManager nsmgr = new XmlNamespaceManager (unitTestPrj.NameTable);
            nsmgr.AddNamespace ("ms", MSBUILD_SCHEMA);
            utGuid = unitTestPrj.SelectSingleNode ("//ms:ProjectGuid", nsmgr).InnerText;

            // get slnGuid
            Regex slnGuidRegex = new Regex ("Project[(]\"(.*)\"[)]");
            var m = slnGuidRegex.Match (slnFileContent);
            slnGuid = m.Groups [1].ToString ();

            // inject project
            int idx = slnFileContent.IndexOf ("Global");
            slnFileContent = slnFileContent.Insert (idx, string.Format (PRJ_TEMPLATE, slnGuid, UNIT_TEST_PRJ_NAME, utFullPath, utGuid));

            // inject build config
            idx = slnFileContent.IndexOf (BUILD_CONFIG_LINE) + BUILD_CONFIG_LINE.Length;
            slnFileContent = slnFileContent.Insert (idx, string.Format (BUILD_CONFIG_TEMPLATE, utGuid));

            File.WriteAllText (slnPath, slnFileContent);

        } catch (Exception ex) {
            UnityEngine.Debug.LogErrorFormat ("UnitTestSolutionPostProcessor: {0}\n{1}", ex.Message, ex.StackTrace);
        }
    }
Ejemplo n.º 17
0
    //gets the weather from yahoo and parses it for wind speed. if wind speed is greater than ten will display message to get engineering
    public void getWeather()
    {
        XmlDocument myXmlDocument = new XmlDocument();
        myXmlDocument.Load("http://weather.yahooapis.com/forecastrss?w=21125");

        XmlNamespaceManager ns = new XmlNamespaceManager(myXmlDocument.NameTable);
        ns.AddNamespace("yweather", "http://xml.weather.yahoo.com/ns/rss/1.0");

        XmlNode node = myXmlDocument.SelectSingleNode("/rss/channel/yweather:wind", ns);

        string windSpeed = node.Attributes.GetNamedItem("speed").Value;
        int windSpeedInt = Convert.ToInt16(windSpeed);

        if (windSpeedInt > 10)
        {
            lblWindSpeed.Text = windSpeed;
            pnlWeather.Visible = true;
        }
    }
Ejemplo n.º 18
0
            public StyleReader(string format)
            {
                try {
                XmlTextReader reader = new XmlTextReader (GetStyleFile (format));
                ValidateWithXSD (reader);

                if (val_success) {
                document = new XmlDocument ();
                document.Load (GetStyleFile (format));
                manager = new XmlNamespaceManager (document.NameTable);
                manager.AddNamespace ("def", "http://www.scielo.org.mx");
                } else {
                Logger.Error ("Estilo de documento {0} no es válido.", format);
                throw new StyleException ("Estilo de documento " + format + " no es valido.");
                }
                } catch (IOException) {
                Logger.Error ("Estilo de documento {0} no existe.", format);
                throw new StyleException ("Estilo de documento " + format + " no existe.");
                }
            }
Ejemplo n.º 19
0
            public StyleReader(Uri uri)
            {
                try {
                XmlTextReader reader = new XmlTextReader (uri.LocalPath);
                ValidateWithXSD (reader);

                if (val_success) {
                document = new XmlDocument ();
                document.Load (uri.LocalPath);
                manager = new XmlNamespaceManager (document.NameTable);
                manager.AddNamespace ("def", "http://www.scielo.org.mx");
                } else {
                Logger.Error ("Estilo de documento {0} no es válido", uri.LocalPath);
                throw new StyleException ("Estilo de documento " + uri.LocalPath + " no es valido.");
                }
                } catch (IOException) {
                Logger.Error ("Estilo de documento {0} no existe.", uri.LocalPath);
                throw new StyleException ("Estilo de documento " + uri.LocalPath + " no existe.");
                }
            }
Ejemplo n.º 20
0
	private static string _GetServiceUrl(string resp)
	{
		XmlDocument desc = new XmlDocument();
		desc.Load(WebRequest.Create(resp).GetResponse().GetResponseStream());
		XmlNamespaceManager nsMgr = new XmlNamespaceManager(desc.NameTable);
		nsMgr.AddNamespace("tns", "urn:schemas-upnp-org:device-1-0");
		XmlNode typen = desc.SelectSingleNode("//tns:device/tns:deviceType/text()", nsMgr);
		if (!typen.Value.Contains("InternetGatewayDevice"))
			return null;
		XmlNode node = desc.SelectSingleNode(
			"//tns:service[tns:serviceType=\"urn:schemas-upnp-org:service:WANIPConnection:1\"]/tns:controlURL/text()",
			nsMgr);
		if (node == null)
			return null;
		XmlNode eventnode = desc.SelectSingleNode(
			"//tns:service[tns:serviceType=\"urn:schemas-upnp-org:service:WANIPConnection:1\"]/tns:eventSubURL/text()",
			nsMgr);
		_CombineUrls(resp, eventnode.Value);
		return _CombineUrls(resp, node.Value);
	}
Ejemplo n.º 21
0
	static void Main(string[] args)
	{
		if (args.Length > 0 && args[0] == "-refsonly")
			onlyRefs = true;

		var nsStr = "http://schemas.microsoft.com/developer/msbuild/2003";
		nsManager = new XmlNamespaceManager(new NameTable());
		nsManager.AddNamespace("p", nsStr);
		ns = nsStr;

		//FeatureSamples.Core
		var coreCsproj = @"Samples/FeatureSamples/Core/Urho.Samples.csproj";
		var coreDoc = XDocument.Load(coreCsproj);
		ReplaceRef(coreDoc, "Urho", "{641886db-2c6c-4d33-88da-97bec0ec5f86}", @"..\..\..\bindings\Urho.csproj", "Urho");
		coreDoc.Save(coreCsproj);

		//FeatureSamples.Droid
		var droidCsproj = @"Samples/FeatureSamples/Android/Urho.Samples.Droid.csproj";
		var droidDoc = XDocument.Load(droidCsproj);
		ReplaceRef(droidDoc, "Urho", "{641886db-2c6c-4d33-88da-97bec0ec5f86}", @"..\..\..\bindings\Urho.csproj", "Urho");
		ReplaceRef(droidDoc, "Urho.Droid", "{f0c1189b-75f7-4bd8-b394-a23d5b03eff6}", @"..\..\..\Bindings\Android\Urho.Droid.csproj", "Urho.Droid");
		ReplaceRef(droidDoc, "Urho.Droid.SdlBindings", "{9438f1bb-e800-48c0-95ce-f158a60abd36}", @"..\..\..\Bindings\Android\Urho.Android.SdlBindings\Urho.Droid.SdlBindings.csproj", "Urho.Droid.SdlBindings");
		RemoveTargets(droidDoc);
		droidDoc.Save(droidCsproj);

		//FeatureSamples.iOS
		var iosCsproj = @"Samples/FeatureSamples/iOS/Urho.Samples.iOS.csproj";
		var iosDoc = XDocument.Load(iosCsproj);
		ReplaceRef(iosDoc, "Urho", "{641886db-2c6c-4d33-88da-97bec0ec5f86}", @"..\..\..\bindings\Urho.csproj", "Urho");
		ReplaceRef(iosDoc, "Urho.iOS", "{9ae80bd9-e1e2-41da-bb6f-712b35028bd9}", @"..\..\..\Bindings\iOS\Urho.iOS.csproj", "Urho.iOS");
		RemoveTargets(iosDoc);
		iosDoc.Save(iosCsproj);

		//FeatureSamples.Desktop
		var desktopCsproj = @"Samples/FeatureSamples/Desktop/Urho.Samples.Desktop.csproj";
		var desktopDoc = XDocument.Load(desktopCsproj);
		ReplaceRef(desktopDoc, "Urho", "{641886db-2c6c-4d33-88da-97bec0ec5f86}", @"..\..\..\bindings\Urho.csproj", "Urho");
		ReplaceRef(desktopDoc, "Urho.Desktop", "{F0359D5E-D6D4-47D3-A9F0-5A97C31DC476}", @"..\..\..\Bindings\Desktop\Urho.Desktop.csproj", "Urho.Desktop");
		RemoveTargets(desktopDoc);
		desktopDoc.Save(desktopCsproj);
	}
Ejemplo n.º 22
0
    public bool Parse(string data)
    {
        //TODO: add error handling
        XmlTextReader reader = new XmlTextReader(new StringReader(data));
        doc = new XPathDocument(reader);
        nsman = new XmlNamespaceManager(reader.NameTable);

        // Add all namespaces that are declared in the root element of the document to the
        // namespaces map, so that they can be used in xpath selectors.
        // Namespaces that are declared anywhere else in the document will not be usable (the
        // XML spec allow declaring them not on the root, but i don't think it's very common,
        // but i may be wrong).
        XPathNavigator nav = doc.CreateNavigator();
        nav.MoveToChild(XPathNodeType.Element);
        IDictionary<string, string> nsis = nav.GetNamespacesInScope(XmlNamespaceScope.Local);
        foreach (KeyValuePair<string, string> nsi in nsis) {
            string prefix = (nsi.Key == string.Empty) ? "global" : nsi.Key;
            nsman.AddNamespace(prefix, nsi.Value);
        }
        return true;
    }
Ejemplo n.º 23
0
    protected void Page_Load(object sender, EventArgs e)
    {
        // Hide het trailerpaneel
        pnlTrailer.Visible = false;

        // Build a document
        xmlDocument = new XmlDocument();
        xmlDocument.Load(Request.MapPath("opgave-2-1.xml"));

        // Let's use a NamespaceManager: we don't want to type urn:mpeg:mpeg21:2002:02-DIDL-NS every time.
        xmlNamespaceManager = new XmlNamespaceManager(xmlDocument.NameTable);
        xmlNamespaceManager.AddNamespace("urn", "urn:mpeg:mpeg21:2002:02-DIDL-NS");

        // Get the description
        Get_Description();

        // Get the amount of trailers
        Get_Trailer_Amount();

        // Refresh the trailers
        Refresh_Trailers();
    }
Ejemplo n.º 24
0
    public void getWeather()
    {
        XmlDocument wData = new XmlDocument();
        wData.Load("http://weather.yahooapis.com/forecastrss?w=" + city + "&u=" + units);

        XmlNamespaceManager manager = new XmlNamespaceManager(wData.NameTable);
        manager.AddNamespace("yweather", "http://xml.weather.yahoo.com/ns/rss/1.0");

        XmlNode channel = wData.SelectSingleNode("rss").SelectSingleNode("channel");
        XmlNodeList node = wData.SelectNodes("/rss/channel/item/yweather:forecastr", manager);

        XmlNode item = channel.SelectSingleNode("item");

        //Current Temperature
        Temperature = channel.SelectSingleNode("item").SelectSingleNode("yweather:condition", manager).Attributes["temp"].Value;
        Condition = channel.SelectSingleNode("item").SelectSingleNode("yweather:condition", manager).Attributes["text"].Value;

        Town = channel.SelectSingleNode("yweather:location", manager).Attributes["city"].Value;

        TFCond = channel.SelectSingleNode("item").SelectSingleNode("yweather:forecast", manager).Attributes["text"].Value;

        TFHigh = channel.SelectSingleNode("item").SelectSingleNode("yweather:forecast", manager).Attributes["high"].Value;

        TFLow = channel.SelectSingleNode("item").SelectSingleNode("yweather:forecast", manager).Attributes["low"].Value;

        //Should we say Good Morning, Afternoon or Evening?
        TimeSpan morning_end = new TimeSpan(12, 00, 0); //10am
        TimeSpan afternoon_end = new TimeSpan(18, 00, 0); //7pm
        TimeSpan now = DateTime.Now.TimeOfDay;
        string greeting = "Good Morning";
        if (now > afternoon_end)
            greeting = "Good Evening";
        else if (now > morning_end)
            greeting = "Good Afternoon";


        Console.WriteLine(greeting + ". The current weather in " + Town + " is " + Condition + " at " + Temperature + " degrees. Today is expected to be " + TFCond + " with a top of " + TFHigh + ", and a low of " + TFLow);
        return;
    }
Ejemplo n.º 25
0
    public void Conditions()
    {
        Wunderground();
        string SavedLocation = "http://weather.yahooapis.com/forecastrss?z=" + ZIP;
        // Create a new XmlDocument
        XmlDocument Weather = new XmlDocument();
        string rss = "http://xml.weather.yahoo.com/ns/rss/1.0";
        string NewLine = Environment.NewLine;
        while (true)
        {
            try
            {
                // Load data
                Weather.Load(SavedLocation);

                // Set up namespace manager for XPath
                XmlNamespaceManager NameSpaceMgr = new XmlNamespaceManager(Weather.NameTable);

                NameSpaceMgr.AddNamespace("yweather", rss);

                // Get forecast with XPath
                XmlNodeList condition = Weather.SelectNodes("/rss/channel/item/yweather:condition", NameSpaceMgr);
                XmlNodeList location = Weather.SelectNodes("/rss/channel/yweather:location", NameSpaceMgr);
                XmlNodeList forecast = Weather.SelectNodes("/rss/channel/item/yweather:forecast", NameSpaceMgr);

                Condition = CleanCondition(condition[0].Attributes["text"].Value);
                Temperature = condition[0].Attributes["temp"].Value;
                break;
            }
            catch
            {
                // Try again.
                Thread.Sleep(5000);
                continue;
            }

        }
    }
Ejemplo n.º 26
0
    public static void Main(string[] args)
    {
        if((args.Length == 0) || (args.Length % 2)!= 0){
           Console.WriteLine("Usage: xpathms query source <zero or more prefix and namespace pairs>");
          return;
           }

           try{

         //Load the file.
         XmlDocument doc = new XmlDocument();
         doc.Load(args[1]);

         //create prefix<->namespace mappings (if any)
         XmlNamespaceManager  nsMgr = new XmlNamespaceManager(doc.NameTable);

         for(int i=2; i < args.Length; i+= 2)
           nsMgr.AddNamespace(args[i], args[i + 1]);

         //Query the document
         XmlNodeList nodes = doc.SelectNodes(args[0], nsMgr);

         //print output
         foreach(XmlNode node in nodes)
           Console.WriteLine(node.OuterXml + "\n");

           }catch(XmlException xmle){
         Console.WriteLine("ERROR: XML Parse error occured because " +
        PrintError(xmle, null));
           }catch(FileNotFoundException fnfe){
         Console.WriteLine("ERROR: " + PrintError(fnfe, null));
           }catch(XPathException xpath){
         Console.WriteLine("ERROR: The following error occured while querying the document: "
             + PrintError(xpath, null));
           }catch(Exception e){
         Console.WriteLine("UNEXPECTED ERROR" + PrintError(e, null));
           }
    }
Ejemplo n.º 27
0
        /// <summary>
        /// Lee la Constancia de Recepción SUNAT y devuelve el contenido
        /// </summary>
        /// <param name="constanciaRecepcion">Trama ZIP del CDR</param>
        /// <returns>Devuelve una clase <see cref="EnviarDocumentoResponse"/></returns>
        public async Task <EnviarDocumentoResponse> GenerarDocumentoRespuesta(string constanciaRecepcion)
        {
            var response   = new EnviarDocumentoResponse();
            var returnByte = Convert.FromBase64String(constanciaRecepcion);

            using (var memRespuesta = new MemoryStream(returnByte))
            {
                if (memRespuesta.Length <= 0)
                {
                    response.MensajeError = "Respuesta SUNAT Vacio";
                    response.Exito        = false;
                }
                else
                {
                    using (var zipFile = ZipFile.Read(memRespuesta))
                    {
                        foreach (var entry   in  zipFile.Entries)
                        {
                            if (!entry.FileName.EndsWith(".xml"))
                            {
                                continue;
                            }
                            using (var ms = new MemoryStream())
                            {
                                entry.Extract(ms);
                                ms.Position = 0;
                                var responseReader = new StreamReader(ms);
                                var responseString = await responseReader.ReadToEndAsync();

                                try
                                {
                                    var xmlDoc = new XmlDocument();
                                    xmlDoc.LoadXml(responseString);

                                    var xmlnsManager = new XmlNamespaceManager(xmlDoc.NameTable);

                                    xmlnsManager.AddNamespace("ar", EspacioNombres.ar);
                                    xmlnsManager.AddNamespace("cac", EspacioNombres.cac);
                                    xmlnsManager.AddNamespace("cbc", EspacioNombres.cbc);

                                    response.CodigoRespuesta  = xmlDoc.SelectSingleNode(EspacioNombres.nodoResponseCode, xmlnsManager)?.InnerText;
                                    response.MensajeRespuesta = xmlDoc.SelectSingleNode(EspacioNombres.nodoDescription, xmlnsManager)?.InnerText;
                                    response.NroTicketCdr     = xmlDoc.SelectSingleNode(EspacioNombres.nodoId, xmlnsManager)?.InnerText;

                                    response.TramaZipCdr   = constanciaRecepcion;
                                    response.NombreArchivo = entry.FileName;
                                    response.Exito         = true;
                                }
                                catch (Exception ex)
                                {
                                    response.MensajeError = ex.Message;
                                    response.Pila         = ex.StackTrace;
                                    response.Exito        = false;
                                }
                            }
                        }
                    }
                }
            }
            return(response);
        }
Ejemplo n.º 28
0
        private static void LoadStylesFromTimedText10(Subtitle subtitle, string title, string header, string headerNoStyles, StringBuilder sb)
        {
            try
            {
                var lines = new List <string>();
                foreach (string s in subtitle.Header.Replace(Environment.NewLine, "\n").Split('\n'))
                {
                    lines.Add(s);
                }
                var tt  = new TimedText10();
                var sub = new Subtitle();
                tt.LoadSubtitle(sub, lines, string.Empty);

                var xml = new XmlDocument();
                xml.LoadXml(subtitle.Header);
                var nsmgr = new XmlNamespaceManager(xml.NameTable);
                nsmgr.AddNamespace("ttml", "http://www.w3.org/ns/ttml");
                XmlNode head          = xml.DocumentElement.SelectSingleNode("ttml:head", nsmgr);
                int     stylexmlCount = 0;
                var     ttStyles      = new StringBuilder();
                foreach (XmlNode node in head.SelectNodes("//ttml:style", nsmgr))
                {
                    string name = null;
                    if (node.Attributes["xml:id"] != null)
                    {
                        name = node.Attributes["xml:id"].Value;
                    }
                    else if (node.Attributes["id"] != null)
                    {
                        name = node.Attributes["id"].Value;
                    }
                    if (name != null)
                    {
                        stylexmlCount++;

                        string fontFamily = "Arial";
                        if (node.Attributes["tts:fontFamily"] != null)
                        {
                            fontFamily = node.Attributes["tts:fontFamily"].Value;
                        }

                        string fontWeight = "normal";
                        if (node.Attributes["tts:fontWeight"] != null)
                        {
                            fontWeight = node.Attributes["tts:fontWeight"].Value;
                        }

                        string fontStyle = "normal";
                        if (node.Attributes["tts:fontStyle"] != null)
                        {
                            fontStyle = node.Attributes["tts:fontStyle"].Value;
                        }

                        string color = "#ffffff";
                        if (node.Attributes["tts:color"] != null)
                        {
                            color = node.Attributes["tts:color"].Value.Trim();
                        }
                        Color c = Color.White;
                        try
                        {
                            if (color.StartsWith("rgb(", StringComparison.Ordinal))
                            {
                                string[] arr = color.Remove(0, 4).TrimEnd(')').Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                                c = Color.FromArgb(int.Parse(arr[0]), int.Parse(arr[1]), int.Parse(arr[2]));
                            }
                            else
                            {
                                c = ColorTranslator.FromHtml(color);
                            }
                        }
                        catch
                        {
                        }

                        string fontSize = "20";
                        if (node.Attributes["tts:fontSize"] != null)
                        {
                            fontSize = node.Attributes["tts:fontSize"].Value.Replace("px", string.Empty).Replace("em", string.Empty);
                        }
                        int fSize;
                        if (!int.TryParse(fontSize, out fSize))
                        {
                            fSize = 20;
                        }

                        const string styleFormat = "Style: {0},{1},{2},{3},65535,65535,-2147483640,-1,0,1,3,0,2,10,10,10,0,1";

                        ttStyles.AppendLine(string.Format(styleFormat, name, fontFamily, fSize, c.ToArgb()));
                    }
                }

                if (stylexmlCount > 0)
                {
                    sb.AppendLine(string.Format(headerNoStyles, title, ttStyles));
                    subtitle.Header = sb.ToString();
                }
                else
                {
                    sb.AppendLine(string.Format(header, title));
                }
            }
            catch
            {
                sb.AppendLine(string.Format(header, title));
            }
        }
Ejemplo n.º 29
0
        //=====================================================================

        /// <summary>
        /// This is used to perform the actual conversion
        /// </summary>
        /// <returns>The new project filename on success.  An exception is thrown if the conversion fails.</returns>
        public override string ConvertProject()
        {
            XmlNamespaceManager nsm;
            XmlDocument         sourceFile;
            XPathNavigator      navProject, navProp;
            SandcastleProject   project = base.Project;
            string includePath, lastProperty = null;

            try
            {
                project.HelpTitle = project.HtmlHelpName = Path.GetFileNameWithoutExtension(base.OldProjectFile);

                sourceFile = new XmlDocument();
                sourceFile.Load(base.OldProjectFile);
                nsm = new XmlNamespaceManager(sourceFile.NameTable);
                nsm.AddNamespace("prj", sourceFile.DocumentElement.NamespaceURI);

                navProject = sourceFile.CreateNavigator();

                // Get the name, topic style, and language ID
                lastProperty = "Name";
                navProp      = navProject.SelectSingleNode("//prj:Project/prj:PropertyGroup/prj:Name", nsm);

                if (navProp != null)
                {
                    project.HtmlHelpName = project.HelpTitle = navProp.Value;
                }

                lastProperty = "TopicStyle";
                navProp      = navProject.SelectSingleNode("//prj:Project/prj:PropertyGroup/prj:TopicStyle", nsm);

                if (navProp != null)
                {
                    project.PresentationStyle = navProp.Value;
                }

                lastProperty = "LanguageId";
                navProp      = navProject.SelectSingleNode("//prj:Project/prj:PropertyGroup/prj:LanguageId", nsm);

                if (navProp != null)
                {
                    project.Language = new CultureInfo(Convert.ToInt32(navProp.Value,
                                                                       CultureInfo.InvariantCulture));
                }

                // Add the documentation sources
                lastProperty = "Dlls|Comments";

                foreach (XPathNavigator docSource in navProject.Select("//prj:Project/prj:ItemGroup/prj:Dlls|" +
                                                                       "//prj:Project/prj:ItemGroup/prj:Comments", nsm))
                {
                    includePath = docSource.GetAttribute("Include", String.Empty);

                    if (!String.IsNullOrEmpty(includePath))
                    {
                        project.DocumentationSources.Add(includePath, null, null, false);
                    }
                }

                // Add the dependencies
                lastProperty = "Dependents";

                foreach (XPathNavigator dependency in navProject.Select(
                             "//prj:Project/prj:ItemGroup/prj:Dependents", nsm))
                {
                    includePath = dependency.GetAttribute("Include", String.Empty);

                    if (includePath.IndexOfAny(new char[] { '*', '?' }) == -1)
                    {
                        project.References.AddReference(Path.GetFileNameWithoutExtension(includePath), includePath);
                    }
                    else
                    {
                        foreach (string file in Directory.EnumerateFiles(Path.GetDirectoryName(includePath),
                                                                         Path.GetFileName(includePath)).Where(f =>
                                                                                                              f.EndsWith(".dll", StringComparison.OrdinalIgnoreCase) ||
                                                                                                              f.EndsWith(".exe", StringComparison.OrdinalIgnoreCase)))
                        {
                            project.References.AddReference(Path.GetFileNameWithoutExtension(file), file);
                        }
                    }
                }

                project.SaveProject(project.Filename);
            }
            catch (Exception ex)
            {
                throw new BuilderException("CVT0005", String.Format(CultureInfo.CurrentCulture,
                                                                    "Error reading project from '{0}' (last property = {1}):\r\n{2}", base.OldProjectFile,
                                                                    lastProperty, ex.Message), ex);
            }

            return(project.Filename);
        }
Ejemplo n.º 30
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="locationUri"></param>
        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);
            }
        }
Ejemplo n.º 31
0
        private void ProcessImscc(string path, Packages package)
        {
            var imsPath = string.Empty;
            var dirPath = string.Empty;
            var dirs    = Directory.GetDirectories(path);

            if (dirs != null && dirs.Length == 1)
            {
                dirPath = dirs[0];
            }

            // Make sure the imsmanifest.xml file exists
            if (File.Exists(path + "imsmanifest.xml"))
            {
                imsPath = path + "imsmanifest.xml";
            }
            else if (File.Exists(dirPath + Path.DirectorySeparatorChar + "imsmanifest.xml"))
            {
                path    = dirPath + Path.DirectorySeparatorChar;
                imsPath = path + "imsmanifest.xml";
            }
            else
            {
                Console.WriteLine("imsmanifest.xml file does not exist! Cannot continue.");
                return;
            }

            Console.WriteLine($"Extracting links from imscc file under path {path}...");

            // Load in the document
            var reader = XmlReader.Create(imsPath);
            var doc    = new XmlDocument();

            doc.Load(reader);

            // Grab the root note
            var manifest = doc.GetElementsByTagName("manifest")[0];

            // Create the namespace manager
            var ns = new XmlNamespaceManager(doc.NameTable);

            ns.AddNamespace("ns", manifest.NamespaceURI);

            var metadata = doc.SelectSingleNode("/ns:manifest/ns:metadata", ns);

            // Update the metadata for the package
            package.ImsSchema        = metadata.SelectSingleNode("ns:schema", ns).InnerText;
            package.ImsSchemaVersion = metadata.SelectSingleNode("ns:schemaversion", ns).InnerText;

            if (doc.GetElementsByTagName("lomimscc:title") != null &&
                doc.GetElementsByTagName("lomimscc:title").Count > 0 &&
                doc.GetElementsByTagName("lomimscc:title").Item(0) != null)
            {
                package.ImsTitle = doc.GetElementsByTagName("lomimscc:title").Item(0).InnerText;
            }

            if (doc.GetElementsByTagName("lomimscc:description") != null &&
                doc.GetElementsByTagName("lomimscc:description").Count > 0 &&
                doc.GetElementsByTagName("lomimscc:description").Item(0) != null)
            {
                package.ImsTitle = doc.GetElementsByTagName("lomimscc:description").Item(0).InnerText;
            }

            // Process the resource nodes
            var resources = doc.SelectNodes("/ns:manifest/ns:resources/ns:resource", ns);

            for (var i = 0; i < resources.Count; i++)
            {
                var resource = resources.Item(i);
                var href     = resource.Attributes != null &&
                               resource.Attributes.GetNamedItem("href") != null
                           ? resource.Attributes.GetNamedItem("href").Value : "";

                if (href.EndsWith(".htm") || href.EndsWith(".html"))
                {
                    ProcessLink(R, path, href, package);
                }
            }
        }
Ejemplo n.º 32
0
        private static void CloudProjectTest(string roleType, bool openServiceDefinition)
        {
            Assert.IsTrue(roleType == "Web" || roleType == "Worker", "Invalid roleType: " + roleType);

            var asm = Assembly.Load("Microsoft.VisualStudio.CloudService.Wizard,Version=1.0.0.0,Culture=neutral,PublicKeyToken=b03f5f7f11d50a3a");

            if (asm != null && asm.GetCustomAttributes(typeof(AssemblyFileVersionAttribute), false)
                .OfType <AssemblyFileVersionAttribute>()
                .Any(a => {
                Version ver;
                return(Version.TryParse(a.Version, out ver) && ver < new Version(2, 5));
            })
                )
            {
                Assert.Inconclusive("Test requires Microsoft Azure Tools 2.5 or later");
            }

            using (var app = new PythonVisualStudioApp())
                using (FileUtils.Backup(TestData.GetPath(@"TestData\CloudProject\ServiceDefinition.csdef"))) {
                    app.OpenProject("TestData\\CloudProject.sln", expectedProjects: 3);

                    var ccproj = app.Dte.Solution.Projects.Cast <Project>().FirstOrDefault(p => p.Name == "CloudProject");
                    Assert.IsNotNull(ccproj);

                    if (openServiceDefinition)
                    {
                        var wnd = ccproj.ProjectItems.Item("ServiceDefinition.csdef").Open();
                        wnd.Activate();
                        app.OnDispose(() => wnd.Close());
                    }

                    IVsHierarchy hier;
                    var          sln = app.GetService <IVsSolution>(typeof(SVsSolution));
                    ErrorHandler.ThrowOnFailure(sln.GetProjectOfUniqueName(ccproj.FullName, out hier));

                    app.ServiceProvider.GetUIThread().InvokeAsync(() =>
                                                                  PythonProjectNode.UpdateServiceDefinition(hier, roleType, roleType + "Role1", app.ServiceProvider)
                                                                  ).GetAwaiter().GetResult();

                    var doc = new XmlDocument();
                    for (int retries = 5; retries > 0; --retries)
                    {
                        try {
                            doc.Load(TestData.GetPath(@"TestData\CloudProject\ServiceDefinition.csdef"));
                            break;
                        } catch (IOException ex) {
                            Console.WriteLine("Exception while reading ServiceDefinition.csdef.{0}{1}", Environment.NewLine, ex);
                        } catch (XmlException) {
                            var copyTo = TestData.GetPath(@"TestData\CloudProject\" + Path.GetRandomFileName());
                            File.Copy(TestData.GetPath(@"TestData\CloudProject\ServiceDefinition.csdef"), copyTo);
                            Console.WriteLine("Copied file to " + copyTo);
                            throw;
                        }
                        Thread.Sleep(100);
                    }
                    var ns = new XmlNamespaceManager(doc.NameTable);
                    ns.AddNamespace("sd", "http://schemas.microsoft.com/ServiceHosting/2008/10/ServiceDefinition");
                    doc.Save(Console.Out);

                    var nav = doc.CreateNavigator();
                    if (roleType == "Web")
                    {
                        Assert.IsNotNull(nav.SelectSingleNode(
                                             "/sd:ServiceDefinition/sd:WebRole[@name='WebRole1']/sd:Startup/sd:Task[@commandLine='ps.cmd ConfigureCloudService.ps1']",
                                             ns
                                             ));
                    }
                    else if (roleType == "Worker")
                    {
                        Assert.IsNotNull(nav.SelectSingleNode(
                                             "/sd:ServiceDefinition/sd:WorkerRole[@name='WorkerRole1']/sd:Startup/sd:Task[@commandLine='bin\\ps.cmd ConfigureCloudService.ps1']",
                                             ns
                                             ));
                        Assert.IsNotNull(nav.SelectSingleNode(
                                             "/sd:ServiceDefinition/sd:WorkerRole[@name='WorkerRole1']/sd:Runtime/sd:EntryPoint/sd:ProgramEntryPoint[@commandLine='bin\\ps.cmd LaunchWorker.ps1']",
                                             ns
                                             ));
                    }
                }
        }
Ejemplo n.º 33
0
        private static TestRunner TestRunnerType(string filePath)
        {
            XmlDocument doc = new XmlDocument();

            XmlNamespaceManager nsmgr;

            try
            {
                doc.Load(filePath);

                if (doc.DocumentElement == null)
                {
                    return(TestRunner.Unknown);
                }

                string fileExtension = Path.GetExtension(filePath).ToLower();

                if (fileExtension.EndsWith("trx"))
                {
                    // MSTest2010
                    nsmgr = new XmlNamespaceManager(doc.NameTable);
                    nsmgr.AddNamespace("ns", "http://microsoft.com/schemas/VisualStudio/TeamTest/2010");

                    // check if its a mstest 2010 xml file
                    // will need to check the "//TestRun/@xmlns" attribute - value = http://microsoft.com/schemas/VisualStudio/TeamTest/2010
                    XmlNode testRunNode = doc.SelectSingleNode("ns:TestRun", nsmgr);
                    if (testRunNode != null && testRunNode.Attributes != null && testRunNode.Attributes["xmlns"] != null && testRunNode.Attributes["xmlns"].InnerText.Contains("2010"))
                    {
                        return(TestRunner.MSTest2010);
                    }
                }

                if (fileExtension.EndsWith("xml"))
                {
                    // Gallio
                    nsmgr = new XmlNamespaceManager(doc.NameTable);
                    nsmgr.AddNamespace("ns", "http://www.gallio.org/");

                    XmlNode model = doc.SelectSingleNode("//ns:testModel", nsmgr);
                    if (model != null)
                    {
                        return(TestRunner.Gallio);
                    }


                    // xUnit - will have <assembly ... test-framework="xUnit.net 2....."/>
                    XmlNode assemblyNode = doc.SelectSingleNode("//assembly");
                    if (assemblyNode != null && assemblyNode.Attributes != null &&
                        assemblyNode.Attributes["test-framework"] != null)
                    {
                        string testFramework = assemblyNode.Attributes["test-framework"].InnerText.ToLower();

                        if (testFramework.Contains("xunit") && testFramework.Contains("2."))
                        {
                            return(TestRunner.XUnitV2);
                        }
                    }


                    // NUnit
                    // NOTE: not all nunit test files (ie when have nunit output format from other test runners) will contain the environment node
                    //            but if it does exist - then it should have the nunit-version attribute
                    XmlNode envNode = doc.SelectSingleNode("//environment");
                    if (envNode != null && envNode.Attributes != null && envNode.Attributes["nunit-version"] != null)
                    {
                        return(TestRunner.NUnit);
                    }

                    // check for test-suite nodes - if it has those - its probably nunit tests
                    var testSuiteNodes = doc.SelectNodes("//test-suite");
                    if (testSuiteNodes != null && testSuiteNodes.Count > 0)
                    {
                        return(TestRunner.NUnit);
                    }


                    // TestNG
                    if (doc.DocumentElement.Name == "testng-results")
                    {
                        return(TestRunner.TestNG);
                    }
                }
            }
            catch { }

            return(TestRunner.Unknown);
        }
Ejemplo n.º 34
0
        public override InvoiceDescriptor Load(Stream stream)
        {
            if (!stream.CanRead)
            {
                throw new IllegalStreamException("Cannot read from stream");
            }

            XmlDocument doc = new XmlDocument();

            doc.Load(stream);
            XmlNamespaceManager nsmgr = new XmlNamespaceManager(doc.DocumentElement.OwnerDocument.NameTable);

            nsmgr.AddNamespace("rsm", "urn:ferd:CrossIndustryDocument:invoice:1p0");
            nsmgr.AddNamespace("ram", "urn:un:unece:uncefact:data:standard:ReusableAggregateBusinessInformationEntity:12");
            nsmgr.AddNamespace("udt", "urn:un:unece:uncefact:data:standard:UnqualifiedDataType:15");

            InvoiceDescriptor retval = new InvoiceDescriptor
            {
                IsTest      = _nodeAsBool(doc.DocumentElement, "//rsm:SpecifiedExchangedDocumentContext/ram:TestIndicator", nsmgr),
                Profile     = default(Profile).FromString(_nodeAsString(doc.DocumentElement, "//ram:GuidelineSpecifiedDocumentContextParameter/ram:ID", nsmgr)),
                Type        = default(InvoiceType).FromString(_nodeAsString(doc.DocumentElement, "//rsm:HeaderExchangedDocument/ram:TypeCode", nsmgr)),
                InvoiceNo   = _nodeAsString(doc.DocumentElement, "//rsm:HeaderExchangedDocument/ram:ID", nsmgr),
                InvoiceDate = _nodeAsDateTime(doc.DocumentElement, "//rsm:HeaderExchangedDocument/ram:IssueDateTime/udt:DateTimeString", nsmgr)
            };

            foreach (XmlNode node in doc.SelectNodes("//rsm:HeaderExchangedDocument/ram:IncludedNote", nsmgr))
            {
                string       content      = _nodeAsString(node, ".//ram:Content", nsmgr);
                string       _subjectCode = _nodeAsString(node, ".//ram:SubjectCode", nsmgr);
                SubjectCodes subjectCode  = default(SubjectCodes).FromString(_subjectCode);
                retval.AddNote(content, subjectCode);
            }

            retval.ReferenceOrderNo = _nodeAsString(doc, "//ram:ApplicableSupplyChainTradeAgreement/ram:BuyerReference", nsmgr);

            retval.Seller = _nodeAsParty(doc.DocumentElement, "//ram:ApplicableSupplyChainTradeAgreement/ram:SellerTradeParty", nsmgr);
            foreach (XmlNode node in doc.SelectNodes("//ram:ApplicableSupplyChainTradeAgreement/ram:SellerTradeParty/ram:SpecifiedTaxRegistration", nsmgr))
            {
                string id       = _nodeAsString(node, ".//ram:ID", nsmgr);
                string schemeID = _nodeAsString(node, ".//ram:ID/@schemeID", nsmgr);

                retval.AddSellerTaxRegistration(id, default(TaxRegistrationSchemeID).FromString(schemeID));
            }

            if (doc.SelectSingleNode("//ram:SellerTradeParty/ram:DefinedTradeContact", nsmgr) != null)
            {
                retval.SellerContact = new Contact()
                {
                    Name         = _nodeAsString(doc.DocumentElement, "//ram:SellerTradeParty/ram:DefinedTradeContact/ram:PersonName", nsmgr),
                    OrgUnit      = _nodeAsString(doc.DocumentElement, "//ram:SellerTradeParty/ram:DefinedTradeContact/ram:DepartmentName", nsmgr),
                    PhoneNo      = _nodeAsString(doc.DocumentElement, "//ram:SellerTradeParty/ram:DefinedTradeContact/ram:TelephoneUniversalCommunication/ram:CompleteNumber", nsmgr),
                    FaxNo        = _nodeAsString(doc.DocumentElement, "//ram:SellerTradeParty/ram:DefinedTradeContact/ram:FaxUniversalCommunication/ram:CompleteNumber", nsmgr),
                    EmailAddress = _nodeAsString(doc.DocumentElement, "//ram:SellerTradeParty/ram:DefinedTradeContact/ram:EmailURIUniversalCommunication/ram:CompleteNumber", nsmgr)
                };
            }

            retval.Buyer = _nodeAsParty(doc.DocumentElement, "//ram:ApplicableSupplyChainTradeAgreement/ram:BuyerTradeParty", nsmgr);
            foreach (XmlNode node in doc.SelectNodes("//ram:ApplicableSupplyChainTradeAgreement/ram:BuyerTradeParty/ram:SpecifiedTaxRegistration", nsmgr))
            {
                string id       = _nodeAsString(node, ".//ram:ID", nsmgr);
                string schemeID = _nodeAsString(node, ".//ram:ID/@schemeID", nsmgr);

                retval.AddBuyerTaxRegistration(id, default(TaxRegistrationSchemeID).FromString(schemeID));
            }

            if (doc.SelectSingleNode("//ram:BuyerTradeParty/ram:DefinedTradeContact", nsmgr) != null)
            {
                retval.BuyerContact = new Contact()
                {
                    Name         = _nodeAsString(doc.DocumentElement, "//ram:BuyerTradeParty/ram:DefinedTradeContact/ram:PersonName", nsmgr),
                    OrgUnit      = _nodeAsString(doc.DocumentElement, "//ram:BuyerTradeParty/DefinedTradeContact/ram:DepartmentName", nsmgr),
                    PhoneNo      = _nodeAsString(doc.DocumentElement, "//ram:BuyerTradeParty/ram:DefinedTradeContact/ram:TelephoneUniversalCommunication/ram:CompleteNumber", nsmgr),
                    FaxNo        = _nodeAsString(doc.DocumentElement, "//ram:BuyerTradeParty/ram:DefinedTradeContact/ram:FaxUniversalCommunication/ram:CompleteNumber", nsmgr),
                    EmailAddress = _nodeAsString(doc.DocumentElement, "//ram:BuyerTradeParty/ram:DefinedTradeContact/ram:EmailURIUniversalCommunication/ram:CompleteNumber", nsmgr)
                };
            }

            retval.ActualDeliveryDate = _nodeAsDateTime(doc.DocumentElement, "//ram:ApplicableSupplyChainTradeDelivery/ram:ActualDeliverySupplyChainEvent/ram:OccurrenceDateTime/udt:DateTimeString", nsmgr);

            string   _deliveryNoteNo   = _nodeAsString(doc.DocumentElement, "//ram:ApplicableSupplyChainTradeDelivery/ram:DeliveryNoteReferencedDocument/ram:ID", nsmgr);
            DateTime?_deliveryNoteDate = _nodeAsDateTime(doc.DocumentElement, "//ram:ApplicableSupplyChainTradeDelivery/ram:DeliveryNoteReferencedDocument/ram:IssueDateTime/udt:DateTimeString", nsmgr);

            if (!_deliveryNoteDate.HasValue)
            {
                _deliveryNoteDate = _nodeAsDateTime(doc.DocumentElement, "//ram:ApplicableSupplyChainTradeDelivery/ram:DeliveryNoteReferencedDocument/ram:IssueDateTime", nsmgr);
            }

            if (_deliveryNoteDate.HasValue || !String.IsNullOrEmpty(_deliveryNoteNo))
            {
                retval.DeliveryNoteReferencedDocument = new DeliveryNoteReferencedDocument()
                {
                    ID            = _deliveryNoteNo,
                    IssueDateTime = _deliveryNoteDate
                };
            }

            retval.InvoiceNoAsReference = _nodeAsString(doc.DocumentElement, "//ram:ApplicableSupplyChainTradeSettlement/ram:PaymentReference", nsmgr);
            retval.Currency             = default(CurrencyCodes).FromString(_nodeAsString(doc.DocumentElement, "//ram:ApplicableSupplyChainTradeSettlement/ram:InvoiceCurrencyCode", nsmgr));

            PaymentMeans _tempPaymentMeans = new PaymentMeans()
            {
                TypeCode               = default(PaymentMeansTypeCodes).FromString(_nodeAsString(doc.DocumentElement, "//ram:ApplicableSupplyChainTradeSettlement/ram:SpecifiedTradeSettlementPaymentMeans/ram:TypeCode", nsmgr)),
                Information            = _nodeAsString(doc.DocumentElement, "//ram:ApplicableSupplyChainTradeSettlement/ram:SpecifiedTradeSettlementPaymentMeans/ram:Information", nsmgr),
                SEPACreditorIdentifier = _nodeAsString(doc.DocumentElement, "//ram:ApplicableSupplyChainTradeSettlement/ram:SpecifiedTradeSettlementPaymentMeans/ram:ID", nsmgr),
                SEPAMandateReference   = _nodeAsString(doc.DocumentElement, "//ram:ApplicableSupplyChainTradeSettlement/ram:SpecifiedTradeSettlementPaymentMeans/ram:ID/@schemeAgencyID", nsmgr)
            };

            retval.PaymentMeans = _tempPaymentMeans;

            XmlNodeList creditorFinancialAccountNodes = doc.SelectNodes("//ram:ApplicableSupplyChainTradeSettlement/ram:SpecifiedTradeSettlementPaymentMeans/ram:PayeePartyCreditorFinancialAccount", nsmgr);
            XmlNodeList creditorFinancialInstitutions = doc.SelectNodes("//ram:ApplicableSupplyChainTradeSettlement/ram:SpecifiedTradeSettlementPaymentMeans/ram:PayeeSpecifiedCreditorFinancialInstitution", nsmgr);

            if (creditorFinancialAccountNodes.Count == creditorFinancialInstitutions.Count)
            {
                for (int i = 0; i < creditorFinancialAccountNodes.Count; i++)
                {
                    BankAccount _account = new BankAccount()
                    {
                        ID           = _nodeAsString(creditorFinancialAccountNodes[0], ".//ram:ProprietaryID", nsmgr),
                        IBAN         = _nodeAsString(creditorFinancialAccountNodes[0], ".//ram:IBANID", nsmgr),
                        BIC          = _nodeAsString(creditorFinancialInstitutions[0], ".//ram:BICID", nsmgr),
                        Bankleitzahl = _nodeAsString(creditorFinancialInstitutions[0], ".//ram:GermanBankleitzahlID", nsmgr),
                        BankName     = _nodeAsString(creditorFinancialInstitutions[0], ".//ram:Name", nsmgr),
                    };

                    retval.CreditorBankAccounts.Add(_account);
                } // !for(i)
            }

            XmlNodeList debitorFinancialAccountNodes = doc.SelectNodes("//ram:ApplicableSupplyChainTradeSettlement/ram:SpecifiedTradeSettlementPaymentMeans/ram:PayerPartyDebtorFinancialAccount", nsmgr);
            XmlNodeList debitorFinancialInstitutions = doc.SelectNodes("//ram:ApplicableSupplyChainTradeSettlement/ram:SpecifiedTradeSettlementPaymentMeans/ram:PayerSpecifiedDebtorFinancialInstitution", nsmgr);

            if (debitorFinancialAccountNodes.Count == debitorFinancialInstitutions.Count)
            {
                for (int i = 0; i < debitorFinancialAccountNodes.Count; i++)
                {
                    BankAccount _account = new BankAccount()
                    {
                        ID           = _nodeAsString(debitorFinancialAccountNodes[0], ".//ram:ProprietaryID", nsmgr),
                        IBAN         = _nodeAsString(debitorFinancialAccountNodes[0], ".//ram:IBANID", nsmgr),
                        BIC          = _nodeAsString(debitorFinancialInstitutions[0], ".//ram:BICID", nsmgr),
                        Bankleitzahl = _nodeAsString(debitorFinancialInstitutions[0], ".//ram:GermanBankleitzahlID", nsmgr),
                        BankName     = _nodeAsString(debitorFinancialInstitutions[0], ".//ram:Name", nsmgr),
                    };

                    retval.DebitorBankAccounts.Add(_account);
                } // !for(i)
            }

            foreach (XmlNode node in doc.SelectNodes("//ram:ApplicableSupplyChainTradeSettlement/ram:ApplicableTradeTax", nsmgr))
            {
                retval.AddApplicableTradeTax(_nodeAsDecimal(node, ".//ram:BasisAmount", nsmgr, 0).Value,
                                             _nodeAsDecimal(node, ".//ram:ApplicablePercent", nsmgr, 0).Value,
                                             default(TaxTypes).FromString(_nodeAsString(node, ".//ram:TypeCode", nsmgr)),
                                             default(TaxCategoryCodes).FromString(_nodeAsString(node, ".//ram:CategoryCode", nsmgr)));
            }

            foreach (XmlNode node in doc.SelectNodes("//ram:SpecifiedTradeAllowanceCharge", nsmgr))
            {
                retval.AddTradeAllowanceCharge(!_nodeAsBool(node, ".//ram:ChargeIndicator", nsmgr), // wichtig: das not (!) beachten
                                               _nodeAsDecimal(node, ".//ram:BasisAmount", nsmgr, 0).Value,
                                               retval.Currency,
                                               _nodeAsDecimal(node, ".//ram:ActualAmount", nsmgr, 0).Value,
                                               _nodeAsString(node, ".//ram:Reason", nsmgr),
                                               default(TaxTypes).FromString(_nodeAsString(node, ".//ram:CategoryTradeTax/ram:TypeCode", nsmgr)),
                                               default(TaxCategoryCodes).FromString(_nodeAsString(node, ".//ram:CategoryTradeTax/ram:CategoryCode", nsmgr)),
                                               _nodeAsDecimal(node, ".//ram:CategoryTradeTax/ram:ApplicablePercent", nsmgr, 0).Value);
            }

            foreach (XmlNode node in doc.SelectNodes("//ram:SpecifiedLogisticsServiceCharge", nsmgr))
            {
                retval.AddLogisticsServiceCharge(_nodeAsDecimal(node, ".//ram:AppliedAmount", nsmgr, 0).Value,
                                                 _nodeAsString(node, ".//ram:Description", nsmgr),
                                                 default(TaxTypes).FromString(_nodeAsString(node, ".//ram:AppliedTradeTax/ram:TypeCode", nsmgr)),
                                                 default(TaxCategoryCodes).FromString(_nodeAsString(node, ".//ram:AppliedTradeTax/ram:CategoryCode", nsmgr)),
                                                 _nodeAsDecimal(node, ".//ram:AppliedTradeTax/ram:ApplicablePercent", nsmgr, 0).Value);
            }

            retval.PaymentTerms = new PaymentTerms()
            {
                Description = _nodeAsString(doc.DocumentElement, "//ram:SpecifiedTradePaymentTerms/ram:Description", nsmgr),
                DueDate     = _nodeAsDateTime(doc.DocumentElement, "//ram:SpecifiedTradePaymentTerms/ram:DueDateDateTime", nsmgr)
            };

            retval.LineTotalAmount      = _nodeAsDecimal(doc.DocumentElement, "//ram:SpecifiedTradeSettlementMonetarySummation/ram:LineTotalAmount", nsmgr, 0).Value;
            retval.ChargeTotalAmount    = _nodeAsDecimal(doc.DocumentElement, "//ram:SpecifiedTradeSettlementMonetarySummation/ram:ChargeTotalAmount", nsmgr, 0).Value;
            retval.AllowanceTotalAmount = _nodeAsDecimal(doc.DocumentElement, "//ram:SpecifiedTradeSettlementMonetarySummation/ram:AllowanceTotalAmount", nsmgr, 0).Value;
            retval.TaxBasisAmount       = _nodeAsDecimal(doc.DocumentElement, "//ram:SpecifiedTradeSettlementMonetarySummation/ram:TaxBasisTotalAmount", nsmgr, 0).Value;
            retval.TaxTotalAmount       = _nodeAsDecimal(doc.DocumentElement, "//ram:SpecifiedTradeSettlementMonetarySummation/ram:TaxTotalAmount", nsmgr, 0).Value;
            retval.GrandTotalAmount     = _nodeAsDecimal(doc.DocumentElement, "//ram:SpecifiedTradeSettlementMonetarySummation/ram:GrandTotalAmount", nsmgr, 0).Value;
            retval.TotalPrepaidAmount   = _nodeAsDecimal(doc.DocumentElement, "//ram:SpecifiedTradeSettlementMonetarySummation/ram:TotalPrepaidAmount", nsmgr, 0).Value;
            retval.DuePayableAmount     = _nodeAsDecimal(doc.DocumentElement, "//ram:SpecifiedTradeSettlementMonetarySummation/ram:DuePayableAmount", nsmgr, 0).Value;

            retval.OrderDate = _nodeAsDateTime(doc.DocumentElement, "//ram:ApplicableSupplyChainTradeAgreement/ram:BuyerOrderReferencedDocument/ram:IssueDateTime/udt:DateTimeString", nsmgr);
            if (!retval.OrderDate.HasValue)
            {
                retval.OrderDate = _nodeAsDateTime(doc.DocumentElement, "//ram:ApplicableSupplyChainTradeAgreement/ram:BuyerOrderReferencedDocument/ram:IssueDateTime", nsmgr);
            }
            retval.OrderNo = _nodeAsString(doc.DocumentElement, "//ram:ApplicableSupplyChainTradeAgreement/ram:BuyerOrderReferencedDocument/ram:ID", nsmgr);


            foreach (XmlNode node in doc.SelectNodes("//ram:IncludedSupplyChainTradeLineItem", nsmgr))
            {
                retval.TradeLineItems.Add(_parseTradeLineItem(node, nsmgr));
            }
            return(retval);
        } // !Load()
Ejemplo n.º 35
0
 public Signature()
 {
     dsigNsmgr = new XmlNamespaceManager(new NameTable());
     dsigNsmgr.AddNamespace("ds", XmlSignature.NamespaceURI);
     list = new ArrayList();
 }
Ejemplo n.º 36
0
    /// <summary>
    /// 设置数据集的结构及定义属性
    /// 需要输出到客户端的项目属性,列属性;name,relation,linkcol,columnkey,printtype,pagesize,
    /// 系统属性:id,typexml,ctrlAlter,ctrlchanged,ctrlschema,ctrlstate,ctrlhlbcmd,ctrlbtcommand,catalog,class,itemname,;
    /// 用户自定义的属性不能与其相同
    /// </summary>
    private void setSchema()
    {
        //数据岛结构信息
        BasePage page = this.Page as BasePage;
        if (null == this.CtrlXmlSchema.Document)
            return;
        string itemAttrs = "name,relation,linkcol,columnkey,printtype,pagesize,";
        string ctrlAttrs = "name,relation,linkcol,columnkey,printtype,pagesize,"
                            + "id,typexml,ctrlAlter,ctrlchanged,ctrlschema,ctrlstate,ctrlhlbcmd,ctrlbtcommand,catalog,class,itemname,";

        XmlDocument xmldocSchema = this.CtrlXmlSchema.Document;

        #region 控件本身使用属性:
        //结构数据岛ID,数据岛类型,客户端提示标签,数据更新标签,结构更新(列宽度)标签,状态标签,命令标签,命令按钮,树节点ID字段,父ID字段,排序字段
        if (null == xmldocSchema.DocumentElement.Attributes["id"])
            xmldocSchema.DocumentElement.Attributes.Append(xmldocSchema.CreateAttribute("id"));
        if (null == xmldocSchema.DocumentElement.Attributes["typexml"])
            xmldocSchema.DocumentElement.Attributes.Append(xmldocSchema.CreateAttribute("typexml"));
        if (null == xmldocSchema.DocumentElement.Attributes["ctrlAlter"])
            xmldocSchema.DocumentElement.Attributes.Append(xmldocSchema.CreateAttribute("ctrlAlert"));
        if (null == xmldocSchema.DocumentElement.Attributes["ctrlchanged"])
            xmldocSchema.DocumentElement.Attributes.Append(xmldocSchema.CreateAttribute("ctrlchanged"));
        if (null == xmldocSchema.DocumentElement.Attributes["ctrlschema"])
            xmldocSchema.DocumentElement.Attributes.Append(xmldocSchema.CreateAttribute("ctrlschema"));
        if (null == xmldocSchema.DocumentElement.Attributes["ctrlstate"])
            xmldocSchema.DocumentElement.Attributes.Append(xmldocSchema.CreateAttribute("ctrlstate"));
        if (null == xmldocSchema.DocumentElement.Attributes["ctrlhlbcmd"])
            xmldocSchema.DocumentElement.Attributes.Append(xmldocSchema.CreateAttribute("ctrlhlbcmd"));
        if (null == xmldocSchema.DocumentElement.Attributes["ctrlbtcommand"])
            xmldocSchema.DocumentElement.Attributes.Append(xmldocSchema.CreateAttribute("ctrlbtcommand"));
        if (null == xmldocSchema.DocumentElement.Attributes["idfld"])
            xmldocSchema.DocumentElement.Attributes.Append(xmldocSchema.CreateAttribute("idfld"));
        if (null == xmldocSchema.DocumentElement.Attributes["pidfld"])
            xmldocSchema.DocumentElement.Attributes.Append(xmldocSchema.CreateAttribute("pidfld"));

        if (null == xmldocSchema.DocumentElement.Attributes["txtfld"])
            xmldocSchema.DocumentElement.Attributes.Append(xmldocSchema.CreateAttribute("txtfld"));

        if (null == xmldocSchema.DocumentElement.Attributes["namefld"])
            xmldocSchema.DocumentElement.Attributes.Append(xmldocSchema.CreateAttribute("namefld"));

        if (null == xmldocSchema.DocumentElement.Attributes["selfid"])
            xmldocSchema.DocumentElement.Attributes.Append(xmldocSchema.CreateAttribute("selfid"));

        if (null == xmldocSchema.DocumentElement.Attributes["valuefld"])
            xmldocSchema.DocumentElement.Attributes.Append(xmldocSchema.CreateAttribute("valuefld"));

        if (null == xmldocSchema.DocumentElement.Attributes["typefld"])
            xmldocSchema.DocumentElement.Attributes.Append(xmldocSchema.CreateAttribute("typefld"));
        
        if (null == xmldocSchema.DocumentElement.Attributes["orderfld"])
            xmldocSchema.DocumentElement.Attributes.Append(xmldocSchema.CreateAttribute("orderfld"));
        
        if (null == xmldocSchema.DocumentElement.Attributes["ntag"])
            xmldocSchema.DocumentElement.Attributes.Append(xmldocSchema.CreateAttribute("ntag"));

        if (null == xmldocSchema.DocumentElement.Attributes["keyfid"])
            xmldocSchema.DocumentElement.Attributes.Append(xmldocSchema.CreateAttribute("keyfid"));

        if (null == xmldocSchema.DocumentElement.Attributes["noexpand"])
            xmldocSchema.DocumentElement.Attributes.Append(xmldocSchema.CreateAttribute("noexpand"));

        xmldocSchema.DocumentElement.Attributes["id"].Value             = this.CtrlXmlID + "_Schema";
        xmldocSchema.DocumentElement.Attributes["typexml"].Value        = "Schema";
        xmldocSchema.DocumentElement.Attributes["ctrlAlert"].Value      = this._ctrlAlertID;
        xmldocSchema.DocumentElement.Attributes["ctrlchanged"].Value    = this.hlbChanged.ClientID;
        xmldocSchema.DocumentElement.Attributes["ctrlschema"].Value     = this.hlbWidth.ClientID;
        xmldocSchema.DocumentElement.Attributes["ctrlstate"].Value      = this.hlbState.ClientID;
        xmldocSchema.DocumentElement.Attributes["ctrlhlbcmd"].Value     = this.hlb_cmd.ClientID;
        xmldocSchema.DocumentElement.Attributes["ctrlbtcommand"].Value  = page.PgBtCmd.ClientID;
        xmldocSchema.DocumentElement.Attributes["idfld"].Value          = this._idField;
        xmldocSchema.DocumentElement.Attributes["pidfld"].Value         = this._pidField;
        xmldocSchema.DocumentElement.Attributes["selfid"].Value         = this._selfidField;
        xmldocSchema.DocumentElement.Attributes["keyfid"].Value         = this._keyField;   //人工关键字段
        xmldocSchema.DocumentElement.Attributes["txtfld"].Value         = this._txtField;
        xmldocSchema.DocumentElement.Attributes["namefld"].Value        = this._nameField;
        xmldocSchema.DocumentElement.Attributes["valuefld"].Value       = this._valueField;
        xmldocSchema.DocumentElement.Attributes["typefld"].Value        = this._typeField;
        xmldocSchema.DocumentElement.Attributes["orderfld"].Value       = this._orderField;
        xmldocSchema.DocumentElement.Attributes["ntag"].Value           = this._nTag;
        if (this._isexpand)
            xmldocSchema.DocumentElement.Attributes["noexpand"].Value = "false";
        else
            xmldocSchema.DocumentElement.Attributes["noexpand"].Value = "true";
        #endregion

        #region workitem定义列属性
        XmlNamespaceManager xmlNsMgl = new XmlNamespaceManager(xmldocSchema.NameTable);
        XmlNode xmlRootEle = xmldocSchema.DocumentElement;
        for (int i = 0; i < xmlRootEle.Attributes.Count; i++)
        {
            string strPrefix = xmlRootEle.Attributes[i].Prefix;
            string strLocalName = xmlRootEle.Attributes[i].LocalName;
            string strURI = xmlRootEle.Attributes[i].Value;
            if ("xmlns" == strLocalName)
                xmlNsMgl.AddNamespace(string.Empty, strURI);
            if ("xmlns" != strPrefix) continue;
            xmlNsMgl.AddNamespace(strLocalName, strURI);
        }
        this._xmlNsMglSchema = xmlNsMgl;
        //定义的项目属性,不需要输出的属性不输出
        XmlNode xmlNodeWorkItem = page.PgUnitItem.UnitNode.SelectSingleNode(".//Item[@name='" + this.CtrlItemName + "']");
        for (int i = 0; i < xmlNodeWorkItem.Attributes.Count; i++)
        {
            string localName = xmlNodeWorkItem.Attributes[i].LocalName;
            if (null != xmldocSchema.DocumentElement.Attributes[localName])
                continue;
            if (itemAttrs.IndexOf(localName + ",") < 0)
                continue;
            XmlAttribute attr = xmldocSchema.CreateAttribute(localName);
            attr.Value = xmlNodeWorkItem.Attributes[i].Value;
            xmldocSchema.DocumentElement.Attributes.Append(attr);
        }
        #endregion
        //页面控件节点自定义属性;
        for (int i = 0; i < this._attrNodeCtrl.Attributes.Count; i++)
        {
            string strAttrName = this._attrNodeCtrl.Attributes[i].Name;
            if (ctrlAttrs.IndexOf(strAttrName + ",") >= 0)
                continue;
            XmlAttribute attrTempCtrl = xmlRootEle.Attributes[strAttrName];
            if (null != attrTempCtrl) continue;
            attrTempCtrl = xmlRootEle.Attributes.Append(xmldocSchema.CreateAttribute(strAttrName));
            attrTempCtrl.Value = this._attrNodeCtrl.Attributes[i].Value;
        }

        #region  列规则属性

        XmlNodeList xmlColNodeList = xmldocSchema.SelectNodes("//xs:sequence//xs:element", xmlNsMgl);
        for (int i = 0; i < xmlColNodeList.Count; i++)
        {
            XmlNode xmlColSchema = xmlColNodeList[i];
            string colName = xmlColSchema.Attributes["name"].Value;
            //自定义属性,如果自定义属性为空,忽略处理
            XmlNode xmlCol = page.PgUnitItem.UnitNode.SelectSingleNode(".//Item[@name='" + this.CtrlItemName + "']/Column[@name='" + colName + "']");
            for (int j = 0; null != xmlCol && j < xmlCol.Attributes.Count; j++)
            {
                string localName = xmlCol.Attributes[j].LocalName;
                if (null != xmlColSchema.Attributes[localName])
                    continue;
                if ("" == xmlCol.Attributes[j].Value)
                    continue;
                XmlAttribute attr = xmlColSchema.OwnerDocument.CreateAttribute(localName);
                attr.Value = xmlCol.Attributes[j].Value;
                xmlColSchema.Attributes.Append(attr);
            }
            if ("RowNum" == colName)
            {
                if (null == xmlColSchema.Attributes["visible"])
                    xmlColSchema.Attributes.SetNamedItem(xmlColSchema.OwnerDocument.CreateAttribute("visible"));
                xmlColSchema.Attributes["visible"].Value = "1";
            }
            //字段列如果有显示格式,说明格式列的字段名称
            if (null != xmlColSchema.Attributes["format"] && "" != xmlColSchema.Attributes["format"].Value)
            {
                xmlColSchema.Attributes.Append(xmlColSchema.OwnerDocument.CreateAttribute("formatfld"));
                xmlColSchema.Attributes["formatfld"].Value = colName + "_格式";
            }
            //字段列如果是字典列,并且text列和value列不同,使用格式显示列
            if (null != xmlColSchema.Attributes["dataitem"] && "" != xmlColSchema.Attributes["dataitem"].Value
                && null != xmlColSchema.Attributes["textcol"] && "" != xmlColSchema.Attributes["textcol"].Value
                && null != xmlColSchema.Attributes["valuecol"] && "" != xmlColSchema.Attributes["valuecol"].Value
                && xmlColSchema.Attributes["valuecol"].Value != xmlColSchema.Attributes["textcol"].Value)
            {
                xmlColSchema.Attributes.SetNamedItem(xmlColSchema.OwnerDocument.CreateAttribute("formatfld"));
                xmlColSchema.Attributes["formatfld"].Value = colName + "_显示";
            }
        }//for(int i=0;i<xmlColNodeList.Count;i++)
        #endregion

    }
Ejemplo n.º 37
0
        public override Task <ThumbnailInfo> GetThumbnailInfoAsync(string url, PostClass post, CancellationToken token)
        {
            return(Task.Run(() =>
            {
                var match = Youtube.UrlPatternRegex.Match(url);
                if (!match.Success)
                {
                    return null;
                }

                var videoId = match.Groups["videoid"].Value;
                var imgUrl = "http://i.ytimg.com/vi/" + videoId + "/default.jpg";

                // 参考
                // http://code.google.com/intl/ja/apis/youtube/2.0/developers_guide_protocol_video_entries.html
                // デベロッパー ガイド: Data API プロトコル - 単独の動画情報の取得 - YouTube の API とツール - Google Code
                // http://code.google.com/intl/ja/apis/youtube/2.0/developers_guide_protocol_understanding_video_feeds.html#Understanding_Feeds_and_Entries
                // デベロッパー ガイド: Data API プロトコル - 動画のフィードとエントリについて - YouTube の API とツール - Google Code
                var videourl = (new HttpVarious()).GetRedirectTo(url);
                Match mc;
                if (videourl.StartsWith("http://www.youtube.com/index?ytsession="))
                {
                    videourl = url;
                    mc = match;
                }
                else
                {
                    mc = Youtube.UrlPatternRegex.Match(videourl);
                }
                if (mc.Success)
                {
                    var apiurl = "http://gdata.youtube.com/feeds/api/videos/" + mc.Groups["videoid"].Value;
                    var src = "";
                    if ((new HttpVarious()).GetData(apiurl, null, out src, 5000))
                    {
                        var sb = new StringBuilder();
                        var xdoc = new XmlDocument();
                        try
                        {
                            xdoc.LoadXml(src);
                            var nsmgr = new XmlNamespaceManager(xdoc.NameTable);
                            nsmgr.AddNamespace("root", "http://www.w3.org/2005/Atom");
                            nsmgr.AddNamespace("app", "http://purl.org/atom/app#");
                            nsmgr.AddNamespace("media", "http://search.yahoo.com/mrss/");

                            var xentryNode = xdoc.DocumentElement.SelectSingleNode("/root:entry/media:group", nsmgr);
                            var xentry = (XmlElement)xentryNode;
                            var tmp = "";
                            try
                            {
                                tmp = xentry["media:title"].InnerText;
                                if (!string.IsNullOrEmpty(tmp))
                                {
                                    sb.Append(Properties.Resources.YouTubeInfoText1);
                                    sb.Append(tmp);
                                    sb.AppendLine();
                                }
                            }
                            catch (Exception)
                            {
                            }

                            try
                            {
                                var sec = 0;
                                if (int.TryParse(xentry["yt:duration"].Attributes["seconds"].Value, out sec))
                                {
                                    sb.Append(Properties.Resources.YouTubeInfoText2);
                                    sb.AppendFormat("{0:d}:{1:d2}", sec / 60, sec % 60);
                                    sb.AppendLine();
                                }
                            }
                            catch (Exception)
                            {
                            }

                            try
                            {
                                var tmpdate = new DateTime();
                                xentry = (XmlElement)xdoc.DocumentElement.SelectSingleNode("/root:entry", nsmgr);
                                if (DateTime.TryParse(xentry["published"].InnerText, out tmpdate))
                                {
                                    sb.Append(Properties.Resources.YouTubeInfoText3);
                                    sb.Append(tmpdate);
                                    sb.AppendLine();
                                }
                            }
                            catch (Exception)
                            {
                            }

                            try
                            {
                                var count = 0;
                                xentry = (XmlElement)xdoc.DocumentElement.SelectSingleNode("/root:entry", nsmgr);
                                tmp = xentry["yt:statistics"].Attributes["viewCount"].Value;
                                if (int.TryParse(tmp, out count))
                                {
                                    sb.Append(Properties.Resources.YouTubeInfoText4);
                                    sb.Append(tmp);
                                    sb.AppendLine();
                                }
                            }
                            catch (Exception)
                            {
                            }

                            try
                            {
                                xentry = (XmlElement)xdoc.DocumentElement.SelectSingleNode("/root:entry/app:control", nsmgr);
                                if (xentry != null)
                                {
                                    sb.Append(xentry["yt:state"].Attributes["name"].Value);
                                    sb.Append(":");
                                    sb.Append(xentry["yt:state"].InnerText);
                                    sb.AppendLine();
                                }
                            }
                            catch (Exception)
                            {
                            }

                            //mc = Regex.Match(videourl, @"^http://www\.youtube\.com/watch\?v=([\w\-]+)", RegexOptions.IgnoreCase)
                            //if (mc.Success)
                            //{
                            // imgurl = mc.Result("http://i.ytimg.com/vi/${1}/default.jpg");
                            //}
                            //mc = Regex.Match(videourl, @"^http://youtu\.be/([\w\-]+)", RegexOptions.IgnoreCase)
                            //if (mc.Success)
                            //{
                            // imgurl = mc.Result("http://i.ytimg.com/vi/${1}/default.jpg");
                            //}
                        }
                        catch (Exception)
                        {
                        }

                        return new ThumbnailInfo
                        {
                            ImageUrl = url,
                            ThumbnailUrl = imgUrl,
                            TooltipText = sb.ToString().Trim(),
                            IsPlayable = true,
                        };
                    }
                }
                return null;
            }, token));
        }
Ejemplo n.º 38
0
        public override async Task <NodeCollections> GetBlogs()
        {
            NodeCollections blogs = new NodeCollections();

            var HTTPResponseMessage = await _HTTPConn.Client.GetAsync(_endpoint);

            if (HTTPResponseMessage.IsSuccessStatusCode)
            {
                string s = await HTTPResponseMessage.Content.ReadAsStringAsync();

                System.Diagnostics.Debug.WriteLine("GET blogs(collection): " + s);

                /*
                 *                  <?xml version="1.0" encoding="utf-8"?>
                 *                  <service xmlns="http://www.w3.org/2007/app">
                 *                    <workspace>
                 *                      <atom:title xmlns:atom="http://www.w3.org/2005/Atom">hoge</atom:title>
                 *                      <collection href="https://127.0.0.1/atom/entry">
                 *                        <atom:title xmlns:atom="http://www.w3.org/2005/Atom">fuga</atom:title>
                 *                        <accept>application/atom+xml;type=entry</accept>
                 *                      </collection>
                 *                    </workspace>
                 *                  </service>
                 */
                XmlDocument xdoc = new XmlDocument();
                try
                {
                    xdoc.LoadXml(s);
                }
                catch (Exception e)
                {
                    // TODO:
                    System.Diagnostics.Debug.WriteLine("LoadXml failed: " + e.Message);
                    return(blogs);
                }

                XmlNamespaceManager atomNsMgr = new XmlNamespaceManager(xdoc.NameTable);
                atomNsMgr.AddNamespace("atom", "http://www.w3.org/2005/Atom");
                atomNsMgr.AddNamespace("app", "http://www.w3.org/2007/app");

                XmlNodeList workspaceList;
                workspaceList = xdoc.SelectNodes("//app:service/app:workspace", atomNsMgr);
                if (workspaceList == null)
                {
                    return(blogs);
                }

                foreach (XmlNode n in workspaceList)
                {
                    XmlNode accountTitle = n.SelectSingleNode("atom:title", atomNsMgr);
                    if (accountTitle == null)
                    {
                        System.Diagnostics.Debug.WriteLine("atom:title is null. ");
                        continue;
                    }

                    NodeCollection blog = new NodeCollection(accountTitle.InnerText);

                    NodeEntries entries = GetEntryNodesFromXML(n, atomNsMgr);
                    foreach (var item in entries.Children)
                    {
                        item.Parent = blog;
                        blog.Children.Add(item);
                    }

                    blog.Expanded = true;

                    blogs.Children.Add(blog);
                    blogs.Expanded = true;
                }
            }

            return(blogs);
        }
    private void parseResponse(string soapResult, string action)
    {
        XmlDocument doc = new XmlDocument();
        doc.LoadXml(soapResult);
        XmlNamespaceManager manager = new XmlNamespaceManager(doc.NameTable);
        manager.AddNamespace("ns", "http://www.nbrm.mk/klservice/");
        XmlNode node = doc.DocumentElement.SelectSingleNode("//ns:GetExchangeRatesResult", manager);
        string text = node.FirstChild.InnerText;

        if (text.Contains("Formatot na parametarot"))
        {
            MyPanel.Visible = true;
            MyTable.Visible = false;
            return;
        }

        MyPanel.Visible = false;
        MyTable.Visible = true;

        string[] parts = text.Split(new string[] { "<KursZbir>", "</KursZbir>" }, StringSplitOptions.None);

        MyTable.Rows.Clear();

        TableHeaderRow row = new TableHeaderRow();

        TableHeaderCell cell = new TableHeaderCell();
        cell.Text = "Date";
        cell.Style.Add("text-align", "center");
        TableHeaderCell cell1 = new TableHeaderCell();
        cell1.Text = "Currency";
        cell1.Style.Add("text-align", "center");
        TableHeaderCell cell2 = new TableHeaderCell();
        cell2.Text = "Unit";
        cell2.Style.Add("text-align", "center");
        TableHeaderCell cell3 = new TableHeaderCell();
        cell3.Text = "Buying rate";
        cell3.Style.Add("text-align", "center");
        TableHeaderCell cell4 = new TableHeaderCell();
        cell4.Text = "Average rate";
        cell4.Style.Add("text-align", "center");
        TableHeaderCell cell5 = new TableHeaderCell();
        cell5.Text = "Selling rate";
        cell5.Style.Add("text-align", "center");

        row.Cells.Add(cell);
        row.Cells.Add(cell1);
        row.Cells.Add(cell2);
        row.Cells.Add(cell3);
        row.Cells.Add(cell4);
        row.Cells.Add(cell5);

        MyTable.Rows.Add(row);

        foreach (string part in parts)
        {
            if (part.Trim().Equals("") || part.StartsWith("<dsKurs>") || part.StartsWith("</dsKurs>"))
            {
                continue;
            }

            string[] otherParts = part.Split(new string[] { "<Datum>", "</Datum>" }, StringSplitOptions.None);

            if (otherParts.Length > 0)
            {
                try
                {
                    TableRow tempRow = new TableRow();

                    string datum = otherParts[1];
                    DateTime date = Convert.ToDateTime(datum);
                    TableCell tempCell1 = new TableCell();
                    if (date.Month <= 9)
                    {
                        tempCell1.Text = date.Day + ".0" + date.Month + "." + date.Year;
                    }
                    else
                    {
                        tempCell1.Text = date.Day + "." + date.Month + "." + date.Year;
                    }
                    
                    tempCell1.Style.Add("text-align", "center");
                    tempRow.Cells.Add(tempCell1);

                    string[] partsS = otherParts[2].Split(new string[] { "<Oznaka>", "</Oznaka>" }, StringSplitOptions.None);
                    string oznaka = partsS[1];
                    TableCell tempCell = new TableCell();
                    tempCell.Text = oznaka;
                    tempCell.Style.Add("text-align", "center");
                    tempRow.Cells.Add(tempCell);

                    string[] parts2 = partsS[2].Split(new string[] { "<Nomin>", "</Nomin>" }, StringSplitOptions.None);
                    string nomin = parts2[1];
                    TableCell tempCell2 = new TableCell();
                    tempCell2.Text = nomin;
                    tempCell2.Style.Add("text-align", "center");
                    tempRow.Cells.Add(tempCell2);

                    string[] parts3 = parts2[2].Split(new string[] { "<Kupoven>", "</Kupoven>" }, StringSplitOptions.None);
                    string kupoven = parts3[1];
                    TableCell tempCell3 = new TableCell();
                    tempCell3.Text = kupoven;
                    tempCell3.Style.Add("text-align", "center");
                    tempRow.Cells.Add(tempCell3);

                    string[] parts4 = parts3[2].Split(new string[] { "<Sreden>", "</Sreden>" }, StringSplitOptions.None);
                    string sreden = parts4[1];
                    TableCell tempCell4 = new TableCell();
                    tempCell4.Text = sreden;
                    tempCell4.Style.Add("text-align", "center");
                    tempRow.Cells.Add(tempCell4);

                    string[] parts5 = parts4[2].Split(new string[] { "<Prodazen>", "</Prodazen>" }, StringSplitOptions.None);
                    string prodazen = parts5[1];
                    TableCell tempCell5 = new TableCell();
                    tempCell5.Text = prodazen;
                    tempCell5.Style.Add("text-align", "center");
                    tempRow.Cells.Add(tempCell5);

                    MyTable.Rows.Add(tempRow);

                }
                catch (Exception ex)
                {

                }
            }
        }
    }
Ejemplo n.º 40
0
        static void Main(string[] args)
        {
            var projectOutputFolder  = args[0];
            var outputFolder         = args[1];
            var wxsFile              = args[2];
            var rootDirectoryId      = args[3];
            var applicationFeatureId = args[4];

            var addedDirectories = new Dictionary <string, string>();

            var doc = new XmlDocument();

            doc.Load(wxsFile);

            var nsmgr = new XmlNamespaceManager(doc.NameTable);

            nsmgr.AddNamespace("wi", "http://schemas.microsoft.com/wix/2006/wi");
            nsmgr.AddNamespace("netfx", "http://schemas.microsoft.com/wix/NetFxExtension");

            var wixNode     = doc.SelectSingleNode("wi:Wix", nsmgr);
            var productNode = wixNode.SelectSingleNode("wi:Product", nsmgr);

            var directoryNode = productNode;

            do
            {
                directoryNode = directoryNode.SelectSingleNode("wi:Directory", nsmgr);
            }while (!directoryNode.Attributes["Id"].Value.Equals(rootDirectoryId));

            var mainDirectoryRefNode = productNode.SelectSingleNode($"wi:DirectoryRef[@Id='{rootDirectoryId}']", nsmgr);
            var featureNode          = productNode.SelectSingleNode($"wi:Feature[@Id='{applicationFeatureId}']", nsmgr);
            var rootDirectory        = new DirectoryInfo(projectOutputFolder).Name;

            foreach (var filePath in Directory.GetFiles(projectOutputFolder, "*.*", SearchOption.AllDirectories))
            {
                var fileName  = Path.GetFileName(filePath);
                var directory = new DirectoryInfo(filePath).Parent.Name;

                //Create the folder in the directory structure of the installer
                if (!directory.Equals(rootDirectory))
                {
                    var directoryId = $"directory_{directory}";

                    if (!addedDirectories.ContainsKey(directory))
                    {
                        addedDirectories.Add(directory, directoryId);

                        var newDirectoryNode = doc.CreateElement("Directory", doc.DocumentElement.NamespaceURI);
                        newDirectoryNode.RemoveAttribute("xmlns");
                        newDirectoryNode.SetAttribute("Id", directoryId);
                        newDirectoryNode.SetAttribute("Name", directory);

                        directoryNode.AppendChild(newDirectoryNode);

                        var newDirectoryRefNode = doc.CreateElement("DirectoryRef", doc.DocumentElement.NamespaceURI);
                        newDirectoryRefNode.SetAttribute("Id", directoryId);
                        newDirectoryRefNode.RemoveAttribute("xmlns");
                        mainDirectoryRefNode.ParentNode.InsertAfter(newDirectoryRefNode, mainDirectoryRefNode);
                    }

                    var directoryRefNode = productNode.SelectSingleNode($"wi:DirectoryRef[@Id='{directoryId}']", nsmgr);

                    AddComponent(doc, directoryRefNode, featureNode, fileName, directory);
                }
                else
                {
                    AddComponent(doc, mainDirectoryRefNode, featureNode, fileName, null);
                }
            }

            doc.Save(outputFolder + "\\Product.wxs");
        }
Ejemplo n.º 41
0
        public override async Task <List <EntryItem> > GetEntries(Uri entriesUrl)
        {
            List <EntryItem> list = new List <EntryItem>();

            var HTTPResponseMessage = await _HTTPConn.Client.GetAsync(entriesUrl);

            string s = await HTTPResponseMessage.Content.ReadAsStringAsync();

            System.Diagnostics.Debug.WriteLine("GET entries: " + s);

            /*
             * <?xml version="1.0" encoding="utf-8"?>
             * <feed xmlns="http://www.w3.org/2005/Atom">
             * <title type="text">dive into mark</title>
             * <subtitle type="html">
             * A &lt;em&gt;lot&lt;/em&gt; of effort
             * went into making this effortless
             * </subtitle>
             * <updated>2005-07-31T12:29:29Z</updated>
             * <id>tag:example.org,2003:3</id>
             * <link rel="alternate" type="text/html"
             * hreflang="en" href="http://example.org/"/>
             * <link rel="self" type="application/atom+xml"
             * href="http://example.org/feed.atom"/>
             * <rights>Copyright (c) 2003, Mark Pilgrim</rights>
             * <generator uri="http://www.example.com/" version="1.0">
             * Example Toolkit
             * </generator>
             * <entry>
             * <title>Atom draft-07 snapshot</title>
             * <link rel="alternate" type="text/html"
             * href="http://example.org/2005/04/02/atom"/>
             * <link rel="enclosure" type="audio/mpeg" length="1337"
             * href="http://example.org/audio/ph34r_my_podcast.mp3"/>
             * <id>tag:example.org,2003:3.2397</id>
             * <updated>2005-07-31T12:29:29Z</updated>
             * <published>2003-12-13T08:29:29-04:00</published>
             * <author>
             * <name>Mark Pilgrim</name>
             * <uri>http://example.org/</uri>
             * <email>[email protected]</email>
             * </author>
             * <contributor>
             * <name>Sam Ruby</name>
             * </contributor>
             * <contributor>
             * <name>Joe Gregorio</name>
             * </contributor>
             * <content type="xhtml" xml:lang="en"
             * xml:base="http://diveintomark.org/">
             * <div xmlns="http://www.w3.org/1999/xhtml">
             * <p><i>[Update: The Atom draft is finished.]</i></p>
             * </div>
             * </content>
             * </entry>
             * </feed>
             */

            XmlDocument xdoc = new XmlDocument();

            try
            {
                xdoc.LoadXml(s);
            }
            catch (Exception e)
            {
                System.Diagnostics.Debug.WriteLine("LoadXml failed: " + e.Message);
                return(list);
            }

            XmlNamespaceManager atomNsMgr = new XmlNamespaceManager(xdoc.NameTable);

            atomNsMgr.AddNamespace("atom", "http://www.w3.org/2005/Atom");
            atomNsMgr.AddNamespace("app", "http://www.w3.org/2007/app");


            XmlNodeList entryList;

            entryList = xdoc.SelectNodes("//atom:feed/atom:entry", atomNsMgr);
            if (entryList == null)
            {
                return(list);
            }

            foreach (XmlNode l in entryList)
            {
                EntryItem ent = new EntryItem("", this);

                FillEntryItemFromXML(ent, l, atomNsMgr);

                list.Add(ent);
            }

            return(list);
        }
Ejemplo n.º 42
0
        void Load()
        {
            using (var xmlReader = XmlReader.Create(WorkflowFilePath))
            {
                var xmlNameTable = xmlReader.NameTable;
                if (xmlNameTable != null)
                {
                    XmlNamespaceManager = new XmlNamespaceManager(xmlNameTable);
                    XmlNamespaceManager.AddNamespace("wf", "urn:wexflow-schema");
                }
                else
                {
                    throw new Exception("xmlNameTable of " + WorkflowFilePath + " is null");
                }

                // Loading settings
                var xdoc = XDocument.Load(WorkflowFilePath);
                XDoc         = xdoc;
                XNamespaceWf = "urn:wexflow-schema";

                Id          = int.Parse(GetWorkflowAttribute(xdoc, "id"));
                Name        = GetWorkflowAttribute(xdoc, "name");
                Description = GetWorkflowAttribute(xdoc, "description");
                LaunchType  = (LaunchType)Enum.Parse(typeof(LaunchType), GetWorkflowSetting(xdoc, "launchType"), true);
                if (LaunchType == LaunchType.Periodic)
                {
                    Period = TimeSpan.Parse(GetWorkflowSetting(xdoc, "period"));
                }
                IsEnabled = bool.Parse(GetWorkflowSetting(xdoc, "enabled"));

                // Loading tasks
                var tasks = new List <Task>();
                foreach (var xTask in xdoc.XPathSelectElements("/wf:Workflow/wf:Tasks/wf:Task", XmlNamespaceManager))
                {
                    var xAttribute = xTask.Attribute("name");
                    if (xAttribute != null)
                    {
                        var name         = xAttribute.Value;
                        var assemblyName = "Wexflow.Tasks." + name;
                        var typeName     = "Wexflow.Tasks." + name + "." + name + ", " + assemblyName;
                        var type         = Type.GetType(typeName);

                        if (type != null)
                        {
                            var task = (Task)Activator.CreateInstance(type, xTask, this);
                            tasks.Add(task);
                        }
                        else
                        {
                            throw new Exception("The type of the task " + name + "could not be loaded.");
                        }
                    }
                    else
                    {
                        throw new Exception("Name attribute of the task " + xTask + " does not exist.");
                    }
                }
                Taks = tasks.ToArray();

                // Loading execution graph
                var xExectionGraph = xdoc.XPathSelectElement("/wf:Workflow/wf:ExecutionGraph", XmlNamespaceManager);
                if (xExectionGraph != null)
                {
                    var taskNodes = GetTaskNodes(xExectionGraph);

                    // Check startup node, parallel tasks and infinite loops
                    if (taskNodes.Any())
                    {
                        CheckStartupNode(taskNodes, "Startup node with parentId=-1 not found in ExecutionGraph execution graph.");
                    }
                    CheckParallelTasks(taskNodes, "Parallel tasks execution detected in ExecutionGraph execution graph.");
                    CheckInfiniteLoop(taskNodes, "Infinite loop detected in ExecutionGraph execution graph.");

                    // OnSuccess
                    GraphEvent onSuccess  = null;
                    var        xOnSuccess = xExectionGraph.XPathSelectElement("wf:OnSuccess", XmlNamespaceManager);
                    if (xOnSuccess != null)
                    {
                        var onSuccessNodes = GetTaskNodes(xOnSuccess);
                        CheckStartupNode(onSuccessNodes, "Startup node with parentId=-1 not found in OnSuccess execution graph.");
                        CheckParallelTasks(onSuccessNodes, "Parallel tasks execution detected in OnSuccess execution graph.");
                        CheckInfiniteLoop(onSuccessNodes, "Infinite loop detected in OnSuccess execution graph.");
                        onSuccess = new GraphEvent(onSuccessNodes);
                    }

                    // OnWarning
                    GraphEvent onWarning  = null;
                    var        xOnWarning = xExectionGraph.XPathSelectElement("wf:OnWarning", XmlNamespaceManager);
                    if (xOnWarning != null)
                    {
                        var onWarningNodes = GetTaskNodes(xOnWarning);
                        CheckStartupNode(onWarningNodes, "Startup node with parentId=-1 not found in OnWarning execution graph.");
                        CheckParallelTasks(onWarningNodes, "Parallel tasks execution detected in OnWarning execution graph.");
                        CheckInfiniteLoop(onWarningNodes, "Infinite loop detected in OnWarning execution graph.");
                        onWarning = new GraphEvent(onWarningNodes);
                    }

                    // OnError
                    GraphEvent onError  = null;
                    var        xOnError = xExectionGraph.XPathSelectElement("wf:OnError", XmlNamespaceManager);
                    if (xOnError != null)
                    {
                        var onErrorNodes = GetTaskNodes(xOnError);
                        CheckStartupNode(onErrorNodes, "Startup node with parentId=-1 not found in OnError execution graph.");
                        CheckParallelTasks(onErrorNodes, "Parallel tasks execution detected in OnError execution graph.");
                        CheckInfiniteLoop(onErrorNodes, "Infinite loop detected in OnError execution graph.");
                        onError = new GraphEvent(onErrorNodes);
                    }

                    ExecutionGraph = new Graph(taskNodes, onSuccess, onWarning, onError);
                }
            }
        }
Ejemplo n.º 43
0
        protected override void OnDataReceived(uint dataTypeCode, byte[] data)
        {
            string chunk = Encoding.UTF8.GetString(data);

            if (this.ServerCapabilities == null)   // This must be server capabilities, old protocol
            {
                this._data.Append(chunk);

                if (!chunk.Contains(_prompt))
                {
                    return;
                }
                try
                {
                    chunk = this._data.ToString();
                    this._data.Clear();

                    this.ServerCapabilities = new XmlDocument();
                    this.ServerCapabilities.LoadXml(chunk.Replace(_prompt, ""));
                }
                catch (XmlException e)
                {
                    throw new NetConfServerException("Server capabilities received are not well formed XML", e);
                }

                XmlNamespaceManager ns = new XmlNamespaceManager(this.ServerCapabilities.NameTable);

                ns.AddNamespace("nc", "urn:ietf:params:xml:ns:netconf:base:1.0");

                this._usingFramingProtocol = (this.ServerCapabilities.SelectSingleNode("/nc:hello/nc:capabilities/nc:capability[text()='urn:ietf:params:netconf:base:1.1']", ns) != null);

                this._serverCapabilitiesConfirmed.Set();
            }
            else if (this._usingFramingProtocol)
            {
                int position = 0;

                for (; ;)
                {
                    Match match = Regex.Match(chunk.Substring(position), @"\n#(?<length>\d+)\n");
                    if (!match.Success)
                    {
                        break;
                    }
                    int fractionLength = Convert.ToInt32(match.Groups["length"].Value);
                    this._rpcReply.Append(chunk, position + match.Index + match.Length, fractionLength);
                    position += match.Index + match.Length + fractionLength;
                }
                if (Regex.IsMatch(chunk.Substring(position), @"\n##\n"))
                {
                    this._rpcReplyReceived.Set();
                }
            }
            else  // Old protocol
            {
                this._data.Append(chunk);

                if (!chunk.Contains(_prompt))
                {
                    return;
                    //throw new NetConfServerException("Server XML message does not end with the prompt " + _prompt);
                }

                chunk = this._data.ToString();
                this._data.Clear();

                this._rpcReply.Append(chunk.Replace(_prompt, ""));
                this._rpcReplyReceived.Set();
            }
        }
Ejemplo n.º 44
0
        /// <summary>
        /// Verify SvcDoc.Core.4632
        /// </summary>
        /// <param name="context">Service context</param>
        /// <param name="info">out parameter to return violation information when rule fail</param>
        /// <returns>true if rule passes; false otherwise</returns>
        public override bool?Verify(ServiceContext context, out ExtensionRuleViolationInfo info)
        {
            if (context == null)
            {
                throw new ArgumentNullException("context");
            }

            bool?passed = null;

            info = null;

            XmlDocument xmlDoc = new XmlDocument();

//            xmlDoc.LoadXml(@"<?xml version=""1.0"" encoding=""utf-8""?>
//<service xml:base=""http://services.odata.org/V4/OData/OData.svc/"" xmlns=""http://www.w3.org/2007/app"" xmlns:atom=""http://www.w3.org/2005/Atom"" xmlns:m=""http://docs.oasis-open.org/odata/ns/metadata"" m:context=""http://services.odata.org/V4/OData/OData.svc/$metadata"">
//  <workspace>
//    <atom:title type=""text"">Default</atom:title>
//    <collection href=""Products"">
//      <atom:title type=""text"">Products</atom:title>
//    </collection>
//    <collection href=""ProductDetails"">
//      <atom:title type=""text"">ProductDetails</atom:title>
//    </collection>
//    <collection href=""Categories"">
//      <atom:title type=""text"">Categories</atom:title>
//    </collection>
//    <collection href=""Suppliers"">
//      <atom:title type=""text"">Suppliers</atom:title>
//    </collection>
//    <collection href=""Persons"">
//      <atom:title type=""text"">Persons</atom:title>
//    </collection>
//    <collection href=""PersonDetails"">
//      <atom:title type=""text"">PersonDetails</atom:title>
//    </collection>
//    <collection href=""Advertisements"">
//      <atom:title type=""text"">Advertisements</atom:title>
//    </collection>
//	<m:function-import href=""TopProducts"" m:name=""TopProducts"">
//      <atom:title>Best-Selling Products</atom:title>
//    </m:function-import>
//	<m:singleton href=""ODatademo.Contoso"" m:name=""Contoso"">
//      <atom:title>Contoso Ltd.</atom:title>
//    </m:singleton>
//	<m:service-document href=""http://services.odata.org/V4/Northwind/Northwind.svc/"">
//		<atom:title>North Wind Company</atom:title>
//	</m:service-document>
//  </workspace>
//</service>");
            xmlDoc.LoadXml(context.ResponsePayload);
            XmlNamespaceManager nsmgr = new XmlNamespaceManager(xmlDoc.NameTable);

            nsmgr.AddNamespace("app", Constants.NSApp);
            nsmgr.AddNamespace("metadata", Constants.NSMetadata);
            XmlNodeList nodes = xmlDoc.SelectNodes(@"//app:workspace/metadata:service-document", nsmgr);

            if (nodes.Count > 0)
            {
                foreach (XmlNode node in nodes)
                {
                    string hrefValue = node.Attributes["href"].Value;

                    // Send request with hrefValue.
                    string   acceptHeader  = Constants.ContentTypeXml;
                    Response response      = WebHelper.Get(new Uri(hrefValue), acceptHeader, RuleEngineSetting.Instance().DefaultMaximumPayloadSize, context.RequestHeaders);
                    var      payloadFormat = response.ResponsePayload.GetFormatFromPayload();
                    var      payloadType   = ContextHelper.GetPayloadType(response.ResponsePayload, payloadFormat, response.ResponseHeaders);

                    if (payloadType == RuleEngine.PayloadType.ServiceDoc)
                    {
                        passed = true;
                    }
                    else
                    {
                        passed = false;
                        info   = new ExtensionRuleViolationInfo(this.ErrorMessage, context.Destination, context.ResponsePayload);
                        break;
                    }
                }
            }

            return(passed);
        }
Ejemplo n.º 45
0
        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("GenerateApplicationManifest", "false");              // Disable $(AndroidVersionCode) support
            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]}");
                }
            }
        }
Ejemplo n.º 46
0
        public override void LoadXml(XmlElement value)
        {
            if (value == null)
            {
                throw new ArgumentNullException(nameof(value));
            }

            XmlNamespaceManager nsm = new XmlNamespaceManager(value.OwnerDocument.NameTable);

            nsm.AddNamespace("enc", EncryptedXml.XmlEncNamespaceUrl);
            nsm.AddNamespace("ds", SignedXml.XmlDsigNamespaceUrl);

            Id        = Utils.GetAttribute(value, "Id", EncryptedXml.XmlEncNamespaceUrl);
            Type      = Utils.GetAttribute(value, "Type", EncryptedXml.XmlEncNamespaceUrl);
            MimeType  = Utils.GetAttribute(value, "MimeType", EncryptedXml.XmlEncNamespaceUrl);
            Encoding  = Utils.GetAttribute(value, "Encoding", EncryptedXml.XmlEncNamespaceUrl);
            Recipient = Utils.GetAttribute(value, "Recipient", EncryptedXml.XmlEncNamespaceUrl);

            XmlNode encryptionMethodNode = value.SelectSingleNode("enc:EncryptionMethod", nsm);

            // EncryptionMethod
            EncryptionMethod = new EncryptionMethod();
            if (encryptionMethodNode != null)
            {
                EncryptionMethod.LoadXml(encryptionMethodNode as XmlElement);
            }

            // Key Info
            KeyInfo = new KeyInfo();
            XmlNode keyInfoNode = value.SelectSingleNode("ds:KeyInfo", nsm);

            if (keyInfoNode != null)
            {
                KeyInfo.LoadXml(keyInfoNode as XmlElement);
            }

            // CipherData
            XmlNode cipherDataNode = value.SelectSingleNode("enc:CipherData", nsm);

            if (cipherDataNode == null)
            {
                throw new System.Security.Cryptography.CryptographicException(SR.Cryptography_Xml_MissingCipherData);
            }

            CipherData = new CipherData();
            CipherData.LoadXml(cipherDataNode as XmlElement);

            // EncryptionProperties
            XmlNode encryptionPropertiesNode = value.SelectSingleNode("enc:EncryptionProperties", nsm);

            if (encryptionPropertiesNode != null)
            {
                // Select the EncryptionProperty elements inside the EncryptionProperties element
                XmlNodeList encryptionPropertyNodes = encryptionPropertiesNode.SelectNodes("enc:EncryptionProperty", nsm);
                if (encryptionPropertyNodes != null)
                {
                    foreach (XmlNode node in encryptionPropertyNodes)
                    {
                        EncryptionProperty ep = new EncryptionProperty();
                        ep.LoadXml(node as XmlElement);
                        EncryptionProperties.Add(ep);
                    }
                }
            }

            // CarriedKeyName
            XmlNode carriedKeyNameNode = value.SelectSingleNode("enc:CarriedKeyName", nsm);

            if (carriedKeyNameNode != null)
            {
                CarriedKeyName = carriedKeyNameNode.InnerText;
            }

            // ReferenceList
            XmlNode referenceListNode = value.SelectSingleNode("enc:ReferenceList", nsm);

            if (referenceListNode != null)
            {
                // Select the DataReference elements inside the ReferenceList element
                XmlNodeList dataReferenceNodes = referenceListNode.SelectNodes("enc:DataReference", nsm);
                if (dataReferenceNodes != null)
                {
                    foreach (XmlNode node in dataReferenceNodes)
                    {
                        DataReference dr = new DataReference();
                        dr.LoadXml(node as XmlElement);
                        ReferenceList.Add(dr);
                    }
                }
                // Select the KeyReference elements inside the ReferenceList element
                XmlNodeList keyReferenceNodes = referenceListNode.SelectNodes("enc:KeyReference", nsm);
                if (keyReferenceNodes != null)
                {
                    foreach (XmlNode node in keyReferenceNodes)
                    {
                        KeyReference kr = new KeyReference();
                        kr.LoadXml(node as XmlElement);
                        ReferenceList.Add(kr);
                    }
                }
            }

            // Save away the cached value
            _cachedXml = value;
        }
Ejemplo n.º 47
0
        public override IEnumerable <dynamic> ParseContent(object content)
        {
            var xmlContent = content as string;

            if (xmlContent == null)
            {
                return(null);
            }
            const string ATOM         = "atom";
            const string COMPANY_INFO = ATOM + ":company-info";

            var filingXml = new XmlDocument();

            filingXml.LoadXml(xmlContent);

            if (!filingXml.HasChildNodes)
            {
                return(null);
            }
            var nsMgr = new XmlNamespaceManager(filingXml.NameTable);

            nsMgr.AddNamespace(ATOM, Edgar.ATOM_XML_NS);

            var cik     = string.Empty;
            var sic     = string.Empty;
            var name    = string.Empty;
            var st      = string.Empty;
            var sicDesc = string.Empty;
            var fiEnd   = string.Empty;

            var cikNode = filingXml.SelectSingleNode("//" + COMPANY_INFO + "/" + ATOM + ":cik", nsMgr);

            if (cikNode != null)
            {
                cik = cikNode.InnerText;
            }

            var sicNode = filingXml.SelectSingleNode("//" + COMPANY_INFO + "/" + ATOM + ":assigned-sic", nsMgr);

            if (sicNode != null)
            {
                sic = sicNode.InnerText;
            }

            var nameNode = filingXml.SelectSingleNode("//" + COMPANY_INFO + "/" + ATOM + ":conformed-name", nsMgr);

            if (nameNode != null)
            {
                name = nameNode.InnerText;
            }

            var stateNode = filingXml.SelectSingleNode("//" + COMPANY_INFO + "/" + ATOM + ":state-of-incorporation",
                                                       nsMgr);

            if (stateNode != null)
            {
                st = stateNode.InnerText;
            }
            else
            {
                stateNode = filingXml.SelectSingleNode("//" + COMPANY_INFO + "/" + ATOM + ":state-location", nsMgr);
                if (stateNode != null)
                {
                    st = stateNode.InnerText;
                }
            }

            var sicDescNode = filingXml.SelectSingleNode("//" + COMPANY_INFO + "/" + ATOM + ":assigned-sic-desc", nsMgr);

            if (sicDescNode != null)
            {
                sicDesc = sicDescNode.InnerText;
            }

            var fiEndNode = filingXml.SelectSingleNode("//" + COMPANY_INFO + "/" + ATOM + ":fiscal-year-end", nsMgr);

            if (fiEndNode != null)
            {
                fiEnd = fiEndNode.InnerText;
            }

            var bizAddrNode =
                filingXml.SelectSingleNode(
                    "//" + COMPANY_INFO + "/" + ATOM + ":addresses/" + ATOM + ":address[@type='business']", nsMgr);
            var mailAddrNode =
                filingXml.SelectSingleNode(
                    "//" + COMPANY_INFO + "/" + ATOM + ":addresses/" + ATOM + ":address[@type='mailing']", nsMgr);

            var bizSt    = string.Empty;
            var bizCity  = string.Empty;
            var bizState = string.Empty;
            var bizZip   = string.Empty;
            var bizPhone = string.Empty;

            if (bizAddrNode != null && bizAddrNode.HasChildNodes)
            {
                var addrStreet =
                    filingXml.SelectSingleNode(
                        "//" + ATOM + ":company-info/" + ATOM + ":addresses/" + ATOM + ":address[@type='business']/" +
                        ATOM + ":street1", nsMgr);
                if (addrStreet != null)
                {
                    bizSt = addrStreet.InnerText;
                }

                var addrCity =
                    filingXml.SelectSingleNode(
                        "//" + ATOM + ":company-info/" + ATOM + ":addresses/" + ATOM + ":address[@type='business']/" +
                        ATOM + ":city", nsMgr);
                if (addrCity != null)
                {
                    bizCity = addrCity.InnerText;
                }

                var addrState =
                    filingXml.SelectSingleNode(
                        "//" + ATOM + ":company-info/" + ATOM + ":addresses/" + ATOM + ":address[@type='business']/" +
                        ATOM + ":state", nsMgr);
                if (addrState != null)
                {
                    bizState = addrState.InnerText;
                }

                var addrZip =
                    filingXml.SelectSingleNode(
                        "//" + ATOM + ":company-info/" + ATOM + ":addresses/" + ATOM + ":address[@type='business']/" +
                        ATOM + ":zip", nsMgr);
                if (addrZip != null)
                {
                    bizZip = addrZip.InnerText;
                }

                var addrPh =
                    filingXml.SelectSingleNode(
                        "//" + ATOM + ":company-info/" + ATOM + ":addresses/" + ATOM + ":address[@type='business']/" +
                        ATOM + ":phone", nsMgr);
                if (addrPh != null)
                {
                    bizPhone = addrPh.InnerText;
                }
            }
            var mailSt    = string.Empty;
            var mailCity  = string.Empty;
            var mailState = string.Empty;
            var mailZip   = string.Empty;
            var mailPhone = string.Empty;

            if (mailAddrNode != null && mailAddrNode.HasChildNodes)
            {
                var addrStreet =
                    filingXml.SelectSingleNode(
                        "//" + ATOM + ":company-info/" + ATOM + ":addresses/" + ATOM + ":address[@type='mailing']/" +
                        ATOM + ":street1", nsMgr);
                if (addrStreet != null)
                {
                    mailSt = addrStreet.InnerText;
                }

                var addrCity =
                    filingXml.SelectSingleNode(
                        "//" + ATOM + ":company-info/" + ATOM + ":addresses/" + ATOM + ":address[@type='mailing']/" +
                        ATOM + ":city", nsMgr);
                if (addrCity != null)
                {
                    mailCity = addrCity.InnerText;
                }

                var addrState =
                    filingXml.SelectSingleNode(
                        "//" + ATOM + ":company-info/" + ATOM + ":addresses/" + ATOM + ":address[@type='mailing']/" +
                        ATOM + ":state", nsMgr);
                if (addrState != null)
                {
                    mailState = addrState.InnerText;
                }

                var addrZip =
                    filingXml.SelectSingleNode(
                        "//" + ATOM + ":company-info/" + ATOM + ":addresses/" + ATOM + ":address[@type='mailing']/" +
                        ATOM + ":zip", nsMgr);
                if (addrZip != null)
                {
                    mailZip = addrZip.InnerText;
                }

                var addrPh =
                    filingXml.SelectSingleNode(
                        "//" + ATOM + ":company-info/" + ATOM + ":addresses/" + ATOM + ":address[@type='mailing']/" +
                        ATOM + ":phone", nsMgr);
                if (addrPh != null)
                {
                    mailPhone = addrPh.InnerText;
                }
            }
            var formerNamesNode = filingXml.SelectSingleNode("//" + COMPANY_INFO + "/" + ATOM + ":formerly-names", nsMgr);
            var formerNames     = new List <dynamic>();

            if (formerNamesNode != null && formerNamesNode.HasChildNodes)
            {
                foreach (var names in formerNamesNode.ChildNodes)
                {
                    var namesNode = names as XmlElement;
                    if (namesNode == null || !namesNode.HasChildNodes)
                    {
                        continue;
                    }

                    var formerNameValue = string.Empty;
                    var formerNameDate  = string.Empty;
                    var firstChild      = namesNode.FirstChild;
                    if (firstChild != null)
                    {
                        formerNameDate = firstChild.InnerText;
                    }

                    var secondChild = firstChild.NextSibling;
                    if (secondChild != null)
                    {
                        formerNameValue = secondChild.InnerText;
                    }
                    formerNames.Add(new { FormerName = formerNameValue, FormerDate = formerNameDate });
                }
            }

            return(new List <dynamic>
            {
                new
                {
                    Name = name,
                    Cik = cik,
                    Sic = sic,
                    IncorpState = st,
                    SicDesc = sicDesc,
                    FiscalYearEnd = fiEnd,
                    BizAddrStreet = bizSt,
                    BizAddrCity = bizCity,
                    BizAddrState = bizState,
                    BizPostalCode = bizZip,
                    BizPhone = bizPhone,
                    MailAddrStreet = mailSt,
                    MailAddrCity = mailCity,
                    MailAddrState = mailState,
                    MailPostalCode = mailZip,
                    MailPhone = mailPhone,
                    FormerNames = formerNames
                }
            });
        }
Ejemplo n.º 48
0
        /// <summary>
        /// Gets currency live rates
        /// </summary>
        /// <param name="exchangeRateCurrencyCode">Exchange rate currency code</param>
        /// <returns>Exchange rates</returns>
        public IList <ExchangeRate> GetCurrencyLiveRates(string exchangeRateCurrencyCode)
        {
            var    exchangeRates = new List <ExchangeRate>();
            string url           = string.Format("http://themoneyconverter.com/rss-feed/{0}/rss.xml", exchangeRateCurrencyCode);

            var request = WebRequest.Create(url) as HttpWebRequest;

            using (var response = request.GetResponse()) {
                var xmlDoc = new XmlDocument();
                xmlDoc.Load(response.GetResponseStream());
                var nsmgr = new XmlNamespaceManager(xmlDoc.NameTable);
                nsmgr.AddNamespace("atom", "http://www.w3.org/2005/Atom");
                nsmgr.AddNamespace("cf", "http://www.microsoft.com/schemas/rss/core/2005");
                nsmgr.AddNamespace("cfi", "http://www.microsoft.com/schemas/rss/core/2005/internal");

                foreach (XmlNode node in xmlDoc.DocumentElement.FirstChild.ChildNodes)
                {
                    if (node.Name == "item")
                    {
                        /*
                         *              <item>
                         *                <title xmlns:cf="http://www.microsoft.com/schemas/rss/core/2005" cf:type="text">AED/NZD</title>
                         *                <link>http://themoneyconverter.com/NZD/AED.aspx</link>
                         *                <guid>http://themoneyconverter.com/NZD/AED.aspx</guid>
                         *                <pubDate>Fri, 20 Feb 2009 08:01:41 GMT</pubDate>
                         *                <atom:published xmlns:atom="http://www.w3.org/2005/Atom">2009-02-20T08:01:41Z</atom:published>
                         *                <atom:updated xmlns:atom="http://www.w3.org/2005/Atom">2009-02-20T08:01:41Z</atom:updated>
                         *                <description xmlns:cf="http://www.microsoft.com/schemas/rss/core/2005" cf:type="html">1 New Zealand Dollar = 1.84499 Arab Emirates Dirham</description>
                         *                <category>Middle-East</category>
                         *                <cfi:id>32</cfi:id>
                         *                <cfi:effectiveId>1074571199</cfi:effectiveId>
                         *                <cfi:read>true</cfi:read>
                         *                <cfi:downloadurl>http://themoneyconverter.com/NZD/rss.xml</cfi:downloadurl>
                         *                <cfi:lastdownloadtime>2009-02-20T08:05:27.168Z</cfi:lastdownloadtime>
                         *              </item>
                         */
                        try {
                            var rate = new ExchangeRate();
                            foreach (XmlNode detailNode in node.ChildNodes)
                            {
                                switch (detailNode.Name)
                                {
                                case "title":
                                    rate.CurrencyCode = detailNode.InnerText.Substring(0, 3);
                                    break;

                                case "pubDate":
                                    rate.UpdatedOn = DateTime.Parse(detailNode.InnerText, CultureInfo.InvariantCulture);
                                    break;

                                case "description":
                                    string description = detailNode.InnerText;
                                    int    x           = description.IndexOf('=');
                                    int    y           = description.IndexOf(' ', x + 2);

                                    //          1         2         3         4
                                    //01234567890123456789012345678901234567890
                                    // 1 New Zealand Dollar = 0.78815 Australian Dollar
                                    // x = 21
                                    // y = 30
                                    string rateText = description.Substring(x + 1, y - x - 1).Trim();
                                    rate.Rate = decimal.Parse(rateText, CultureInfo.InvariantCulture);
                                    break;

                                default:
                                    break;
                                }
                            }

                            // Update the Rate in the collection if its already in there
                            if (rate.CurrencyCode != null)
                            {
                                exchangeRates.Add(rate);
                            }
                        }
                        catch (Exception exc) {
                            _logger.Warning(string.Format("Error parsing currency rates (MC): {0}", exc.Message), exc);
                        }
                    }             // if node is an item
                }                 // foreach child node under <channel>
            }

            return(exchangeRates);
        }
        /// <summary>
        /// Processes the request.
        /// </summary>
        /// <param name="server">The <see cref="WebDavServer" /> through which the request came in from the client.</param>
        /// <param name="context">The
        /// <see cref="IHttpListenerContext" /> object containing both the request and response
        /// objects to use.</param>
        /// <param name="store">The <see cref="IWebDavStore" /> that the <see cref="WebDavServer" /> is hosting.</param>
        public void ProcessRequest(WebDavServer server, IHttpListenerContext context, IWebDavStore store)
        {
            ILog log = LogManager.GetCurrentClassLogger();

            /***************************************************************************************************
            * Retreive al the information from the request
            ***************************************************************************************************/

            // Get the URI to the location
            Uri requestUri = context.Request.Url;

            // Initiate the XmlNamespaceManager and the XmlNodes
            XmlNamespaceManager manager  = null;
            XmlNode             propNode = null;

            // try to read the body
            try
            {
                StreamReader reader      = new StreamReader(context.Request.InputStream, Encoding.UTF8);
                string       requestBody = reader.ReadToEnd();

                if (!String.IsNullOrEmpty(requestBody))
                {
                    XmlDocument requestDocument = new XmlDocument();
                    requestDocument.LoadXml(requestBody);

                    if (requestDocument.DocumentElement != null)
                    {
                        if (requestDocument.DocumentElement.LocalName != "propertyupdate")
                        {
                            log.Debug("PROPPATCH method without propertyupdate element in xml document");
                        }

                        manager = new XmlNamespaceManager(requestDocument.NameTable);
                        manager.AddNamespace("D", "DAV:");
                        manager.AddNamespace("Office", "schemas-microsoft-com:office:office");
                        manager.AddNamespace("Repl", "http://schemas.microsoft.com/repl/");
                        manager.AddNamespace("Z", "urn:schemas-microsoft-com:");

                        propNode = requestDocument.DocumentElement.SelectSingleNode("D:set/D:prop", manager);
                    }
                }
            }
            catch (Exception ex)
            {
                log.Warn(ex.Message);
            }

            /***************************************************************************************************
            * Take action
            ***************************************************************************************************/

            // Get the parent collection of the item
            IWebDavStoreCollection collection = GetParentCollection(server, store, context.Request.Url);

            // Get the item from the collection
            IWebDavStoreItem item = GetItemFromCollection(collection, context.Request.Url);

            FileInfo fileInfo = new FileInfo(item.ItemPath);

            if (propNode != null && fileInfo.Exists)
            {
                foreach (XmlNode node in propNode.ChildNodes)
                {
                    switch (node.LocalName)
                    {
                    case "Win32CreationTime":
                        fileInfo.CreationTime = Convert.ToDateTime(node.InnerText).ToUniversalTime();
                        break;

                    case "Win32LastAccessTime":
                        fileInfo.LastAccessTime = Convert.ToDateTime(node.InnerText).ToUniversalTime();
                        break;

                    case "Win32LastModifiedTime":
                        fileInfo.LastWriteTime = Convert.ToDateTime(node.InnerText).ToUniversalTime();
                        break;

                    case "Win32FileAttributes":
                        //fileInfo.Attributes =
                        //fileInfo.Attributes = Convert.ToDateTime(node.InnerText);
                        break;
                    }
                }
            }


            /***************************************************************************************************
            * Create the body for the response
            ***************************************************************************************************/

            // Create the basic response XmlDocument
            XmlDocument  responseDoc = new XmlDocument();
            const string responseXml = "<?xml version=\"1.0\" encoding=\"utf-8\" ?><D:multistatus " +
                                       "xmlns:Z=\"urn:schemas-microsoft-com:\" xmlns:D=\"DAV:\">" +
                                       "<D:response></D:response></D:multistatus>";

            responseDoc.LoadXml(responseXml);

            // Select the response node
            XmlNode responseNode = responseDoc.DocumentElement.SelectSingleNode("D:response", manager);

            // Add the elements

            // The href element
            WebDavProperty hrefProperty = new WebDavProperty("href", requestUri.ToString());

            responseNode.AppendChild(hrefProperty.ToXmlElement(responseDoc));

            // The propstat element
            WebDavProperty propstatProperty = new WebDavProperty("propstat", "");
            XmlElement     propstatElement  = propstatProperty.ToXmlElement(responseDoc);

            // The propstat/status element
            WebDavProperty statusProperty = new WebDavProperty("status", "HTTP/1.1 " + context.Response.StatusCode + " " +
                                                               HttpWorkerRequest.GetStatusDescription(context.Response.StatusCode));

            propstatElement.AppendChild(statusProperty.ToXmlElement(responseDoc));

            // The other propstat children
            foreach (WebDavProperty property in from XmlNode child in propNode.ChildNodes
                     where child.Name.ToLower()
                     .Contains("creationtime") || child.Name.ToLower()
                     .Contains("fileattributes") || child.Name.ToLower()
                     .Contains("lastaccesstime") || child.Name.ToLower()
                     .Contains("lastmodifiedtime")
                     let node = propNode.SelectSingleNode(child.Name, manager)
                                select node != null
                    ? new WebDavProperty(child.LocalName, "", node.NamespaceURI)
                    : new WebDavProperty(child.LocalName, "", ""))
            {
                propstatElement.AppendChild(property.ToXmlElement(responseDoc));
            }

            responseNode.AppendChild(propstatElement);

            /***************************************************************************************************
            * Send the response
            ***************************************************************************************************/

            // convert the StringBuilder
            string resp = responseDoc.InnerXml;

            byte[] responseBytes = Encoding.UTF8.GetBytes(resp);


            // HttpStatusCode doesn't contain WebDav status codes, but HttpWorkerRequest can handle these WebDav status codes
            context.Response.StatusCode        = (int)WebDavStatusCode.MultiStatus;
            context.Response.StatusDescription = HttpWorkerRequest.GetStatusDescription((int)WebDavStatusCode.MultiStatus);

            // set the headers of the response
            context.Response.ContentLength64             = responseBytes.Length;
            context.Response.AdaptedInstance.ContentType = "text/xml";

            // the body
            context.Response.OutputStream.Write(responseBytes, 0, responseBytes.Length);

            context.Response.Close();
        }
Ejemplo n.º 50
0
        private void ServicesReceived(IAsyncResult result)
        {
            HttpWebResponse response = null;

            try
            {
                int            abortCount  = 0;
                int            bytesRead   = 0;
                byte[]         buffer      = new byte[10240];
                StringBuilder  servicesXml = new StringBuilder();
                XmlDocument    xmldoc      = new XmlDocument();
                HttpWebRequest request     = result.AsyncState as HttpWebRequest;
                response = request.EndGetResponse(result) as HttpWebResponse;
                Stream s = response.GetResponseStream();

                if (response.StatusCode != HttpStatusCode.OK)
                {
                    NatUtility.Log("{0}: Couldn't get services list: {1}", HostEndPoint, response.StatusCode);
                    return;                     // FIXME: This the best thing to do??
                }

                while (true)
                {
                    bytesRead = s.Read(buffer, 0, buffer.Length);
                    servicesXml.Append(Encoding.UTF8.GetString(buffer, 0, bytesRead));
                    try
                    {
                        xmldoc.LoadXml(servicesXml.ToString());
                        response.Close();
                        break;
                    }
                    catch (XmlException)
                    {
                        // If we can't receive the entire XML within 500ms, then drop the connection
                        // Unfortunately not all routers supply a valid ContentLength (mine doesn't)
                        // so this hack is needed to keep testing our recieved data until it gets successfully
                        // parsed by the xmldoc. Without this, the code will never pick up my router.
                        if (abortCount++ > 50)
                        {
                            response.Close();
                            return;
                        }
                        NatUtility.Log("{0}: Couldn't parse services list", HostEndPoint);
                        System.Threading.Thread.Sleep(10);
                    }
                }

                NatUtility.Log("{0}: Parsed services list", HostEndPoint);
                XmlNamespaceManager ns = new XmlNamespaceManager(xmldoc.NameTable);
                ns.AddNamespace("ns", "urn:schemas-upnp-org:device-1-0");
                XmlNodeList nodes = xmldoc.SelectNodes("//*/ns:serviceList", ns);

                foreach (XmlNode node in nodes)
                {
                    //Go through each service there
                    foreach (XmlNode service in node.ChildNodes)
                    {
                        //If the service is a WANIPConnection, then we have what we want
                        string type = service["serviceType"].InnerText;
                        NatUtility.Log("{0}: Found service: {1}", HostEndPoint, type);
                        StringComparison c = StringComparison.OrdinalIgnoreCase;
                        if (type.Equals(this.serviceType, c))
                        {
                            this.controlUrl = service["controlURL"].InnerText;
                            NatUtility.Log("{0}: Found upnp service at: {1}", HostEndPoint, controlUrl);
                            try
                            {
                                Uri u = new Uri(controlUrl);
                                if (u.IsAbsoluteUri)
                                {
                                    EndPoint old = hostEndPoint;
                                    this.hostEndPoint = new IPEndPoint(IPAddress.Parse(u.Host), u.Port);
                                    NatUtility.Log("{0}: Absolute URI detected. Host address is now: {1}", old, HostEndPoint);
                                    this.controlUrl = controlUrl.Substring(u.GetLeftPart(UriPartial.Authority).Length);
                                    NatUtility.Log("{0}: New control url: {1}", HostEndPoint, controlUrl);
                                }
                            }
                            catch
                            {
                                NatUtility.Log("{0}: Assuming control Uri is relative: {1}", HostEndPoint, controlUrl);
                            }
                            NatUtility.Log("{0}: Handshake Complete", HostEndPoint);
                            this.callback(this);
                            return;
                        }
                    }
                }

                //If we get here, it means that we didn't get WANIPConnection service, which means no uPnP forwarding
                //So we don't invoke the callback, so this device is never added to our lists
            }
            catch (WebException ex)
            {
                // Just drop the connection, FIXME: Should i retry?
                NatUtility.Log("{0}: Device denied the connection attempt: {1}", HostEndPoint, ex);
            }
            finally
            {
                if (response != null)
                {
                    response.Close();
                }
            }
        }
 protected override void RegisterXmlNamespaces(XmlNamespaceManager namespaceManager)
 {
     namespaceManager.AddNamespace("log4net", "urn:log4net");
 }
Ejemplo n.º 52
0
        static XmlDocument signDocument(X509Certificate2 certificate, MemoryStream stream, String correlationId)
        {
            var         signable = Encoding.UTF8.GetString(stream.ToArray());
            XmlDocument doc      = new XmlDocument();

            //Preserve white space for readability.
            doc.PreserveWhitespace = true;
            //Load the file.
            doc.LoadXml(signable);

            var signedXml = new SignedSOAPRequest(doc);

            var key = certificate.GetRSAPrivateKey();

            signedXml.SigningKey = key;
            signedXml.SignedInfo.CanonicalizationMethod = SignedXml.XmlDsigExcC14NTransformUrl;
            signedXml.SignedInfo.SignatureMethod        = SignedXml.XmlDsigRSASHA1Url;

            KeyInfo         keyInfo  = new KeyInfo();
            KeyInfoX509Data x509data = new KeyInfoX509Data(certificate);

            keyInfo.AddClause(x509data);
            signedXml.KeyInfo = keyInfo;

            Reference reference0 = new Reference();

            reference0.Uri = "#_0";
            var t0 = new XmlDsigExcC14NTransform();

            reference0.AddTransform(t0);
            reference0.DigestMethod = SignedXml.XmlDsigSHA1Url;
            signedXml.AddReference(reference0);
            signedXml.ComputeSignature();
            XmlElement xmlDigitalSignature = signedXml.GetXml();

            XmlNode info = null;

            for (int i = 0; i < xmlDigitalSignature.ChildNodes.Count; i++)
            {
                var node = xmlDigitalSignature.ChildNodes[i];
                if (node.Name == "KeyInfo")
                {
                    info = node;
                    break;
                }
            }
            info.RemoveAll();

            XmlElement securityTokenReference = doc.CreateElement("o", "SecurityTokenReference", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd");
            XmlElement reference = doc.CreateElement("o", "Reference", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd");

            reference.SetAttribute("ValueType", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-x509-token-profile-1.0#X509v3");
            reference.SetAttribute("URI", "#" + correlationId);
            securityTokenReference.AppendChild(reference);
            info.AppendChild(securityTokenReference);
            var nsmgr = new XmlNamespaceManager(doc.NameTable);

            nsmgr.AddNamespace("o", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd");
            nsmgr.AddNamespace("s", "http://schemas.xmlsoap.org/soap/envelope/");
            var security_node = doc.SelectSingleNode("/s:Envelope/s:Header/o:Security", nsmgr);

            security_node.AppendChild(xmlDigitalSignature);
            return(doc);
        }
Ejemplo n.º 53
0
        XmlElement VerifyInput2(MessageBuffer buf)
        {
            Message      msg2 = buf.CreateMessage();
            StringWriter sw   = new StringWriter();

            using (XmlDictionaryWriter w = XmlDictionaryWriter.CreateDictionaryWriter(XmlWriter.Create(sw))) {
                msg2.WriteMessage(w);
            }
            XmlDocument doc = new XmlDocument();

            doc.PreserveWhitespace = true;
            doc.LoadXml(sw.ToString());

            // decrypt the key with service certificate privkey
            PaddingMode  mode   = PaddingMode.PKCS7;          // not sure which is correct ... ANSIX923, ISO10126, PKCS7, Zeros, None.
            EncryptedXml encXml = new EncryptedXml(doc);

            encXml.Padding = mode;
            X509Certificate2    cert2 = new X509Certificate2(TestResourceHelper.GetFullPathOfResource("Test/Resources/test.pfx"), "mono");
            XmlNamespaceManager nsmgr = new XmlNamespaceManager(doc.NameTable);

            nsmgr.AddNamespace("s", "http://www.w3.org/2003/05/soap-envelope");
            nsmgr.AddNamespace("c", "http://schemas.xmlsoap.org/ws/2005/02/sc");
            nsmgr.AddNamespace("o", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd");
            nsmgr.AddNamespace("e", "http://www.w3.org/2001/04/xmlenc#");
            nsmgr.AddNamespace("dsig", "http://www.w3.org/2000/09/xmldsig#");
            XmlNode n = doc.SelectSingleNode("//o:Security/e:EncryptedKey/e:CipherData/e:CipherValue", nsmgr);

            Assert.IsNotNull(n, "premise: enckey does not exist");
            string raw = n.InnerText;

            byte [] rawbytes             = Convert.FromBase64String(raw);
            RSACryptoServiceProvider rsa = (RSACryptoServiceProvider)cert2.PrivateKey;

            byte [] decryptedKey = EncryptedXml.DecryptKey(rawbytes, rsa, true);             //rsa.Decrypt (rawbytes, true);

#if false
            // create derived keys
            Dictionary <string, byte[]>  keys = new Dictionary <string, byte[]> ();
            InMemorySymmetricSecurityKey skey =
                new InMemorySymmetricSecurityKey(decryptedKey);
            foreach (XmlElement el in doc.SelectNodes("//o:Security/c:DerivedKeyToken", nsmgr))
            {
                n = el.SelectSingleNode("c:Offset", nsmgr);
                int offset = (n == null) ? 0 :
                             int.Parse(n.InnerText, CultureInfo.InvariantCulture);
                n = el.SelectSingleNode("c:Length", nsmgr);
                int length = (n == null) ? 32 :
                             int.Parse(n.InnerText, CultureInfo.InvariantCulture);
                n = el.SelectSingleNode("c:Label", nsmgr);
                byte [] label = (n == null) ? decryptedKey :
                                Convert.FromBase64String(n.InnerText);
                n = el.SelectSingleNode("c:Nonce", nsmgr);
                byte [] nonce = (n == null) ? new byte [0] :
                                Convert.FromBase64String(n.InnerText);
                byte [] derkey = skey.GenerateDerivedKey(
                    //SecurityAlgorithms.Psha1KeyDerivation,
                    "http://schemas.xmlsoap.org/ws/2005/02/sc/dk/p_sha1",
// FIXME: maybe due to the label, this key resolution somehow does not seem to work.
                    label,
                    nonce,
                    length * 8,
                    offset);

                keys [el.GetAttribute("Id", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd")] = derkey;
            }
#endif

            // decrypt the signature with the decrypted key
#if true
            n = doc.SelectSingleNode("//o:Security/e:EncryptedData/e:CipherData/e:CipherValue", nsmgr);
            Assert.IsNotNull(n, "premise: encdata does not exist");
            raw      = n.InnerText;
            rawbytes = Convert.FromBase64String(raw);
            Rijndael aes = RijndaelManaged.Create();
//			aes.Key = keys [n.SelectSingleNode ("../../dsig:KeyInfo/o:SecurityTokenReference/o:Reference/@URI", nsmgr).InnerText.Substring (1)];
            aes.Key     = decryptedKey;
            aes.Mode    = CipherMode.CBC;
            aes.Padding = mode;
            MemoryStream ms = new MemoryStream();
            CryptoStream cs = new CryptoStream(ms, aes.CreateDecryptor(), CryptoStreamMode.Write);
            cs.Write(rawbytes, 0, rawbytes.Length);
            cs.Close();
            byte [] decryptedSignature = ms.ToArray();
#else
            Rijndael aes = RijndaelManaged.Create();
//			aes.Key = keys [n.SelectSingleNode ("../../dsig:KeyInfo/o:SecurityTokenReference/o:Reference/@URI", nsmgr).InnerText.Substring (1)];
            aes.Key     = decryptedKey;
            aes.Mode    = CipherMode.CBC;
            aes.Padding = mode;

            EncryptedData ed = new EncryptedData();
            n = doc.SelectSingleNode("//o:Security/e:EncryptedData", nsmgr);
            Assert.IsNotNull(n, "premise: encdata does not exist");
            ed.LoadXml(n as XmlElement);
            byte [] decryptedSignature = encXml.DecryptData(ed, aes);
#endif
//Console.Error.WriteLine (Encoding.UTF8.GetString (decryptedSignature));
//Console.Error.WriteLine ("============= Decrypted Signature End ===========");

            // decrypt the body with the decrypted key
#if true
            n = doc.SelectSingleNode("//s:Body/e:EncryptedData/e:CipherData/e:CipherValue", nsmgr);
            Assert.IsNotNull(n, "premise: encdata does not exist");
            raw      = n.InnerText;
            rawbytes = Convert.FromBase64String(raw);
//			aes.Key = keys [n.SelectSingleNode ("../../dsig:KeyInfo/o:SecurityTokenReference/o:Reference/@URI", nsmgr).InnerText.Substring (1)];
            aes.Key = decryptedKey;
            ms      = new MemoryStream();
            cs      = new CryptoStream(ms, aes.CreateDecryptor(), CryptoStreamMode.Write);
            cs.Write(rawbytes, 0, rawbytes.Length);
            cs.Close();
            byte [] decryptedBody = ms.ToArray();
#else
            // decrypt the body with the decrypted key
            EncryptedData ed2 = new EncryptedData();
            XmlElement    el  = doc.SelectSingleNode("/s:Envelope/s:Body/e:EncryptedData", nsmgr) as XmlElement;
            ed2.LoadXml(el);
//			aes.Key = keys [n.SelectSingleNode ("../../dsig:KeyInfo/o:SecurityTokenReference/o:Reference/@URI", nsmgr).InnerText.Substring (1)];
            aes.Key = decryptedKey;
            byte [] decryptedBody = encXml.DecryptData(ed2, aes);
#endif
//foreach (byte b in decryptedBody) Console.Error.Write ("{0:X02} ", b);
            Console.Error.WriteLine(Encoding.UTF8.GetString(decryptedBody));
            Console.Error.WriteLine("============= Decrypted Body End ===========");

            // FIXME: find out what first 16 bytes mean.
            for (int mmm = 0; mmm < 16; mmm++)
            {
                decryptedBody [mmm] = 0x20;
            }
            doc.LoadXml(Encoding.UTF8.GetString(decryptedBody));
            Assert.AreEqual("RequestSecurityToken", doc.DocumentElement.LocalName, "#b-1");
            Assert.AreEqual("http://schemas.xmlsoap.org/ws/2005/02/trust", doc.DocumentElement.NamespaceURI, "#b-2");

            return(doc.DocumentElement);
        }
Ejemplo n.º 54
0
        public override string ToText(Subtitle subtitle, string title)
        {
            var ss = Configuration.Settings.SubtitleSettings;

            if (!string.IsNullOrEmpty(ss.CurrentDCinemaEditRate))
            {
                string[] temp = ss.CurrentDCinemaEditRate.Split(" ".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
                double   d1, d2;
                if (temp.Length == 2 && double.TryParse(temp[0], out d1) && double.TryParse(temp[1], out d2))
                {
                    frameRate = d1 / d2;
                }
            }

            string xmlStructure =
                "<dcst:SubtitleReel xmlns:dcst=\"http://www.smpte-ra.org/schemas/428-7/2007/DCST\" xmlns:xs=\"http://www.w3.org/2001/XMLSchema\">" + Environment.NewLine +
                "  <dcst:Id>urn:uuid:7be835a3-cfb4-43d0-bb4b-f0b4c95e962e</dcst:Id>" + Environment.NewLine +
                "  <dcst:ContentTitleText></dcst:ContentTitleText> " + Environment.NewLine +
                "  <dcst:AnnotationText>This is a subtitle file</dcst:AnnotationText>" + Environment.NewLine +
                "  <dcst:IssueDate>2012-06-26T12:33:59.000-00:00</dcst:IssueDate>" + Environment.NewLine +
                "  <dcst:ReelNumber>1</dcst:ReelNumber>" + Environment.NewLine +
                "  <dcst:Language>en</dcst:Language>" + Environment.NewLine +
                "  <dcst:EditRate>25 1</dcst:EditRate>" + Environment.NewLine +
                "  <dcst:TimeCodeRate>25</dcst:TimeCodeRate>" + Environment.NewLine +
                "  <dcst:StartTime>00:00:00:00</dcst:StartTime> " + Environment.NewLine +
                "  <dcst:LoadFont ID=\"theFontId\">urn:uuid:3dec6dc0-39d0-498d-97d0-928d2eb78391</dcst:LoadFont>" + Environment.NewLine +
                "  <dcst:SubtitleList>" + Environment.NewLine +
                "    <dcst:Font ID=\"theFontId\" Size=\"39\" Weight=\"normal\" Color=\"FFFFFFFF\" Effect=\"border\" EffectColor=\"FF000000\">" + Environment.NewLine +
                "    </dcst:Font>" + Environment.NewLine +
                "  </dcst:SubtitleList>" + Environment.NewLine +
                "</dcst:SubtitleReel>";

            var xml = new XmlDocument();

            xml.LoadXml(xmlStructure);
            xml.PreserveWhitespace = true;
            var nsmgr = new XmlNamespaceManager(xml.NameTable);

            nsmgr.AddNamespace("dcst", xml.DocumentElement.NamespaceURI);

            if (string.IsNullOrEmpty(ss.CurrentDCinemaMovieTitle))
            {
                ss.CurrentDCinemaMovieTitle = title;
            }

            if (ss.CurrentDCinemaFontSize == 0 || string.IsNullOrEmpty(ss.CurrentDCinemaFontEffect))
            {
                Configuration.Settings.SubtitleSettings.InitializeDCinameSettings(true);
            }

            xml.DocumentElement.SelectSingleNode("dcst:ContentTitleText", nsmgr).InnerText = ss.CurrentDCinemaMovieTitle;
            if (string.IsNullOrEmpty(ss.CurrentDCinemaSubtitleId) || !ss.CurrentDCinemaSubtitleId.StartsWith("urn:uuid:"))
            {
                ss.CurrentDCinemaSubtitleId = "urn:uuid:" + Guid.NewGuid().ToString();
            }
            xml.DocumentElement.SelectSingleNode("dcst:Id", nsmgr).InnerText         = ss.CurrentDCinemaSubtitleId;
            xml.DocumentElement.SelectSingleNode("dcst:ReelNumber", nsmgr).InnerText = ss.CurrentDCinemaReelNumber;
            xml.DocumentElement.SelectSingleNode("dcst:IssueDate", nsmgr).InnerText  = ss.CurrentDCinemaIssueDate;
            if (string.IsNullOrEmpty(ss.CurrentDCinemaLanguage))
            {
                ss.CurrentDCinemaLanguage = "en";
            }
            xml.DocumentElement.SelectSingleNode("dcst:Language", nsmgr).InnerText = ss.CurrentDCinemaLanguage;
            if (ss.CurrentDCinemaEditRate == null && ss.CurrentDCinemaTimeCodeRate == null)
            {
                if (Configuration.Settings.General.CurrentFrameRate == 24)
                {
                    ss.CurrentDCinemaEditRate     = "24 1";
                    ss.CurrentDCinemaTimeCodeRate = "24";
                }
                else
                {
                    ss.CurrentDCinemaEditRate     = "25 1";
                    ss.CurrentDCinemaTimeCodeRate = "25";
                }
            }
            xml.DocumentElement.SelectSingleNode("dcst:EditRate", nsmgr).InnerText     = ss.CurrentDCinemaEditRate;
            xml.DocumentElement.SelectSingleNode("dcst:TimeCodeRate", nsmgr).InnerText = ss.CurrentDCinemaTimeCodeRate;
            if (string.IsNullOrEmpty(ss.CurrentDCinemaStartTime))
            {
                ss.CurrentDCinemaStartTime = "00:00:00:00";
            }
            xml.DocumentElement.SelectSingleNode("dcst:StartTime", nsmgr).InnerText = ss.CurrentDCinemaStartTime;
            xml.DocumentElement.SelectSingleNode("dcst:LoadFont", nsmgr).InnerText  = ss.CurrentDCinemaFontUri;
            int    fontSize     = ss.CurrentDCinemaFontSize;
            string loadedFontId = "Font1";

            if (!string.IsNullOrEmpty(ss.CurrentDCinemaFontId))
            {
                loadedFontId = ss.CurrentDCinemaFontId;
            }
            xml.DocumentElement.SelectSingleNode("dcst:LoadFont", nsmgr).Attributes["ID"].Value = loadedFontId;
            xml.DocumentElement.SelectSingleNode("dcst:SubtitleList/dcst:Font", nsmgr).Attributes["Size"].Value        = fontSize.ToString();
            xml.DocumentElement.SelectSingleNode("dcst:SubtitleList/dcst:Font", nsmgr).Attributes["Color"].Value       = "FF" + Utilities.ColorToHex(ss.CurrentDCinemaFontColor).TrimStart('#').ToUpper();
            xml.DocumentElement.SelectSingleNode("dcst:SubtitleList/dcst:Font", nsmgr).Attributes["ID"].Value          = loadedFontId;
            xml.DocumentElement.SelectSingleNode("dcst:SubtitleList/dcst:Font", nsmgr).Attributes["Effect"].Value      = ss.CurrentDCinemaFontEffect;
            xml.DocumentElement.SelectSingleNode("dcst:SubtitleList/dcst:Font", nsmgr).Attributes["EffectColor"].Value = "FF" + Utilities.ColorToHex(ss.CurrentDCinemaFontEffectColor).TrimStart('#').ToUpper();

            XmlNode mainListFont = xml.DocumentElement.SelectSingleNode("dcst:SubtitleList/dcst:Font", nsmgr);
            int     no           = 0;

            foreach (Paragraph p in subtitle.Paragraphs)
            {
                if (p.Text != null)
                {
                    XmlNode subNode = xml.CreateElement("dcst:Subtitle", "dcst");

                    XmlAttribute id = xml.CreateAttribute("SpotNumber");
                    id.InnerText = (no + 1).ToString();
                    subNode.Attributes.Append(id);

                    XmlAttribute fadeUpTime = xml.CreateAttribute("FadeUpTime");
                    fadeUpTime.InnerText = "00:00:00:00"; //Configuration.Settings.SubtitleSettings.DCinemaFadeUpDownTime.ToString();
                    subNode.Attributes.Append(fadeUpTime);

                    XmlAttribute fadeDownTime = xml.CreateAttribute("FadeDownTime");
                    fadeDownTime.InnerText = "00:00:00:00"; //Configuration.Settings.SubtitleSettings.DCinemaFadeUpDownTime.ToString();
                    subNode.Attributes.Append(fadeDownTime);

                    XmlAttribute start = xml.CreateAttribute("TimeIn");
                    start.InnerText = ConvertToTimeString(p.StartTime);
                    subNode.Attributes.Append(start);

                    XmlAttribute end = xml.CreateAttribute("TimeOut");
                    end.InnerText = ConvertToTimeString(p.EndTime);
                    subNode.Attributes.Append(end);


                    bool alignLeft = p.Text.StartsWith("{\\a1}") || p.Text.StartsWith("{\\a5}") || p.Text.StartsWith("{\\a9}") ||      // sub station alpha
                                     p.Text.StartsWith("{\\an1}") || p.Text.StartsWith("{\\an4}") || p.Text.StartsWith("{\\an7}");     // advanced sub station alpha

                    bool alignRight = p.Text.StartsWith("{\\a3}") || p.Text.StartsWith("{\\a7}") || p.Text.StartsWith("{\\a11}") ||    // sub station alpha
                                      p.Text.StartsWith("{\\an3}") || p.Text.StartsWith("{\\an6}") || p.Text.StartsWith("{\\an9}");    // advanced sub station alpha

                    bool alignVTop = p.Text.StartsWith("{\\a5}") || p.Text.StartsWith("{\\a6}") || p.Text.StartsWith("{\\a7}") ||      // sub station alpha
                                     p.Text.StartsWith("{\\an7}") || p.Text.StartsWith("{\\an8}") || p.Text.StartsWith("{\\an9}");     // advanced sub station alpha

                    bool alignVCenter = p.Text.StartsWith("{\\a9}") || p.Text.StartsWith("{\\a10}") || p.Text.StartsWith("{\\a11}") || // sub station alpha
                                        p.Text.StartsWith("{\\an4}") || p.Text.StartsWith("{\\an5}") || p.Text.StartsWith("{\\an6}");  // advanced sub station alpha

                    // remove styles for display text (except italic)
                    string text = RemoveSubStationAlphaFormatting(p.Text);


                    string[] lines      = text.Split(Environment.NewLine.ToCharArray(), StringSplitOptions.RemoveEmptyEntries);
                    int      vPos       = 1 + lines.Length * 7;
                    int      vPosFactor = (int)Math.Round(fontSize / 7.4);
                    if (alignVTop)
                    {
                        vPos = Configuration.Settings.SubtitleSettings.DCinemaBottomMargin; // Bottom margin is normally 8
                    }
                    else if (alignVCenter)
                    {
                        vPos = (int)Math.Round((lines.Length * vPosFactor * -1) / 2.0);
                    }
                    else
                    {
                        vPos = (lines.Length * vPosFactor) - vPosFactor + Configuration.Settings.SubtitleSettings.DCinemaBottomMargin; // Bottom margin is normally 8
                    }

                    bool isItalic = false;
                    int  fontNo   = 0;
                    System.Collections.Generic.Stack <string> fontColors = new Stack <string>();
                    foreach (string line in lines)
                    {
                        XmlNode textNode = xml.CreateElement("dcst:Text", "dcst");

                        XmlAttribute vPosition = xml.CreateAttribute("Vposition");
                        vPosition.InnerText = vPos.ToString();
                        textNode.Attributes.Append(vPosition);

                        XmlAttribute vAlign = xml.CreateAttribute("Valign");
                        if (alignVTop)
                        {
                            vAlign.InnerText = "top";
                        }
                        else if (alignVCenter)
                        {
                            vAlign.InnerText = "center";
                        }
                        else
                        {
                            vAlign.InnerText = "bottom";
                        }
                        textNode.Attributes.Append(vAlign); textNode.Attributes.Append(vAlign);

                        XmlAttribute hAlign = xml.CreateAttribute("Halign");
                        if (alignLeft)
                        {
                            hAlign.InnerText = "left";
                        }
                        else if (alignRight)
                        {
                            hAlign.InnerText = "right";
                        }
                        else
                        {
                            hAlign.InnerText = "center";
                        }
                        textNode.Attributes.Append(hAlign);

                        XmlAttribute direction = xml.CreateAttribute("Direction");
                        direction.InnerText = "ltr";
                        textNode.Attributes.Append(direction);

                        int     i        = 0;
                        var     txt      = new StringBuilder();
                        var     html     = new StringBuilder();
                        XmlNode nodeTemp = xml.CreateElement("temp");
                        while (i < line.Length)
                        {
                            if (!isItalic && line.Substring(i).StartsWith("<i>"))
                            {
                                if (txt.Length > 0)
                                {
                                    nodeTemp.InnerText = txt.ToString();
                                    html.Append(nodeTemp.InnerXml);
                                    txt = new StringBuilder();
                                }
                                isItalic = true;
                                i       += 2;
                            }
                            else if (isItalic && line.Substring(i).StartsWith("</i>"))
                            {
                                if (txt.Length > 0)
                                {
                                    XmlNode fontNode = xml.CreateElement("dcst:Font", "dcst");

                                    XmlAttribute italic = xml.CreateAttribute("Italic");
                                    italic.InnerText = "yes";
                                    fontNode.Attributes.Append(italic);

                                    if (line.Length > i + 5 && line.Substring(i + 4).StartsWith("</font>"))
                                    {
                                        XmlAttribute fontColor = xml.CreateAttribute("Color");
                                        fontColor.InnerText = fontColors.Pop();
                                        fontNode.Attributes.Append(fontColor);
                                        fontNo--;
                                        i += 7;
                                    }

                                    fontNode.InnerText = Utilities.RemoveHtmlTags(txt.ToString());
                                    html.Append(fontNode.OuterXml);
                                    txt = new StringBuilder();
                                }
                                isItalic = false;
                                i       += 3;
                            }
                            else if (line.Substring(i).StartsWith("<font color=") && line.Substring(i + 3).Contains(">"))
                            {
                                int endOfFont = line.IndexOf(">", i);
                                if (txt.Length > 0)
                                {
                                    nodeTemp.InnerText = txt.ToString();
                                    html.Append(nodeTemp.InnerXml);
                                    txt = new StringBuilder();
                                }
                                string c = line.Substring(i + 12, endOfFont - (i + 12));
                                c = c.Trim('"').Trim('\'').Trim();
                                if (c.StartsWith("#"))
                                {
                                    c = c.TrimStart('#').ToUpper().PadLeft(8, 'F');
                                }
                                fontColors.Push(c);
                                fontNo++;
                                i += endOfFont - i;
                            }
                            else if (fontNo > 0 && line.Substring(i).StartsWith("</font>"))
                            {
                                if (txt.Length > 0)
                                {
                                    XmlNode fontNode = xml.CreateElement("dcst:Font", "dcst");

                                    XmlAttribute fontColor = xml.CreateAttribute("Color");
                                    fontColor.InnerText = fontColors.Pop();
                                    fontNode.Attributes.Append(fontColor);

                                    if (line.Length > i + 9 && line.Substring(i + 7).StartsWith("</i>"))
                                    {
                                        XmlAttribute italic = xml.CreateAttribute("Italic");
                                        italic.InnerText = "yes";
                                        fontNode.Attributes.Append(italic);
                                        isItalic = false;
                                        i       += 4;
                                    }

                                    fontNode.InnerText = Utilities.RemoveHtmlTags(txt.ToString());
                                    html.Append(fontNode.OuterXml);
                                    txt = new StringBuilder();
                                }
                                fontNo--;
                                i += 6;
                            }
                            else
                            {
                                txt.Append(line.Substring(i, 1));
                            }
                            i++;
                        }

                        if (fontNo > 0)
                        {
                            if (txt.Length > 0)
                            {
                                XmlNode fontNode = xml.CreateElement("dcst:Font", "dcst");

                                XmlAttribute fontColor = xml.CreateAttribute("Color");
                                fontColor.InnerText = fontColors.Peek();
                                fontNode.Attributes.Append(fontColor);

                                if (isItalic)
                                {
                                    XmlAttribute italic = xml.CreateAttribute("Italic");
                                    italic.InnerText = "yes";
                                    fontNode.Attributes.Append(italic);
                                }

                                fontNode.InnerText = Utilities.RemoveHtmlTags(txt.ToString());
                                html.Append(fontNode.OuterXml);
                            }
                            else if (html.Length > 0 && html.ToString().StartsWith("<dcst:Font "))
                            {
                                XmlDocument temp = new XmlDocument();
                                temp.LoadXml("<root>" + html.ToString().Replace("dcst:Font", "Font") + "</root>");
                                XmlNode fontNode = xml.CreateElement("dcst:Font");
                                fontNode.InnerXml = temp.DocumentElement.SelectSingleNode("Font").InnerXml;
                                foreach (XmlAttribute a in temp.DocumentElement.SelectSingleNode("Font").Attributes)
                                {
                                    XmlAttribute newA = xml.CreateAttribute(a.Name);
                                    newA.InnerText = a.InnerText;
                                    fontNode.Attributes.Append(newA);
                                }

                                XmlAttribute fontColor = xml.CreateAttribute("Color");
                                fontColor.InnerText = fontColors.Peek();
                                fontNode.Attributes.Append(fontColor);

                                html = new StringBuilder();
                                html.Append(fontNode.OuterXml);
                            }
                        }
                        else if (isItalic)
                        {
                            if (txt.Length > 0)
                            {
                                XmlNode fontNode = xml.CreateElement("dcst:Font", "dcst");

                                XmlAttribute italic = xml.CreateAttribute("Italic");
                                italic.InnerText = "yes";
                                fontNode.Attributes.Append(italic);

                                fontNode.InnerText = Utilities.RemoveHtmlTags(line);
                                html.Append(fontNode.OuterXml);
                            }
                        }
                        else
                        {
                            if (txt.Length > 0)
                            {
                                nodeTemp.InnerText = txt.ToString();
                                html.Append(nodeTemp.InnerXml);
                            }
                        }
                        textNode.InnerXml = html.ToString();

                        subNode.AppendChild(textNode);
                        vPos -= vPosFactor;
                    }
                    if (subNode.InnerXml.Length == 0)
                    { // Empty text is just one space
                        XmlNode textNode = xml.CreateElement("dcst:Text", "dcst");
                        textNode.InnerXml = " ";
                        subNode.AppendChild(textNode);

                        XmlAttribute vPosition = xml.CreateAttribute("Vposition");
                        vPosition.InnerText = vPos.ToString();
                        textNode.Attributes.Append(vPosition);

                        XmlAttribute vAlign = xml.CreateAttribute("Valign");
                        vAlign.InnerText = "bottom";
                        textNode.Attributes.Append(vAlign);
                    }
                    mainListFont.AppendChild(subNode);
                    no++;
                }
            }
            string result = ToUtf8XmlString(xml).Replace("encoding=\"utf-8\"", "encoding=\"UTF-8\"").Replace(" xmlns:dcst=\"dcst\"", string.Empty);

            string res = "Nikse.SubtitleEdit.Resources.SMPTE-428-7-2007-DCST.xsd.gz";

            System.Reflection.Assembly asm = System.Reflection.Assembly.GetExecutingAssembly();
            Stream strm = asm.GetManifestResourceStream(res);

            if (strm != null)
            {
                try
                {
                    var xmld = new XmlDocument();
                    var rdr  = new StreamReader(strm);
                    using (var zip = new GZipStream(rdr.BaseStream, CompressionMode.Decompress))
                    {
                        xmld.LoadXml(result);
                        var xr = XmlReader.Create(zip);
                        xmld.Schemas.Add(null, xr);
                        xmld.Validate(ValidationCallBack);
                        xr.Close();
                        strm.Close();
                    }
                    rdr.Close();
                }
                catch (Exception exception)
                {
                    if (!BatchMode)
                    {
                        System.Windows.Forms.MessageBox.Show("SMPTE-428-7-2007-DCST.xsd: " + exception.Message);
                    }
                }
            }
            return(result);
        }
        /// <summary>
        /// This method ensures the tabular model is online and populates the CompatibilityLevel property.
        /// </summary>
        /// <param name="closedBimFile">A Boolean specifying if the user cancelled the comparison. For the case where running in Visual Studio, the user has the option of cancelling if the project BIM file is open.</param>
        public void InitializeCompatibilityLevel(bool closedBimFile = false)
        {
            if (UseProject)
            {
                //Initialize _projectDirectoryInfo
                FileInfo projectFileInfo;
                if (_project == null)
                {
                    //Probably running in command-line mode
                    projectFileInfo = new FileInfo(_projectFile);
                }
                else
                {
                    projectFileInfo = new FileInfo(_project.FullName);
                }
                _projectDirectoryInfo = new DirectoryInfo(projectFileInfo.Directory.FullName);

                //Read settings file to get workspace server/db
                ReadSettingsFile();

                //Read project file to get deployment server/cube names, and bim file
                ReadProjectFile();
            }

            Server amoServer = new Server();

            try
            {
                amoServer.Connect($"Provider=MSOLAP;Data Source={this.ServerName};Initial Catalog={this.DatabaseName}");
            }
            catch (ConnectionException) when(UseProject)
            {
                //See if can find integrated workspace server

                bool foundServer = false;

                string tempDataDir = Path.GetTempPath() + @"Microsoft\Microsoft SQL Server\OLAP\LocalServer\Data";

                if (Directory.Exists(tempDataDir))
                {
                    var subDirs = Directory.GetDirectories(tempDataDir).OrderByDescending(d => new DirectoryInfo(d).CreationTime); //Need to order by descending in case old folders hanging around when VS was killed and SSDT didn't get a chance to clean up after itself
                    foreach (string subDir in subDirs)
                    {
                        string[] iniFilePath = Directory.GetFiles(subDir, "msmdsrv.ini");
                        if (iniFilePath.Length == 1 && File.ReadAllText(iniFilePath[0]).Contains("<DataDir>" + _projectDirectoryInfo.FullName + @"\bin\Data</DataDir>")) //Todo: proper xml lookup
                        {
                            //Assuming this must be the folder, so now get the port number
                            string[] portFilePath = Directory.GetFiles(subDir, "msmdsrv.port.txt");
                            if (portFilePath.Length == 1)
                            {
                                string port = File.ReadAllText(portFilePath[0]).Replace("\0", "");
                                this.ServerName = $"localhost:{Convert.ToString(port)}";
                                amoServer.Connect($"Provider=MSOLAP;Data Source={this.ServerName};Initial Catalog={this.DatabaseName}");
                                foundServer = true;
                                break;
                            }
                        }
                    }
                }

                if (!foundServer)
                {
                    throw;
                }
            }

            ////non-admins can't see any ServerProperties: social.msdn.microsoft.com/Forums/sqlserver/en-US/3d0bf49c-9034-4416-9c51-77dc32bf8b73/determine-current-user-permissionscapabilities-via-amo-or-xmla
            //if (!(amoServer.ServerProperties.Count > 0)) //non-admins can't see any ServerProperties
            //{
            //    throw new Microsoft.AnalysisServices.ConnectionException($"Current user {WindowsIdentity.GetCurrent().Name} is not an administrator on the Analysis Server " + this.ServerName);
            //}

            if (amoServer.ServerMode != ServerMode.Tabular)
            {
                throw new ConnectionException($"Analysis Server {this.ServerName} is not running in Tabular mode");
            }

            Database tabularDatabase = amoServer.Databases.FindByName(this.DatabaseName);

            if (tabularDatabase == null)
            {
                if (!this.UseProject)
                {
                    throw new ConnectionException("Could not connect to database " + this.DatabaseName);
                }
                else
                {
                    /* Check if folder exists using SystemGetSubdirs. If so attach. If not, do nothing - when execute BIM file below will create automatically.
                     * Using XMLA to run SystemGetSubdirs rather than ADOMD.net here don't want a reference to ADOMD.net Dll.
                     * Also, can't use Server.Execute method because it only takes XMLA execute commands (as opposed to XMLA discover commands), so need to submit the full soap envelope
                     */

                    string dataDir = amoServer.ServerProperties["DataDir"].Value;
                    if (dataDir.EndsWith("\\"))
                    {
                        dataDir = dataDir.Substring(0, dataDir.Length - 1);
                    }
                    string      commandStatement = String.Format("SystemGetSubdirs '{0}'", dataDir);
                    XmlNodeList rows             = Core.Comparison.ExecuteXmlaCommand(amoServer, "", commandStatement);

                    string dbDir = "";
                    foreach (XmlNode row in rows)
                    {
                        XmlNode dirNode     = null;
                        XmlNode allowedNode = null;

                        foreach (XmlNode childNode in row.ChildNodes)
                        {
                            if (childNode.Name == "Dir")
                            {
                                dirNode = childNode;
                            }
                            else if (childNode.Name == "Allowed")
                            {
                                allowedNode = childNode;
                            }
                        }

                        if (dirNode != null && allowedNode != null && dirNode.InnerText.Length >= this.DatabaseName.Length && dirNode.InnerText.Substring(0, this.DatabaseName.Length) == this.DatabaseName && allowedNode.InnerText.Length > 0 && allowedNode.InnerText == "1")
                        {
                            dbDir = dataDir + "\\" + dirNode.InnerText;
                            break;
                        }
                    }

                    if (dbDir != "")
                    {
                        //attach
                        amoServer.Attach(dbDir);
                        amoServer.Refresh();
                        tabularDatabase = amoServer.Databases.FindByName(this.DatabaseName);
                    }
                }
            }

            if (this.UseProject)
            {
                //_bimFileFullName = GetBimFileFullName();
                if (String.IsNullOrEmpty(_bimFileFullName))
                {
                    throw new ConnectionException("Could not load BIM file for Project " + this.ProjectName);
                }

                if (!closedBimFile) //If just closed BIM file, no need to execute it
                {
                    //Execute BIM file contents as script on workspace database

                    //We don't know the compatibility level yet, so try parsing json, if fail, try xmla ...
                    try
                    {
                        //Replace "SemanticModel" with db name.
                        JObject jDocument = JObject.Parse(File.ReadAllText(_bimFileFullName));

                        if (jDocument["name"] == null || jDocument["id"] == null)
                        {
                            throw new ConnectionException("Could not read JSON in BIM file " + _bimFileFullName);
                        }

                        jDocument["name"] = DatabaseName;
                        jDocument["id"]   = DatabaseName;

                        //Todo: see if Tabular helper classes for this once documentation available after CTP
                        string command =
                            $@"{{
  ""createOrReplace"": {{
    ""object"": {{
      ""database"": ""{DatabaseName}""
    }},
    ""database"": {jDocument.ToString()}
    }}
}}
";
                        amoServer.Execute(command);
                    }
                    catch (JsonReaderException)
                    {
                        //Replace "SemanticModel" with db name.  Could do a global replace, but just in case it's not called SemanticModel, use dom instead
                        //string xmlaScript = File.ReadAllText(xmlaFileFullName);
                        XmlDocument document = new XmlDocument();
                        document.Load(_bimFileFullName);
                        XmlNamespaceManager nsmgr = new XmlNamespaceManager(document.NameTable);
                        nsmgr.AddNamespace("myns1", "http://schemas.microsoft.com/analysisservices/2003/engine");

                        XmlNode objectDatabaseIdNode             = document.SelectSingleNode("//myns1:Object/myns1:DatabaseID", nsmgr);
                        XmlNode objectDefinitionDatabaseIdNode   = document.SelectSingleNode("//myns1:ObjectDefinition/myns1:Database/myns1:ID", nsmgr);
                        XmlNode objectDefinitionDatabaseNameNode = document.SelectSingleNode("//myns1:ObjectDefinition/myns1:Database/myns1:Name", nsmgr);

                        if (objectDatabaseIdNode == null || objectDefinitionDatabaseIdNode == null || objectDefinitionDatabaseNameNode == null)
                        {
                            throw new ConnectionException("Could not access XMLA in BIM file " + _bimFileFullName);
                        }

                        objectDatabaseIdNode.InnerText             = DatabaseName;
                        objectDefinitionDatabaseIdNode.InnerText   = DatabaseName;
                        objectDefinitionDatabaseNameNode.InnerText = DatabaseName;

                        //1103, 1100 projects store the xmla as Alter (equivalent to createOrReplace), so just need to execute
                        amoServer.Execute(document.OuterXml);
                    }
                }

                //need next lines in case just created the db using the Execute method
                //amoServer.Refresh(); //todo workaround for bug 9719887 on 3/10/17 need to disconnect and reconnect
                amoServer.Disconnect();
                amoServer.Connect($"Provider=MSOLAP;Data Source={this.ServerName};Initial Catalog={this.DatabaseName}");

                tabularDatabase = amoServer.Databases.FindByName(this.DatabaseName);
            }

            if (tabularDatabase == null)
            {
                throw new ConnectionException($"Can not load/find database {this.DatabaseName}.");
            }
            _compatibilityLevel = tabularDatabase.CompatibilityLevel;
            _dataSourceVersion  = tabularDatabase.Model.DefaultPowerBIDataSourceVersion.ToString();
            _directQuery        = ((tabularDatabase.Model != null && tabularDatabase.Model.DefaultMode == Microsoft.AnalysisServices.Tabular.ModeType.DirectQuery) ||
                                   tabularDatabase.DirectQueryMode == DirectQueryMode.DirectQuery || tabularDatabase.DirectQueryMode == DirectQueryMode.InMemoryWithDirectQuery || tabularDatabase.DirectQueryMode == DirectQueryMode.DirectQueryWithInMemory);
        }
Ejemplo n.º 56
0
        private void DisableClientSideSettings()
        {
            WSManHelper   helper       = new WSManHelper(this);
            IWSManSession m_SessionObj = CreateWSManSession();

            if (m_SessionObj == null)
            {
                return;
            }

            try
            {
                string      result      = m_SessionObj.Get(helper.CredSSP_RUri, 0);
                XmlDocument resultopxml = new XmlDocument();
                string      inputXml    = null;
                resultopxml.LoadXml(result);
                XmlNamespaceManager nsmgr = new XmlNamespaceManager(resultopxml.NameTable);
                nsmgr.AddNamespace("cfg", helper.CredSSP_XMLNmsp);
                XmlNode xNode = resultopxml.SelectSingleNode(helper.CredSSP_SNode, nsmgr);
                if (!(xNode == null))
                {
                    inputXml = @"<cfg:Auth xmlns:cfg=""http://schemas.microsoft.com/wbem/wsman/1/config/client/auth""><cfg:CredSSP>false</cfg:CredSSP></cfg:Auth>";
                }
                else
                {
                    InvalidOperationException ex = new InvalidOperationException();
                    ErrorRecord er = new ErrorRecord(ex, helper.GetResourceMsgFromResourcetext("WinrmNotConfigured"), ErrorCategory.InvalidOperation, null);
                    WriteError(er);
                    return;
                }

                m_SessionObj.Put(helper.CredSSP_RUri, inputXml, 0);

                if (Thread.CurrentThread.GetApartmentState() == ApartmentState.STA)
                {
                    this.DeleteUserDelegateSettings();
                }
                else
                {
                    ThreadStart start  = new ThreadStart(this.DeleteUserDelegateSettings);
                    Thread      thread = new Thread(start);
                    thread.SetApartmentState(ApartmentState.STA);
                    thread.Start();
                    thread.Join();
                }

                if (!helper.ValidateCreadSSPRegistryRetry(false, null, applicationname))
                {
                    helper.AssertError(helper.GetResourceMsgFromResourcetext("DisableCredSSPPolicyValidateError"), false, null);
                }
            }
            catch (System.Xml.XPath.XPathException ex)
            {
                ErrorRecord er = new ErrorRecord(ex, "XpathException", ErrorCategory.InvalidOperation, null);
                WriteError(er);
            }
            finally
            {
                if (!String.IsNullOrEmpty(m_SessionObj.Error))
                {
                    helper.AssertError(m_SessionObj.Error, true, null);
                }

                if (m_SessionObj != null)
                {
                    Dispose(m_SessionObj);
                }
            }
        }
    protected void Page_Load(object sender, EventArgs e)
    {
        string _url = "https://staging.payu.co.za"+ serviceAPI; //web service url       

        string soapContent = ""; //soap content

        soapContent = "<ns0:setTransaction>";
        soapContent += "<Api>ONE_ZERO</Api>";
        soapContent += "<Safekey>{45D5C765-16D2-45A4-8C41-8D6F84042F8C}</Safekey>";

        //Payment type   
        soapContent += "<TransactionType>RESERVE</TransactionType>";
        soapContent += "<Stage>'True'</Stage>";

        // Additional
        soapContent += "<AdditionalInformation>";
        
        // The cancel url for redirect shuold be configured accordingly
        soapContent += "<cancelUrl>http://197.84.206.122/dev/integration/demo/developer/payu-redirect-payment-page/cancel-page.php</cancelUrl>";
        
        soapContent += "<merchantReference>1351079862</merchantReference>";

        // The return url for redirect shuold be configured accordingly
        soapContent += "<returnUrl>http://197.84.206.122/dev/integration/demo/developer/payu-redirect-payment-page/send-getTransaction-via-soap.php</returnUrl>";
        soapContent += "<supportedPaymentMethods>CREDITCARD</supportedPaymentMethods>";
        soapContent += "</AdditionalInformation>";

        //Customer
        soapContent += "<Customer>";
        soapContent += "<merchantUserId>1351079862</merchantUserId>";
        soapContent += "<email>[email protected]</email>";
        soapContent += "<firstName>firstName_1349862936</firstName>";
        soapContent += "<lastName>lastName_1349862936</lastName>";
        soapContent += "<mobile>27123456789</mobile>";
        soapContent += "</Customer>";

        // Basket
        soapContent += "<Basket>";
        soapContent += "<amountInCents>9394</amountInCents>";
        soapContent += "<currencyCode>ZAR</currencyCode>";
        soapContent += "<description>Test Store Order: 1351079862</description>";
        soapContent += "</Basket>";
        soapContent += "</ns0:setTransaction>";
        // construct soap object

        XmlDocument soapEnvelopeXml = CreateSoapEnvelope(soapContent);

        // create username and password namespace
        XmlNamespaceManager nsmgr = new XmlNamespaceManager(soapEnvelopeXml.NameTable);
        nsmgr.AddNamespace("wsse", "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd");


        // set soap username
        XmlNode userName = soapEnvelopeXml.SelectSingleNode("//wsse:Username",nsmgr);
        userName.InnerText = "Staging Integration Store 1";

        // set soap password
        XmlNode userPassword = soapEnvelopeXml.SelectSingleNode("//wsse:Password",nsmgr);
        userPassword.InnerText = "78cXrW1W";

        // construct web request object
        HttpWebRequest webRequest = CreateWebRequest(_url);

        // insert soap envelope into web request
        InsertSoapEnvelopeIntoWebRequest(soapEnvelopeXml, webRequest);

        // get the PayU reference number from the completed web request.
        string soapResult;

        using (WebResponse webResponse = webRequest.GetResponse())
        using (StreamReader rd = new StreamReader(webResponse.GetResponseStream()))
        {
            soapResult = rd.ReadToEnd();
        }

        // create an empty soap result object
        XmlDocument soapResultXml = new XmlDocument();
        soapResultXml.LoadXml(soapResult.ToString());

        string success = soapResultXml.SelectSingleNode("//successful").InnerText;
            if (success == "true") {
                StringBuilder builder = new StringBuilder();

                builder.Append("https://staging.payu.co.za" + redirectAPI);

                // retrieve payU reference & build url with payU reference query string
                string payURef = soapResultXml.SelectSingleNode("//payUReference").InnerText;
                builder.Append(payURef);

                // redirect to payU site
                Response.Redirect(builder.ToString()); 
            }
    }
Ejemplo n.º 58
0
    public static void Main()
    {
        XmlSchema schema = new XmlSchema();

        // <xs:element name="cat" type="string"/>
        XmlSchemaElement elementCat = new XmlSchemaElement();

        schema.Items.Add(elementCat);
        elementCat.Name           = "cat";
        elementCat.SchemaTypeName = new XmlQualifiedName("string", "http://www.w3.org/2001/XMLSchema");

        // <xs:element name="dog" type="string"/>
        XmlSchemaElement elementDog = new XmlSchemaElement();

        schema.Items.Add(elementDog);
        elementDog.Name           = "dog";
        elementDog.SchemaTypeName = new XmlQualifiedName("string", "http://www.w3.org/2001/XMLSchema");

        // <xs:element name="redDog" substitutionGroup="dog" />
        XmlSchemaElement elementRedDog = new XmlSchemaElement();

        schema.Items.Add(elementRedDog);
        elementRedDog.Name = "redDog";
        elementRedDog.SubstitutionGroup = new XmlQualifiedName("dog");


        // <xs:element name="brownDog" substitutionGroup ="dog" />
        XmlSchemaElement elementBrownDog = new XmlSchemaElement();

        schema.Items.Add(elementBrownDog);
        elementBrownDog.Name = "brownDog";
        elementBrownDog.SubstitutionGroup = new XmlQualifiedName("dog");


        // <xs:element name="pets">
        XmlSchemaElement elementPets = new XmlSchemaElement();

        schema.Items.Add(elementPets);
        elementPets.Name = "pets";

        // <xs:complexType>
        XmlSchemaComplexType complexType = new XmlSchemaComplexType();

        elementPets.SchemaType = complexType;

        // <xs:choice minOccurs="0" maxOccurs="unbounded">
        XmlSchemaChoice choice = new XmlSchemaChoice();

        complexType.Particle   = choice;
        choice.MinOccurs       = 0;
        choice.MaxOccursString = "unbounded";

        // <xs:element ref="cat"/>
        XmlSchemaElement catRef = new XmlSchemaElement();

        choice.Items.Add(catRef);
        catRef.RefName = new XmlQualifiedName("cat");

        // <xs:element ref="dog"/>
        XmlSchemaElement dogRef = new XmlSchemaElement();

        choice.Items.Add(dogRef);
        dogRef.RefName = new XmlQualifiedName("dog");

        XmlSchemaSet schemaSet = new XmlSchemaSet();

        schemaSet.ValidationEventHandler += new ValidationEventHandler(ValidationCallbackOne);
        schemaSet.Add(schema);
        schemaSet.Compile();

        XmlSchema compiledSchema = null;

        foreach (XmlSchema schema1 in schemaSet.Schemas())
        {
            compiledSchema = schema1;
        }

        XmlNamespaceManager nsmgr = new XmlNamespaceManager(new NameTable());

        nsmgr.AddNamespace("xs", "http://www.w3.org/2001/XMLSchema");
        compiledSchema.Write(Console.Out, nsmgr);
    }
Ejemplo n.º 59
0
 protected void TreeLand_Load(object sender, System.EventArgs e)
 {
     // 在此处放置用户代码以初始化页面
     string strIsPostBackFull = leofun.valtag(this.hlbState.Value, "IsPostBackFull");
     if (null != this.ViewState["XmlSchema"])
     {
         this.CtrlXmlLand.Document = new XmlDocument();
         if (null != this.ViewState["XmlLand"] && "true" != strIsPostBackFull)
             this.CtrlXmlLand.Document.LoadXml(this.ViewState["XmlLand"].ToString());
         else
         {
             this.CtrlXmlLand.Document.LoadXml("<" + this.CtrlItemName + "/>");
             XmlDocument xmldoc = this.CtrlXmlLand.Document;
             XmlAttribute xmlAtt = xmldoc.DocumentElement.Attributes.Append(xmldoc.CreateAttribute("id"));
             xmlAtt.Value = this.CtrlXmlID;
             xmlAtt = xmldoc.DocumentElement.Attributes.Append(xmldoc.CreateAttribute("itemname"));
             xmlAtt.Value = this.CtrlItemName;
             xmlAtt = xmldoc.DocumentElement.Attributes.Append(xmldoc.CreateAttribute("typexml"));
             xmlAtt.Value = "Data";
         }
         this.CtrlDBXmlDoc = this.CtrlXmlLand.Document;
         this.CtrlXmlDelete.Document = new XmlDocument();
         if (null != this.ViewState["XmlDelete"] && "true" != strIsPostBackFull)
             this.CtrlXmlDelete.Document.LoadXml(this.ViewState["XmlDelete"].ToString());
         else
         {
             this.CtrlXmlDelete.Document.LoadXml("<" + this.CtrlItemName + "/>");
             XmlDocument xmldocDel = this.CtrlXmlDelete.Document;
             XmlAttribute xmlAtt = xmldocDel.DocumentElement.Attributes.Append(xmldocDel.CreateAttribute("id"));
             xmlAtt.Value = this.CtrlXmlID + "_Delete";
             xmlAtt = xmldocDel.DocumentElement.Attributes.Append(xmldocDel.CreateAttribute("typexml"));
             xmlAtt.Value = "Delete";
             xmldocDel.DocumentElement.Attributes.Append(xmldocDel.CreateAttribute("itemname"));
             xmlAtt.Value = this.CtrlItemName;
         }
         this.CtrlXmlSchema.Document = new XmlDocument();
         this.CtrlXmlSchema.Document.LoadXml(this.ViewState["XmlSchema"].ToString());
         this.CtrlDBSchema = this.CtrlXmlSchema.Document;
         this.CtrlXmlCount.Document = new XmlDocument();
         if (null != this.ViewState["XmlCount"])
             this.CtrlXmlCount.Document.LoadXml(this.ViewState["XmlCount"].ToString());
         this.CtrlXmlDict.Document = new XmlDocument();
         if (null != this.ViewState["XmlDict"])
             this.CtrlXmlDict.Document.LoadXml(this.ViewState["XmlDict"].ToString());
         if (null == this._xmlNsMglSchema)
         {
             XmlNamespaceManager xmlNsMgl = new XmlNamespaceManager(this.CtrlXmlSchema.Document.NameTable);
             XmlNode xmlRootEle = this.CtrlXmlSchema.Document.DocumentElement;
             for (int i = 0; i < xmlRootEle.Attributes.Count; i++)
             {
                 string strPrefix = xmlRootEle.Attributes[i].Prefix;
                 string strLocalName = xmlRootEle.Attributes[i].LocalName;
                 string strURI = xmlRootEle.Attributes[i].Value;
                 if ("xmlns" == strLocalName)
                     xmlNsMgl.AddNamespace(string.Empty, strURI);
                 if ("xmlns" != strPrefix) continue;
                 xmlNsMgl.AddNamespace(strLocalName, strURI);
             }
             this._xmlNsMglSchema = xmlNsMgl;
         }
         this.setChanged();
     }
     else if (this.IsPostBack && !this._enablevs)
     {
         this.CtrlDataBind();
         this.setChanged();
     }
 }
Ejemplo n.º 60
0
        /// <summary>
        /// Runs this instance.
        /// </summary>
        /// <param name="PushToNuget">if set to <c>true</c> [push to nuget].</param>
        /// <returns>True if it runs successfully, false otherwise</returns>
        public bool Run(bool PushToNuget)
        {
            var Text = new FileInfo(@"..\..\..\Utilities\Utilities.csproj").Read();
            var Doc  = new XmlDocument();

            Doc.LoadXml(Text);
            var Manager = new XmlNamespaceManager(Doc.NameTable);

            Manager.AddNamespace("Util", "http://schemas.microsoft.com/developer/msbuild/2003");
            var Nodes    = Doc.DocumentElement.SelectNodes("//Util:ItemGroup/Util:Compile", Manager);
            var Projects = new List <Project>();

            foreach (XmlNode Node in Nodes)
            {
                string Path      = Node.Attributes["Include"].InnerText;
                var    Splitter  = new string[] { "\\" };
                var    PathItems = Path.Split(Splitter, StringSplitOptions.None);
                if (Projects.Find(x => x.Name == PathItems[0]) != null)
                {
                    Projects.Find(x => x.Name == PathItems[0]).Includes.Add(Path);
                }
                else if (PathItems[0] != "Properties" && PathItems[0] != "GlobalSuppressions.cs")
                {
                    var Temp = new Project();
                    Temp.Includes = new List <string>();
                    Temp.Name     = PathItems[0];
                    Temp.Includes.Add(Path);
                    Projects.Add(Temp);
                }
            }
            Projects.ForEach(x => new DirectoryInfo("..\\..\\..\\Utilities\\" + x.Name)
                             .CopyTo(new DirectoryInfo("..\\..\\..\\Utilities." + x.Name + "\\" + x.Name),
                                     Utilities.IO.Enums.CopyOptions.CopyIfNewer));
            foreach (Project Project in Projects.Where(x => new FileInfo("..\\..\\..\\Utilities." + x.Name + "\\Utilities." + x.Name + ".csproj").Exists))
            {
                bool Changed     = false;
                var  ProjectText = new FileInfo("..\\..\\..\\Utilities." + Project.Name + "\\Utilities." + Project.Name + ".csproj").Read();
                var  ProjectDoc  = new XmlDocument();

                ProjectDoc.LoadXml(ProjectText);
                var Manager2 = new XmlNamespaceManager(ProjectDoc.NameTable);
                Manager2.AddNamespace("Util", "http://schemas.microsoft.com/developer/msbuild/2003");
                Nodes = ProjectDoc.DocumentElement.SelectNodes("//Util:ItemGroup/Util:Compile", Manager2);
                foreach (XmlNode Node in Nodes)
                {
                    string Path = Node.Attributes["Include"].InnerText;
                    if (!Project.Includes.Remove(Path) && !Path.StartsWith("Properties", StringComparison.Ordinal))
                    {
                        Node.ParentNode.RemoveChild(Node);
                        new FileInfo("..\\..\\..\\Utilities." + Project.Name + "\\" + Path).Delete();
                        Changed = true;
                    }
                }

                XmlNode Parent = null;
                foreach (XmlNode Node in Nodes)
                {
                    Parent = Node.ParentNode;
                    if (Parent != null)
                    {
                        break;
                    }
                }
                foreach (string Path in Project.Includes)
                {
                    var Node = ProjectDoc.CreateElement("Compile", "http://schemas.microsoft.com/developer/msbuild/2003");
                    Node.RemoveAllAttributes();
                    var Attribute = ProjectDoc.CreateAttribute("Include");
                    Node.Attributes.Append(Attribute);
                    Attribute.InnerText = Path;
                    Parent.AppendChild(Node);
                    Changed = true;
                }
                if (Changed)
                {
                    ProjectDoc.Save("..\\..\\..\\Utilities." + Project.Name + "\\Utilities." + Project.Name + ".csproj");
                }
            }
            return(true);
        }