/// <summary>
        /// Saves the application settings to the specified file.
        /// </summary>
        /// <param name="filePath">
        /// The path of the file to which settings are to be saved.
        /// </param>
        private void Save(string filePath)
        {
            try
            {
                // Serialize the current object to a memory stream.
                System.IO.MemoryStream   plaintextStream = new System.IO.MemoryStream();
                System.Xml.XmlTextWriter plaintextWriter = new System.Xml.XmlTextWriter(plaintextStream, System.Text.Encoding.Unicode);
                XmlSerializer            serializer      = EncryptedSettings.Serializer;
                lock (serializer)
                {
                    plaintextWriter.Indentation = 0;
                    plaintextWriter.Formatting  = System.Xml.Formatting.None;
                    serializer.Serialize(plaintextWriter, this);
                }

                // Convert the plaintext memory stream to an array of bytes.
                byte[] plaintextBytes = plaintextStream.ToArray();

                // Encrypt the plaintext byte array.
                byte[] ciphertextBytes = ProtectedData.Protect(plaintextBytes, null, DataProtectionScope.LocalMachine);

                plaintextWriter.Close();
                plaintextWriter.Dispose();

                System.IO.Directory.CreateDirectory(System.IO.Path.GetDirectoryName(filePath));

                // Write the encrypted byte array to the file.
                System.IO.FileStream ciphertextStream = new System.IO.FileStream(filePath, System.IO.FileMode.Create, System.IO.FileAccess.Write);
                ciphertextStream.Write(ciphertextBytes, 0, ciphertextBytes.Length);
                ciphertextStream.Close();
            }
            catch (System.InvalidOperationException)
            {
                throw;
            }

            /*
             * // This is the unencrypted version.
             * try
             * {
             *  System.IO.Directory.CreateDirectory(System.IO.Path.GetDirectoryName(filePath));
             *  System.Xml.XmlTextWriter writer = new System.Xml.XmlTextWriter(filePath, System.Text.Encoding.Unicode);
             *  XmlSerializer serializer = EncryptedSettings.Serializer;
             *  lock (serializer)
             *  {
             *      writer.Indentation = 1;
             *      writer.IndentChar = '\t';
             *      writer.Formatting = System.Xml.Formatting.Indented;
             *      serializer.Serialize(writer, this);
             *  }
             *  writer.Close();
             * }
             * catch (System.InvalidOperationException)
             * {
             *  throw;
             * }
             */
        }
 public ActionResult ViewDrivingLicense(string id)
 {
     if (id == null)
     {
         return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
     }
     DLDetails inventory = _dbContext.DLDetailss.Find(id);
     generateXML(inventory);
     XslTransform xslt = new XslTransform();
     String path = HostingEnvironment.MapPath("~/XMLClasses/DrivingLicense.xsl");
     xslt.Load(path);
     path = HostingEnvironment.MapPath("~/XMLClasses/DrivingLicense.xml");
     XPathDocument xpathdocument = new
     XPathDocument(path);
     path = HostingEnvironment.MapPath("~/XMLClasses/MyDrivingLicense.html");
     XmlTextWriter writer = new XmlTextWriter(path, UTF8Encoding.UTF8);
     writer.Formatting = Formatting.Indented;
     xslt.Transform(xpathdocument, null, writer, null);
     writer.Flush();
     writer.Close();
     writer.Dispose();
     return new FilePathResult(path, "text/html");
 }
