Example #1
3
    // Sign an XML file and save the signature in a new file. This method does not  
    // save the public key within the XML file.  This file cannot be verified unless  
    // the verifying code has the key with which it was signed.
    public static void SignXmlFile(string FileName, string SignedFileName, RSA Key)
    {
        // Create a new XML document.
        XmlDocument doc = new XmlDocument();

        // Load the passed XML file using its name.
        doc.Load(new XmlTextReader(FileName));

        // Create a SignedXml object.
        SignedXml signedXml = new SignedXml(doc);

        // Add the key to the SignedXml document. 
        signedXml.SigningKey = Key;

        // Create a reference to be signed.
        Reference reference = new Reference();
        reference.Uri = "";

        // Add an enveloped transformation to the reference.
        XmlDsigEnvelopedSignatureTransform env = new XmlDsigEnvelopedSignatureTransform();
        reference.AddTransform(env);

        // Add the reference to the SignedXml object.
        signedXml.AddReference(reference);

        // Compute the signature.
        signedXml.ComputeSignature();

        // Get the XML representation of the signature and save
        // it to an XmlElement object.
        XmlElement xmlDigitalSignature = signedXml.GetXml();

        // Append the element to the XML document.
        doc.DocumentElement.AppendChild(doc.ImportNode(xmlDigitalSignature, true));

        if (doc.FirstChild is XmlDeclaration)
        {
            doc.RemoveChild(doc.FirstChild);
        }

        // Save the signed XML document to a file specified
        // using the passed string.
        XmlTextWriter xmltw = new XmlTextWriter(SignedFileName, new UTF8Encoding(false));
        doc.WriteTo(xmltw);
        xmltw.Close();
    }
    protected void btnLahetaPalaute_Click(object sender, EventArgs e)
    {
        string filename = MapPath("~/App_Data/Palautteet.xml");

        XmlDocument doc = new XmlDocument();

        doc.Load(filename);

        XmlElement newElem = doc.CreateElement("palaute");

        newElem.InnerXml = "<pvm>" + this.tbxPvm.Text + "</pvm>" +
            "<tekija>" + this.tbxNimi.Text + "</tekija>" +
            "<opittu>" + this.tbxOlenOppinut.Text + "</opittu>" +
            "<haluanoppia>" + this.tbxHaluanOppia.Text + "</haluanoppia>" +
            "<hyvaa>" + this.tbxHyvaa.Text + "</hyvaa>" +
            "<parannettavaa>" + this.tbxHuonoa.Text + "</parannettavaa>" +
            "<muuta>" + this.tbxMuuta.Text + "</muuta>";

        doc.DocumentElement.SelectNodes("/palautteet")[0].AppendChild(newElem);

        XmlWriter w = new XmlTextWriter(filename, System.Text.Encoding.UTF8);
        doc.WriteTo(w);
        w.Close();

        this.tbxPvm.Text = "";
        this.tbxNimi.Text = "";
        this.tbxOlenOppinut.Text = "";
        this.tbxHaluanOppia.Text = "";
        this.tbxHyvaa.Text = "";
        this.tbxHuonoa.Text = "";
        this.tbxMuuta.Text = "";
    }
Example #3
0
    public List<string> GetSpeaking_PracticeContents(int ID_Unit)
    {
        IEnumerable<SPEAKING> speaking_Practices = this.GetSpeakingUnit(ID_Unit);

        List<string> list = new List<string>();

        foreach (SPEAKING item in speaking_Practices)
        {
            XmlDocument xmlDoc = new XmlDocument();
            Stream stream;
            try
            {
                stream = File.OpenRead(System.Web.Hosting.HostingEnvironment.MapPath("~/ClientBin/" + item.Suggestion));                
                xmlDoc.Load(stream);                
            }
            catch (XmlException e)
            {
                Console.WriteLine(e.Message);
            }
            // Now create StringWriter object to get data from xml document.
            StringWriter sw = new StringWriter();
            XmlTextWriter xw = new XmlTextWriter(sw);

            xmlDoc.WriteTo(xw);
            list.Add(sw.ToString());

        }

        return list;        
    }
Example #4
0
    protected void Page_Load(object sender, EventArgs e)
    {
        XmlDocument xml = new XmlDocument();
        DataTable dt = CreateDataSource();
        DataSet ds = new DataSet("testDS");
        ds.Tables.Add(dt);
        xml.LoadXml(ds.GetXml());

        HttpContext.Current.Response.Clear();
        HttpContext.Current.Response.ContentType = "text/xml ";
        HttpContext.Current.Response.Charset = "UTF-8 ";
        XmlTextWriter writer = new XmlTextWriter(HttpContext.Current.Response.OutputStream, System.Text.Encoding.UTF8);
        writer.Formatting = Formatting.Indented;
        xml.WriteTo(writer);
        writer.Flush();
        HttpContext.Current.Response.End();
    }
    // Create example data to sign.
    public static void CreateSomeXml(string FileName)
    {
        // Create a new XmlDocument object.
        XmlDocument document = new XmlDocument();

        // Create a new XmlNode object.
        XmlNode node = document.CreateNode(XmlNodeType.Element, "", "MyElement", "samples");

        // Add some text to the node.
        node.InnerText = "Example text to be signed.";

        // Append the node to the document.
        document.AppendChild(node);

        // Save the XML document to the file name specified.
        XmlTextWriter xmltw = new XmlTextWriter(FileName, new UTF8Encoding(false));
        document.WriteTo(xmltw);
        xmltw.Close();
    }
Example #6
0
 /// <summary>
 /// 删除[appSettings]节点中包含Key值的子节点,返回成功与否布尔值
 /// </summary>
 /// <param name="configurationFile">要操作的配置文件名称,枚举常量</param>
 /// <param name="key">要删除的子节点Key值</param>
 /// <returns>返回成功与否布尔值</returns>
 public static bool DeleteByKey(ConfigurationFile configurationFile, string key)
 {
     bool isSuccess = false;
     string filename = string.Empty;
     if (configurationFile.ToString() == ConfigurationFile.AppConfig.ToString())
     {
         filename = System.Windows.Forms.Application.ExecutablePath + ".config";
     }
     else
     {
         filename = System.AppDomain.CurrentDomain.BaseDirectory + "web.config";
     }
     XmlDocument doc = new XmlDocument();
     doc.Load(filename); //加载配置文件
     XmlNode node = doc.SelectSingleNode("//appSettings");   //得到[appSettings]节点
     ////得到[appSettings]节点中关于Key的子节点
     XmlElement element = (XmlElement)node.SelectSingleNode("//add[@key='" + key + "']");
     if (element != null)
     {
         //存在则删除子节点
         element.ParentNode.RemoveChild(element);
     }
     else
     {
         //不存在
     }
     try
     {
         //保存至配置文件(方式一)
         using (XmlTextWriter xmlwriter = new XmlTextWriter(filename, null))
         {
             xmlwriter.Formatting = Formatting.Indented;
             doc.WriteTo(xmlwriter);
             xmlwriter.Flush();
         }
         isSuccess = true;
     }
     catch (Exception ex)
     {
         isSuccess = false;
     }
     return isSuccess;
 }
 public static string FormatXMLString(string sUnformattedXML)
 {
     XmlDocument xd = new XmlDocument();
     xd.LoadXml(sUnformattedXML);
     StringBuilder sb = new StringBuilder();
     StringWriter sw = new StringWriter(sb);
     XmlTextWriter xtw = null;
     try
     {
         xtw = new XmlTextWriter(sw);
         xtw.Formatting = Formatting.Indented;
         xd.WriteTo(xtw);
     }
     finally
     {
         if (xtw != null)
             xtw.Close();
     }
     return sb.ToString();
 }
Example #8
0
File: test.cs Project: mono/gert
	void IXmlSerializable.WriteXml (XmlWriter writer)
	{
		XmlDocument doc = new XmlDocument ();
		doc.LoadXml (mFuncXmlNode.OuterXml);

		// On function level
		if (doc.DocumentElement.Name == "Func") {
			try { doc.DocumentElement.Attributes.Remove (doc.DocumentElement.Attributes ["ReturnType"]); } catch { }
			try { doc.DocumentElement.Attributes.Remove (doc.DocumentElement.Attributes ["ReturnTId"]); } catch { }
			try { doc.DocumentElement.Attributes.Remove (doc.DocumentElement.Attributes ["CSharpType"]); } catch { }
		} else {
			UpgradeSchema (doc.DocumentElement);
		}

		// Make sure lrt is saved according to latest schema
		foreach (XmlNode n in doc.DocumentElement.ChildNodes) {
			UpgradeSchema (n);
		}

		doc.WriteTo (writer);
	}
    /// <summary>
    /// Output an XML file in the format that Tableau expects
    /// </summary>
    /// <param name="xmlDoc"></param>
    /// <param name="pathToOutput"></param>
    public static void WriteTableauXmlFile(XmlDocument xmlDoc, string pathToOutput)
    {
        //[2015-03-20]   Presently Server will error if it gets a TWB (XML) document uploaded that has a Byte Order Marker
        //                  (this will however work if the TWB is within a TWBX).  
        //                  To accomodate we need to write out XML without a BOM
        var utf8_noBOM = new System.Text.UTF8Encoding(false);
        using (var textWriter = new XmlTextWriter(pathToOutput, utf8_noBOM))                   
        {
            xmlDoc.WriteTo(textWriter);
            textWriter.Close();
        }

        //Write out the modified XML
//        var textWriter = new XmlTextWriter(_pathToTwbOutput, Encoding.UTF8);  //[2015-03-20] FAILS in TWB uploads (works in TWBX uploads) because Server errrors if it hits the byte order marker
//        var textWriter = new XmlTextWriter(_pathToTwbOutput, Encoding.ASCII); //[2015-03-20] Succeeds; but too limiting.  We want UTF-8
//        using (textWriter)
//        {
//            xmlDoc.WriteTo(textWriter);
//            textWriter.Close();
//        }
    }
Example #10
0
 public static void Main( string[] args ) {
     if ( args.Length != 2 ) {
         return;
     }
     string indir = args[0];
     string outdir = args[1];
     if ( !Directory.Exists( indir ) || !Directory.Exists( outdir ) ) {
         Console.WriteLine( "error; directory not exists" );
         return;
     }
     
     List<string> files = new List<string>( Directory.GetFiles( "*.htm" ) );
     files.AddRange( Directory.GetFiles( "*.html" ) );
     foreach ( string name in files ) {
         string path = Path.Combine( indir, name );
         XmlDocument doc = new XmlDocument();
         doc.Load( path );
         XmlTextWriter xtw = new XmlTextWriter( new FileStream( Path.Combine( outdir, name ), FileMode.OpenOrCreate, FileAccess.Write ), System.Text.Encoding.GetEncoding( "Shift_JIS" ) );
         doc.WriteTo( xtw );
         xtw.Close();
     }
 }
    protected void btnLahetaPalaute_Click(object sender, EventArgs e)
    {
        XmlDocument doc = new XmlDocument();
        doc.Load(MapPath("~/App_Data/Palautteet.xml"));

        XmlElement newElem = doc.CreateElement("palaute");

        string dateNow = Convert.ToString(DateTime.Today.ToShortDateString());
        newElem.InnerXml = "<pvm>" + dateNow + "</pvm>" +
            "<tekija>" + this.txtNimi.Text + "</tekija>" +
            "<opittu>" + this.txtOppinut.Text + "</opittu>" +
            "<haluanoppia>" + this.txtHaluan.Text + "</haluanoppia>" +
            "<hyvaa>" + this.txtHyvaa.Text + "</hyvaa>" +
            "<parannettavaa>" + this.txtParannettavaa.Text + "</parannettavaa>" +
            "<muuta>" + this.txtMuuta.Text + "</muuta>";

        doc.DocumentElement.SelectNodes("/palautteet")[0].AppendChild(newElem);

        XmlTextWriter wrtr = new XmlTextWriter(MapPath("~/App_Data/Palautteet.xml"), System.Text.Encoding.UTF8);
        doc.WriteTo(wrtr);
        wrtr.Close();
    }
    public String Write(Environment env)
    {
        XmlDocument xmlDoc = new XmlDocument ();
        string basexml = @"<?xml version=""1.0"" encoding=""UTF-8""?>
        <eeml xmlns=""http://www.eeml.org/xsd/0.5.1""
              xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" version=""0.5.1""
              xsi:schemaLocation=""http://www.eeml.org/xsd/0.5.1 http://www.eeml.org/xsd/0.5.1/0.5.1.xsd""></eeml>";
        xmlDoc.LoadXml (basexml);
        XmlNode root = xmlDoc.DocumentElement;

        //It seems we must explicitly specify each node's namespace
        //If we leave ns out, it won't just inherit from parent re ns but will say xmlns=""
        XmlElement nEnv = xmlDoc.CreateElement ("environment",xmlDoc.DocumentElement.NamespaceURI);

        //Add the node to the document.
        root.AppendChild (nEnv);
        nEnv.SetAttribute ("id", env.id);
        nEnv.AppendChild (UtilSimpleTextNode (xmlDoc, "title", env.title));
        nEnv.AppendChild (UtilSimpleTextNode (xmlDoc, "description", env.description));
        nEnv.AppendChild (UtilSimpleTextNode (xmlDoc, "website", env.website));
        nEnv.AppendChild (MakeLocationXML (env.location, xmlDoc));
        foreach (String tag in env.tags) {
            nEnv.AppendChild (UtilSimpleTextNode (xmlDoc, "tag", tag));
        }
        foreach (Datastream ds in env.datastreams) {
            nEnv.AppendChild (MakeDatastreamXML (ds, xmlDoc));
        }

        // Now create StringWriter object to get data from xml document.
        StringWriter sw = new StringWriter ();
        XmlTextWriter xw = new XmlTextWriter (sw);
        xw.Formatting = Formatting.Indented;
        xw.Indentation = 4;
        xmlDoc.WriteTo (xw);
        return sw.ToString ();
    }
Example #13
0
 private static void WriteXmlToStream(XmlDocument document, Stream input)
 {
     using (var w = CreateXmlWriter(input))
         document.WriteTo(w);
 }
        public static string CreateEstimate(Estimate data)
        {
            try
            {
                String finalString = "";

                XmlDocument xmlDoc = new XmlDocument();
                XmlNode rootNode = xmlDoc.CreateElement("issue");
                xmlDoc.AppendChild(rootNode);

                XmlNode idNode = xmlDoc.CreateElement("project_id");
                idNode.InnerText = data.project_id.ToString();//pass project id
                rootNode.AppendChild(idNode);

                XmlNode nameNode = xmlDoc.CreateElement("subject");
                nameNode.InnerText = data.subject;
                rootNode.AppendChild(nameNode);

                XmlNode identifierNode = xmlDoc.CreateElement("priority_id");
                identifierNode.InnerText = priorityId;
                rootNode.AppendChild(identifierNode);

                XmlNode statusNode = xmlDoc.CreateElement("status_id");
                statusNode.InnerText = data.status_id.ToString();
                rootNode.AppendChild(statusNode);

                XmlNode trackerNode = xmlDoc.CreateElement("tracker_id");
                trackerNode.InnerText = trackerId;
                rootNode.AppendChild(trackerNode);

                string XmlizedString = "";
                using (StringWriter sw = new StringWriter())
                {
                    using (XmlTextWriter tx = new XmlTextWriter(sw))
                    {
                        xmlDoc.WriteTo(tx);
                        XmlizedString = sw.ToString();
                    }
                }
                finalString = XmlizedString.Replace("<?xml version=\"1.0\" encoding=\"utf-16\"?>", "");
                string postirl = System.Configuration.ConfigurationManager.AppSettings["hostUrl"] + "issues.xml?key=" + System.Configuration.ConfigurationManager.AppSettings["apiKey"];
                HttpWebRequest request = (HttpWebRequest)WebRequest.Create(postirl);
                byte[] bytes;
                bytes = System.Text.Encoding.ASCII.GetBytes(finalString);
                request.ContentType = "application/xml; encoding='utf-8'";
                request.ContentLength = bytes.Length;
                request.Method = "POST";
                Stream requestStream = request.GetRequestStream();
                requestStream.Write(bytes, 0, bytes.Length);
                requestStream.Close();
                HttpWebResponse response;
                response = (HttpWebResponse)request.GetResponse();
                Uri res = (Uri)response.ResponseUri;
                string resLocation = response.Headers["Location"].ToString();
                string issueIdCreated = resLocation.Split(new string[] { "issues/" }, StringSplitOptions.None)[1];
                return issueIdCreated;
            }
            catch (Exception ex)
            {
                Logger.Error("PostData.PostMethod" + ex.ToString());
                return string.Empty;
            }
        }