Exemplo n.º 3
0
        public static void Save(TilesMap tilesmap, string path)
        {
            if (tilesmap == null)
                throw new ArgumentException("Argument does not accept null", "tilesmap");
            if (path == null)
                throw new ArgumentException("Argument does not accept null", "path");
            using (XmlTextWriter wr = new XmlTextWriter(path, Encoding.UTF8))
            {
                wr.Formatting = Formatting.Indented;
                wr.WriteStartDocument();
                wr.WriteStartElement("Tilesmap");
                {
                    wr.WriteAttributeString("columns", tilesmap.Columns.ToString());
                    wr.WriteAttributeString("rows", tilesmap.Rows.ToString());

                    wr.WriteStartElement("MatrixIndex");
                    {
                        for (int i = 0; i < tilesmap.Rows; i++)
                        {
                            wr.WriteStartElement("Row");
                            {
                                wr.WriteAttributeString("id", i.ToString());
                                for (int j = 0; j < tilesmap.Columns; j++)
                                {
                                    wr.WriteString(tilesmap[j, i].ToString());
                                    if (j != tilesmap.Columns - 1)
                                        wr.WriteString("\t");
                                }
                            }
                            wr.WriteEndElement(); // rows
                        }
                    }
                    wr.WriteEndElement();   // Matrixindex
                    if (tilesmap.TileSet != null)
                    {
                        TileSet.Save(wr, tilesmap.TileSet, path);
                    }
                    if (tilesmap.ListObject.Any())
                    {
                        ObjectEditor.Save(wr, tilesmap.ListObject, path);
                    }

                }

                wr.WriteEndElement();       // Tiles map
                wr.WriteEndDocument();
                wr.Close();
                wr.Dispose();
            }
        }
Exemplo n.º 4
0
        public int TransformResolver(String szXmlFile, XmlResolver xr, bool errorCase)
        {
            szXmlFile = FullFilePath(szXmlFile);

            _output.WriteLine("Loading XML " + szXmlFile);
            IXPathNavigable xd = LoadXML(szXmlFile, _navType);

            _output.WriteLine("Executing transform");
            xrXSLT = null;
            Stream strmTemp = null;

            switch (_nOutput)
            {
                case OutputType.Stream:
                    try
                    {
                        strmTemp = new FileStream(_strOutFile, FileMode.Create, FileAccess.ReadWrite);
                        xslt.Transform(xd, null, strmTemp);
                    }
                    catch (Exception ex)
                    {
                        throw (ex);
                    }
                    finally
                    {
                        if (strmTemp != null)
                            strmTemp.Dispose();
                    }
                    break;

                case OutputType.Writer:
                    XmlWriter xw = null;
                    try
                    {
                        xw = new XmlTextWriter(_strOutFile, Encoding.UTF8);
                        xw.WriteStartDocument();
                        xslt.Transform(xd, null, xw);
                    }
                    catch (Exception ex)
                    {
                        throw (ex);
                    }
                    finally
                    {
                        if (xw != null)
                            xw.Dispose();
                    }
                    break;

                case OutputType.TextWriter:
                    TextWriter tw = null;
                    try
                    {
                        tw = new StreamWriter(new FileStream(_strOutFile, FileMode.Create, FileAccess.Write), Encoding.UTF8);
                        xslt.Transform(xd, null, tw);
                    }
                    catch (Exception ex)
                    {
                        throw (ex);
                    }
                    finally
                    {
                        if (tw != null)
                            tw.Dispose();
                    }
                    break;
            }
            return 1;
        }
Exemplo n.º 5
0
    public void Save(string strName, bool fOverWrite, System.Text.Encoding Encoding)
    {
        CXmlBase rNode;
        XmlTextWriter rXmlTextWriter = null;

        try
        {
            if (fOverWrite)
            {
                File.Delete(strName);
            }

            rXmlTextWriter = new XmlTextWriter(strName, Encoding);
            rXmlTextWriter.Namespaces = _fNamespaces;

            for (rNode = _rDocumentRootNode._rFirstChildNode; rNode != null; rNode = rNode._rNextNode)
            {
                rNode.Write(rXmlTextWriter);
            }
            rXmlTextWriter.Dispose();
        }
        catch (Exception e)
        {
            DebugTrace(e.ToString());
            if (rXmlTextWriter != null)
                rXmlTextWriter.Dispose();
            throw (e);
        }
    }
Exemplo n.º 6
0
        public bool Table_Save(Guid tableId, object table)
        {
            var returnValue = false;

            try
            {
                var fileName = Path.Combine(this._tableDirectoryPath, tableId + ".xml");
                var fileStream = base.GetFileWriteStream(fileName);
                var xmlTextWriter = new XmlTextWriter(fileStream, encoding);

                Serializer.Serialize(xmlTextWriter, table);

                fileStream.Close();
                fileStream.Dispose();

                xmlTextWriter.Close();
                xmlTextWriter.Dispose();
            }
            catch (Exception ex)
            {
                if (this._logger != null)
                {
                    this._logger.Log(ex.Message, Category.Exception, Priority.High);
                }
            }

            return returnValue;
        }
        public void export(String fileName)
        {
            WindowTitle = "Exporting Tags";

            XmlTextWriter outFile = null;
            try
            {
                if (CancellationToken.IsCancellationRequested) return;

                outFile = new XmlTextWriter(fileName, Encoding.UTF8);
                outFile.Formatting = Formatting.Indented;
                Type[] knownTypes = new Type[] { typeof(TagDTO), typeof(TagCategoryDTO) };

                DataContractSerializer tagSerializer = new DataContractSerializer(typeof(List<TagDTO>), knownTypes);

                using (var tagCommands = new TagDbCommands())
                {
                    tagCommands.Db.Configuration.ProxyCreationEnabled = false;
                    List<Tag> tags = tagCommands.getAllTags(true);
                    TotalProgressMax = tags.Count;
                    TotalProgress = 0;
                    List<TagDTO> tagsDTO = new List<TagDTO>();

                    foreach (Tag tag in tags)
                    {
                        if (CancellationToken.IsCancellationRequested) return;

                        var tagDTO = Mapper.Map<Tag, TagDTO>(tag, new TagDTO());

                        ItemInfo = "Exporting: " + tagDTO.Name;
                        ItemProgress = 0;

                        tagsDTO.Add(tagDTO);

                        ItemProgress = 100;
                        InfoMessages.Add("Exported: " + tagDTO.Name);
                        TotalProgress++;
                    }

                    tagSerializer.WriteObject(outFile, tagsDTO);
                }               
            }
            catch (Exception e)
            {
                InfoMessages.Add("Error exporting tags: " + e.Message);                           
            }
            finally
            {
                operationFinished();    

                if (outFile != null)
                {
                    outFile.Dispose();
                }
            }
        }