Example #15
0
        public void TestAuthnRequest()
        {
            AuthnRequestType authnRequest = new AuthnRequestType();

            authnRequest.ID = "test-id";
            authnRequest.AssertionConsumerServiceURL = "http://test.assertion.consumer";
            authnRequest.Destination     = "http://destination";
            authnRequest.ForceAuthn      = true;
            authnRequest.ProtocolBinding = "urn:test:protocol:binding";
            authnRequest.Version         = "2.0";
            authnRequest.IssueInstant    = DateTime.Now.ToUniversalTime();

            NameIDType issuer = new NameIDType();

            issuer.Value        = "test-issuer";
            authnRequest.Issuer = issuer;

            NameIDPolicyType nameIdPolicy = new NameIDPolicyType();

            nameIdPolicy.AllowCreate          = true;
            nameIdPolicy.AllowCreateSpecified = true;
            authnRequest.NameIDPolicy         = nameIdPolicy;

            XmlSerializerNamespaces ns = new XmlSerializerNamespaces();

            ns.Add("samlp", "urn:oasis:names:tc:SAML:2.0:protocol");
            ns.Add("saml", "urn:oasis:names:tc:SAML:2.0:assertion");
            //ns.Add("ds", "http://www.w3.org/2000/09/xmldsig#");

            XmlRootAttribute xRoot = new XmlRootAttribute();

            xRoot.ElementName = "AuthnRequest";
            xRoot.Namespace   = "urn:oasis:names:tc:SAML:2.0:protocol";
            XmlSerializer serializer    = new XmlSerializer(typeof(AuthnRequestType), xRoot);
            MemoryStream  memoryStream  = new MemoryStream();
            XmlTextWriter xmlTextWriter = new XmlTextWriter(memoryStream, Encoding.UTF8);

            serializer.Serialize(xmlTextWriter, authnRequest, ns);
            memoryStream = (MemoryStream)xmlTextWriter.BaseStream;
            string result = new UTF8Encoding().GetString(memoryStream.ToArray());

            Console.WriteLine("result: " + result);

            XmlDocument document = new XmlDocument();

            memoryStream.Seek(0, SeekOrigin.Begin);
            document.Load(memoryStream);
            String xmlString = document.OuterXml;

            Console.WriteLine("DOM result: " + xmlString);

            RSACryptoServiceProvider Key = new RSACryptoServiceProvider();

            SignedXml signedXml = new SignedXml(document);

            signedXml.SigningKey = Key;
            Signature signature = signedXml.Signature;

            signature.SignedInfo.CanonicalizationMethod = SignedXml.XmlDsigExcC14NTransformUrl;
            Reference reference = new Reference("#" + authnRequest.ID);
            XmlDsigEnvelopedSignatureTransform env = new XmlDsigEnvelopedSignatureTransform();

            reference.AddTransform(env);
            XmlDsigExcC14NTransform excC14NTransform = new XmlDsigExcC14NTransform("ds saml samlp");

            reference.AddTransform(excC14NTransform);
            signature.SignedInfo.AddReference(reference);

            signedXml.ComputeSignature();

            XmlElement xmlDigitalSignature = signedXml.GetXml();

            document.DocumentElement.AppendChild(document.ImportNode(xmlDigitalSignature, true));

            result = document.OuterXml;
            Console.WriteLine("result: " + result);

            XmlTextWriter xmltw = new XmlTextWriter(TestConstants.workDir + "\\test.xml", new UTF8Encoding(false));

            document.WriteTo(xmltw);
            xmltw.Close();
        }
 /// <summary>
 /// Writes the assertion to the XmlWriter.
 /// </summary>
 /// <param name="writer">The writer.</param>
 public void WriteAssertion(XmlWriter writer)
 {
     _encryptedAssertion.WriteTo(writer);
 }