Exemplo n.º 8
0
        public int Transform_ArgList(String szXmlFile, bool errorCase)
        {
            lock (s_outFileMemoryLock)
            {
                szXmlFile = FullFilePath(szXmlFile);

                _output.WriteLine("Loading XML {0}", szXmlFile);
                IXPathNavigable xd = LoadXML(szXmlFile, _docType);

                _output.WriteLine("Executing transform");
                xrXSLT = null;
                Stream strmTemp = null;
                switch (_nTransform)
                {
                    case TransformType.Reader:
                        xrXSLT = xslt.Transform(xd, m_xsltArg);
                        if (errorCase)
                        {
                            try
                            {
                                while (xrXSLT.Read()) { }
                            }
                            catch (Exception ex)
                            {
                                throw (ex);
                            }
                            finally
                            {
                                if (xrXSLT != null)
                                    xrXSLT.Dispose();
                            }
                        }
                        break;

                    case TransformType.Stream:
                        try
                        {
                            strmTemp = new FileStream(_strOutFile, FileMode.Create, FileAccess.ReadWrite);
                            xslt.Transform(xd, m_xsltArg, strmTemp);
                        }
                        catch (Exception ex)
                        {
                            throw (ex);
                        }
                        finally
                        {
                            if (strmTemp != null)
                                strmTemp.Dispose();
                        }
                        break;

                    case TransformType.Writer:
                        XmlWriter xw = null;
                        try
                        {
                            xw = new XmlTextWriter(_strOutFile, Encoding.UTF8);
                            xw.WriteStartDocument();
                            xslt.Transform(xd, m_xsltArg, xw);
                        }
                        catch (Exception ex)
                        {
                            throw (ex);
                        }
                        finally
                        {
                            if (xw != null)
                                xw.Dispose();
                        }
                        break;

                    case TransformType.TextWriter:
                        TextWriter tw = null;
                        try
                        {
                            tw = new StreamWriter(new FileStream(_strOutFile, FileMode.Create, FileAccess.Write), Encoding.UTF8);
                            xslt.Transform(xd, m_xsltArg, tw);
                        }
                        catch (Exception ex)
                        {
                            throw (ex);
                        }
                        finally
                        {
                            if (tw != null)
                            {
                                tw.Dispose();
                            }
                        }
                        break;
                }
                return 1;
            }
        }
        private void createXML()
        {
            XmlTextWriter textWritter;
            XmlDocument document;
            XmlNode element;
            XmlAttribute attribute;
            XmlNode subElement;

            #region ore.xml
            //создание ore.xml
            textWritter = new XmlTextWriter("ore.xml", Encoding.UTF8);
            textWritter.WriteStartDocument();
            textWritter.WriteStartElement("head");
            textWritter.WriteEndElement();

            //запись в ore.xml
            document = new XmlDocument();
            document.Load("ore.xml");

            //заполнение ore.xml
            foreach (KeyValuePair<string, TradeSystem.Goods.Ore> pair in oreList)
            {
                element = document.CreateElement("ore");
                document.DocumentElement.AppendChild(element);
                attribute = document.CreateAttribute("Имя");
                attribute.Value = pair.Value.getName();
                element.Attributes.Append(attribute);

                subElement = document.CreateElement("price");
                subElement.InnerText = pair.Value.getPrice().ToString();
                element.AppendChild(subElement);

                subElement = document.CreateElement("rarity");
                subElement.InnerText = pair.Value.getRarity().ToString();
                element.AppendChild(subElement);

                subElement = document.CreateElement("product");
                subElement.InnerText = pair.Value.getProduct().ToString();
                element.AppendChild(subElement);

                subElement = document.CreateElement("refTime");
                subElement.InnerText = pair.Value.getRefTime().ToString();
                element.AppendChild(subElement);

                subElement = document.CreateElement("need");
                subElement.InnerText = pair.Value.getNeed().ToString();
                element.AppendChild(subElement);

                subElement = document.CreateElement("demand");
                subElement.InnerText = pair.Value.getDemand().ToString();
                element.AppendChild(subElement);

                subElement = document.CreateElement("supply");
                subElement.InnerText = pair.Value.getSupply().ToString();
                element.AppendChild(subElement);

                subElement = document.CreateElement("labor");
                subElement.InnerText = pair.Value.getLabor().ToString();
                element.AppendChild(subElement);
            }
            document.Save("ore.xml");
            textWritter.Close();
            textWritter.Dispose();
            #endregion

            #region ignots.xml
            textWritter = new XmlTextWriter("ignots.xml", Encoding.UTF8);
            textWritter.WriteStartDocument();
            textWritter.WriteStartElement("head");
            textWritter.WriteEndElement();
            document = new XmlDocument();
            document.Load("ignots.xml");

            foreach (KeyValuePair<string, TradeSystem.Goods.Ignots> pair in ignotsList)
            {
                element = document.CreateElement("ignot");
                document.DocumentElement.AppendChild(element);
                attribute = document.CreateAttribute("Имя");
                attribute.Value = pair.Value.getName();
                element.Attributes.Append(attribute);

                subElement = document.CreateElement("price");
                subElement.InnerText = pair.Value.getPrice().ToString();
                element.AppendChild(subElement);
            }
            document.Save("ignots.xml");
            textWritter.Close();
            textWritter.Dispose();
            #endregion
        }
Exemplo n.º 10
0
 public void TransformStrStrResolver1()
 {
     String szFullFilename = FullFilePath("fruits.xml");
     try
     {
         if (LoadXSL("xmlResolver_main.xsl", new XmlUrlResolver()) == 1)
         {
             XmlTextReader xr = new XmlTextReader(szFullFilename);
             XmlTextWriter xw = new XmlTextWriter("out.xml", Encoding.Unicode);
             xslt.Transform(xr, null, xw, null);
             xr.Dispose();
             xw.Dispose();
             if (CheckResult(403.7784431795) == 1)
                 return;
             else
                 Assert.True(false);
         }
     }
     catch (Exception e)
     {
         _output.WriteLine(e.ToString());
         Assert.True(false);
     }
     Assert.True(false);
 }
Exemplo n.º 11
0
        public void TransformStrStrResolver1()
        {
            String szFullFilename = FullFilePath("fruits.xml");
            string expected = @"<result>
  <fruit>Apple</fruit>
  <fruit>orange</fruit>
</result>";

            if (LoadXSL("XmlResolver_Main.xsl", new XmlUrlResolver()) == 1)
            {
                XmlTextReader xr = new XmlTextReader(szFullFilename);
                XmlTextWriter xw = new XmlTextWriter("out.xml", Encoding.Unicode);
                xslt.Transform(xr, null, xw, null);
                xr.Dispose();
                xw.Dispose();
                VerifyResult(expected);
                return;
            }
            Assert.True(false);
        }
Exemplo n.º 12
0
 public void Save()
 {
     string name = _Doc.DocumentElement.Name +".xml";
     XmlTextWriter xtw = new XmlTextWriter(name,null);
     xtw.Formatting = Formatting.Indented;
     _Doc.Save(xtw);
     xtw.Dispose();
     LoadXMLDoc(name);
 }
        /// <summary>
        /// Enables inspection or modification of a message before a request message is sent to a service.
        /// </summary>
        /// <param name="request">The message to be sent to the service.</param>
        /// <param name="channel">The WCF client object channel.</param>
        /// <returns>The object that is returned as the correlationState argument of the AfterReceiveReply method. This is null if no correlation state is used.</returns>
        /// <exception cref="System.ArgumentNullException">
        /// request
        /// or
        /// channel
        /// </exception>
        /// <exception cref="ArgumentNullException">The <paramref name="request"/> parameter is null.</exception>
        /// <exception cref="ArgumentNullException">The <paramref name="channel"/> parameter is null.</exception>
        public object BeforeSendRequest(ref Message request, IClientChannel channel)
        {
            if (request == null)
                throw new ArgumentNullException("request");

            if (channel == null)
                throw new ArgumentNullException("channel");

            var message = request;

            var extension = OperationContext.Current.Extensions.Find<IntegrationServiceOperationContextExtension>();

            if (extension == null)
                return null;

            foreach (var attributes in
                extension.HeaderAttributes.Where(attributes => attributes.IsActorSet || attributes.IsMustUnderstandSet || attributes.IsRelaySet))
            {
                int index;
               
                for (index = 0; index < message.Headers.Count; ++index)
                {
                    var header = message.Headers[index];
                    if (header.Name == attributes.HeaderName && header.Namespace == attributes.HeaderNamespace)
                        break;
                }

                if (index >= message.Headers.Count)
                    continue;

                var oldHeader = message.Headers[index];
                var sb = new StringBuilder();

                StringWriter writer = null;
                XmlTextWriter xmlWriter = null;
                
                try
                {
                    writer = new StringWriter(sb, CultureInfo.InvariantCulture);

                    xmlWriter = new XmlTextWriter(writer);
                    xmlWriter.WriteStartDocument();
                    message.Headers.WriteHeader(index, xmlWriter);
                }
                finally
                {
                    if (xmlWriter != null)
                        xmlWriter.Dispose();
                    else
                    {
                        if (writer != null)
                            writer.Dispose();
                    }
                }

                var xmlDocument = new XmlDocument();
                xmlDocument.LoadXml(sb.ToString());

                var mustUnderstand = attributes.IsMustUnderstandSet ? attributes.MustUnderstand : oldHeader.MustUnderstand;
                var actor = attributes.IsActorSet ? attributes.Actor : oldHeader.Actor;
                var relay = attributes.IsRelaySet ? attributes.Relay : oldHeader.Relay;

                var newHeader = new XmlElementMessageHeader(
                    oldHeader.Name, oldHeader.Namespace, mustUnderstand, actor, relay, xmlDocument.DocumentElement);

                message.Headers.RemoveAt(index);
                message.Headers.Insert(index, newHeader);
            }

            return null;
        }