Example #17
0
        private void ImprimirRemisionElectronica(EntradaSalida entSal)
        {
            try
            {
                Sesion sesion = (Sesion)Session["Sesion" + Session.SessionID];
                List <EntradaSalidaDetalle> listaProdFacturaEspecialFinal = new List <EntradaSalidaDetalle>();

                entSal.Es_Estatus = "I";
                int verificador = 0;
                entSal.Id_Emp = sesion.Id_Emp;
                new CN_CapEntradaSalida().ModificarEntradaSalida_Estatus(entSal, sesion.Emp_Cnx, ref verificador);


                CN_CatCliente cn_catcliente = new CN_CatCliente();
                Clientes      clientes      = new Clientes();
                clientes.Id_Emp = sesion.Id_Emp;
                clientes.Id_Cd  = sesion.Id_Cd_Ver;
                clientes.Id_Cte = entSal.Id_Cte;
                cn_catcliente.ConsultaClientes(ref clientes, sesion.Emp_Cnx);
                entSal.Id_Emp = sesion.Id_Emp;
                CN_CapEntradaSalida cn_catensal = new CN_CapEntradaSalida();
                cn_catensal.ConsultarEntradaSalidaDetalles(sesion, entSal, ref listaProdFacturaEspecialFinal);

                CN_CatCentroDistribucion cn_cd = new CN_CatCentroDistribucion();
                CentroDistribucion       cd    = new CentroDistribucion();
                double iva = 0;
                cn_cd.ConsultarIva(sesion.Id_Emp, sesion.Id_Cd_Ver, ref iva, sesion.Emp_Cnx);



                StringBuilder XML_Enviar = new StringBuilder();
                XML_Enviar.Append("<?xml version=\"1.0\" encoding=\"iso-8859-1\"?>");
                XML_Enviar.Append("<RemisionCuentaNacional");
                XML_Enviar.Append(" TipoDocumento=\"\">");


                XML_Enviar.Append(" <Sucursal");
                XML_Enviar.Append(" CDINum=\"\"");
                XML_Enviar.Append(" CDINom=\"\"");
                XML_Enviar.Append(" CDIIVA=\"\"/>");

                XML_Enviar.Append(" <Documento");
                XML_Enviar.Append(" Folio=\"\"");
                XML_Enviar.Append(" CuentaNacional=\"\"");
                XML_Enviar.Append(" Status=\"\"");
                XML_Enviar.Append(" Fecha=\"\"");
                XML_Enviar.Append(" Remision=\"\"");
                XML_Enviar.Append(" Total=\"\"/>");



                XML_Enviar.Append(" <DetalleKey>");
                if (listaProdFacturaEspecialFinal.Count() > 0)
                {
                    foreach (EntradaSalidaDetalle d in listaProdFacturaEspecialFinal)
                    {
                        XML_Enviar.Append(" <Producto");
                        XML_Enviar.Append(" Codigo=\"" + d.Id_Prd.ToString() + "\"");
                        XML_Enviar.Append(" Descipcion=\"" + d.Prd_Descripcion.ToString().Replace("\"", "").Replace("'", "").Replace("&", "")
                                          + "\"");
                        XML_Enviar.Append(" Cantidad=\"" + d.Es_Cantidad + "\"");
                        XML_Enviar.Append(" Unidad=\"" + d.Prd_Unidad + "\"");
                        XML_Enviar.Append(" Presentacion=\"" + d.Prd_Presentacion + "\"");
                        XML_Enviar.Append(" Precio=\"" + d.Es_Costo + "\"");
                        XML_Enviar.Append(" />");
                    }
                }
                XML_Enviar.Append(" </DetalleKey>");

                XML_Enviar.Append(" </RemisionCuentaNacional>");



                XmlDocument xml = new XmlDocument();

                xml.LoadXml(XML_Enviar.ToString());


                XmlNode RemisionCuentaNacional = xml.SelectSingleNode("RemisionCuentaNacional");
                RemisionCuentaNacional.Attributes["TipoDocumento"].Value = "Entrada";

                XmlNode Sucursal = RemisionCuentaNacional.SelectSingleNode("Sucursal");
                Sucursal.Attributes["CDINum"].Value = entSal.Id_Cd.ToString();
                Sucursal.Attributes["CDINom"].Value = "Prueba";
                Sucursal.Attributes["CDIIVA"].Value = iva.ToString();


                XmlNode Documento = RemisionCuentaNacional.SelectSingleNode("Documento");
                Documento.Attributes["Folio"].Value          = entSal.Id_Es.ToString();
                Documento.Attributes["Status"].Value         = entSal.Es_Estatus.ToString();
                Documento.Attributes["CuentaNacional"].Value = entSal.Es_CteCuentaNacional.ToString();
                Documento.Attributes["Remision"].Value       = entSal.Es_Referencia.ToString();
                Documento.Attributes["Fecha"].Value          = entSal.Es_Fecha.ToShortDateString();
                Documento.Attributes["Total"].Value          = entSal.Es_Total.ToString();



                StringWriter  sw = new StringWriter();
                XmlTextWriter tx = new XmlTextWriter(sw);
                xml.WriteTo(tx);
                string xmlString = sw.ToString();

                WS_RemElectronicaCtaNacional.Service1 remelectronica = new WS_RemElectronicaCtaNacional.Service1();

                string sianRemisionElectronicaResult = remelectronica.Imprime_Entrada(xmlString).ToString();

                byte[] PDFRemision = this.Base64ToByte(sianRemisionElectronicaResult);


                string tempPDFname   = string.Concat("BAJAREMISION_", entSal.Id_Emp.ToString(), "_", entSal.Id_Cd.ToString(), "_", entSal.Id_U.ToString(), ".pdf");
                string URLtempPDF    = Server.MapPath(string.Concat(System.Configuration.ConfigurationManager.AppSettings["URLtempPDF"].ToString(), tempPDFname));
                string WebURLtempPDF = string.Concat(System.Configuration.ConfigurationManager.AppSettings["WebURLtempPDF"].ToString(), tempPDFname);
                this.ByteToTempPDF(URLtempPDF, PDFRemision);
                RadAjaxManager1.ResponseScripts.Add(string.Concat(@"AbrirFacturaPDF('", WebURLtempPDF, "')"));
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Example #18
0
        void Process(SgmlReader reader, string uri, bool loadAsStream)
        {
            if (uri == null)
            {
                reader.InputStream = Console.In;
            }
            else if (loadAsStream)
            {
                Uri location = new Uri(uri);
                if (location.IsFile)
                {
                    reader.InputStream = new StreamReader(uri);
                }
                else
                {
                    WebRequest wr = WebRequest.Create(location);
                    reader.InputStream = new StreamReader(wr.GetResponse().GetResponseStream());
                }
            }
            else
            {
                reader.Href = uri;
            }

            if (debug)
            {
                Debug(reader);
                reader.Close();
                return;
            }
            if (crawl)
            {
                StartCrawl(reader, uri, basify);
                return;
            }

            if (this.encoding == null)
            {
                this.encoding = reader.GetEncoding();
            }


            XmlTextWriter w = null;

            if (output != null)
            {
                w = new XmlTextWriter(output, this.encoding);
            }
            else
            {
                w = new XmlTextWriter(Console.Out);
            }
            if (formatted)
            {
                w.Formatting = Formatting.Indented;
            }
            if (!noxmldecl)
            {
                w.WriteStartDocument();
            }
            if (testdoc)
            {
                XmlDocument doc = new XmlDocument();
                try {
                    doc.Load(reader);
                    doc.WriteTo(w);
                } catch (XmlException e) {
                    Console.WriteLine("Error:" + e.Message);
                    Console.WriteLine("at line " + e.LineNumber + " column " + e.LinePosition);
                }
            }
            else
            {
                reader.Read();
                while (!reader.EOF)
                {
                    w.WriteNode(reader, true);
                }
            }
            w.Flush();
            w.Close();
        }
    private static bool ParseRoomTemplates(RoomTemplateManager roomTemplateManager)
    {
        bool success = true;
        string template_path = roomTemplateManager.mapTemplatePath;
        string[] templateFiles = null;
        List<CompressedRoomTemplate> compressedRoomTemplates = new List<CompressedRoomTemplate>();

        try
        {
            templateFiles = Directory.GetFiles(template_path, "*.oel");

        }
        catch (System.Exception ex)
        {
            Debug.LogError("RoomTemplateParser: ERROR: Invalid template folder directory: "+template_path);
            Debug.LogException(ex);
            success = false;
        }

        if (success)
        {
            if (templateFiles != null && templateFiles.Length > 0)
            {
                foreach (string templateFile in templateFiles)
                {
                    string templateName = Path.GetFileNameWithoutExtension(templateFile);

                    try
                    {
                        RoomTemplate roomTemplate = null;
                        byte[] compressedNavCells = null;
                        byte[] compressedPVS = null;

                        // Parse the XML template from the file
                        XmlDocument doc = new XmlDocument();
                        doc.Load(templateFile);

                        try
                        {
                            // Parse the room template xml into a room template object
                            roomTemplate = RoomTemplate.ParseXML(templateName, doc);

                            // Extract the nav-mesh and visibility data in compressed form to save into the DB
                            roomTemplate.NavMeshTemplate.ToCompressedData(out compressedNavCells, out compressedPVS);

                            // Remove everything from the template XML that we wont care about at runtime
                            RemoveXmlNodeByXPath(doc, "/level/NavMesh");
                            RemoveXmlNodeByXPath(doc, "/level/Entities");
                        }
                        catch (System.Exception ex)
                        {
                            Debug.LogError("RoomTemplateParser: ERROR: Problem(s) parsing room template:"+templateFile);
                            Debug.LogException(ex);
                            roomTemplate = null;
                            success = false;
                        }

                        if (roomTemplate != null &&
                            ValidateRoomTemplate(
                                templateName,
                                roomTemplate,
                                compressedNavCells,
                                compressedPVS))
                        {
                            // Save the XML back into string
                            StringWriter stringWriter = new StringWriter();
                            XmlTextWriter xmlWriter = new XmlTextWriter(stringWriter);
                            doc.WriteTo(xmlWriter);

                            compressedRoomTemplates.Add(
                                new CompressedRoomTemplate
                                {
                                    templateName = templateName,
                                    xml = stringWriter.ToString(),
                                    compressedNavCells = compressedNavCells,
                                    compressedVisibility = compressedPVS
                                });

                            Debug.Log("RoomTemplateParser: Added Room Template: " + templateName);
                        }
                        else
                        {
                            Debug.LogError("RoomTemplateParser: ERROR: Problem(s) validating room template: "+templateFile);
                            success = false;
                        }
                    }
                    catch (XmlException ex)
                    {
                        Debug.LogError("RoomTemplateParser: ERROR: Unable to parse XML: " + templateFile);
                        Debug.LogException(ex);
                        success = false;
                    }
                    catch (Exception ex)
                    {
                        Debug.LogError("RoomTemplateParser: ERROR: Unknown error parsing template file: "+templateFile);
                        Debug.LogException(ex);
                        success = false;
                    }
                }
            }
            else
            {
                Debug.LogError("RoomTemplateParser: ERROR: No room template files (*.oel) found in directory:" + template_path);
                success = false;
            }
        }

        // Store the compressed templates into the room template manager
        if (success)
        {
            Log(string.Format("RoomTemplateParser: Caching {0} compressed template(s) in room template manager.", compressedRoomTemplates.Count));
            roomTemplateManager.CacheCompressedRoomTemplates(compressedRoomTemplates.ToArray());
        }

        return success;
    }
    public void MergeXMLs(string source, string dest)
    {
        System.IO.StreamReader reader = new System.IO.StreamReader(source);
        string xmldata = reader.ReadToEnd();
        reader.Close();
        XmlDocument doc_source = new XmlDocument();
        doc_source.LoadXml(xmldata);

        reader = new System.IO.StreamReader(dest);
        xmldata = reader.ReadToEnd();
        reader.Close();
        XmlDocument doc_dest = new XmlDocument();
        doc_dest.LoadXml(xmldata);

        foreach (XmlNode childs in doc_source.DocumentElement.ChildNodes)
        {
            XmlNode imported = doc_dest.ImportNode(childs, true);
            if (getNodeAsChild(imported, doc_dest.DocumentElement) == null)
                doc_dest.DocumentElement.AppendChild(imported);
        }

        XmlTextWriter	writer = new XmlTextWriter(dest, System.Text.Encoding.UTF8);
        writer.Indentation = 4;
        writer.Formatting = Formatting.Indented;
        writer.Settings.NewLineHandling = NewLineHandling.Entitize;
        writer.Settings.NewLineOnAttributes = true;
        doc_dest.WriteTo(writer);
        writer.Close();
    }
Example #21
0
        // Sign an XML file and save the signature in a new file.
        public static void SignXmlFile(string FileName, string SignedFileName, RSA Key, X509Certificate2 Certificate)
        {
            // Create a new XML document.
            XmlDocument doc = new XmlDocument();

            // Format the document to ignore white spaces.
            doc.PreserveWhitespace = false;

            // Load the passed XML file using it's name.
            doc.Load(new XmlTextReader(FileName));

            // Create a SignedXml object.
            SignedXml signedXml = new SignedXml(doc);

            // Add the key to the SignedXml document.
            signedXml.SigningKey = Key;

            // Create a reference to be signed.
            Reference reference = new Reference();

            reference.Uri = "";

            // Add an enveloped transformation to the reference.
            XmlDsigEnvelopedSignatureTransform env = new XmlDsigEnvelopedSignatureTransform();

            reference.AddTransform(env);

            // Add the reference to the SignedXml object.
            signedXml.AddReference(reference);

            // Create a new KeyInfo object.
            KeyInfo keyInfo = new KeyInfo();

            // Load the X509 certificate.
            //X509Certificate MSCert = X509Certificate.CreateFromCertFile(Certificate);

            // Load the certificate into a KeyInfoX509Data object
            // and add it to the KeyInfo object.
            keyInfo.AddClause(new KeyInfoX509Data(Certificate));

            // Add the KeyInfo object to the SignedXml object.
            signedXml.KeyInfo = keyInfo;

            // Compute the signature.
            signedXml.ComputeSignature();

            // Get the XML representation of the signature and save
            // it to an XmlElement object.
            XmlElement xmlDigitalSignature = signedXml.GetXml();

            // Append the element to the XML document.
            doc.DocumentElement.AppendChild(doc.ImportNode(xmlDigitalSignature, true));


            if (doc.FirstChild is XmlDeclaration)
            {
                doc.RemoveChild(doc.FirstChild);
            }

            // Save the signed XML document to a file specified
            // using the passed string.
            XmlTextWriter xmltw = new XmlTextWriter(SignedFileName, new UTF8Encoding(false));

            doc.WriteTo(xmltw);
            xmltw.Close();
        }
Example #22
0
    // <Snippet2>
    // Sign an XML file and save the signature in a new file.
    public static void SignXmlFile(string FileName, string SignedFileName, string SubjectName)
    {
        if (null == FileName)
        {
            throw new ArgumentNullException("FileName");
        }
        if (null == SignedFileName)
        {
            throw new ArgumentNullException("SignedFileName");
        }
        if (null == SubjectName)
        {
            throw new ArgumentNullException("SubjectName");
        }

        // Load the certificate from the certificate store.
        X509Certificate2 cert = GetCertificateBySubject(SubjectName);

        // Create a new XML document.
        XmlDocument doc = new XmlDocument();

        // Format the document to ignore white spaces.
        doc.PreserveWhitespace = false;

        // Load the passed XML file using it's name.
        doc.Load(new XmlTextReader(FileName));

        // Create a SignedXml object.
        SignedXml signedXml = new SignedXml(doc);

        // Add the key to the SignedXml document.
        signedXml.SigningKey = cert.PrivateKey;

        // Create a reference to be signed.
        Reference reference = new Reference();

        reference.Uri = "";

        // Add an enveloped transformation to the reference.
        XmlDsigEnvelopedSignatureTransform env = new XmlDsigEnvelopedSignatureTransform();

        reference.AddTransform(env);

        // Add the reference to the SignedXml object.
        signedXml.AddReference(reference);

        // Create a new KeyInfo object.
        KeyInfo keyInfo = new KeyInfo();

        // Load the certificate into a KeyInfoX509Data object
        // and add it to the KeyInfo object.
        KeyInfoX509Data X509KeyInfo = new KeyInfoX509Data(cert, X509IncludeOption.WholeChain);

        keyInfo.AddClause(X509KeyInfo);

        // Add the KeyInfo object to the SignedXml object.
        signedXml.KeyInfo = keyInfo;

        // Compute the signature.
        signedXml.ComputeSignature();

        // Get the XML representation of the signature and save
        // it to an XmlElement object.
        XmlElement xmlDigitalSignature = signedXml.GetXml();

        // Append the element to the XML document.
        doc.DocumentElement.AppendChild(doc.ImportNode(xmlDigitalSignature, true));


        if (doc.FirstChild is XmlDeclaration)
        {
            doc.RemoveChild(doc.FirstChild);
        }

        // Save the signed XML document to a file specified
        // using the passed string.
        using (XmlTextWriter xmltw = new XmlTextWriter(SignedFileName, new UTF8Encoding(false)))
        {
            doc.WriteTo(xmltw);
            xmltw.Close();
        }
    }
        /// <summary>
        /// Kept separate so get good stack trace in case of an exception
        /// </summary>
        private void SetupForTraceImpl()
        {
            this.configFileState = File.Exists(this.configFileName) ? ConfigFileState.Existed : ConfigFileState.Missing;

            XmlDocument config = new XmlDocument();

            if (this.configFileState == ConfigFileState.Existed)
            {
                config.Load(this.configFileName);
            }

            XPathNavigator configNav = config.CreateNavigator();

            // Add <configuration> element if not already present
            XPathNavigator configurationElementNav = configNav.SelectSingleNode("/configuration");

            if (configurationElementNav == null)
            {
                configNav.AppendChildElement(null, "configuration", null, null);
                configurationElementNav = configNav.SelectSingleNode("/configuration");
            }

            // Add system.diagnostics section, replace any existing section
            XPathNavigator systemDiagnosticsElementNav = configNav.SelectSingleNode("/configuration/system.diagnostics");

            if (systemDiagnosticsElementNav != null)
            {
                systemDiagnosticsElementNav.ReplaceSelf(DiagnosticsSectionTemplate.Replace("#LOGFILE#", this.traceFileName));
            }
            else
            {
                configurationElementNav.PrependChild(DiagnosticsSectionTemplate.Replace("#LOGFILE#", this.traceFileName));
            }

            // Add <system.serviceModel> element if not already present
            XPathNavigator serviceModelNav = configNav.SelectSingleNode("/configuration/system.serviceModel");

            if (serviceModelNav == null)
            {
                configurationElementNav.AppendChildElement(null, "system.serviceModel", null, null);
                serviceModelNav = configNav.SelectSingleNode("/configuration/system.serviceModel");
            }

            // Add service model diagnostics section, replace any existing section
            XPathNavigator serviceModelDiagnosticsElementNav = configNav.SelectSingleNode("/configuration/system.serviceModel/diagnostics");

            if (serviceModelDiagnosticsElementNav != null)
            {
                serviceModelDiagnosticsElementNav.ReplaceSelf(ServiceModelSection);
            }
            else
            {
                serviceModelNav.PrependChild(ServiceModelSection);
            }

            // Write the new config file
            try
            {
                if (this.configFileState == ConfigFileState.Existed)
                {
                    this.renamedConfigFileName = this.configFileName + "._wcfunit";
                    File.Move(this.configFileName, this.renamedConfigFileName);
                    this.configFileState = ConfigFileState.Moved;
                    Trace.WriteLine(string.Format(CultureInfo.InvariantCulture, "Renamed application config file for the program under test to {0}", this.renamedConfigFileName));
                }

                XmlWriterSettings settings = new XmlWriterSettings();
                settings.Indent      = true;
                settings.CloseOutput = true;
                settings.Encoding    = Encoding.UTF8;
                using (XmlWriter xw = XmlWriter.Create(this.configFileName, settings))
                {
                    config.WriteTo(xw);
                }
            }
            catch (UnauthorizedAccessException uae)
            {
                if (this.configFileState == ConfigFileState.Moved)
                {
                    File.Move(this.renamedConfigFileName, this.configFileName);
                    this.configFileState = ConfigFileState.Unknown;
                }

                throw new UserException(Messages.SRMAccessDenied, uae);
            }
            catch (Exception)
            {
                // Make sure we put things back if we can whatever happens
                if (this.configFileState == ConfigFileState.Moved)
                {
                    File.Move(this.renamedConfigFileName, this.configFileName);
                    this.configFileState = ConfigFileState.Unknown;
                }

                throw;
            }
        }
        public void ProcessSmilrefNodes(XmlDocument instanceDoc, string baseUri, bool WriteInterrim)
        {
            System.Collections.Hashtable smilfiles = new System.Collections.Hashtable();
            XmlNamespaceManager          xukNsmgr  = new XmlNamespaceManager(instanceDoc.NameTable);

            xukNsmgr.AddNamespace("xuk", XUK_NS);
            XmlNodeList cnNodes = instanceDoc.SelectNodes(
                "//xuk:TreeNode[xuk:mProperties/xuk:XmlProperty/xuk:XmlAttribute[@name='smilref']]",
                xukNsmgr);
            int count         = 0;
            int nextFireCount = 0;

            foreach (XmlNode nod in cnNodes)
            {
                count++;
                if (count > nextFireCount)
                {
                    FireProgress(String.Format(
                                     "Handling smilrefs {0:0}%",
                                     (100 * count) / cnNodes.Count));
                    nextFireCount += cnNodes.Count / 10;
                }
                XmlElement coreNode    = (XmlElement)nod;
                XmlElement smilrefAttr = (XmlElement)coreNode.SelectSingleNode(
                    "xuk:mProperties/xuk:XmlProperty/xuk:XmlAttribute[@name='smilref']",
                    xukNsmgr);
                string[] temps = smilrefAttr.InnerText.Split('#');
                if (temps.Length == 2)
                {
                    string  id       = "";
                    XmlNode tempNode = coreNode.SelectSingleNode(
                        "xuk:mProperties/xuk:XmlProperty/xuk:XmlAttribute[@name='id']",
                        xukNsmgr);
                    if (tempNode != null)
                    {
                        id = tempNode.InnerText.Trim();
                    }
                    if (id.IndexOfAny(new char[] { '\'', '\"' }) != -1)
                    {
                        Console.WriteLine("Invalid id attribute value {0}", id);
                    }
                    string smilPath   = temps[0];
                    string smilAnchor = temps[1];
                    if (smilAnchor.IndexOfAny(new char[] { '\'', '\"' }) != -1)
                    {
                        Console.WriteLine("Invalid smil anchor {0}", smilAnchor);
                        continue;
                    }
                    XmlDocument smilDoc;
                    if (smilfiles.ContainsKey(smilPath))
                    {
                        smilDoc = (XmlDocument)smilfiles[smilPath];
                    }
                    else
                    {
                        smilDoc = new XmlDocument();
                        try
                        {
                            smilDoc.Load(System.IO.Path.Combine(
                                             System.IO.Path.GetDirectoryName(baseUri),
                                             smilPath));
                        }
                        catch (Exception e)
                        {
                            Console.WriteLine("Could not load smilfile {0}: {1}", smilPath, e.Message);
                            continue;
                        }
                        smilfiles.Add(smilPath, smilDoc);
                    }
                    string smilPrefix         = "";
                    XmlNamespaceManager nsmgr = new XmlNamespaceManager(smilDoc.NameTable);
                    if (smilDoc.DocumentElement.NamespaceURI != "")
                    {
                        smilPrefix = "smil:";
                        nsmgr.AddNamespace("smil", smilDoc.DocumentElement.NamespaceURI);
                    }
                    tempNode = (XmlElement)smilDoc.GetElementById(smilAnchor);
                    if (tempNode == null)
                    {
                        Console.WriteLine("Could not find smil time container {0}", smilrefAttr.
                                          InnerText);
                        continue;
                    }
                    XmlElement targetTimeContainer = (XmlElement)tempNode;
                    string     textLinkBackSrc     = "";
                    string     xpath = String.Format(
                        "descendant-or-self::{0}text[substring-after(@src, '#')='{2}']/@src",
                        smilPrefix, smilAnchor, id);
                    tempNode = targetTimeContainer.SelectSingleNode(xpath, nsmgr);
                    if (tempNode != null)
                    {
                        textLinkBackSrc = tempNode.Value.Trim();
                    }
                    if (textLinkBackSrc == "")
                    {
                        Console.WriteLine("No text linking back found for smilref {0}", smilrefAttr.Value);
                        continue;
                    }
                    else if (textLinkBackSrc.IndexOfAny(new char[] { '\'', '\"' }) != -1)
                    {
                        Console.WriteLine("Invalid src attribute of text linking back: {0}", textLinkBackSrc);
                        continue;
                    }
                    xpath = String.Format(".//{0}par[{0}text[@src='{1}']]", smilPrefix, textLinkBackSrc);
                    XmlNodeList smilTimeContainers = targetTimeContainer.ParentNode.SelectNodes(xpath, nsmgr);
                    if (smilTimeContainers.Count > 1)
                    {
                        xpath = String.Format(
                            ".//{0}par[{0}text[@src='{1}']] "
                            + "| .//{0}par[(preceding::{0}text[@src='{1}']) and (following::{0}text[@src='{1}'])]",
                            smilPrefix, textLinkBackSrc);
                        smilTimeContainers = targetTimeContainer.ParentNode.SelectNodes(xpath, nsmgr);
                    }
                    XmlElement   audioChannelMapping = instanceDoc.CreateElement("ChannelMapping", XUK_NS);
                    XmlElement[] audioMedias         = new XmlElement[0];
                    audioChannelMapping.SetAttribute("channel", "audioChannel");
                    xpath = String.Format(".//{0}audio", smilPrefix);
                    for (int tcNo = 0; tcNo < smilTimeContainers.Count; tcNo++)
                    {
                        XmlNodeList sans = smilTimeContainers[tcNo].SelectNodes(xpath, nsmgr);
                        if (sans.Count > 0)
                        {
                            XmlElement[] tempAM = audioMedias;
                            audioMedias = new XmlElement[tempAM.Length + sans.Count];
                            tempAM.CopyTo(audioMedias, 0);
                            for (int i = 0; i < sans.Count; i++)
                            {
                                XmlElement smilAudioElem = (XmlElement)sans[i];
                                XmlElement audioMedia    = instanceDoc.CreateElement("Media");
                                audioMedia = instanceDoc.CreateElement("AudioMedia", XUK_NS);
                                audioMedia.SetAttribute("clipBegin", smilAudioElem.GetAttribute("clipBegin"));
                                audioMedia.SetAttribute("clipEnd", smilAudioElem.GetAttribute("clipEnd"));
                                audioMedia.SetAttribute("id", smilAudioElem.GetAttribute("id"));
                                audioMedia.SetAttribute("src", smilAudioElem.GetAttribute("src"));
                                audioMedias[i + tempAM.Length] = audioMedia;
                            }
                        }
                    }
                    switch (audioMedias.Length)
                    {
                    case 0:
                        break;

                    case 1:
                        audioChannelMapping.AppendChild(audioMedias[0]);
                        break;

                    default:
                        XmlElement seqMedia = instanceDoc.CreateElement("SequenceMedia", XUK_NS);
                        foreach (XmlElement am in audioMedias)
                        {
                            seqMedia.AppendChild(am);
                        }
                        audioChannelMapping.AppendChild(seqMedia);
                        break;
                    }
                    if (audioMedias.Length > 0)
                    {
                        if (coreNode.SelectNodes("TreeNode[.//XmlAttribute[@name='smilref']]").Count > 0)
                        {
                            XmlElement NonDistributedAudios = instanceDoc.CreateElement("NonDistributedAudios", XUK_NS);
                            NonDistributedAudios.SetAttribute("smilref", smilrefAttr.Value);
                            NonDistributedAudios.AppendChild(audioChannelMapping);
                            coreNode.AppendChild(NonDistributedAudios);
                        }
                        else
                        {
                            coreNode.SelectSingleNode("xuk:mProperties/xuk:ChannelsProperty", xukNsmgr).AppendChild(audioChannelMapping);
                        }
                        smilrefAttr.ParentNode.RemoveChild(smilrefAttr);
                    }
                }
            }
            if (WriteInterrim)
            {
                string interrimPath =
                    System.IO.Path.Combine(
                        System.IO.Path.GetDirectoryName(DTBOOKPath),
                        System.IO.Path.GetFileNameWithoutExtension(DTBOOKPath))
                    + ".interrim.xuk";
                try
                {
                    XmlTextWriter wr = new XmlTextWriter(
                        interrimPath, System.Text.Encoding.UTF8);
                    wr.Indentation = 1;
                    wr.Formatting  = Formatting.Indented;
                    instanceDoc.WriteTo(wr);
                    wr.Close();
                }
                catch (Exception e)
                {
                    throw new ApplicationException(
                              String.Format("Could not write interrim XUK: {0}", e.Message),
                              e);
                }
            }
            ProcessNestedSmilrefNodes(instanceDoc);
            foreach (XmlNode mediaNod in instanceDoc.SelectNodes(".//Media[@id]"))
            {
                XmlElement media = (XmlElement)mediaNod;
                media.Attributes.RemoveNamedItem("id");
            }
        }
Example #25
0
        public int Execute(PackOptions options)
        {
            var sourcePath = Path.GetFullPath(options.ManifestPath);
            var outputPath = Path.GetDirectoryName(Path.GetFullPath(options.OutputPath));

            var stagingPath = Path.Combine(outputPath, Path.GetFileNameWithoutExtension(options.OutputPath));

            var doc = new XmlDocument();

            doc.Load(Path.Combine(sourcePath, "manifest.xml"));

            if (!Directory.Exists(stagingPath))
            {
                Directory.CreateDirectory(stagingPath);
            }
            if (Directory.EnumerateFileSystemEntries(stagingPath).Any())
            {
                throw new ApplicationException("Staging folder was not cleaned up");
            }

            var package = doc["package"];

            // Stage Forms

            if (package["FormList"] != null)
            {
                foreach (var form in package["FormList"].ChildNodes.Cast <XmlNode>().Where(n => n.LocalName == "Form"))
                {
                    Console.WriteLine($"Staging Form {form.Attributes["mname"].Value}");
                    var sourceFile = form.Attributes["fname"].Value;
                    File.Copy(Path.Combine(sourcePath, sourceFile), Path.Combine(stagingPath, sourceFile));
                }
            }

            // Stage Form Codebase Assemblies

            if (package["AssemblyList"] != null)
            {
                foreach (var codebase in package["AssemblyList"].ChildNodes.Cast <XmlNode>().Where(n => n.LocalName == "Assembly"))
                {
                    Console.WriteLine($"Staging Form Codebase {codebase.Attributes["name"].Value}");
                    var sourceFile = codebase.Attributes["fname"].Value;

                    if (options.SetAssemblyVersions)
                    {
                        var assemblyVersion = Assembly.ReflectionOnlyLoadFrom(Path.Combine(sourcePath, sourceFile)).GetName().Version;
                        Console.WriteLine("Assembly Version {0}", assemblyVersion);

                        if (codebase.Attributes["version"] == null)
                        {
                            codebase.Attributes.Append(doc.CreateAttribute("version"));
                        }

                        codebase.Attributes["version"].Value = assemblyVersion.ToString();
                    }

                    File.Copy(Path.Combine(sourcePath, sourceFile), Path.Combine(stagingPath, sourceFile));
                }
            }

            // Stage Plugin Assemblies

            if (package["PluginList"] != null)
            {
                Directory.CreateDirectory(Path.Combine(stagingPath, "Plugins"));

                foreach (var plugin in package["PluginList"].ChildNodes.Cast <XmlNode>().Where(n => n.LocalName == "Plugin"))
                {
                    Console.WriteLine($"Staging Plugin {plugin.Attributes["name"].Value}");
                    var sourceFile = plugin.Attributes["fname"].Value;

                    if (options.SetAssemblyVersions)
                    {
                        var assemblyVersion = Assembly.ReflectionOnlyLoadFrom(Path.Combine(sourcePath, sourceFile)).GetName().Version;
                        Console.WriteLine("Assembly Version {0}", assemblyVersion);

                        if (plugin.Attributes["version"] == null)
                        {
                            plugin.Attributes.Append(doc.CreateAttribute("version"));
                        }

                        plugin.Attributes["version"].Value = assemblyVersion.ToString();
                    }

                    File.Copy(Path.Combine(sourcePath, sourceFile), Path.Combine(stagingPath, "Plugins", sourceFile));
                }
            }


            // Stage Custom Data Objects

            if (package["CustomDataObjectList"] != null)
            {
                Directory.CreateDirectory(Path.Combine(stagingPath, "CustomData"));

                foreach (var cdo in package["CustomDataObjectList"].ChildNodes.Cast <XmlNode>().Where(n => n.LocalName == "CustomDataObject"))
                {
                    Console.WriteLine($"Staging Custom Data Object {cdo.Attributes["name"].Value}");
                    var sourceFile = cdo.Attributes["fname"].Value;
                    File.Copy(Path.Combine(sourcePath, "CustomData", sourceFile), Path.Combine(stagingPath, "CustomData", sourceFile));
                }
            }

            // Stage Manifest

            Console.WriteLine("Staging Manifest");
            using (var writer = XmlWriter.Create(Path.Combine(stagingPath, "manifest.xml"), new XmlWriterSettings
            {
                Indent = true,
                OmitXmlDeclaration = true,
            }))
            {
                doc.WriteTo(writer);
            }

            // Make the Package File

            ZipFile.CreateFromDirectory(stagingPath, options.OutputPath, CompressionLevel.Optimal, includeBaseDirectory: false);

            // Clean up the staging directory

            Directory.Delete(stagingPath, recursive: true);

            return(0);
        }
Example #26
0
    // Sign an XML file and save the signature in a new file.
    public static void SignXmlFile(string FileName, string SignedFileName, RSA Key, string[] ElementsToSign)
    {
        // Check the arguments.
        if (FileName == null)
        {
            throw new ArgumentNullException(nameof(FileName));
        }
        if (SignedFileName == null)
        {
            throw new ArgumentNullException(nameof(SignedFileName));
        }
        if (Key == null)
        {
            throw new ArgumentNullException(nameof(Key));
        }
        if (ElementsToSign == null)
        {
            throw new ArgumentNullException(nameof(ElementsToSign));
        }

        // Create a new XML document.
        XmlDocument doc = new XmlDocument();

        // Format the document to ignore white spaces.
        doc.PreserveWhitespace = false;

        // Load the passed XML file using it's name.
        doc.Load(new XmlTextReader(FileName));

        // Create a SignedXml object.
        SignedXml signedXml = new SignedXml(doc);

        // Add the key to the SignedXml document.
        signedXml.SigningKey = Key;

        // Loop through each passed element to sign
        // and create a reference.
        foreach (string s in ElementsToSign)
        {
            // Create a reference to be signed.
            Reference reference = new Reference();
            reference.Uri = s;

            // Add an enveloped transformation to the reference.
            XmlDsigEnvelopedSignatureTransform env = new XmlDsigEnvelopedSignatureTransform();
            reference.AddTransform(env);

            // Add the reference to the SignedXml object.
            signedXml.AddReference(reference);
        }

        // Add an RSAKeyValue KeyInfo (optional; helps recipient find key to validate).
        KeyInfo keyInfo = new KeyInfo();

        keyInfo.AddClause(new RSAKeyValue((RSA)Key));
        signedXml.KeyInfo = keyInfo;

        // Compute the signature.
        signedXml.ComputeSignature();

        // Get the XML representation of the signature and save
        // it to an XmlElement object.
        XmlElement xmlDigitalSignature = signedXml.GetXml();

        // Append the element to the XML document.
        doc.DocumentElement.AppendChild(doc.ImportNode(xmlDigitalSignature, true));

        if (doc.FirstChild is XmlDeclaration)
        {
            doc.RemoveChild(doc.FirstChild);
        }

        // Save the signed XML document to a file specified
        // using the passed string.
        XmlTextWriter xmltw = new XmlTextWriter(SignedFileName, new UTF8Encoding(false));

        doc.WriteTo(xmltw);
        xmltw.Close();
    }
    protected void bttnExport_Click(object sender, EventArgs e)
    {

        ISession session = (ISession)Context.Items[Constant.NHibernateSessionSign];

        Response.AddHeader("Content-disposition", "attachment; filename=numeric_settings.xml");
        Response.ContentType = "text/xml";
        int count = 0;
        //IList<NumericConfiguration> numericConfigurations = ServicesList.ConfigurationService.GetNumericSettings(this.CurrentPlayer, out count, session);

        XmlDocument document = new XmlDocument();
        
        document.AppendChild(document.CreateXmlDeclaration("1.0", "utf-8", "yes"));
        XmlNode numerics = document.AppendChild(document.CreateNode(XmlNodeType.Element, "numerics", null));

        foreach (NumericConfiguration config in Configuration.TribalWarsConfiguration.NumericConfiguration.Values)
        {
            XmlNode parentNode = numerics.AppendChild(document.CreateNode(XmlNodeType.Element, "numeric", null));
            XmlNode keyNode = parentNode.AppendChild(document.CreateNode(XmlNodeType.Element, "key", null));
            keyNode.AppendChild(document.CreateNode(XmlNodeType.Text, "key", null)).Value = config.Key;
            XmlNode valueNode = parentNode.AppendChild(document.CreateNode(XmlNodeType.Element, "value", null));
            valueNode.AppendChild(document.CreateNode(XmlNodeType.Text, "value", null)).Value = config.Value.ToString();
        }

        System.IO.TextWriter sw = new System.IO.StringWriter();
        XmlTextWriter xtw = new XmlTextWriter(sw);
        xtw.Formatting = Formatting.Indented;
        document.WriteTo(xtw);

        Response.Write(sw.ToString());
        Response.End();
        
    }
Example #28
0
 private string XmlToString(XmlDocument doc)
 {
     StringWriter sw = new StringWriter();
     XmlTextWriter tw = new XmlTextWriter(sw);
     doc.WriteTo(tw);
     return sw.ToString();
 }
Example #29
0
        /// <summary>
        /// Commit into the database the ldapsetting
        /// </summary>
        public void Commit()
        {
            if (settingChangeMap != 0)
            {
                // Build a path to the Simias.config file.
                string configFilePath =
                    Path.Combine(storePath, Simias.Configuration.DefaultConfigFileName);

                // Load the configuration file into an xml document.
                XmlDocument configDoc = new XmlDocument();
                configDoc.Load(configFilePath);

                if ((settingChangeMap & ChangeMap.uri) != ChangeMap.unchanged)
                {
                    SetConfigValue(configDoc, LdapAuthenticationSection, UriKey, uri.ToString());
                }
                else if ((settingChangeMap & (ChangeMap.scheme | ChangeMap.host | ChangeMap.port)) != ChangeMap.unchanged)
                {
                    UriBuilder ub = new UriBuilder(scheme, host, port);
                    SetConfigValue(configDoc, LdapAuthenticationSection, UriKey, ub.Uri.ToString());
                }

                if ((settingChangeMap & ChangeMap.proxy) == ChangeMap.proxy)
                {
                    SetConfigValue(configDoc, LdapAuthenticationSection, ProxyDNKey, proxy);
                }

                if ((settingChangeMap & ChangeMap.namingAttribute) == ChangeMap.namingAttribute)
                {
                    SetConfigValue(configDoc, LdapSystemBookSection, NamingAttributeKey, namingAttribute);
                }

                if ((settingChangeMap & ChangeMap.searchContexts) == ChangeMap.searchContexts)
                {
                    XmlElement searchElement = GetSearchElement(configDoc);
                    if (searchElement != null)
                    {
                        XmlNodeList contextNodes = searchElement.SelectNodes(XmlContextTag);
                        foreach (XmlElement contextNode in contextNodes)
                        {
                            searchElement.RemoveChild(contextNode);
                        }

                        foreach (string dn in searchContexts)
                        {
                            XmlElement element = configDoc.CreateElement(XmlContextTag);
                            element.SetAttribute(XmlDNAttr, dn);
                            searchElement.AppendChild(element);
                        }
                    }
                }

                if ((settingChangeMap & ChangeMap.password) == ChangeMap.password)
                {
                    SetProxyPasswordInFile();
                }

                switch (ldapType)
                {
                case LdapDirectoryType.ActiveDirectory:
                    SetConfigValue(configDoc, IdentitySection, AssemblyKey, "Simias.ADLdapProvider");
                    SetConfigValue(configDoc, IdentitySection, ClassKey, "Simias.ADLdapProvider.User");
                    break;

                case LdapDirectoryType.eDirectory:
                    SetConfigValue(configDoc, IdentitySection, AssemblyKey, "Simias.LdapProvider");
                    SetConfigValue(configDoc, IdentitySection, ClassKey, "Simias.LdapProvider.User");
                    break;

                case LdapDirectoryType.OpenLDAP:
                    SetConfigValue(configDoc, IdentitySection, AssemblyKey, "Simias.OpenLdapProvider");
                    SetConfigValue(configDoc, IdentitySection, ClassKey, "Simias.OpenLdapProvider.User");
                    break;

                default:
                    throw new Exception("The LDAP directory type is unknown!");
                }

                // Write the configuration file settings.
                XmlTextWriter xtw = new XmlTextWriter(configFilePath, Encoding.UTF8);
                try
                {
                    xtw.Formatting = Formatting.Indented;
                    configDoc.WriteTo(xtw);
                }
                finally
                {
                    xtw.Close();
                }
            }
        }
Example #30
0
        public HttpResponseMessage ExportUsersToXML()
        {
            var users = userService.Find().Where(i => !i.IsDeleted).Select(i => new
            {
                i.Id,
                i.FirstName,
                i.LastName,
                i.UserName,
                i.Email
            }).ToList();

            try
            {
                using (MemoryStream ms = new MemoryStream())
                {
                    XmlWriterSettings xmlWriterSettings = new XmlWriterSettings()
                    {
                        Indent = true
                    };
                    using (XmlWriter writer = XmlWriter.Create(ms, xmlWriterSettings))
                    {
                        XmlDocument doc = new XmlDocument();
                        doc.LoadXml("<Users></Users>");
                        foreach (var user in users)
                        {
                            XmlElement userElem = doc.CreateElement("User");
                            doc.DocumentElement.AppendChild(userElem);

                            XmlElement newElem = doc.CreateElement("FirstName");
                            newElem.InnerText = user.FirstName;
                            userElem.AppendChild(newElem);

                            newElem           = doc.CreateElement("LastName");
                            newElem.InnerText = user.LastName;
                            userElem.AppendChild(newElem);

                            newElem           = doc.CreateElement("UserName");
                            newElem.InnerText = user.UserName;
                            userElem.AppendChild(newElem);

                            newElem           = doc.CreateElement("Email");
                            newElem.InnerText = user.Email;
                            userElem.AppendChild(newElem);
                        }

                        doc.WriteTo(writer); // Write to memorystream
                    }
                    var result = new HttpResponseMessage(HttpStatusCode.OK)
                    {
                        Content = new ByteArrayContent(ms.ToArray())
                    };
                    result.Content.Headers.ContentType        = new MediaTypeHeaderValue("application/xml");
                    result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
                    {
                        FileName = "Users_" + DateTime.UtcNow.ToLocalTime().ToString("MMddyyyy_hhmm") + ".xml"
                    };
                    return(result);
                }
            }
            catch (Exception)
            {
                return(new HttpResponseMessage(HttpStatusCode.InternalServerError)
                {
                    Content = new StringContent("Export failed")
                });
            }
        }
Example #31
0
        /*
         *
         *
         *
         *  <?xml version="1.0" encoding="UTF-8"?>
         *  <request  protocol=”SmesX” version="2.2"
         *  user="******" password="******">
         *  <send_sms>
         *  <msisdn>Numer_MSISDN</msisdn>
         *  <body>Tutaj treść SMS-a</body>
         *  <expire_at>yyyy-mm-dd hh:mi:ss</expire_at>
         *  <sender>Nadawca</sender>
         *  <sms_type>Kod typu smsa</sms_type>
         *  <send_after>yyyy-mm-dd hh:mi:ss</send_after>
         *  </send_sms>
         *  </request
         *
         *
         */
        //do sprawdzenie i poprawienia, pradwdopodobnie wogole nie wysyla poprawnie xml-a, ale zakladajac ze uda sie wyslac xml-a wiadomosc powinna sie wyslac.
        //UWAGAŁ login i haslo nie jest to samo co podczas zakladania konta w serwisie. Prawdilowe dostepne jest dopiero po zalogowaniu w dziale interfejsy
        public string sendSMSbySmeskom(string recipient, string sender, string message)
        {
            XmlDocument doc     = new XmlDocument();
            XmlNode     docNode = doc.CreateXmlDeclaration("1.0", "UTF-8", null);

            doc.AppendChild(docNode);

            XmlNode      requestNode        = doc.CreateElement("request");
            XmlAttribute requestAttributePr = doc.CreateAttribute("protocol");

            requestAttributePr.Value = "SmesX";
            requestNode.Attributes.Append(requestAttributePr);
            XmlAttribute requestAttributeVer = doc.CreateAttribute("version");

            requestAttributeVer.Value = "2.2";
            requestNode.Attributes.Append(requestAttributeVer);
            XmlAttribute requestAttributeUser = doc.CreateAttribute("user");

            requestAttributeUser.Value = "htguser3113";
            requestNode.Attributes.Append(requestAttributeUser);
            XmlAttribute requestAttributePassword = doc.CreateAttribute("password");

            requestAttributePassword.Value = "qmWuU3pP";
            requestNode.Attributes.Append(requestAttributePassword);
            doc.AppendChild(requestNode);

            XmlNode sendSmsNode = doc.CreateElement("send_sms");

            requestNode.AppendChild(sendSmsNode);

            XmlNode msisdnNode = doc.CreateElement("msisdn");

            msisdnNode.AppendChild(doc.CreateTextNode("604 212 480"));
            sendSmsNode.AppendChild(msisdnNode);
            XmlNode bodyNode = doc.CreateElement("body");

            bodyNode.AppendChild(doc.CreateTextNode("Tekst"));
            sendSmsNode.AppendChild(bodyNode);


            StringWriter  sw = new StringWriter();
            XmlTextWriter xw = new XmlTextWriter(sw);

            doc.WriteTo(xw);
            string xml = sw.ToString();

            Console.WriteLine(xml);
            byte[] bytes = Encoding.UTF8.GetBytes(xml);


            WebRequest request =
                WebRequest.Create("https://smesx1.smeskom.pl:2200/smesx");

            request.Method        = "POST";
            request.ContentLength = bytes.Length;
            request.Timeout       = 300;
            request.ContentType   = "text/xml; encoding='UTF-8'";
            request.Method        = "_POST";
            //request.Credentials = new
            NetworkCredential("htguser3112", "qmWuU3pP");
            Stream requestStream = request.GetRequestStream();

            requestStream.Write(bytes, 0, bytes.Length);
            WebResponse  response = request.GetResponse();
            StreamReader reader   = new
                                    StreamReader(response.GetResponseStream());
            string str = reader.ReadLine();

            while (str != null)
            {
                Console.WriteLine(str);
                str = reader.ReadLine();
            }



            return("test");
        }
Example #32
0
        void RunTest(SgmlReader reader, int line, string args, string input, string expectedOutput)
        {
            bool testdoc = false;

            foreach (string arg in args.Split(' '))
            {
                string sarg = arg.Trim();
                if (sarg.Length == 0)
                {
                    continue;
                }
                if (sarg[0] == '-')
                {
                    switch (sarg.Substring(1))
                    {
                    case "html":
                        reader.DocType = "html";
                        break;

                    case "lower":
                        reader.CaseFolding = CaseFolding.ToLower;
                        break;

                    case "upper":
                        reader.CaseFolding = CaseFolding.ToUpper;
                        break;

                    case "testdoc":
                        testdoc = true;
                        break;
                    }
                }
            }
            this.tests++;
            reader.InputStream        = new StringReader(input);
            reader.WhitespaceHandling = WhitespaceHandling.None;
            StringWriter  output = new StringWriter();
            XmlTextWriter w      = new XmlTextWriter(output);

            w.Formatting = Formatting.Indented;
            if (testdoc)
            {
                XmlDocument doc = new XmlDocument();
                doc.Load(reader);
                doc.WriteTo(w);
            }
            else
            {
                reader.Read();
                while (!reader.EOF)
                {
                    w.WriteNode(reader, true);
                }
            }
            w.Close();
            string actualOutput = output.ToString();

            if (actualOutput.Trim() != expectedOutput.Trim())
            {
                Console.WriteLine("ERROR: Test failed on line {0}", line);
                Console.WriteLine("---- Expected output");
                Console.WriteLine(expectedOutput);
                Console.WriteLine("---- Actual output");
                Console.WriteLine(actualOutput);
            }
            else
            {
                this.passed++;
            }
        }
Example #33
0
        private void PopulateSeries(string studyInstanceUid)
        {
            LogTextPanel.Text  = "";
            StatisticsLog.Text = "";
            HeaderStreamingServiceClient proxy = null;

            try
            {
                proxy = new HeaderStreamingServiceClient();
                HeaderStreamingParameters parms = new HeaderStreamingParameters();
                parms.StudyInstanceUID = studyInstanceUid;
                parms.ServerAETitle    = ServerAE.Text;
                parms.ReferenceID      = Guid.NewGuid().ToString();

                TimeSpanStatistics servicecall = new TimeSpanStatistics();
                servicecall.Start();
                Stream stream = proxy.GetStudyHeader(AETitle.Text, parms);

                servicecall.End();


                TimeSpanStatistics decompression = new TimeSpanStatistics();
                decompression.Start();

                //GZipStream gzipStream = new GZipStream(stream, CompressionMode.Decompress);
                XmlDocument doc = new XmlDocument();
                StudyXmlIo.ReadGzip(doc, stream);
                //doc.Load(gzipStream);

                decompression.End();


                XmlWriterSettings settings = new XmlWriterSettings();
                //settings.Indent = true;
                settings.NewLineOnAttributes = false;
                settings.OmitXmlDeclaration  = true;
                settings.Encoding            = Encoding.UTF8;
                StringWriter sw     = new StringWriter();
                XmlWriter    writer = XmlWriter.Create(sw, settings);
                doc.WriteTo(writer);
                writer.Flush();
                Log(sw.ToString());

                TimeSpanStatistics loading = new TimeSpanStatistics();
                loading.Start();

                StudyXml xml = new StudyXml();
                xml.SetMemento(doc);
                loading.End();

                int sopCounter = 0;
                SeriesTree.Nodes.Clear();
                foreach (SeriesXml series in xml)
                {
                    TreeNode seriesNode = new TreeNode(series.SeriesInstanceUid);
                    SeriesTree.Nodes.Add(seriesNode);
                    foreach (InstanceXml instance in series)
                    {
                        TreeNode instanceNode = new TreeNode(instance.SopInstanceUid);
                        seriesNode.Nodes.Add(instanceNode);
                        sopCounter++;
                    }
                }



                StatisticsLog.Text  = "";
                StatisticsLog.Text += String.Format("\r\nHeader Size (Decompressed): {0} KB", sw.ToString().Length / 1024);

                StatisticsLog.Text += String.Format("\r\nWCF Service call  : {0} ms", servicecall.Value.TotalMilliseconds);
                StatisticsLog.Text += String.Format("\r\nDecompression    : {0} ms", decompression.Value.TotalMilliseconds);
                StatisticsLog.Text += String.Format("\r\nLoading StudyXml : {0} ms", loading.Value.TotalMilliseconds);


                SeriesLabel.Text = String.Format("Series : {0} \tInstances: {1}", SeriesTree.Nodes.Count, sopCounter);

                stream.Close();
            }
            catch (FaultException <StudyIsInUseFault> ex)
            {
                timer1.Stop();
                MessageBox.Show(String.Format("StudyIsInUseFault received:{0}\n\nState={1}",
                                              ex.Message, ex.Detail.StudyState));
            }
            catch (FaultException <StudyIsNearlineFault> ex)
            {
                timer1.Stop();
                MessageBox.Show("StudyIsNearlineFault received:\n" + ex.Message);
            }
            catch (FaultException <StudyNotFoundFault> ex)
            {
                timer1.Stop();
                MessageBox.Show("StudyNotFoundFault received:\n" + ex.Message);
            }
            catch (Exception ex)
            {
                timer1.Stop();
                MessageBox.Show(ex.Message);
            }
            finally
            {
                if (proxy.State == CommunicationState.Opened)
                {
                    proxy.Close();
                }
            }
        }
Example #34
0
        /// <summary>
        /// Letölti az aktuális terméklistát a HRP szerveréről.
        /// A termékek a munkaasztal HRP listájába kerülnek.
        /// </summary>
        /// <param name="_termekszamlekeresenkent">Mennyi terméket kérjen le egyszerre egy POST requestben.</param>
        /// <param name="_endofsaleseldob">Már nem forgalmazott termékeket eldob?</param>
        /// <param name="_canceltoken"></param>
        /// <returns></returns>
        public static async Task Letolt(int _termekszamlekeresenkent, bool _endofsaleseldob, CancellationToken _canceltoken)
        {
            if (_canceltoken == null)
            {
                throw new ArgumentNullException(nameof(_canceltoken));
            }

            FolyamatValtozott?.Invoke(0, 0, string.Format("{0}/{1} termék lekérve ({2:P2})", 0, 0, 0));

            Globalisok.Munkaasztal.FrissTermekLista = new ObservableCollection <Model.Termek>();

            int oldalszam = 1, elemszam, lekertelemszam = 0;

            do
            {
                if (_canceltoken.IsCancellationRequested)
                {
                    break;
                }

                // Request XML létrehozása
                XmlDocument xml = HRP.Szolgaltatas.MetodusXML(Szolgaltatas.Metodusok.Termeklista);

                // Authentikációs kód megadása
                (xml.SelectSingleNode("/Envelope/Body/Request/Base/AuthCode") as XmlElement).InnerText = Globalisok.Beallitasok.HRPAuthKod;

                // Lekérdezésenkénti termékszám megadása
                (xml.SelectSingleNode("/Envelope/Body/Request/ItemsOnPage") as XmlElement).InnerText = _termekszamlekeresenkent.ToString("D");

                // Oldalszám megadása
                (xml.SelectSingleNode("/Envelope/Body/Request/CurrentPageIndex") as XmlElement).InnerText = oldalszam.ToString("D");

                // Request XML sztringgé alakítása
                string request_xml;

                using (var stringWriter = new StringWriter())
                    using (var xmlTextWriter = XmlWriter.Create(stringWriter, new XmlWriterSettings()
                    {
                        Indent = true
                    }))
                    {
                        xml.WriteTo(xmlTextWriter);
                        xmlTextWriter.Flush();
                        request_xml = stringWriter.GetStringBuilder().ToString();
                    }

                // POST request küldése és a válasz sztring kinyerése
                string rv_xml = await POST.Keres(Globalisok.Beallitasok.HRPURL + HRP.Szolgaltatas.MetodusNev(Szolgaltatas.Metodusok.Termeklista), request_xml);

                // Válasz XML létrehozása
                XmlDocument res_xml = new XmlDocument();

                res_xml.LoadXml(rv_xml);

                // Eredmény kiolvasása a válasz XML-ből
                XmlElement kod       = res_xml.SelectSingleNode("/Envelope/Body/Response/Header/Control/ReturnCode") as XmlElement,
                           uzenet    = res_xml.SelectSingleNode("/Envelope/Body/Response/Header/Control/ReturnText") as XmlElement,
                           listcount = res_xml.SelectSingleNode("/Envelope/Body/Response/Body/ListCount") as XmlElement;

                elemszam = Convert.ToInt32(listcount.InnerText);

                if (elemszam == 0)
                {
                    break;
                }

                // Terméklista kiolvasása a válasz XML-ből
                List <Model.Termek> termeklista = new List <Model.Termek>(_termekszamlekeresenkent);
                XmlNodeList         termeknodes = res_xml.SelectNodes("Envelope/Body/Response/Body/Items/CatalogueItem") as XmlNodeList;

                foreach (XmlNode node in termeknodes)
                {
                    Model.Termek termek = new Model.Termek()
                    {
                        ID                          = (node["ProductId"] as XmlElement).InnerText,
                        Cikkszam                    = (node["PartNumber"] as XmlElement).InnerText,
                        Megnevezes                  = (node["Name"] as XmlElement).InnerText,
                        Leiras                      = (node["Description"] as XmlElement).InnerText,
                        GyartoID                    = ((node["Manufacturer"] as XmlNode)["ManufacturerId"] as XmlElement).InnerText,
                        GyartoMegnevezes            = ((node["Manufacturer"] as XmlNode)["ManufacturerName"] as XmlElement).InnerText,
                        ElsoKategoriaID             = ((node["FirstLevelCategory"] as XmlNode)["FirstLevelCategoryId"] as XmlElement).InnerText,
                        ElsoKategoriaMegnevezes     = ((node["FirstLevelCategory"] as XmlNode)["FirstLevelCategoryName"] as XmlElement).InnerText,
                        MasodikKategoriaID          = ((node["SecondLevelCategory"] as XmlNode)["SecondLevelCategoryId"] as XmlElement).InnerText,
                        MasodikKategoriaMegnevezes  = ((node["SecondLevelCategory"] as XmlNode)["SecondLevelCategoryName"] as XmlElement).InnerText,
                        HarmadikKategoriaID         = ((node["ThirdLevelCategory"] as XmlNode)["ThirdLevelCategoryId"] as XmlElement).InnerText,
                        HarmadikKategoriaMegnevezes = ((node["ThirdLevelCategory"] as XmlNode)["ThirdLevelCategoryName"] as XmlElement).InnerText,
                        GaranciaMod                 = ((node["Garanty"] as XmlNode)["GarantyMode"] as XmlElement).InnerText,
                        GaranciaIdo                 = ((node["Garanty"] as XmlNode)["GarantyTime"] as XmlElement).InnerText,
                        Uj                          = Convert.ToBoolean((node["New"] as XmlElement).InnerText),
                        Kedvezmeny                  = Convert.ToBoolean((node["Discount"] as XmlElement).InnerText),
                        KeszletInfo                 = ((node["Stock"] as XmlNode)["StockInfo"] as XmlElement).InnerText,
                        VanRaktaron                 = Convert.ToBoolean(((node["Stock"] as XmlNode)["HasStock"] as XmlElement).InnerText),
                        KeszletSzam                 = Convert.ToInt32(((node["Stock"] as XmlNode)["Value"] as XmlElement).InnerText),
                        KulsoKeszletSzam            = Convert.ToInt32(((node["Stock"] as XmlNode)["ExternalStock"] as XmlElement).InnerText),
                        ErtekesitesVege             = Convert.ToBoolean((node["EndOfSales"] as XmlElement).InnerText),
                        KepID                       = (node["PictureId"] as XmlElement).InnerText,
                        Vonalkod                    = (node["BarCode"] as XmlElement).InnerText,
                        HasonloTermekID             = (node["PtaSimilarProduct"] as XmlElement).InnerText
                    };

#if CSAKNOTEBOOK
                    if (!termek.ElsoKategoriaID.Equals("M001") || !termek.MasodikKategoriaID.Equals("N001"))
                    {
                        continue;
                    }
#endif

                    if (_endofsaleseldob && termek.ErtekesitesVege)
                    {
                        continue;
                    }

                    //termek.Megnevezes = termek.Megnevezes.Replace('\n', ',').Replace('\r', ',');
                    termek.Leiras = termek.Leiras.Replace('\n', ',').Replace('\r', ',');

                    string tempstr = (node["Price"] as XmlElement).InnerText; termek.Ar = Convert.ToInt32((tempstr.Substring(0, tempstr.Length - 4)));

                    tempstr = (node["NetWeight"] as XmlElement).InnerText; if (!string.IsNullOrEmpty(tempstr))
                    {
                        termek.NettoSuly = Convert.ToDouble(tempstr, System.Globalization.CultureInfo.InvariantCulture);
                    }
                    tempstr = (node["GrossWeight"] as XmlElement).InnerText; if (!string.IsNullOrEmpty(tempstr))
                    {
                        termek.BruttoSuly = Convert.ToDouble(tempstr, System.Globalization.CultureInfo.InvariantCulture);
                    }
                    tempstr = (node["GrossWidth"] as XmlElement).InnerText; if (!string.IsNullOrEmpty(tempstr))
                    {
                        termek.Szelesseg = Convert.ToDouble(tempstr, System.Globalization.CultureInfo.InvariantCulture);
                    }
                    tempstr = (node["GrossHeight"] as XmlElement).InnerText; if (!string.IsNullOrEmpty(tempstr))
                    {
                        termek.Magassag = Convert.ToDouble(tempstr, System.Globalization.CultureInfo.InvariantCulture);
                    }
                    tempstr = (node["GrossDepth"] as XmlElement).InnerText; if (!string.IsNullOrEmpty(tempstr))
                    {
                        termek.Hossz = Convert.ToDouble(tempstr, System.Globalization.CultureInfo.InvariantCulture);
                    }

                    termek.LetoltesIdopontja = DateTime.Now;

                    Globalisok.Munkaasztal.FrissTermekLista.Add(termek);
                }

                lekertelemszam += termeknodes.Count;
                FolyamatValtozott?.Invoke(lekertelemszam, elemszam, string.Format("{0}/{1} termék lekérve ({2:P2})", lekertelemszam, elemszam, (double)lekertelemszam / (double)elemszam));

                ++oldalszam;
            } while (elemszam != 0);

            FolyamatValtozott?.Invoke(1, 1, "A termékek letöltése sikeresen végbement.");

            // Kategóriák kinyerése a friss terméklistából
            KategoriakTermeklistabol(Globalisok.Munkaasztal.FrissTermekLista);

            // Kategóriák szinkornizálása a kategória-megfeleltető listával
            Model.KategoriaMegfeleltetes.HRPKategoriakatSzinkronizal();
        }
Example #35
0
        public void Save(String filename)
        {
            XmlDocument xdGame = new XmlDocument();
            XmlElement  xeGame = xdGame.CreateElement("game");

            xdGame.AppendChild(xeGame);

            MemoryStream    msRandom = new MemoryStream();
            BinaryFormatter bf       = new BinaryFormatter();

            bf.Serialize(msRandom, this.RNG);
            msRandom.Close();
            XmlElement xe = xdGame.CreateElement("rng");

            xe.InnerText = Convert.ToBase64String(msRandom.ToArray());
            xeGame.AppendChild(xe);

            xe           = xdGame.CreateElement("start_time");
            xe.InnerText = this.StartTime.ToString();
            xeGame.AppendChild(xe);

            xe           = xdGame.CreateElement("state");
            xe.InnerText = this.State.ToString();
            xeGame.AppendChild(xe);

            xe = xdGame.CreateElement("activeplayer");
            if (this.ActivePlayer != null)
            {
                xe.InnerText = this.ActivePlayer.UniqueId.ToString();
            }
            xeGame.AppendChild(xe);

            XmlElement xeSettings = xdGame.CreateElement("settings");

            xeGame.AppendChild(xeSettings);

            Cards.CardCollection allCards = Cards.CardCollection.GetAllCards(c => true);

            XmlSerializer xsSettings = new XmlSerializer(typeof(GameSettings), GetAllSerializingTypes(allCards).ToArray());
            StringWriter  swSettings = new StringWriter();

            xsSettings.Serialize(swSettings, this.Settings);
            swSettings.Close();

            XmlDocument xdSettings = new XmlDocument();

            xdSettings.LoadXml(swSettings.ToString());
            xeSettings.AppendChild(xdGame.ImportNode(xdSettings.DocumentElement, true));

            xeGame.AppendChild(this.Table.GenerateXml(xdGame, "table"));

            xeGame.AppendChild(this.Players.GenerateXml(xdGame));

            xeGame.AppendChild(this.TurnsTaken.GenerateXml(xdGame, "turns"));

            xdGame.Save("gamedump.xml");

            using (StringWriter sw = new StringWriter())
                using (XmlWriter xw = XmlWriter.Create(sw))
                {
                    xdGame.WriteTo(xw);
                    xw.Flush();
                    System.IO.File.WriteAllBytes(filename, Utilities.StringUtility.Zip(Utilities.StringUtility.Encrypt(sw.GetStringBuilder().ToString())));
                }
        }
Example #36
0
        public void SaveToFile(string filename)
        {
            var doc = new XmlDocument();

            var root        = doc.CreateElement("bdtclient");
            var service     = doc.CreateElement(WordService);
            var socks       = doc.CreateElement(WordSocks);
            var proxy       = doc.CreateElement(WordProxy);
            var proxyAuth   = doc.CreateElement(WordAuthentication);
            var proxyConfig = doc.CreateElement(WordConfiguration);
            var forward     = doc.CreateElement(WordForward);
            var logs        = doc.CreateElement(WordLogs);
            var logsConsole = doc.CreateElement(WordConsole);
            var logsFile    = doc.CreateElement(WordFile);

            doc.AppendChild(root);
            root.AppendChild(service);
            root.AppendChild(socks);
            root.AppendChild(proxy);
            root.AppendChild(forward);
            root.AppendChild(logs);
            logs.AppendChild(logsConsole);
            logs.AppendChild(logsFile);

            service.Attributes.Append(CreateAttribute(doc, WordName, ServiceName));
            service.Attributes.Append(CreateAttribute(doc, WordProtocol, ServiceProtocol));
            service.Attributes.Append(CreateAttribute(doc, WordAddress, ServiceAddress));
            service.Attributes.Append(CreateAttribute(doc, WordPort, ServicePort));
            service.Attributes.Append(CreateAttribute(doc, WordUsername, ServiceUserName));
            service.Attributes.Append(CreateAttribute(doc, WordPassword, ServicePassword));
            service.Attributes.Append(CreateAttribute(doc, WordCulture, ServiceCulture));

            socks.Attributes.Append(CreateAttribute(doc, WordEnabled, SocksEnabled));
            socks.Attributes.Append(CreateAttribute(doc, WordShared, SocksShared));
            socks.Attributes.Append(CreateAttribute(doc, WordPort, SocksPort));

            proxy.Attributes.Append(CreateAttribute(doc, WordEnabled, ProxyEnabled));
            proxy.Attributes.Append(CreateAttribute(doc, WordExpect100, Expect100Continue));
            proxy.AppendChild(proxyAuth);
            proxy.AppendChild(proxyConfig);

            proxyAuth.Attributes.Append(CreateAttribute(doc, WordAuto, ProxyAutoAuthentication));
            proxyAuth.Attributes.Append(CreateAttribute(doc, WordUsername, ProxyUserName));
            proxyAuth.Attributes.Append(CreateAttribute(doc, WordPassword, ProxyPassword));
            proxyAuth.Attributes.Append(CreateAttribute(doc, WordDomain, ProxyDomain));

            proxyConfig.Attributes.Append(CreateAttribute(doc, WordAuto, ProxyAutoConfiguration));
            proxyConfig.Attributes.Append(CreateAttribute(doc, WordAddress, ProxyAddress));
            proxyConfig.Attributes.Append(CreateAttribute(doc, WordPort, ProxyPort));

            foreach (var portforward in Forwards.Values)
            {
                var pf = doc.CreateElement(WordPort + portforward.LocalPort.ToString(CultureInfo.InvariantCulture));
                forward.AppendChild(pf);
                pf.Attributes.Append(CreateAttribute(doc, WordEnabled, portforward.Enabled));
                pf.Attributes.Append(CreateAttribute(doc, WordShared, portforward.Shared));
                pf.Attributes.Append(CreateAttribute(doc, WordAddress, portforward.Address));
                pf.Attributes.Append(CreateAttribute(doc, WordPort, portforward.RemotePort));
            }

            logsConsole.Attributes.Append(CreateAttribute(doc, BaseLogger.ConfigEnabled, ConsoleLogger.Enabled));
            logsConsole.Attributes.Append(CreateAttribute(doc, BaseLogger.ConfigFilter, ConsoleLogger.Filter));
            logsConsole.Attributes.Append(CreateAttribute(doc, BaseLogger.ConfigStringFormat, ConsoleLogger.StringFormat));
            logsConsole.Attributes.Append(CreateAttribute(doc, BaseLogger.ConfigDateFormat, ConsoleLogger.DateFormat));

            logsFile.Attributes.Append(CreateAttribute(doc, BaseLogger.ConfigEnabled, FileLogger.Enabled));
            logsFile.Attributes.Append(CreateAttribute(doc, BaseLogger.ConfigFilter, FileLogger.Filter));
            logsFile.Attributes.Append(CreateAttribute(doc, BaseLogger.ConfigStringFormat, FileLogger.StringFormat));
            logsFile.Attributes.Append(CreateAttribute(doc, BaseLogger.ConfigDateFormat, FileLogger.DateFormat));
            logsFile.Attributes.Append(CreateAttribute(doc, FileLogger.ConfigFilename, FileLogger.Filename));
            logsFile.Attributes.Append(CreateAttribute(doc, FileLogger.ConfigAppend, FileLogger.Append));

            var xmltw = new XmlTextWriter(filename, new UTF8Encoding())
            {
                Formatting = Formatting.Indented
            };

            doc.WriteTo(xmltw);
            xmltw.Close();
        }
Example #37
0
        public static void Write(XmlDocument xmlDocument, string fileName)
        {
            StringWriter stringWriter = new StringWriter ();
            XmlTextWriter xmlTextWriter = new XmlTextWriter(stringWriter);
            //xmlTextWriter.Settings.NewLineOnAttributes = true;
            //xmlTextWriter.Settings.Indent = true;
            xmlTextWriter.Formatting = Formatting.Indented;

            xmlDocument.WriteTo (xmlTextWriter);
            Write (stringWriter.ToString(), fileName);
        }
Example #38
0
        async Task <FirmadoResponse> ICertificador.FirmarXml(FirmadoRequest request)
        {
            var task = Task.Factory.StartNew(() =>
            {
                var response = new FirmadoResponse();

                var certificate = new X509Certificate2();
                certificate.Import(Convert.FromBase64String(request.CertificadoDigital),
                                   request.PasswordCertificado, X509KeyStorageFlags.MachineKeySet | X509KeyStorageFlags.UserKeySet);

                var xmlDoc = new XmlDocument();

                string resultado;

                var betterBytes = Encoding.Convert(Encoding.GetEncoding(Formatos.EncodingIso),
                                                   Encoding.GetEncoding(Formatos.EncodingIso),
                                                   Convert.FromBase64String(request.TramaXmlSinFirma));

                using (var documento = new MemoryStream(betterBytes))
                {
                    xmlDoc.PreserveWhitespace = false;
                    xmlDoc.Load(documento);


                    var indiceNodo = 0;

                    var nodoExtension = xmlDoc.GetElementsByTagName("ExtensionContent", EspacioNombres.ext)
                                        .Item(indiceNodo);
                    if (nodoExtension == null)
                    {
                        throw new InvalidOperationException("No se pudo encontrar el nodo ExtensionContent en el XML");
                    }
                    nodoExtension.RemoveAll();

                    // Creamos el objeto SignedXml.
                    var signedXml = new SignedXml(xmlDoc)
                    {
                        SigningKey = certificate.PrivateKey
                    };
                    var xmlSignature = signedXml.Signature;

                    var env = new XmlDsigEnvelopedSignatureTransform();

                    var reference = new Reference(string.Empty);
                    reference.AddTransform(env);
                    xmlSignature.SignedInfo.AddReference(reference);

                    var keyInfo  = new KeyInfo();
                    var x509Data = new KeyInfoX509Data(certificate);

                    x509Data.AddSubjectName(certificate.Subject);

                    keyInfo.AddClause(x509Data);
                    xmlSignature.KeyInfo = keyInfo;
                    xmlSignature.Id      = "SignOpenInvoicePeru";
                    signedXml.ComputeSignature();

                    // Recuperamos el valor Hash de la firma para este documento.
                    if (reference.DigestValue != null)
                    {
                        response.ResumenFirma = Convert.ToBase64String(reference.DigestValue);
                    }
                    response.ValorFirma = Convert.ToBase64String(signedXml.SignatureValue);

                    nodoExtension.AppendChild(signedXml.GetXml());

                    using (var memDoc = new MemoryStream())
                    {
                        using (var writer = XmlWriter.Create(memDoc,
                                                             new XmlWriterSettings {
                            Encoding = Encoding.GetEncoding(Formatos.EncodingIso)
                        }))
                        {
                            xmlDoc.WriteTo(writer);
                        }

                        resultado = Convert.ToBase64String(memDoc.ToArray());
                    }
                }
                response.TramaXmlFirmado = resultado;

                return(response);
            });

            return(await task);
        }
Example #39
0
        private void ComboBoxMoveScuQueryLevelSelectedIndexChanged(object sender, EventArgs e)
        {
            var doc = new XmlDocument();

            string xmlFile;

            if (comboBoxMoveScuQueryType.SelectedIndex == 0)
            {
                if (comboBoxMoveScuQueryLevel.SelectedItem.Equals("STUDY"))
                {
                    xmlFile = "Macro.Dicom.Samples.SampleXml.StudyRootMoveStudy.xml";
                }
                else if (comboBoxMoveScuQueryLevel.SelectedItem.Equals("SERIES"))
                {
                    xmlFile = "Macro.Dicom.Samples.SampleXml.StudyRootMoveSeries.xml";
                }
                else
                {
                    xmlFile = "Macro.Dicom.Samples.SampleXml.StudyRootMoveImage.xml";
                }
            }
            else
            {
                if (comboBoxMoveScuQueryLevel.SelectedItem.Equals("PATIENT"))
                {
                    xmlFile = "Macro.Dicom.Samples.SampleXml.PatientRootMovePatient.xml";
                }
                else if (comboBoxMoveScuQueryLevel.SelectedItem.Equals("STUDY"))
                {
                    xmlFile = "Macro.Dicom.Samples.SampleXml.PatientRootMoveStudy.xml";
                }
                else if (comboBoxMoveScuQueryLevel.SelectedItem.Equals("SERIES"))
                {
                    xmlFile = "Macro.Dicom.Samples.SampleXml.PatientRootMoveSeries.xml";
                }
                else
                {
                    xmlFile = "Macro.Dicom.Samples.SampleXml.PatientRootMoveImage.xml";
                }
            }

            Stream stream = GetType().Assembly.GetManifestResourceStream(xmlFile);

            if (stream != null)
            {
                doc.Load(stream);
                stream.Close();
            }

            var sw = new StringWriter();

            var xmlSettings = new XmlWriterSettings
            {
                Encoding            = Encoding.UTF8,
                ConformanceLevel    = ConformanceLevel.Fragment,
                Indent              = true,
                NewLineOnAttributes = false,
                CheckCharacters     = true,
                IndentChars         = "  "
            };


            XmlWriter tw = XmlWriter.Create(sw, xmlSettings);

            if (tw != null)
            {
                doc.WriteTo(tw);
                tw.Close();
            }

            textBoxMoveMessage.Text = sw.ToString();
        }
Example #40
0
            public void WriteWix(FileInfo xmlFile)
            {
                _doc     = new XmlDocument();
                _wix     = _doc.CreateElement("Wix", _xmlns);
                _product = Product();

                _doc.AppendChild(_wix);
                _wix.AppendChild(_product);

                _product.AppendChild(Package());
                _product.AppendChild(Media());

                XmlElement dirTarget    = Directory("TARGETDIR", "SourceDir", _product);
                XmlElement dirProgFiles = Directory("ProgramFilesFolder", null, dirTarget);
                XmlElement dirInstall   = Directory("PROGRAMFILELOCATION", _productName, dirProgFiles);

                _programFilesComponents.AddRange(
                    AddFileComponents(_programFilesFiles, dirInstall));

                if (_desktopFolderFiles != null &&
                    _desktopFolderFiles.Length > 0)
                {
                    XmlElement dirDesktop       = Directory("DesktopFolder", null, dirTarget);
                    XmlElement dirDesktopFolder = Directory("DESKTOPLOCATION", _productName, dirDesktop);

                    _desktopFilesComponents.AddRange(
                        AddFileComponents2(_desktopFolderFiles, dirDesktopFolder));

                    if (_desktopFolderSubFiles != null)
                    {
                        foreach (KeyValuePair <string, FileInfo[]> kv in _desktopFolderSubFiles)
                        {
                            XmlElement subFolder = Directory(UniqueId(), kv.Key, dirDesktopFolder);
                            _desktopFilesComponents.AddRange(
                                AddFileComponents2(kv.Value, subFolder));
                        }
                    }
                }

                XmlElement dirMenuPrograms    = Directory("ProgramMenuFolder", "PMFolder", dirTarget);
                XmlElement dirMenuProgramsDir = Directory("ApplicationProgramsFolder", _productName, dirMenuPrograms);

                XmlElement dirRefMenuProgramsDir = DirectoryRef("ApplicationProgramsFolder");

                _product.AppendChild(dirRefMenuProgramsDir);

                XmlElement featureProgramFiles = Feature("FeatureProgramFiles",
                                                         _programFilesFeatureName, "PROGRAMFILELOCATION");

                foreach (Shortcut shortcut in _shortcuts)
                {
                    XmlElement shortcutComponent = Component(UniqueId());
                    XmlElement cut = Shortcut(shortcut,
                                              "ApplicationProgramsFolder",
                                              "PROGRAMFILELOCATION");

                    shortcutComponent.AppendChild(cut);
                    shortcutComponent.AppendChild(RemoveFolder());
                    shortcutComponent.AppendChild(RegistryValueHKCU(shortcut.RegistryKey));

                    dirRefMenuProgramsDir.AppendChild(shortcutComponent);

                    featureProgramFiles.AppendChild(ComponentRef(shortcutComponent.Attributes["Id"].Value));
                }

                foreach (XmlElement c in _programFilesComponents)
                {
                    featureProgramFiles.AppendChild(ComponentRef(
                                                        c.Attributes["Id"].Value));
                }

                _product.AppendChild(featureProgramFiles);

                if (_desktopFilesComponents != null && _programFilesFeatureName.Length > 0)
                {
                    XmlElement featureDesktopFiles = Feature("FeatureDesktopFiles",
                                                             _desktopFilesFeatureName, "DESKTOPLOCATION");

                    foreach (XmlElement c in _desktopFilesComponents)
                    {
                        featureDesktopFiles.AppendChild(ComponentRef(
                                                            c.Attributes["Id"].Value));
                    }

                    _product.AppendChild(featureDesktopFiles);
                }

                if (_licenceFile != null && _licenceFile.Exists)
                {
                    _product.AppendChild(WixVariable(
                                             "WixUILicenseRtf", _licenceFile.FullName));
                }

                if (_bannrbmp != null && _bannrbmp.Exists)
                {
                    _product.AppendChild(WixVariable(
                                             "WixUIBannerBmp", _bannrbmp.FullName));
                }

                if (_dlgbmp != null && _dlgbmp.Exists)
                {
                    _product.AppendChild(WixVariable(
                                             "WixUIDialogBmp", _dlgbmp.FullName));
                }

                _product.AppendChild(ConditionNetFramwork());

                _product.AppendChild(UIRef("WixUI_FeatureTree"));
                _product.AppendChild(UIRef("WixUI_ErrorProgressText"));

                // Write XML file

                XmlWriterSettings settings = new XmlWriterSettings();

                settings.Indent = true;
                settings.NewLineOnAttributes = true;

                Console.WriteLine("Creating " + xmlFile.FullName);

                using (XmlWriter xwriter = XmlWriter.Create(xmlFile.FullName, settings))
                {
                    _doc.WriteTo(xwriter);
                }
            }
        public void TestValidXmlOutput()
        {
            using (MemoryStream ms = new MemoryStream())
            {
                // generate the dataset
                DicomAttributeCollection dataset = new DicomAttributeCollection();
                {
                    Trace.WriteLine("Generating dataset using Unicode data");
                    Trace.WriteLine(" * US-ASCII Characters (0-127)");
                    // the line feed characters /r and /n are deliberately excluded because
                    // automatic line end handling would otherwise mangle them in the DicomAttribute
                    dataset[DicomTags.FailedAttributesSequence].AddSequenceItem(CreateSequenceItem(GenerateBinaryString(0, 0xA)));
                    dataset[DicomTags.FailedAttributesSequence].AddSequenceItem(CreateSequenceItem(GenerateBinaryString(0xB, 0xD)));
                    dataset[DicomTags.FailedAttributesSequence].AddSequenceItem(CreateSequenceItem(GenerateBinaryString(0xE, 128)));
                    Trace.WriteLine(" * Extended ASCII Characters (128-255)");
                    dataset[DicomTags.FailedAttributesSequence].AddSequenceItem(CreateSequenceItem(GenerateBinaryString(128, 256)));
                    Trace.WriteLine(" * Unicode Basic Multilingual Plane");
                    dataset[DicomTags.FailedAttributesSequence].AddSequenceItem(CreateSequenceItem(GenerateBinaryString(256, 0x4000)));
                    dataset[DicomTags.FailedAttributesSequence].AddSequenceItem(CreateSequenceItem(GenerateBinaryString(0x4000, 0x8000)));
                    dataset[DicomTags.FailedAttributesSequence].AddSequenceItem(CreateSequenceItem(GenerateBinaryString(0x8000, 0xC000)));
                    dataset[DicomTags.FailedAttributesSequence].AddSequenceItem(CreateSequenceItem(GenerateBinaryString(0xC000, 0xD800)));
                    dataset[DicomTags.FailedAttributesSequence].AddSequenceItem(CreateSequenceItem(GenerateBinaryString(0xE000, 0x10000)));
                    Trace.WriteLine(" * Unicode UTF-16 Surrogate Pairs");
                    dataset[DicomTags.FailedAttributesSequence].AddSequenceItem(CreateSequenceItem(GenerateSurrogatesBinaryString()));
                }

                // generate the InstanceXml document and dump into the MemoryStream
                {
                    XmlDocument xmlDocument = new XmlDocument();
                    xmlDocument.AppendChild(xmlDocument.CreateXmlDeclaration("1.0", "UTF-8", null));
                    InstanceXml instanceXml = new InstanceXml(dataset, SopClass.RawDataStorage, TransferSyntax.ExplicitVrLittleEndian);
                    Assert.IsTrue(instanceXml[DicomTags.FailedAttributesSequence].Count > 0);
                    XmlElement xmlRoot = xmlDocument.CreateElement("test");
                    xmlDocument.AppendChild(xmlRoot);
                    XmlElement xmlElement = instanceXml.GetMemento(xmlDocument, new StudyXmlOutputSettings());
                    xmlRoot.AppendChild(xmlElement);
                    XmlWriter xmlWriter = XmlWriter.Create(ms);
                    xmlDocument.WriteTo(xmlWriter);
                    xmlWriter.Close();
                    Assert.IsTrue(ms.Length > 0);
                    Trace.WriteLine(string.Format("XML fragment length: {0}", ms.Length));
                }

                // write the xml to a file
                ms.Seek(0, SeekOrigin.Begin);
                using (FileStream fs = File.OpenWrite("InstanceXmlTests.TestValidXmlOutput.Result.xml"))
                {
                    ms.WriteTo(fs);
                    fs.Close();
                }

                // parse and validate the xml using .NET
                ms.Seek(0, SeekOrigin.Begin);
                {
                    XmlReaderSettings xmlReaderSettings = new XmlReaderSettings();
                    xmlReaderSettings.CheckCharacters  = true;
                    xmlReaderSettings.ConformanceLevel = ConformanceLevel.Fragment;
                    XmlReader xmlReader = XmlReader.Create(ms, xmlReaderSettings);
                    while (xmlReader.Read())
                    {
                    }
                    xmlReader.Close();
                }

                // read it back as an InstanceXml
                ms.Seek(0, SeekOrigin.Begin);
                {
                    XmlDocument xmlDocument = new XmlDocument();
                    xmlDocument.Load(ms);
                    InstanceXml instanceXml = new InstanceXml(xmlDocument.GetElementsByTagName("test")[0].FirstChild, new DicomAttributeCollection());
                    Assert.IsTrue(instanceXml[DicomTags.FailedAttributesSequence].Count > 0);

                    int i = 0;
                    Trace.WriteLine("Validating decoded dataset for correct Unicode data");
                    Trace.WriteLine(" * US-ASCII Characters (0-127)");
                    // the line feed characters /r and /n are deliberately excluded because
                    // automatic line end handling would otherwise mangle them in the DicomAttribute
                    Assert.AreEqual(GenerateBinaryString(0, 0xA), ReadSequenceItem(instanceXml[DicomTags.FailedAttributesSequence], i++));
                    Assert.AreEqual(GenerateBinaryString(0xB, 0xD), ReadSequenceItem(instanceXml[DicomTags.FailedAttributesSequence], i++));
                    Assert.AreEqual(GenerateBinaryString(0xE, 128), ReadSequenceItem(instanceXml[DicomTags.FailedAttributesSequence], i++));
                    Trace.WriteLine(" * Extended ASCII Characters (128-255)");
                    Assert.AreEqual(GenerateBinaryString(128, 256), ReadSequenceItem(instanceXml[DicomTags.FailedAttributesSequence], i++));
                    Trace.WriteLine(" * Unicode Basic Multilingual Plane");
                    Assert.AreEqual(GenerateBinaryString(256, 0x4000), ReadSequenceItem(instanceXml[DicomTags.FailedAttributesSequence], i++));
                    Assert.AreEqual(GenerateBinaryString(0x4000, 0x8000), ReadSequenceItem(instanceXml[DicomTags.FailedAttributesSequence], i++));
                    Assert.AreEqual(GenerateBinaryString(0x8000, 0xC000), ReadSequenceItem(instanceXml[DicomTags.FailedAttributesSequence], i++));
                    Assert.AreEqual(GenerateBinaryString(0xC000, 0xD800), ReadSequenceItem(instanceXml[DicomTags.FailedAttributesSequence], i++));
                    Assert.AreEqual(GenerateBinaryString(0xE000, 0x10000), ReadSequenceItem(instanceXml[DicomTags.FailedAttributesSequence], i++));
                    Trace.WriteLine(" * Unicode UTF-16 Surrogate Pairs");
                    Assert.AreEqual(GenerateSurrogatesBinaryString(), ReadSequenceItem(instanceXml[DicomTags.FailedAttributesSequence], i++));
                }

                ms.Close();
            }
        }
Example #42
0
        public void Notify()
        {
            string      Logmsg = string.Empty;
            XmlDocument xd     = new XmlDocument();

            Stream postdata = Request.InputStream;

            if (postdata != null)
            {
                var res = XDocument.Load(postdata);
                if (res.Element("xml").Element("return_code").Value == "SUCCESS")
                {
                    string out_trade_no   = res.Element("xml").Element("out_trade_no").Value;
                    string openid         = res.Element("xml").Element("openid").Value;
                    string transaction_id = res.Element("xml").Element("transaction_id").Value;
                    //在数据库中检查out_trade_no是否已经支付过了如果支付过了直接返回SUCCESS
                    //修改数据库中该out_trade_no单据的状态为已支付返回SUCCESS
                    try
                    {
                        this.customerOrder.UpdateOrderPayStatus(int.Parse(out_trade_no));
                        xd.LoadXml("<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>");
                    }
                    catch (Exception ex)
                    {
                        xd.LoadXml("<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[updateorderpaystatus error]]></return_msg></xml>");
                        Logmsg = string.Format("Notify:transaction_id->{0},openid->{1},out_trade_no->{2},error->{3}", transaction_id, openid, out_trade_no, ex.Message);
                    }
                }
                else
                {
                    string error_msg = res.Element("xml").Element("err_code_des").Value;
                    xd.LoadXml("<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[return error]]></return_msg></xml>");
                    Logmsg = string.Format("Notify:return_error->code->{0},msg->{1}", res.Element("xml").Element("err_code").Value, res.Element("xml").Element("err_code_des").Value);
                }
            }
            else
            {
                xd.LoadXml("<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[no post data]]></return_msg></xml>");
                Logmsg = string.Format("Notify:no post data");
            }
            //if (postdata != null)
            //{
            //    byte[] b = new byte[postdata.Length];
            //    postdata.Read(b, 0, (int)postdata.Length);
            //    string postStr = Encoding.UTF8.GetString(b);
            //    Log.Logger.Write("weixinpay_notify_post:" + postStr);
            //}
            try
            {
                Response.Clear();
                Response.ContentType = "text/xml";
                Response.Charset     = "UTF-8";
                XmlTextWriter writer = new XmlTextWriter(Response.OutputStream, System.Text.Encoding.UTF8);
                writer.Formatting = Formatting.Indented;
                xd.WriteTo(writer);
                writer.Flush();
                Response.End();
            }
            catch (Exception ex)
            {
                Logmsg = string.Format("Notify:response_errror->{0}", ex.Message);
            }
            finally
            {
                if (Logmsg != string.Empty)
                {
                    Log.Logger.Write(Logmsg);
                }
            }
        }
Example #43
0
    /// <summary>
    /// Change the xmlDoc to a string for the client
    /// </summary>
    /// <param name="myxml"></param>
    /// <returns></returns>
    private string GetXMLAsString(XmlDocument myxml)
    {
        StringWriter sw = new StringWriter();
        XmlTextWriter tx = new XmlTextWriter(sw);
        myxml.WriteTo(tx);

        string str = sw.ToString();//
        return str;
    }
    private string Get_Formatted_XML(XmlDocument Query)
    {
        string RetVal;
        StringBuilder XmlContent;
        StringWriter StringWriter;
        XmlTextWriter XmlTextWriter;

        XmlContent = new StringBuilder();
        StringWriter = new StringWriter(XmlContent);
        XmlTextWriter = new XmlTextWriter(StringWriter);

        XmlTextWriter.Formatting = Formatting.Indented;
        Query.WriteTo(XmlTextWriter);
        RetVal = this.Server.HtmlEncode(XmlContent.ToString());

        return RetVal;
    }
Example #45
0
        void UpdateWebConfigRefs()
        {
            var refs = new List <string> ();

            foreach (var reference in References)
            {
                //local copied assemblies are copied to the bin directory so ASP.NET references them automatically
                if (reference.LocalCopy && (reference.ReferenceType == ReferenceType.Project || reference.ReferenceType == ReferenceType.Assembly))
                {
                    continue;
                }
                if (string.IsNullOrEmpty(reference.Reference))
                {
                    continue;
                }
                //these assemblies are referenced automatically by ASP.NET
                if (IsSystemReference(reference.Reference))
                {
                    continue;
                }
                //bypass non dotnet projects
                if ((reference.ReferenceType == ReferenceType.Project) &&
                    (!(reference.OwnerProject.ParentSolution.FindProjectByName(reference.Reference) is DotNetProject)))
                {
                    continue;
                }
                refs.Add(reference.Reference);
            }

            var webConfig = GetWebConfig();

            if (webConfig == null || !File.Exists(webConfig.FilePath))
            {
                return;
            }

            var textFile = MonoDevelop.Ide.TextFileProvider.Instance.GetEditableTextFile(webConfig.FilePath);

            //use textfile API because it's write safe (writes out to another file then moves)
            if (textFile == null)
            {
                textFile = MonoDevelop.Projects.Text.TextFile.ReadFile(webConfig.FilePath);
            }

            //can't use System.Web.Configuration.WebConfigurationManager, as it can only access virtual paths within an app
            //so need full manual handling
            try {
                System.Xml.XmlDocument doc = new XmlDocument();

                //FIXME: PreserveWhitespace doesn't handle whitespace in attribute lists
                //doc.PreserveWhitespace = true;
                doc.LoadXml(textFile.Text);

                //hunt our way to the assemblies element, creating elements if necessary
                XmlElement configElement = doc.DocumentElement;
                if (configElement == null || string.Compare(configElement.Name, "configuration", StringComparison.OrdinalIgnoreCase) != 0)
                {
                    configElement = (XmlElement)doc.AppendChild(doc.CreateNode(XmlNodeType.Document, "configuration", null));
                }
                XmlElement webElement      = GetNamedXmlElement(doc, configElement, "system.web");
                XmlElement compilationNode = GetNamedXmlElement(doc, webElement, "compilation");
                XmlElement assembliesNode  = GetNamedXmlElement(doc, compilationNode, "assemblies");

                List <XmlNode> existingAdds = new List <XmlNode> ();
                foreach (XmlNode node in assembliesNode)
                {
                    if (string.Compare(node.Name, "add", StringComparison.OrdinalIgnoreCase) == 0)
                    {
                        existingAdds.Add(node);
                    }
                }

                //add refs to the doc if they're not in it
                foreach (string reference in refs)
                {
                    int  index = 0;
                    bool found = false;
                    while (index < existingAdds.Count)
                    {
                        XmlNode      node = existingAdds[index];
                        XmlAttribute att  = (XmlAttribute)node.Attributes.GetNamedItem("assembly");
                        if (att == null)
                        {
                            continue;
                        }
                        string refAtt = att.Value;
                        if (refAtt != null && refAtt == reference)
                        {
                            existingAdds.RemoveAt(index);
                            found = true;
                            break;
                        }
                        else
                        {
                            index++;
                        }
                    }
                    if (!found)
                    {
                        XmlElement   newAdd = doc.CreateElement("add");
                        XmlAttribute newAtt = doc.CreateAttribute("assembly");
                        newAtt.Value = reference;
                        newAdd.Attributes.Append(newAtt);
                        assembliesNode.AppendChild(newAdd);
                    }
                }

                //any nodes that weren't removed from the existingAdds list are old/redundant, so remove from doc
                foreach (XmlNode node in existingAdds)
                {
                    assembliesNode.RemoveChild(node);
                }

                StringWriter  sw = new StringWriter();
                XmlTextWriter tw = new XmlTextWriter(sw);
                tw.Formatting = Formatting.Indented;
                doc.WriteTo(tw);
                tw.Flush();
                textFile.Text = sw.ToString();

                MonoDevelop.Projects.Text.TextFile tf = textFile as MonoDevelop.Projects.Text.TextFile;
                if (tf != null)
                {
                    tf.Save();
                }
            } catch (Exception e) {
                LoggingService.LogWarning("Could not modify application web.config in project " + this.Name, e);
            }
        }
Example #46
0
 /// <summary>
 /// 更新或新增[appSettings]节点的子节点值,存在则更新子节点Value,不存在则新增子节点,返回成功与否布尔值
 /// </summary>
 /// <param name="configurationFile">要操作的配置文件名称,枚举常量</param>
 /// <param name="key">子节点Key值</param>
 /// <param name="value">子节点value值</param>
 /// <returns>返回成功与否布尔值</returns>
 public static bool UpdateOrCreateAppSetting(ConfigurationFile configurationFile, string key, string value)
 {
     bool isSuccess = false;
     string filename = string.Empty;
     if (configurationFile.ToString() == ConfigurationFile.AppConfig.ToString())
     {
         filename = System.Windows.Forms.Application.ExecutablePath + ".config";
     }
     else
     {
         filename = System.AppDomain.CurrentDomain.BaseDirectory + "web.config";
     }
     XmlDocument doc = new XmlDocument();
     doc.Load(filename); //加载配置文件
     XmlNode node = doc.SelectSingleNode("//appSettings");   //得到[appSettings]节点
     try
     {
         ////得到[appSettings]节点中关于Key的子节点
         XmlElement element = (XmlElement)node.SelectSingleNode("//add[@key='" + key + "']");
         if (element != null)
         {
             //存在则更新子节点Value
             element.SetAttribute("value", value);
         }
         else
         {
             //不存在则新增子节点
             XmlElement subElement = doc.CreateElement("add");
             subElement.SetAttribute("key", key);
             subElement.SetAttribute("value", value);
             node.AppendChild(subElement);
         }
         //保存至配置文件(方式一)
         using (XmlTextWriter xmlwriter = new XmlTextWriter(filename, null))
         {
             xmlwriter.Formatting = Formatting.Indented;
             doc.WriteTo(xmlwriter);
             xmlwriter.Flush();
         }
         isSuccess = true;
     }
     catch (Exception ex)
     {
         isSuccess = false;
         throw ex;
     }
     return isSuccess;
 }
Example #47
0
        public static void GenerateFormXml()
        {
            // Create, load, and then extract the Form XML document without specified controls.
            // the filepath to your Form XML.
            var formxml = new XmlDocument();

            // TODO: update path to: <filepathpath>Form_blank.xml
            formxml.Load(@"");

            // Add namespaces to the namespace manager (prefix and then namespace) in Form XML.
            var formsnsmgr = new XmlNamespaceManager(formxml.NameTable);

            formsnsmgr.AddNamespace("n", "http://schemas.datacontract.org/2004/07/Nintex.Forms");
            formsnsmgr.AddNamespace("n1", "http://schemas.datacontract.org/2004/07/Nintex.Forms.FormControls");
            formsnsmgr.AddNamespace("d2p1", "http://schemas.microsoft.com/2003/10/Serialization/Arrays");

            //Set the values for the form used in the layout process.
            var yLeft     = 0; // y coordinates of position in layout.
            var xTop      = 0; // X coordinates of position in layout.
            var formWidth = 701;
            // Width of the Form in the Form layout. Form height (default 600) in desktop is not used in the app.

            //Add the path to your form instructions XML document.
            var formInst = new XmlDocument();

            // TODO: update path to: <filepathpath>Form_input.xml
            formInst.Load(@"");

            // Loop through each control in the instruction XML
            var xmlControl = formInst.GetElementsByTagName("control");

            for (var i = 0; i < xmlControl.Count; i++)
            {
                var con = i + 1;

                // FormControlUniqueId
                var iterguid = Guid.NewGuid(); // Guid for control set (controlproperties and contorllayout)

                //Read the height value for the control in the form instruction.
                var xpathHeight = "/form/control[" + con + "]/height";
                var n1          = formInst.DocumentElement.SelectSingleNode(xpathHeight);
                var val1        = n1.FirstChild.Value;
                var height      = int.Parse(val1);

                //Read the width value for the control in the form instruction.
                var xpathWidth = "/form/control[" + con + "]/width";
                var n2         = formInst.DocumentElement.SelectSingleNode(xpathWidth);
                var val2       = n2.FirstChild.Value;
                var width      = int.Parse(val2);

                // Create the contorllayout object and assign the height, width, and current control layout positon (X, Y).
                var controllayout = new FormControlLayout();
                controllayout.FormControlUniqueId = iterguid;
                controllayout.Height = height;
                controllayout.Width  = width;
                controllayout.Top    = xTop;
                controllayout.Left   = yLeft;

                //Point to FormControLayouts in the Form XML and add the layout object using AddControlLayout method.
                var laypath = "/n:Form/n:FormLayouts/n:FormLayout/n:FormControlLayouts";
                var laynode = formxml.DocumentElement.SelectSingleNode(laypath, formsnsmgr);
                AddControlLayout(laynode, controllayout);

                //Read the type of control and then add, and then run the routine for adding each to the Form XML.
                var xpathType   = "/form/control[" + con + "]/type";
                var typeNode    = formInst.DocumentElement.SelectSingleNode(xpathType);
                var controlType = typeNode.FirstChild.Value;

                //Read the type of control and then add, and then run the routine for adding each to the Form XML.
                var xpathText   = "/form/control[" + con + "]/text";
                var textNode    = formInst.DocumentElement.SelectSingleNode(xpathText);
                var controlText = textNode.FirstChild.Value;

                switch (controlType)
                {
                case "TextBox":
                    AddTextBoxProperties(formxml, formsnsmgr, iterguid, controlText);
                    break;

                case "Label":
                    AddLabelProperties(formxml, formsnsmgr, iterguid, controlText);
                    break;

                case "YesNo":
                    AddYesNoProperties(formxml, formsnsmgr, iterguid, controlText);
                    break;

                case "Button":
                    AddButtonProperties(formxml, formsnsmgr, iterguid, controlText);
                    break;

                case "ListBox":
                    // Load choces into the choiceList=
                    var choicesPath        = "/form/control[" + con + "]/choices";
                    var controlChoicesNode = formInst.DocumentElement.SelectSingleNode(choicesPath);
                    // XmlNodeList controlChoices = controlChoicesNode.ChildNodes;
                    var choiceArray = new string[controlChoicesNode.ChildNodes.Count];
                    for (var c = 0; c < controlChoicesNode.ChildNodes.Count; c++)
                    {
                        var aChoice = controlChoicesNode.ChildNodes[c].InnerText;
                        choiceArray[c] = aChoice;
                    }
                    AddChoiceProperties(formxml, formsnsmgr, iterguid, controlText, choiceArray);
                    break;

                case "Image":
                    //Load the image URL value.
                    var xpathTypeUrl = "/form/control[" + con + "]/url";
                    var imUrl        = formInst.DocumentElement.SelectSingleNode(xpathTypeUrl);
                    var controlUrl   = imUrl.InnerText;
                    AddImageProperties(formxml, formsnsmgr, iterguid, controlText, controlUrl);
                    break;
                }

                // This the routine that will perform the autolayout of the form controls by moving the control layout position with
                // in the bounds of the form width.
                yLeft += width;
                if (yLeft + width > formWidth)
                {
                    yLeft = 0;
                    xTop += height;
                }
            }

            //Convert the form to text, and strip the namespace string fragment inserted on the serialization
            //of the formcontrollayout object, and then save the file to the the target location.
            var stringWriter  = new StringWriter();
            var xmlTextWriter = new XmlTextWriter(stringWriter);

            formxml.WriteTo(xmlTextWriter);
            var outprocess = stringWriter.ToString();

            outprocess = outprocess.Replace("xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns=\"\"", " ");
            // TODO: update path to: <filepathpath>. Use the path and filename of the outputfile.
            File.WriteAllText(@"", outprocess);
            Console.WriteLine(outprocess);
            Console.ReadLine();
        }
Example #48
0
    private static void NewSnippet(string content, string tabTrigger, string description, string fileName)
    {
        XmlDocument doc = new XmlDocument();
        {
            XmlElement rootNode = doc.CreateElement("snippet");
            doc.AppendChild(rootNode);
            {
                XmlElement contentNode = doc.CreateElement("content");
                rootNode.AppendChild(contentNode);
                {
                    XmlCDataSection cdataNode = doc.CreateCDataSection(content);
                    contentNode.AppendChild(cdataNode);
                }

                XmlElement tabTriggerNode = doc.CreateElement("tabTrigger");
                rootNode.AppendChild(tabTriggerNode);
                {
                    XmlText textNode = doc.CreateTextNode(tabTrigger);
                    tabTriggerNode.AppendChild(textNode);
                }

                XmlElement scopeNode = doc.CreateElement("scope");
                rootNode.AppendChild(scopeNode);
                {
                    XmlText textNode = doc.CreateTextNode("source.lua");
                    scopeNode.AppendChild(textNode);
                }

                XmlElement descriptionNode = doc.CreateElement("description");
                rootNode.AppendChild(descriptionNode);
                {
                    XmlText textNode = doc.CreateTextNode(description);
                    descriptionNode.AppendChild(textNode);
                }
            }
        }

        StringBuilder sb = new StringBuilder();
        StringWriter sw = new StringWriter(sb);
        XmlTextWriter xtw = null;
        try
        {
            xtw = new XmlTextWriter(sw);
            xtw.Formatting = Formatting.Indented;
            xtw.Indentation = 1;
            xtw.IndentChar = '\t';
            doc.WriteTo(xtw);
        }
        catch(Exception e)
        {
            throw e;
        }
        finally
        {
            if(xtw != null)
            {
                xtw.Close();
                xtw = null;
            }
        }

        File.WriteAllText(saveToFolder + "/" + fileName + ".sublime-snippet", sb.ToString());
    }
Example #49
0
        public static string ExportXMLString(Google2uWorksheet in_sheet, Google2uExportOptions in_options)
        {
            var bConvertArrays = !in_options.XMLCellArrayToString;

            // Create the System.Xml.XmlDocument.
            var xmlDoc   = new XmlDocument();
            var rootNode = xmlDoc.CreateElement("Sheets");

            xmlDoc.AppendChild(rootNode);

            var sheetNode = xmlDoc.CreateElement("sheet");
            var sheetName = xmlDoc.CreateAttribute("name");

            sheetName.Value = in_sheet.WorksheetName;


            var curRow = 0;

            sheetNode.Attributes.Append(sheetName);
            rootNode.AppendChild(sheetNode);

            // Iterate through each row, printing its cell values.
            foreach (var row in in_sheet.Rows)
            {
                if (curRow < 1)
                {
                    curRow++;
                    continue;
                }
                if (in_sheet.UseTypeRow == true && curRow == 1)
                {
                    curRow++;
                    continue;
                }

                var rowType   = row[0].GetTypeFromValue();
                var rowHeader = row[0].CellValueString;
                if (string.IsNullOrEmpty(rowHeader))
                // if this header is empty
                {
                    if (in_options.XMLCullRows)
                    {
                        break;
                    }
                    curRow++;
                    continue;
                }

                if (rowType == SupportedType.Void ||
                    rowHeader.Equals("void", StringComparison.InvariantCultureIgnoreCase))
                // if this cell is void, then skip the row completely
                {
                    curRow++;
                    continue;
                }


                if (in_options.XMLColsAsChildTags)
                {
                    XmlNode rowNode = xmlDoc.CreateElement("row");
                    var     rowName = xmlDoc.CreateAttribute("name");
                    rowName.Value = row[0].CellValueString;
                    if (rowNode.Attributes == null)
                    {
                        continue;
                    }
                    rowNode.Attributes.Append(rowName);
                    sheetNode.AppendChild(rowNode);


                    // Iterate over the remaining columns, and print each cell value
                    for (var i = 1; i < in_sheet.Rows[0].Count; i++)
                    {
                        // Don't process rows or columns marked for ignore
                        if ((row[i].MyType == SupportedType.Void ||
                             string.IsNullOrEmpty(row[0].CellValueString) ||
                             in_sheet.Rows[0][i].MyType == SupportedType.Void ||
                             string.IsNullOrEmpty(in_sheet.Rows[0][i].CellValueString) ||
                             in_sheet.Rows[0][i].CellValueString.Equals("void",
                                                                        StringComparison.InvariantCultureIgnoreCase) ||
                             in_sheet.Rows[0][i].CellValueString.Equals("ignore",
                                                                        StringComparison.InvariantCultureIgnoreCase) ||
                             (in_options.XMLCullColumns && i >= in_sheet.FirstBlankCol)))
                        {
                            continue;
                        }

                        XmlNode colNode = xmlDoc.CreateElement(in_sheet.Rows[0][i].CellValueString);

                        var colType = xmlDoc.CreateAttribute("type");
                        colType.Value = row[i].CellTypeString;
                        if (colNode.Attributes != null)
                        {
                            colNode.Attributes.Append(colType);
                        }

                        if (bConvertArrays && IsSupportedArrayType(row[i].MyType))
                        {
                            var delim = in_options.DelimiterOptions[in_options.ArrayDelimiters].ToCharArray();

                            if (row[i].MyType == SupportedType.StringArray)
                            {
                                delim = in_options.DelimiterOptions[in_options.StringArrayDelimiters].ToCharArray();
                            }

                            var value = row[i].CellValueString.Split(delim, StringSplitOptions.RemoveEmptyEntries);
                            foreach (var s in value)
                            {
                                XmlNode arrNode = xmlDoc.CreateElement("entry");
                                if (row[i].MyType == SupportedType.BoolArray)
                                {
                                    var val = s.ToLower();
                                    if (val == "1")
                                    {
                                        val = "true";
                                    }
                                    if (val == "0")
                                    {
                                        val = "false";
                                    }
                                    arrNode.InnerText = val;
                                }
                                else
                                {
                                    arrNode.InnerText = s;
                                }

                                colNode.AppendChild(arrNode);
                            }
                        }
                        else
                        {
                            colNode.InnerText = row[i].CellValueString;
                        }

                        rowNode.AppendChild(colNode);
                    }
                    curRow++;
                }
                else
                {
                    XmlNode rowNode = xmlDoc.CreateElement("row");
                    if (rowNode.Attributes == null)
                    {
                        continue;
                    }

                    var rowAttribute = xmlDoc.CreateAttribute("UID");
                    rowAttribute.Value = row[0].CellValueString;
                    rowNode.Attributes.Append(rowAttribute);

                    // Iterate over the remaining columns, and print each cell value
                    for (var i = 1; i < in_sheet.Rows[0].Count; i++)
                    {
                        // Don't process rows or columns marked for ignore
                        if ((row[i].MyType == SupportedType.Void ||
                             string.IsNullOrEmpty(row[0].CellValueString) ||
                             in_sheet.Rows[0][i].MyType == SupportedType.Void ||
                             string.IsNullOrEmpty(in_sheet.Rows[0][i].CellValueString) ||
                             in_sheet.Rows[0][i].CellValueString.Equals("void",
                                                                        StringComparison.InvariantCultureIgnoreCase) ||
                             in_sheet.Rows[0][i].CellValueString.Equals("ignore",
                                                                        StringComparison.InvariantCultureIgnoreCase) ||
                             (in_options.XMLCullColumns && i >= in_sheet.FirstBlankCol)))
                        {
                            continue;
                        }

                        rowAttribute       = xmlDoc.CreateAttribute(in_sheet.Rows[0][i].CellValueString);
                        rowAttribute.Value = row[i].CellValueString;

                        rowNode.Attributes.Append(rowAttribute);
                    }


                    sheetNode.AppendChild(rowNode);

                    curRow++;
                }
            }

            string retstring;

            using (var stringWriter = new StringWriter())
            {
                using (var xmlTextWriter = new XmlTextWriter(stringWriter))
                {
                    xmlTextWriter.Formatting = Formatting.Indented;
                    xmlDoc.WriteTo(xmlTextWriter);
                    retstring = stringWriter.ToString();
                }
            }

            return(retstring);
        }
Example #50
0
        private void SignLicense(object sender, System.EventArgs e)
        {
            if (!File.Exists(LicenseTextBox.Text))
            {
                return;
            }

            XmlDocument xmldoc = new XmlDocument();

            xmldoc.Load(LicenseTextBox.Text);

            CspParameters parms = new CspParameters(1);

            parms.Flags            = CspProviderFlags.UseMachineKeyStore;
            parms.KeyContainerName = "ObjectServerLicense";
            parms.KeyNumber        = 2;
            RSACryptoServiceProvider csp = new RSACryptoServiceProvider(parms);

            SignedXml sxml = new SignedXml(xmldoc);

            sxml.SigningKey = csp;

            sxml.SignedInfo.CanonicalizationMethod = SignedXml.XmlDsigCanonicalizationUrl;

            Reference r = new Reference("");

            r.AddTransform(new XmlDsigEnvelopedSignatureTransform(false));

            sxml.AddReference(r);

            sxml.ComputeSignature();

            XmlElement sig = sxml.GetXml();

            xmldoc.DocumentElement.AppendChild(sig);

            if (SaveDialog.ShowDialog(this) != DialogResult.OK)
            {
                return;
            }

            string filename = SaveDialog.FileName;

            XmlTextWriter writer = new XmlTextWriter(filename, System.Text.Encoding.UTF8);

            writer.Formatting = Formatting.Indented;

            try
            {
                xmldoc.WriteTo(writer);
                MessageBox.Show(this, "Licence created");;
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, "Licence creation failed " + ex.Message);
            }
            finally
            {
                writer.Flush();
                writer.Close();
            }
        }
Example #51
0
        private static void GenerateNUnitTestResults(string basePath, string platform, CompareResult compareResult, string buildId)
        {
            var resultsId       = $"{DateTime.Now:yyyyMMdd-hhmmss}";
            var resultsFilePath = Path.Combine(basePath, $"Results-{platform}-{resultsId}.xml");

            var success      = !compareResult.Tests.Any(t => t.ResultRun.LastOrDefault()?.HasChanged ?? false);
            var successCount = compareResult.Tests.Count(t => t.ResultRun.LastOrDefault()?.HasChanged ?? false);

            var doc      = new XmlDocument();
            var rootNode = doc.CreateElement("test-run");

            doc.AppendChild(rootNode);
            rootNode.SetAttribute("id", buildId);
            rootNode.SetAttribute("name", resultsId);
            rootNode.SetAttribute("testcasecount", compareResult.TotalTests.ToString());
            rootNode.SetAttribute("result", success ? "Passed" : "Failed");
            rootNode.SetAttribute("time", "0");
            rootNode.SetAttribute("total", compareResult.TotalTests.ToString());
            rootNode.SetAttribute("errors", (compareResult.TotalTests - compareResult.UnchangedTests).ToString());
            rootNode.SetAttribute("passed", successCount.ToString());
            rootNode.SetAttribute("failed", "0");
            rootNode.SetAttribute("inconclusive", "0");
            rootNode.SetAttribute("skipped", "0");
            rootNode.SetAttribute("asserts", "0");

            var now = DateTimeOffset.Now;

            rootNode.SetAttribute("run-date", now.ToString("yyyy-MM-dd"));
            rootNode.SetAttribute("start-time", now.ToString("HH:mm:ss"));
            rootNode.SetAttribute("end-time", now.ToString("HH:mm:ss"));

            var testSuiteAssemblyNode = doc.CreateElement("test-suite");

            rootNode.AppendChild(testSuiteAssemblyNode);
            testSuiteAssemblyNode.SetAttribute("type", "Assembly");
            testSuiteAssemblyNode.SetAttribute("name", platform);

            var environmentNode = doc.CreateElement("environment");

            testSuiteAssemblyNode.AppendChild(environmentNode);
            environmentNode.SetAttribute("machine-name", Environment.MachineName);
            environmentNode.SetAttribute("platform", platform);

            var testSuiteFixtureNode = doc.CreateElement("test-suite");

            testSuiteAssemblyNode.AppendChild(testSuiteFixtureNode);


            testSuiteFixtureNode.SetAttribute("type", "TestFixture");
            testSuiteFixtureNode.SetAttribute("name", platform + "-" + resultsId);
            testSuiteFixtureNode.SetAttribute("executed", "true");

            testSuiteFixtureNode.SetAttribute("testcasecount", compareResult.TotalTests.ToString());
            testSuiteFixtureNode.SetAttribute("result", success ? "Passed" : "Failed");
            testSuiteFixtureNode.SetAttribute("time", "0");
            testSuiteFixtureNode.SetAttribute("total", compareResult.TotalTests.ToString());
            testSuiteFixtureNode.SetAttribute("errors", (compareResult.TotalTests - compareResult.UnchangedTests).ToString());
            testSuiteFixtureNode.SetAttribute("passed", successCount.ToString());
            testSuiteFixtureNode.SetAttribute("failed", "0");
            testSuiteFixtureNode.SetAttribute("inconclusive", "0");
            testSuiteFixtureNode.SetAttribute("skipped", "0");
            testSuiteFixtureNode.SetAttribute("asserts", "0");

            foreach (var run in compareResult.Tests)
            {
                var testCaseNode = doc.CreateElement("test-case");
                testSuiteFixtureNode.AppendChild(testCaseNode);

                var lastTestRun = run.ResultRun.LastOrDefault();

                testCaseNode.SetAttribute("name", platform + "-" + SanitizeTestName(run.TestName));
                testCaseNode.SetAttribute("fullname", platform + "-" + SanitizeTestName(run.TestName));
                testCaseNode.SetAttribute("duration", "0");
                testCaseNode.SetAttribute("time", "0");

                var testRunSuccess = !(lastTestRun?.HasChanged ?? false);
                testCaseNode.SetAttribute("result", testRunSuccess ? "Passed" : "Failed");

                if (lastTestRun != null)
                {
                    if (!testRunSuccess)
                    {
                        var failureNode = doc.CreateElement("failure");
                        testCaseNode.AppendChild(failureNode);

                        var messageNode = doc.CreateElement("message");
                        failureNode.AppendChild(messageNode);

                        messageNode.InnerText = $"Results are different";
                    }

                    var attachmentsNode = doc.CreateElement("attachments");
                    testCaseNode.AppendChild(attachmentsNode);

                    AddAttachment(doc, attachmentsNode, lastTestRun.FilePath, "Result output");

                    if (!testRunSuccess)
                    {
                        AddAttachment(doc, attachmentsNode, lastTestRun.DiffResultImage, "Image diff");

                        var previousRun = run.ResultRun.ElementAtOrDefault(run.ResultRun.Count - 2);
                        AddAttachment(doc, attachmentsNode, previousRun.FilePath, "Previous result output");
                    }
                }
            }

            using (var file = XmlWriter.Create(File.OpenWrite(resultsFilePath), new XmlWriterSettings {
                Indent = true
            }))
            {
                doc.WriteTo(file);
            }
        }
	private void ParseDOMDocument(XmlDocument document)
	{
		//UnityEngine.Debug.Log ("OCConnectorSingleton::ParseDOMDocument");
		// Handles action-plans

		bool wrotePlan = false;
		
		if(!wrotePlan)
		{
			System.IO.StringWriter stringWriter = new System.IO.StringWriter();
			XmlTextWriter xmlTextWriter = new XmlTextWriter(stringWriter);
	
			document.WriteTo(xmlTextWriter);
			
			if(stringWriter.ToString().IndexOf("oc:emotional-feeling") == -1)
			{
				UnityEngine.Debug.Log("A plan! " + stringWriter.ToString());	
				wrotePlan = true;	
			}
		}
		
		XmlNodeList list = document.GetElementsByTagName(OCEmbodimentXMLTags.ACTION_PLAN_ELEMENT);
		for(int i = 0; i < list.Count; i++)
		{
			UnityEngine.Debug.Log("OCConnectorSingleton::ParseDOMDocument: ParseActionPlanElement");
			ParseActionPlanElement((XmlElement)list.Item(i));
		}

		// Handles emotional-feelings       
		XmlNodeList feelingsList = document.GetElementsByTagName(OCEmbodimentXMLTags.EMOTIONAL_FEELING_ELEMENT);
		for(int i = 0; i < feelingsList.Count; i++)
		{
			//UnityEngine.Debug.Log ("OCConnectorSingleton::ParseDOMDocument: ParseEmotionalFeelingElement");
			ParseEmotionalFeelingElement((XmlElement)feelingsList.Item(i));
		}
        
		// Handle psi-demand
		XmlNodeList demandsList = document.GetElementsByTagName(OCEmbodimentXMLTags.PSI_DEMAND_ELEMENT);
		for(int i = 0; i< demandsList.Count; i++)
		{
			UnityEngine.Debug.Log("OCConnectorSingleton::ParseDOMDocument: ParsePsiDemandElement");
			ParsePsiDemandElement((XmlElement)demandsList.Item(i));
		}
		
		// Handle single-action-command
		XmlNodeList singleActionList = document.GetElementsByTagName(OCEmbodimentXMLTags.SINGLE_ACTION_COMMAND_ELEMENT);
		for(int i = 0; i< singleActionList.Count; i++)
		{
			UnityEngine.Debug.Log("OCConnectorSingleton::ParseDOMDocument: ParseSingleActionElement");
			ParseSingleActionElement((XmlElement)singleActionList.Item(i));
		}
	}
    // Sign an XML file and save the signature in a new file.
    public static void SignXmlFile(string FileName, string SignedFileName, RSA Key)
    {
        // Create a new XML document.
        XmlDocument doc = new XmlDocument();

        // Format the document to ignore white spaces.
        doc.PreserveWhitespace = false;

        // Load the passed XML file using it's name.
        doc.Load(new XmlTextReader(FileName));

        // Create a SignedXml object.
        SignedXml signedXml = new SignedXml(doc);

        // Add the key to the SignedXml document.
        signedXml.SigningKey = Key;

        // Specify a canonicalization method.
        signedXml.SignedInfo.CanonicalizationMethod = SignedXml.XmlDsigExcC14NWithCommentsTransformUrl;

        // Set the InclusiveNamespacesPrefixList property.
        XmlDsigExcC14NWithCommentsTransform canMethod = (XmlDsigExcC14NWithCommentsTransform)signedXml.SignedInfo.CanonicalizationMethodObject;

        canMethod.InclusiveNamespacesPrefixList = "Sign";

        // Create a reference to be signed.
        Reference reference = new Reference();

        reference.Uri = "";

        // Add an enveloped transformation to the reference.
        XmlDsigEnvelopedSignatureTransform env = new XmlDsigEnvelopedSignatureTransform();

        reference.AddTransform(env);

        // Add the reference to the SignedXml object.
        signedXml.AddReference(reference);


        // Add an RSAKeyValue KeyInfo (optional; helps recipient find key to validate).
        KeyInfo keyInfo = new KeyInfo();

        keyInfo.AddClause(new RSAKeyValue((RSA)Key));
        signedXml.KeyInfo = keyInfo;

        // Compute the signature.
        signedXml.ComputeSignature();

        // Get the XML representation of the signature and save
        // it to an XmlElement object.
        XmlElement xmlDigitalSignature = signedXml.GetXml();

        // Append the element to the XML document.
        doc.DocumentElement.AppendChild(doc.ImportNode(xmlDigitalSignature, true));


        if (doc.FirstChild is XmlDeclaration)
        {
            doc.RemoveChild(doc.FirstChild);
        }

        // Save the signed XML document to a file specified
        // using the passed string.
        XmlTextWriter xmltw = new XmlTextWriter(SignedFileName, new UTF8Encoding(false));

        doc.WriteTo(xmltw);
        xmltw.Close();
    }