Exemplo n.º 14
0
        void IExportLeonFormatService.GenerateLeonFormat(List<Lag> items)
        {
            try
            {
                List<Lag> itemsToConvert = items.OrderBy(x => x.LagNummer).ToList();
                foreach (var lag in itemsToConvert)
                {
                    lag.SkiverILaget = lag.SkiverILaget.OrderBy(y => y.SkiveNummer).ToList();
                }

            if (itemsToConvert != null)
            {
                    var outputXmlStream = new MemoryStream { Position = 0 };
                    var memStevne = new MemoryStream();
                    XmlTextWriter write = new XmlTextWriter(memStevne, new UTF8Encoding(false));
                    this.m_serLag.Serialize(write, itemsToConvert);
                    write.Flush();
                    memStevne.Position = 0;

                    var debugStrem = new MemoryStream(memStevne.ToArray());
                    debugStrem.Position = 0;
                    var settings = new XmlReaderSettings();

                    XmlReader xmlReader = XmlReader.Create(debugStrem, settings);
                    XmlDocument docdebug = new XmlDocument();
                    docdebug.Load(xmlReader);

                    memStevne.Position = 0;
                    XPathDocument xpathDoc;
                    var enc = new UTF8Encoding(false);
                    var reader = new StreamReader(memStevne, enc, true);

                    // XmlTextReader xmlReader = new XmlTextReader(reader);
                    xpathDoc = new XPathDocument(reader);
                    this.m_xsltLeonFormat.Transform(xpathDoc, null, outputXmlStream);
                    outputXmlStream.Position = 0;
                    XmlDocument docSaver = new XmlDocument();
                    StreamReader readerOut = new StreamReader(outputXmlStream, enc, true);
                    XmlTextReader xmlReaderOut = new XmlTextReader(readerOut);
                    docSaver.Load(xmlReaderOut);
                     string fileexportName = Path.Combine(m_exportDirLeon, "Paameldinger.xml");
                    if (!string.IsNullOrEmpty(fileexportName))
                    {
                        Log.Info("Generating new Start List {0}", fileexportName);
                        var encServer = Encoding.GetEncoding("UTF-8");
                        XmlTextWriter writer = new XmlTextWriter(fileexportName, encServer);
                        writer.Formatting = Formatting.Indented;
                        docSaver.Save(writer);
                        writer.Flush();
                        writer.Close();
                        writer.Dispose();
                    }

                    string debugfileexportName = Path.Combine(m_exportDirLeon, "InputXml.xml");
                    if (!string.IsNullOrEmpty(debugfileexportName))
                    {
                        Log.Info("Generating new DebugXml {0}", debugfileexportName);
                        var encServer = Encoding.GetEncoding("UTF-8");
                        XmlTextWriter writer = new XmlTextWriter(debugfileexportName, encServer);
                        writer.Formatting = Formatting.Indented;
                        docdebug.Save(writer);
                        writer.Flush();
                        writer.Close();
                        writer.Dispose();
                    }
                }
            }
            catch (Exception e)
            {
                Log.Error(e, "Error GenerateLeonFormat");
                throw;
            }
        }
Exemplo n.º 15
0
        private static void CreateXmlPhonebook(string pathToTxtFile)
        {
            int lineNumber = 0;
            var writer = new XmlTextWriter("../../phonebook.xml", Encoding.UTF8);
            writer.WriteStartDocument();
            writer.WriteStartElement("entries");
            using (var reader = new StreamReader(pathToTxtFile))
            {
                while (!reader.EndOfStream)
                {
                    switch (lineNumber % 3)
                    {
                        case 0: writer.WriteStartElement("entry");
                                writer.WriteElementString("name", reader.ReadLine());
                            break;
                        case 1: writer.WriteElementString("address", reader.ReadLine());
                            break;
                        case 2: writer.WriteElementString("phone", reader.ReadLine());
                                writer.WriteEndElement();
                            break;
                    }

                    lineNumber++;
                }
            }

            writer.WriteEndElement();
            writer.WriteEndDocument();
            writer.Close();
            writer.Dispose();
        }