Ejemplo n.º 1
0
        private string GetArk(string ia_struct)
        {
            string marc_field = "<datafield tag=\"955\" ind1=\" \" ind2=\" \">";

            System.Xml.XmlTextReader rd;
            rd = new System.Xml.XmlTextReader(new System.IO.StringReader(ia_struct));
            try
            {
                //System.Windows.Forms.MessageBox.Show("here");
                while (rd.Read())
                {
                    //This is where we find the head of the record,
                    //then process the values within the record.
                    //We also need to do character encoding here if necessary.

                    if (rd.NodeType == System.Xml.XmlNodeType.Element)
                    {
                        //System.Windows.Forms.MessageBox.Show(rd.LocalName);
                        if (rd.LocalName == "identifier-ark")
                        {
                            marc_field += "<subfield code=\"b\">" + rd.ReadString() + "</subfield>";
                        }
                        else if (rd.LocalName == "identifier")
                        {
                            marc_field += "<subfield code=\"q\">" + rd.ReadString() + "</subfield>";
                        }
                    }
                }

                marc_field += "</datafield>";
            }
            catch { }
            rd.Close();
            return(marc_field);
        }
Ejemplo n.º 2
0
 public static void FromXml(System.IO.Stream stream, PackageMatchDelegate callback)
 {
     System.Xml.XmlTextReader reader = new System.Xml.XmlTextReader(stream);
     FromXml(reader, callback);
     reader.Close();
     stream.Close();
 }
Ejemplo n.º 3
0
        private static UserPreferences ReadUserPreferences()
        {
            string          sPath   = System.IO.Path.ChangeExtension(System.Reflection.Assembly.GetExecutingAssembly().Location, "pref.xml");
            UserPreferences oReturn = null;

            if (System.IO.File.Exists(sPath))
            {
                System.Xml.Serialization.XmlSerializer oSerializer = new System.Xml.Serialization.XmlSerializer(typeof(UserPreferences));
                System.Xml.XmlTextReader oReader = new System.Xml.XmlTextReader(sPath);

                try
                {
                    oReturn = (UserPreferences)oSerializer.Deserialize(oReader);
                }
                catch (Exception)
                {
                    oReturn = new UserPreferences();
                }
                finally
                {
                    oReader.Close();
                }
            }

            if (oReturn == null)
            {
                oReturn = new UserPreferences();
            }

            return(oReturn);
        }
Ejemplo n.º 4
0
        /// <summary>
        /// Load L-System definition file
        /// </summary>
        public void LoadDefinition()
        {
            Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
            dlg.DefaultExt = ".ls";                                           // Default file extension
            dlg.Filter     = "L-System files(*.ls)|*.ls|All files (*.*)|*.*"; // Filter files by extension

            // Show save file dialog box
            bool?result = dlg.ShowDialog();

            // Process save file dialog box results
            if (result == true)
            {
                // Load document
                string filename = dlg.FileName;
                try
                {
                    System.Xml.Serialization.XmlSerializer x = new System.Xml.Serialization.XmlSerializer(_model.GetType());
                    using (System.Xml.XmlReader reader = new System.Xml.XmlTextReader(filename))
                    {
                        if (x.CanDeserialize(reader))
                        {
                            _model = x.Deserialize(reader) as SettingsModel;
                        }
                        reader.Close();
                    }
                }
                catch
                {
                    System.Windows.MessageBox.Show("Couldn't load L-System, please try again later.", "Error", System.Windows.MessageBoxButton.OK, System.Windows.MessageBoxImage.Error);
                }
            }

            // update all properties
            InvokePropertyChanged(null);
        }
Ejemplo n.º 5
0
        string connStr()
        {
            string Retorno = "";
            string path    = System.IO.Directory.GetCurrentDirectory();

            string[] parts = path.Split('\\'); path = "";
            for (int i = 0; i < parts.Length - 2; i++)
            {
                path = path + parts[i].ToString() + "\\";
            }

            path = path + "config.xml";

            // Create an isntance of XmlTextReader and call Read method to read the file
            System.Xml.XmlTextReader textReader = new System.Xml.XmlTextReader(path);
            textReader.Read();
            // If the node has value
            while (textReader.Read())
            {
                //  Here we check the type of the node, in this case we are looking for element
                if (textReader.NodeType == System.Xml.XmlNodeType.Element)
                {
                    //  If the element is "profile"
                    if (textReader.Name == "add")
                    {
                        //  Add the attribute value of "username" to the listbox
                        Retorno = textReader.GetAttribute("connectionString");
                    }
                }
            }
            textReader.Close();
            return(Retorno);
        }
Ejemplo n.º 6
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="xml"></param>
        /// <param name="objectType"></param>
        /// <returns></returns>
        public static Object ObjectToXML(string xml, Type objectType)
        {
            StringReader strReader = null;

            System.Xml.Serialization.XmlSerializer serializer = null;
            System.Xml.XmlTextReader xmlReader = null;
            Object obj = null;

            try
            {
                strReader  = new StringReader(xml);
                serializer = new System.Xml.Serialization.XmlSerializer(objectType);
                xmlReader  = new System.Xml.XmlTextReader(strReader);
                obj        = serializer.Deserialize(xmlReader);
            }
            catch (Exception exp)
            {
                //Handle Exception Code
            }
            finally
            {
                if (xmlReader != null)
                {
                    xmlReader.Close();
                }
                if (strReader != null)
                {
                    strReader.Close();
                }
            }
            return(obj);
        }
Ejemplo n.º 7
0
        /// <summary>
        /// This event displays a printer selection dialog and then starts the print
        /// process.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">An EventArgs that contains the event data.</param>
        private void PrintButton_Click(object sender, System.EventArgs e)
        {
            // Perform the print within a try block in case a failure
            // of any type occurs.  For this sample, all errors will
            // be handled generically by simply displaying a messagebox.
            try
            {
                // Open the XML Data file.
                xmlReader = new System.Xml.XmlTextReader("..\\..\\..\\Misc\\ReportData.xml");

                // Position the pointer to the first element.
                xmlReader.Read();

                // Display a printer selection dialog.
                // Only print the document if the user clicks OK.
                if (printDialog1.ShowDialog() == DialogResult.OK)
                {
                    // This starts the actual print.  The code to output
                    // text to the selected printer resides in the PrintDocument1_PrintPage
                    // event handler.
                    printDocument1.Print();
                }

                // Close the data file.
                xmlReader.Close();
            }
            catch (Exception ex)
            {
                // If any error occurs, display a messagebox.
                MessageBox.Show("Error printing report: \r\n" + ex.Message);
            }
        }
Ejemplo n.º 8
0
 public void closeFile()
 {
     if (xtr != null)
     {
         xtr.Close();
     }
 }
Ejemplo n.º 9
0
        private void FillDataSet()
        {
            //ReadSchemaFromXmlTextReader
            // Create a FileStream object with the file path and name.
            System.IO.FileStream myFileStream = new System.IO.FileStream("programes.xsd", System.IO.FileMode.Open);

            // Create a new XmlTextReader object with the FileStream.
            System.Xml.XmlTextReader myXmlTextReader =
                new System.Xml.XmlTextReader(myFileStream);
            // Read the schema into the DataSet and close the reader.
            dsSource.ReadXmlSchema(myXmlTextReader);
            myXmlTextReader.Close();


            // Read the XML document back in.
            // Create new FileStream to read schema with.
            System.IO.FileStream fsReadXml = new System.IO.FileStream
                                                 ("programes.xml", System.IO.FileMode.Open);

            System.Xml.XmlTextReader myXmlReader = new System.Xml.XmlTextReader(fsReadXml);

            dsSource.ReadXml(myXmlReader);
            myXmlReader.Close();

            dataGrid.DataSource = dsSource.Tables["programes"];
        }
Ejemplo n.º 10
0
 /// <summary>
 /// 从HTML读取器中加载对象数据
 /// </summary>
 /// <param name="myReader"></param>
 /// <returns></returns>
 internal override bool InnerRead(HTMLTextReader myReader)
 {
     strLoadErrorMsg = null;
     strSourceXML    = myReader.ReadToEndTag(this.TagName);
     try
     {
         myXMLDocument.RemoveAll();
         System.Xml.XmlNamespaceManager nsm = new System.Xml.XmlNamespaceManager(myXMLDocument.NameTable);
         foreach (HTMLAttribute attr in myOwnerDocument.Attributes)
         {
             string vName = attr.Name;
             if (vName.ToLower().StartsWith(StringConstAttributeName.XMLNS))
             {
                 int index = vName.IndexOf(":");
                 if (index > 0)
                 {
                     string NsName = vName.Substring(index + 1);
                     nsm.AddNamespace(NsName, attr.Value);
                 }
             }
         }
         System.Xml.XmlParserContext pc          = new System.Xml.XmlParserContext(myXMLDocument.NameTable, nsm, null, System.Xml.XmlSpace.None);
         System.Xml.XmlTextReader    myXMLReader = new System.Xml.XmlTextReader(strSourceXML, System.Xml.XmlNodeType.Element, pc);
         myXMLDocument.Load(myXMLReader);
         myXMLReader.Close();
     }
     catch (Exception ext)
     {
         myXMLDocument.RemoveAll();
         strLoadErrorMsg = "加载XML数据岛信息错误 - " + ext.Message;
     }
     return(true);
 }
Ejemplo n.º 11
0
        /// <summary>
        /// loads a configuration from a xml-file - if there isn't one, use default settings
        /// </summary>
        public void ReadSettings()
        {
            bool dirty = false;

            Reset();
            try
            {
                System.Xml.XmlTextReader xmlConfigReader = new System.Xml.XmlTextReader("settings.xml");
                while (xmlConfigReader.Read())
                {
                    if (xmlConfigReader.NodeType == System.Xml.XmlNodeType.Element)
                    {
                        switch (xmlConfigReader.Name)
                        {
                        case "display":
                            fullscreen  = Convert.ToBoolean(xmlConfigReader.GetAttribute("fullscreen"));
                            resolutionX = Convert.ToInt32(xmlConfigReader.GetAttribute("resolutionX"));
                            resolutionY = Convert.ToInt32(xmlConfigReader.GetAttribute("resolutionY"));

                            // validate resolution
                            // TODO

                            /*  if (!GraphicsAdapter.DefaultAdapter.SupportedDisplayModes.Any(x => x.Format == SurfaceFormat.Color &&
                             *                                                                x.Height == resolutionY && x.Width == resolutionX))
                             * {
                             *    ChooseStandardResolution();
                             *    dirty = true;
                             * } */
                            break;
                        }
                    }
                }
                xmlConfigReader.Close();
            }
            catch
            {
                // error in xml document - write a new one with standard values
                try
                {
                    Reset();
                    dirty = true;
                }
                catch
                {
                }
            }

            // override fullscreen resolutions
            if (fullscreen)
            {
                ResolutionX = System.Windows.Forms.Screen.PrimaryScreen.WorkingArea.Width;
                ResolutionY = System.Windows.Forms.Screen.PrimaryScreen.WorkingArea.Height;
            }

            if (dirty)
            {
                Save();
            }
        }
Ejemplo n.º 12
0
 private void LoadHighlightingDefinition()
 {
   var xshdUri = App.GetResourceUri("simai.xshd");
   var rs = Application.GetResourceStream(xshdUri);
   var reader = new System.Xml.XmlTextReader(rs.Stream);
   definition = HighlightingLoader.Load(reader, HighlightingManager.Instance);
   reader.Close();
 }
Ejemplo n.º 13
0
 /// <summary>
 ///		Cambia el modo de resalte desde un stream
 /// </summary>
 public void LoadHighLight(System.IO.Stream stmFile)
 {
     using (System.Xml.XmlTextReader rdrXml = new System.Xml.XmlTextReader(stmFile))
     {
         // Cambia el modo de resalte
         txtEditor.SyntaxHighlighting = ICSharpCode.AvalonEdit.Highlighting.Xshd.HighlightingLoader.Load(rdrXml, HighlightingManager.Instance);
         // Cierra el lector
         rdrXml.Close();
     }
 }
Ejemplo n.º 14
0
 public void LoadFromFile(string FilePath)
 {
     if (FilePath.Length == 0)
     {
         FilePath = m_FilePath;
     }
     System.Xml.XmlTextReader xml = new System.Xml.XmlTextReader(FilePath);
     try
     {
         LoadFromXml(xml);
         xml.Close();
     }
     catch (Exception x)
     {
         xml.Close();
         throw new Exception("Unable to load job definition file '" + FilePath + "'.  " + x.ToString());
     }
     m_FilePath = FilePath;
 }
Ejemplo n.º 15
0
        public dynamic FileReader <T>(T item, string Filelocation)
        {
            XmlSerializer deserializer = new XmlSerializer(typeof(T));
            var           reader       = new System.Xml.XmlTextReader(Filelocation);
            object        obj          = deserializer.Deserialize(reader);
            T             XmlData      = (T)obj;

            reader.Close();
            return(XmlData);
        }
Ejemplo n.º 16
0
        public static int FromXml(System.IO.Stream stream, ChannelDelegate callback)
        {
            System.Xml.XmlTextReader reader = new System.Xml.XmlTextReader(stream);
            int count = FromXml(reader, callback);

            reader.Close();
            stream.Close();

            return(count);
        }
Ejemplo n.º 17
0
 /// <summary>
 /// Currently a naive implementation. Treats all fields under summary as text.
 /// </summary>
 /// <param name="xmlDocumentation"></param>
 /// <returns></returns>
 public string GetSummary(string xmlDocumentation)
 {
     var frag = new System.Xml.XmlTextReader(xmlDocumentation, System.Xml.XmlNodeType.Element, null);
     string result = "";
     while (frag.Read()) {
         result += frag.Value;
     }
     frag.Close();
     return result;
 }
Ejemplo n.º 18
0
        /// <summary>
        /// loads a configuration from a xml-file - if there isn't one, use default settings
        /// </summary>
        public void ReadSettings()
        {
            bool dirty = false;
            Reset();
            try
            {
                System.Xml.XmlTextReader xmlConfigReader = new System.Xml.XmlTextReader("settings.xml");
                while (xmlConfigReader.Read())
                {
                    if (xmlConfigReader.NodeType == System.Xml.XmlNodeType.Element)
                    {
                        switch (xmlConfigReader.Name)
                        {
                            case "display":
                                fullscreen = Convert.ToBoolean(xmlConfigReader.GetAttribute("fullscreen"));
                                resolutionX = Convert.ToInt32(xmlConfigReader.GetAttribute("resolutionX"));
                                resolutionY = Convert.ToInt32(xmlConfigReader.GetAttribute("resolutionY"));

                                // validate resolution
                                // TODO
                              /*  if (!GraphicsAdapter.DefaultAdapter.SupportedDisplayModes.Any(x => x.Format == SurfaceFormat.Color &&
                                                                                                x.Height == resolutionY && x.Width == resolutionX))
                                {
                                    ChooseStandardResolution();
                                    dirty = true;
                                } */
                                break;
                        }
                    }
                }
                xmlConfigReader.Close();
            }
            catch
            {
                // error in xml document - write a new one with standard values
                try
                {
                    Reset();
                    dirty = true;
                }
                catch
                {
                }
            }

            // override fullscreen resolutions
            if (fullscreen)
            {
                ResolutionX = System.Windows.Forms.Screen.PrimaryScreen.WorkingArea.Width;
                ResolutionY = System.Windows.Forms.Screen.PrimaryScreen.WorkingArea.Height;
            }

            if(dirty)
                Save();
        }
        public ProjectConfig Load(string filename)
        {
            XmlSerializer xs = new XmlSerializer(typeof(ProjectConfig));

            // TODO: Exceptions...
            System.Xml.XmlTextReader xtr = new System.Xml.XmlTextReader(filename);
            ProjectConfig            pc  = (ProjectConfig)xs.Deserialize(xtr);

            xtr.Close();
            return(pc);
        }
Ejemplo n.º 20
0
 /// <summary>
 /// Reads the XML file.
 /// </summary>
 /// <param name="myData">My data.</param>
 public void readXMLFile(DataSet myData)
 {
     System.Xml.XmlTextReader myXmlReader;
     using (FileStream myFileStream = new System.IO.FileStream(filename, System.IO.FileMode.Open))
     {
         //Create an XmlTextReader with the fileStream.
         myXmlReader = new System.Xml.XmlTextReader(myFileStream);
     }
     myData.ReadXml(myXmlReader);
     myXmlReader.Close();
 }
        public static ImageDescriptors Deserialize(string path)
        {
            System.Xml.Serialization.XmlSerializer serializer = new XmlSerializer(typeof(ImageDescriptors));

            System.Xml.XmlTextReader reader = new System.Xml.XmlTextReader(path);

            ImageDescriptors result = (ImageDescriptors)serializer.Deserialize(reader);

            reader.Close();

            return(result);
        }
Ejemplo n.º 22
0
            /// <summary>
            /// This is the worker thread.
            /// </summary>
            /// <param name="stateInfo">Not used.</param>
            void ProcessFiles(object stateInfo)
            {
                System.Text.StringBuilder stb = null;

                while (_filesToProcess.Count > 0)
                {
                    string fullfilename = _filesToProcess.Dequeue();
                    try
                    {
                        string   category     = null;
                        string   name         = null;
                        DateTime creationTime = DateTime.MinValue;
                        string   description  = string.Empty;

                        System.Xml.XmlTextReader xmlReader = new System.Xml.XmlTextReader(fullfilename);
                        xmlReader.MoveToContent();
                        while (xmlReader.Read())
                        {
                            if (xmlReader.NodeType == System.Xml.XmlNodeType.Element && xmlReader.LocalName == "Category")
                            {
                                category     = xmlReader.ReadElementString();
                                name         = xmlReader.ReadElementString("Name");
                                creationTime = System.Xml.XmlConvert.ToDateTime(xmlReader.ReadElementString("CreationTime"), System.Xml.XmlDateTimeSerializationMode.Local);
                                if (xmlReader.LocalName == "Description")
                                {
                                    description = xmlReader.ReadElementString("Description");
                                }
                                break;
                            }
                        }
                        xmlReader.Close();

                        AddFitFunctionEntry(category, name, creationTime, description, fullfilename);
                    }
                    catch (Exception ex)
                    {
                        if (stb == null)
                        {
                            stb = new StringBuilder();
                        }

                        stb.AppendLine(ex.ToString());
                    }
                }

                if (stb != null)
                {
                    Current.Console.WriteLine("Exception(s) thrown in " + this.GetType().ToString() + " during parsing of fit functions, details will follow:");
                    Current.Console.WriteLine(stb.ToString());
                }
                _threadIsWorking = false;
            }
Ejemplo n.º 23
0
 public Clips Load(string filename)
 {
     System.Xml.XmlTextReader xtw = new System.Xml.XmlTextReader(filename);
     try
     {
         Clips clips = (Clips)s_ser.Deserialize(xtw);
         return(clips);
     }
     finally
     {
         xtw.Close();
     }
 }
Ejemplo n.º 24
0
        protected void Page_Load(object sender, EventArgs e)
        {
            SectionReport rpt = new SectionReport();

            var reportsPath = Path.Combine(Server.MapPath("~"), "Reports") + @"\";

            rpt.ResourceLocator = new DefaultResourceLocator(new Uri(reportsPath));
            System.Xml.XmlTextReader xtr = new System.Xml.XmlTextReader(Path.Combine(reportsPath, "Invoice.rpx"));
            rpt.LoadLayout(xtr);
            xtr.Close();
            try
            {
                rpt.Run(false);
            }
            catch (ReportException eRunReport)
            {
                // Failure running report, just report the error to the user.
                Response.Clear();
                Response.Write(GetLocalResourceObject("Error"));
                Response.Write(eRunReport.ToString());
                return;
            }

            // Tell the browser this is a PDF document so it will use an appropriate viewer.
            // If the report has been exported in a different format, the content-type will
            // need to be changed as noted in the following table:
            //	ExportType  ContentType
            //	PDF	   "application/pdf"  (needs to be in lowercase)
            //	RTF	   "application/rtf"
            //	TIFF	  "image/tiff"	   (will open in separate viewer instead of browser)
            //	HTML	  "message/rfc822"   (only applies to compressed HTML pages that includes images)
            //	Excel	 "application/vnd.ms-excel"
            //	Excel	 "application/excel" (either of these types should work)
            //	Text	  "text/plain"
            Response.ContentType = "application/pdf";

            Response.AddHeader("content-disposition", "inline; filename=MyPDF.PDF");

            // Create the PDF export object.
            PdfExport pdf = new PdfExport();

            // Create a new memory stream that will hold the pdf output.
            System.IO.MemoryStream memStream = new System.IO.MemoryStream();
            // Export the report to PDF.
            pdf.Export(rpt.Document, memStream);
            // Write the PDF stream to the output stream.
            Response.BinaryWrite(memStream.ToArray());
            // Send all buffered content to the client.
            Response.End();
        }
Ejemplo n.º 25
0
        private void btnInput_Click(object sender, System.EventArgs e)
        {
            if (this.tbxFilePath.Text == "")
            {
                MessageBox.Show("请先选择导入的XML文件!", "系统提示");
                return;
            }
            DataSet dsFrom     = new DataSet();
            DataSet dsTo       = new DataSet();
            var     dbProvider = DbFactoryProvider.GetProvider(SystemInfo.WorkFlowDbType, SystemInfo.WorkFlowDbConnectionString);

            System.IO.FileStream     fsReadXml1  = new System.IO.FileStream(_inputFilePath, System.IO.FileMode.Open);
            System.Xml.XmlTextReader myXmlReader = new System.Xml.XmlTextReader(fsReadXml1);
            dsFrom.ReadXml(myXmlReader);
            myXmlReader.Close();
            try
            {
                if (this.rbtnAll.Checked)
                {
                    this.progressBar1.Maximum = 13;
                    if (InputWorkflow(dsFrom, dsTo)) //导入原形
                    {
                        InputPage(dsFrom, dsTo);     //导入表单
                    }
                    //dbProvider.UpdateDSWithTranse(dsTo);
                }
                else
                if (this.rbtnWorkFlow.Checked)
                {
                    this.progressBar1.Maximum = 10;
                    if (InputWorkflow(dsFrom, dsTo))     //导入原形
                    {
                        //dbProvider.UpdateDSWithTranse(dsTo);
                    }
                }
                else
                if (this.rdbtNewWorkFlow.Checked)
                {
                    this.progressBar1.Maximum = 10;
                    InputNewWorkflow(dsFrom);
                }
                //this.progressBar1.Maximum=0;
                lbStep.Text = "导入成功!";
            }
            catch (Exception ex)
            {
                InputFlowId = "";//一定要放在开始导入后,导入失败后该值为空
                MessageBox.Show("导入错误,错误代码:" + ex.Message.ToString(), "系统提示");
            }
        }
Ejemplo n.º 26
0
 public bool LoadFromFile(string FileName)
 {
     try {
         Reader = new System.Xml.XmlTextReader(FileName);
         Reader.MoveToContent();
         base.Load(Reader);
         Reader.Close();
         Reader = null;
     } catch (System.Exception Excpt) {
         Err.Add(Excpt);
         return(false);
     }
     return(true);
 }
Ejemplo n.º 27
0
 public void Close()
 {
     if (HFile == null)
     {
         return;
     }
     try {
         HFile.Close();
     } catch (System.Exception Excpt) {
         Err.Add(Excpt);
     }
     HFile      = null;
     LayerNames = null;
 }
        public override WebServiceResponse Unmarshall(XmlUnmarshallerContext context)
        {
            System.Xml.XmlTextReader reader = new System.Xml.XmlTextReader(context.ResponseStream);
            Message message = new Message();

            while (reader.Read())
            {
                switch (reader.NodeType)
                {
                    case System.Xml.XmlNodeType.Element:
                        switch (reader.LocalName)
                        {
                            case MNSConstants.XML_ELEMENT_MESSAGE_ID:
                                message.Id = reader.ReadElementContentAsString();
                                break;
                            case MNSConstants.XML_ELEMENT_RECEIPT_HANDLE:
                                message.ReceiptHandle = reader.ReadElementContentAsString();
                                break;
                            case MNSConstants.XML_ELEMENT_MESSAGE_BODY_MD5:
                                message.BodyMD5 = reader.ReadElementContentAsString();
                                break;
                            case MNSConstants.XML_ELEMENT_MESSAGE_BODY:
                                message.Body = reader.ReadElementContentAsString();
                                break;
                            case MNSConstants.XML_ELEMENT_ENQUEUE_TIME:
                                message.EnqueueTime = AliyunSDKUtils.ConvertFromUnixEpochSeconds(reader.ReadElementContentAsLong());
                                break;
                            case MNSConstants.XML_ELEMENT_NEXT_VISIBLE_TIME:
                                message.NextVisibleTime = AliyunSDKUtils.ConvertFromUnixEpochSeconds(reader.ReadElementContentAsLong());
                                break;
                            case MNSConstants.XML_ELEMENT_FIRST_DEQUEUE_TIME:
                                message.FirstDequeueTime = AliyunSDKUtils.ConvertFromUnixEpochSeconds(reader.ReadElementContentAsLong());
                                break;
                            case MNSConstants.XML_ELEMENT_DEQUEUE_COUNT:
                                message.DequeueCount = (uint)reader.ReadElementContentAsInt();
                                break;
                            case MNSConstants.XML_ELEMENT_PRIORITY:
                                message.Priority = (uint)reader.ReadElementContentAsInt();
                                break;
                        }
                        break;
                }
            }
            reader.Close();
            return new ReceiveMessageResponse()
            {
                Message = message
            };
        }
Ejemplo n.º 29
0
        private string GenerateAlmaRecord(string s, string id = "")
        {
            //We need to extract the record part (not the collection part)
            System.Xml.XmlTextReader rd;
            string sRec = "";

            try
            {
                rd = new System.Xml.XmlTextReader(s, System.Xml.XmlNodeType.Document, null);
                //rd = new System.Xml.XmlTextReader(prawXML, System.Xml.XmlNodeType.Document, null);
            } catch (System.Exception pp) {
                //System.Windows.Forms.MessageBox.Show(pp.ToString());
                return("");
            }

            try
            {
                //System.Windows.Forms.MessageBox.Show("here");
                while (rd.Read())
                {
                    //This is where we find the head of the record,
                    //then process the values within the record.
                    //We also need to do character encoding here if necessary.

                    if (rd.NodeType == System.Xml.XmlNodeType.Element)
                    {
                        //System.Windows.Forms.MessageBox.Show(rd.LocalName);
                        if (rd.LocalName == "record")
                        {
                            sRec = rd.ReadOuterXml();
                            break;
                        }
                    }
                }
                rd.Close();
                sRec = sRec.Replace("marc:", "");
                string sidtag = "";
                if (!string.IsNullOrEmpty(id))
                {
                    sidtag = "<mms_id>" + id + "</mms_id>";
                }
                sRec = "<bib>" + sidtag + "<record_format>marc21</record_format><suppress_from_publishing>false</suppress_from_publishing>" + sRec + "</bib>";
                return(sRec);
            }
            catch (System.Exception ppp) {
                //System.Windows.Forms.MessageBox.Show(ppp.ToString());
                return("");
            }
        }
Ejemplo n.º 30
0
        } // End Function XmlUnescape

        public static System.Xml.XmlDocument File2XmlDocument(string strFileName)
        {
            // http://blogs.msdn.com/b/tolong/archive/2007/11/15/read-write-xml-in-memory-stream.aspx
            System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
            // doc.Load(memorystream);
            // doc.Load(FILE_NAME);
            // doc.Load(strFileName);
            using (System.Xml.XmlTextReader xtrReader = new System.Xml.XmlTextReader(strFileName))
            {
                doc.Load(xtrReader);
                xtrReader.Close();
            } // End Using xtrReader

            return(doc);
        } // End Function File2XmlDocument
Ejemplo n.º 31
0
 public static System.Data.DataTable ConvertXMLFileToDataSet(string xmlData)
 {
     System.Xml.XmlTextReader reader = null;
     try {
         System.Data.DataTable xmlDS = new System.Data.DataTable();
         reader = new System.Xml.XmlTextReader(new System.IO.StringReader(xmlData));
         xmlDS.ReadXml(reader);
         return(xmlDS);
     } catch (System.Exception ex) {
         throw ex;
     } finally {
         if (reader != null)
         {
             reader.Close();
         }
     }
 }
Ejemplo n.º 32
0
        /// <summary>
        /// Read XML file send by EasyWarePro.</summary>
        /// <param name="strPath">full path to the xml file</param>
        /// <returns><c>true</c>: successfull</returns>
        /// <remarks>required</remarks>
        protected string ReceiveXmlFile(string strPath)
        {
            // Create the reader.
            using (System.Xml.XmlReader reader = new System.Xml.XmlTextReader(strPath))
            {
                try
                {
                    //Example of data processing handled within this PlugIn
                    string strReturnMsg = ReceiveXmlMessage(reader);
                    return(strReturnMsg);
                }
                finally
                {
                    reader.Close();

                    if (UseCmdFile)
                    {
                        //example of data processing handled outside of this plugIn
                        try
                        {
                            FileInfo fi = new FileInfo(strPath);

                            if (fi.Exists)
                            {
                                fi.MoveTo(Path.Combine(_FileExchangeFolder, _CmdFileOut));
                            }
                        }
                        catch { }
                    }
                    else
                    {
                        //someone has to delete the file
                        //delete file
                        try
                        {
                            if (File.Exists(strPath))
                            {
                                File.Delete(strPath);
                            }
                        }
                        catch { }
                    }
                }
            }
        }
Ejemplo n.º 33
0
        private void Read_Configuration_File(string config_file)
        {
            System.IO.StreamReader   reader    = new System.IO.StreamReader(config_file);
            System.Xml.XmlTextReader xmlReader = new System.Xml.XmlTextReader(reader);
            while (xmlReader.Read())
            {
                if (xmlReader.NodeType == System.Xml.XmlNodeType.Element)
                {
                    string node_name = xmlReader.Name.ToLower();
                    switch (node_name)
                    {
                    case "connection_string":
                        if (xmlReader.MoveToAttribute("type"))
                        {
                            db_type = xmlReader.Value.ToString();
                        }
                        xmlReader.Read();
                        connection_string = xmlReader.Value;
                        break;

                    case "error_emails":
                        xmlReader.Read();
                        error_emails = xmlReader.Value;
                        break;

                    case "error_page":
                        xmlReader.Read();
                        error_page = xmlReader.Value;
                        break;

                    case "ghostscript_executable":
                        xmlReader.Read();
                        ghostscript = xmlReader.Value;
                        break;

                    case "imagemagick_executable":
                        xmlReader.Read();
                        imagemagick = xmlReader.Value;
                        break;
                    }
                }
            }
            xmlReader.Close();
            reader.Close();
        }
Ejemplo n.º 34
0
        private static void FromXml(System.Xml.XmlTextReader reader, PackageMatchDelegate callback)
        {
            reader.MoveToContent();

            while (reader.Read())
            {
                if (reader.NodeType == System.Xml.XmlNodeType.Element && reader.LocalName == "match")
                {
                    PackageMatch match = ParseMatch(reader);

                    if (!callback(match))
                    {
                        break;
                    }
                }
            }

            reader.Close();
        }
        public static System.Xml.XmlDocument GetReport(string reportName)
        {
            // http://blogs.msdn.com/b/tolong/archive/2007/11/15/read-write-xml-in-memory-stream.aspx
            System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
            // doc.Load(memorystream);
            // doc.Load(FILE_NAME);
            // doc.Load(strFileName);

            using (System.IO.Stream strm = GetEmbeddedReport(reportName))
            {

                using (System.Xml.XmlTextReader xtrReader = new System.Xml.XmlTextReader(strm))
                {
                    doc.Load(xtrReader);
                    xtrReader.Close();
                } // End Using xtrReader

            } // End Using strm

            return doc;
        }
 //Method two: Get is medium trust (get if config is set as medium trust)
 private static bool IsMediumTrustSetInConfig()
 {
     bool result = false;
     try
     {
         string webConfigFile = System.IO.Path.Combine(System.Web.HttpContext.Current.Request.PhysicalApplicationPath, "web.config");
         System.Xml.XmlTextReader webConfigReader = new System.Xml.XmlTextReader(new System.IO.StreamReader(webConfigFile));
         webConfigReader.ReadToFollowing("trust");
         result = webConfigReader.GetAttribute("level") == "Medium";
         webConfigReader.Close(); //Close before return
         return result;
     }
     catch
     {
         return result;
     }
 }
Ejemplo n.º 37
0
        /// <summary>
        /// Recursive function that finds and 
        /// graphs Wikipedia links
        /// </summary>
        /// <param name="g">The graph</param>
        /// <param name="lookupValue">Name of orgin article</param>
        /// <param name="hops">How many degrees of separation from the original article</param>
        private void addLinks(Kitware.VTK.vtkMutableDirectedGraph g, string lookupValue, int hops)
        {
            vtkStringArray label = (vtkStringArray)g.GetVertexData().GetAbstractArray("label");
            long parent = label.LookupValue(lookupValue);
            //if lookupValue is not in the graph add it
            if (parent < 0)
            {
                rotateLogo();
                parent = g.AddVertex();
                label.InsertNextValue(lookupValue);
                arrListSmall.Add(lookupValue);
            }
            //Parse Wikipedia for the lookupValue
            string underscores = lookupValue.Replace(' ', '_');
            System.Net.HttpWebRequest webRequest = (System.Net.HttpWebRequest)System.Net.WebRequest.Create("http://en.wikipedia.org/wiki/Special:Export/" + underscores);
            webRequest.Credentials = System.Net.CredentialCache.DefaultCredentials;
            webRequest.Accept = "text/xml";
            try
            {
                System.Net.HttpWebResponse webResponse = (System.Net.HttpWebResponse)webRequest.GetResponse();
                System.IO.Stream responseStream = webResponse.GetResponseStream();
                System.Xml.XmlReader reader = new System.Xml.XmlTextReader(responseStream);
                String NS = "http://www.mediawiki.org/xml/export-0.4/";
                System.Xml.XPath.XPathDocument doc = new System.Xml.XPath.XPathDocument(reader);
                reader.Close();
                webResponse.Close();
                System.Xml.XPath.XPathNavigator myXPahtNavigator = doc.CreateNavigator();
                System.Xml.XPath.XPathNodeIterator nodesText = myXPahtNavigator.SelectDescendants("text", NS, false);

                String fullText = "";
                //Parse the wiki page for links
                while (nodesText.MoveNext())
                    fullText += nodesText.Current.InnerXml + " ";
                System.Text.RegularExpressions.Match m = System.Text.RegularExpressions.Regex.Match(fullText, "\\[\\[.*?\\]\\]");
                int max;
                try
                {
                    max = System.Convert.ToInt32(toolStripTextBox2.Text);
                }
                catch (Exception)
                {
                    max = -1;
                }
                int count = 0;
                while (m.Success && ((count < max) || (max < 0)))
                {
                    String s = m.ToString();
                    int index = s.IndexOf('|');
                    String substring = "";
                    if (index > 0)
                    {
                        substring = s.Substring(2, index - 2);
                    }
                    else
                    {
                        substring = s.Substring(2, s.Length - 4);
                    }
                    //if the new substring is not already there add it
                    long v = label.LookupValue(substring);
                    if (v < 0)
                    {
                        rotateLogo();
                        v = g.AddVertex();
                        label.InsertNextValue(substring);
                        arrListSmall.Add(substring);
                        if (hops > 1)
                        {
                            addLinks(g, substring, hops - 1);
                        }
                    }
                    else if (arrListSmall.IndexOf(substring) < 0)
                    {
                        arrListSmall.Add(substring);
                        if (hops > 1)
                        {
                            addLinks(g, substring, hops - 1);
                        }
                    }
                    //Make sure nothing is linked to twice by expanding the graph
                    vtkAdjacentVertexIterator avi = vtkAdjacentVertexIterator.New();
                    g.GetAdjacentVertices((int)parent, avi);
                    m = m.NextMatch();
                    ++count;

                    while (avi.HasNext())
                    {
                        long id = avi.Next();
                        if (id == v)
                        {
                            return;
                        }
                    }
                    rotateLogo();
                    g.AddGraphEdge((int)parent, (int)v);

                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }
        private void Read_Configuration_File(string config_file)
        {
            System.IO.StreamReader reader = new System.IO.StreamReader(config_file);
            System.Xml.XmlTextReader xmlReader = new System.Xml.XmlTextReader(reader);
            while (xmlReader.Read())
            {
                if (xmlReader.NodeType == System.Xml.XmlNodeType.Element)
                {
                    string node_name = xmlReader.Name.ToLower();
                    switch (node_name)
                    {
                        case "connection_string":
                            if (xmlReader.MoveToAttribute("type"))
                            {
                                db_type = xmlReader.Value.ToString();

                            }
                            xmlReader.Read();
                            connection_string = xmlReader.Value;
                            break;

                        case "error_emails":
                            xmlReader.Read();
                            error_emails = xmlReader.Value;
                            break;

                        case "error_page":
                            xmlReader.Read();
                            error_page = xmlReader.Value;
                            break;

                        case "ghostscript_executable":
                            xmlReader.Read();
                            ghostscript = xmlReader.Value;
                            break;

                        case "imagemagick_executable":
                            xmlReader.Read();
                            imagemagick = xmlReader.Value;
                            break;
                    }
                }
            }
            xmlReader.Close();
            reader.Close();
        }
Ejemplo n.º 39
0
        /// <summary>
        /// Load L-System definition file
        /// </summary>
        public void LoadDefinition()
        {
            Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
            dlg.DefaultExt = ".ls"; // Default file extension
            dlg.Filter = "L-System files(*.ls)|*.ls|All files (*.*)|*.*"; // Filter files by extension

            // Show save file dialog box
            bool? result = dlg.ShowDialog();

            // Process save file dialog box results
            if (result == true)
            {
                // Load document
                string filename = dlg.FileName;
                try
                {
                    System.Xml.Serialization.XmlSerializer x = new System.Xml.Serialization.XmlSerializer(_model.GetType());
                    using (System.Xml.XmlReader reader = new System.Xml.XmlTextReader(filename))
                    {
                        if (x.CanDeserialize(reader))
                            _model = x.Deserialize(reader) as SettingsModel;
                        reader.Close();
                    }
                }
                catch
                {
                    System.Windows.MessageBox.Show("Couldn't load L-System, please try again later.", "Error", System.Windows.MessageBoxButton.OK, System.Windows.MessageBoxImage.Error);
                }
            }

            // update all properties
            InvokePropertyChanged(null);
        }
Ejemplo n.º 40
0
        private System.Collections.ArrayList Process_SRU(string xml)
        {
            System.Xml.XmlTextReader rd;
            System.Collections.ArrayList tp = new System.Collections.ArrayList();

            System.Xml.XmlDocument objDoc = new System.Xml.XmlDocument();
            objDoc.XmlResolver = null;
            System.Xml.XmlNamespaceManager Manager = new System.Xml.XmlNamespaceManager(objDoc.NameTable);
            System.Xml.XmlNodeList objNodes;
            string RetrievedRecords = "0";
            System.Collections.ArrayList RecordSet = new System.Collections.ArrayList();

            rd = new System.Xml.XmlTextReader(xml, System.Xml.XmlNodeType.Document, null);
            string RecordPosition = "1";

            while (rd.Read())
            {
                if (rd.NodeType == System.Xml.XmlNodeType.Element)
                {
                    if (rd.Name.IndexOf("numberOfRecords") > -1)
                    {
                        RetrievedRecords = rd.ReadString();
                    }
                    if (rd.Name.IndexOf("recordData") > -1)
                    {
                        RecordSet.Add(rd.ReadInnerXml());
                        //this needs to go somewhere
                    }
                    if (rd.Name.IndexOf("recordPosition") > -1)
                    {
                        RecordPosition = rd.ReadString();
                    }
                }
            }

            rd.Close();

            for (int x = 0; x < RecordSet.Count; x++)
            {
                struct_Records st_recs = new struct_Records();
                st_recs.xml = (string)RecordSet[x];

                Manager.AddNamespace("marc", "http://www.loc.gov/MARC21/slim");
                //try
                //{
                objDoc.LoadXml((string)RecordSet[x]);
                objNodes = objDoc.SelectNodes("marc:record/marc:datafield[@tag='150']", Manager);
                if (objNodes == null)
                {
                    objNodes = objDoc.SelectNodes("record/datafield[@tag='150']", Manager);
                }
                foreach (System.Xml.XmlNode objNode in objNodes)
                {
                    st_recs.xml = objNode.InnerXml;

                    System.Xml.XmlNodeList codes = objNode.SelectNodes("marc:subfield", Manager);
                    if (codes == null)
                    {
                        codes = objNode.SelectNodes("subfield", Manager);
                    }

                    foreach (System.Xml.XmlNode objN in codes)
                    {
                        st_recs.display += objN.InnerText + " -- ";
                        st_recs.main += "$" + objN.Attributes["code"].InnerText + objN.InnerText;
                    }

                    if (st_recs.display != null)
                    {
                        st_recs.display = st_recs.display.TrimEnd(" -".ToCharArray());
                    }
                    else
                    {
                        st_recs.display = "";
                    }

                }

                if (objNodes.Count <= 0)
                {

                    st_recs.main = "Undefined";
                    st_recs.xml = "<undefined>undefined</undefined>";
                }
                //}
                //catch
                //{
                //    return null;
                //}
                tp.Add(st_recs);
            }

            RecordCount = System.Convert.ToInt32(RetrievedRecords);
            return tp;
        }
Ejemplo n.º 41
0
        public static string FeetchTemplate(string tplFile, object[] data)
        {
            if (!File.Exists(tplFile))
                return "";

            if (!Directory.Exists(AppConfig.Path_Temp))
                Directory.CreateDirectory(AppConfig.Path_Temp);

            string dCor = string.Empty;
            for (byte i = 0; i < AppConfig.APP_MoneyDecimals; i++)
                dCor += '0';

            //Set directives
            byte LoAN = 15;
            byte LoAD = 20;
            byte TSpL = 0;
            string PrMk = string.Empty;
            string PrBcMk = string.Empty;
            //Load messages
            Dictionary<string, string> _MSG = new Dictionary<string, string>();
            using (System.Xml.XmlTextReader xmlRd = new System.Xml.XmlTextReader(AppConfig.Path_Templates + "\\" + "Messages.xml"))
            {
                string varName = string.Empty;
                xmlRd.WhitespaceHandling = System.Xml.WhitespaceHandling.None;
                while (xmlRd.Read())
                    if (xmlRd.NodeType == System.Xml.XmlNodeType.Element && xmlRd.Name != null
                        && xmlRd.Name != string.Empty && xmlRd.Name.ToUpper() != "MESSAGES")
                    {
                        varName = xmlRd.Name;
                        xmlRd.Read();
                        _MSG.Add(varName.ToUpper(), xmlRd.Value.TrimStart('\r', '\n').TrimEnd('\r', '\n'));
                    }
                xmlRd.Close();
            }

            // Aligment blocks
            string[][] _alignBlocks = new string[2][];
            string[] _separators = new string[] { "[hex:", "[dec:" };
            _alignBlocks[0] = new string[] { "[right]", "[center]" };
            _alignBlocks[1] = new string[] { "[\\right]", "[\\center]" };
            // Separators

            //Making info values
            object[] infoV = null;
            #region Info values
            //input data
            //0 - chqTable (DataTable)
            //1 - chqNumber (string)
            //2 - retriveCheque (bool)
            //3 - fix (bool)
            //4 - chequeSuma (double)
            //5 - realSuma (double)
            //6 - paymentTypes (List)
            //7 - buyersCash (double)
            //8 - buyersItemCash (List)
            //9 - buyersRest (double)
            //10 - useTotDiscount (bool)
            //11 - discountPercent (double[])
            //12 - discountCash (double[])
            //13 - discConstPercent (double)
            //14 - null
            //15 - discOnlyPercent (double)
            //16 - discOnlyCash (double)
            //17 - discCommonPercent (double)
            //18 - discCommonCash (double)
            //19 - billNumber (string)
            //20 - billComment (string)

            string SiMask = "{0:0." + dCor + ";0." + dCor + ";0." + dCor + "}";
            string DiMask = "{0:0." + dCor + ";0." + dCor + ";!ZeRo!}";
            List<byte> paymentTypes = (List<byte>)data[6];
            List<double> buyersMoney = (List<double>)data[8];

            //Info values (is as type).
            object[] sValues = new object[40];
            //00 - subUnit (byte)
            sValues[00] = AppConfig.APP_SubUnit;//0
            //01 - subUnitName (string)
            sValues[01] = AppConfig.APP_SubUnitName;//1
            //02 - payDesk (byte)
            sValues[02] = AppConfig.APP_PayDesk;//2
            //03 - cashierName (string)
            sValues[03] = UserConfig.UserID;//3
            //04 - currentDateTime (DateTime)
            sValues[04] = DateTime.Now;//4
            //05 - chequeNumber (string)
            sValues[05] = data[1] != null ? data[1] : string.Empty;//5
            //06 - chequeType (bool) fix || !fix
            sValues[06] = data[3] != null && (bool)data[3] ? 1 : 0;//6
            //07 - retirveCheque (bool)
            sValues[07] = data[2] != null && (bool)data[2] ? 1 : 0;//7
            //08 - chequeSuma (double)
            sValues[08] = data[4] != null ? data[4] : 0.0;//8
            //09 - realSuma (double)
            sValues[09] = data[5] != null ? data[5] : 0.0;//9
            //10 - --null-- payment Type [cash] (string)
            sValues[10] = null;//_MSG["PAYMENT_CASH"],//10
            //11 - --null-- payment Type [card] (string)
            sValues[11] = null;//_MSG["PAYMENT_CARD"],//11
            //12 - --null-- payment Type [credit] (string)
            sValues[12] = null;//_MSG["PAYMENT_CREDIT"],//12
            //13 - --null-- payment Type [cheque] (string)
            sValues[13] = null;//_MSG["PAYMENT_CHEQUE"],//13
            //14 - buyers money [cash] (double)
            sValues[14] = (paymentTypes != null && buyersMoney != null && paymentTypes.IndexOf((byte)3) >= 0) ? buyersMoney[paymentTypes.IndexOf((byte)3)] : 0;//14
            //15 - buyers money [card] (double)
            sValues[15] = (paymentTypes != null && buyersMoney != null && paymentTypes.IndexOf((byte)0) >= 0) ? buyersMoney[paymentTypes.IndexOf((byte)0)] : 0;//15
            //16 - buyers money [credit] (double)
            sValues[16] = (paymentTypes != null && buyersMoney != null && paymentTypes.IndexOf((byte)1) >= 0) ? buyersMoney[paymentTypes.IndexOf((byte)1)] : 0;//16
            //17 - buyers money [cheque] (double)
            sValues[17] = (paymentTypes != null && buyersMoney != null && paymentTypes.IndexOf((byte)2) >= 0) ? buyersMoney[paymentTypes.IndexOf((byte)2)] : 0;//17
            //18 - billNumber (string)
            sValues[18] = data[19] != null ? data[19] : string.Empty;//18
            //19 - billComment (string)
            sValues[19] = data[20] != null ? data[20] : string.Empty;//19
            //20 - buyersCash (double)
            sValues[20] = data[7] != null ? data[7] : 0.0;//20
            //21 - buyersRest (double)
            sValues[21] = (paymentTypes != null && buyersMoney != null && buyersMoney.Count == 1 && paymentTypes[0] == 3) ? data[9] : 0;//21
            //22 - useTotDiscount (bool)
            sValues[22] = data[10] != null && (bool)data[10] ? 1 : 0;//22
            //23 - discountPercent (double)
            sValues[23] = data[11] != null && ((double[])data[11])[0] != null ? ((double[])data[11])[0] : 0.0;//23
            //24 - [-discountPercent] (double)
            sValues[24] = data[11] != null && ((double[])data[11])[1] != null ? ((double[])data[11])[1] : 0.0; ;//24
            //25 - discountCash (double)
            sValues[25] = data[12] != null && ((double[])data[12])[0] != null ? ((double[])data[12])[0] : 0.0; ;//25
            //26 - [-discountCash] (double)
            sValues[26] = data[12] != null && ((double[])data[12])[1] != null ? ((double[])data[12])[1] : 0.0; ;//26
            //27 - discountConstPercent (double)
            sValues[27] = data[13] != null ? data[13] : 0.0;//27
            //28 - -
            sValues[28] = null;//28
            //29 - E_discountPercent[] (double)
            sValues[29] = data[15] != null ? data[15] : 0.0;//29
            //30 - E_discountCash[] (double)
            sValues[30] = data[16] != null ? data[16] : 0.0;//30
            //31 - discountCommonPercent (double)
            sValues[31] = data[17] != null ? data[17] : 0.0;//31
            //32 - discountCommonCash (double)
            sValues[32] = data[18] != null ? data[18] : 0.0;//32
            //33 - -
            sValues[33] = null;//33
            //34 - -
            sValues[34] = null;//34
            //35 - true or false to detect bill type
            sValues[35] = (data[19] != null || data[20] != null) ? 1 : 0;//35
            //36 - -
            sValues[36] = null;//36
            //37 - -
            sValues[37] = null;//37
            //38 - -
            sValues[38] = null;//38
            //39 - -
            sValues[39] = null;//39

            infoV = new object[sValues.Length];
            Array.Copy(sValues, infoV, sValues.Length);

            //Info values (type parsed to string (used SiMaks)).
            object[] sStrValues = new object[40];
            //40 - -
            sStrValues[00] = null;//40
            //41 - -
            sStrValues[01] = null;//41
            //42 - -
            sStrValues[02] = null;//42
            //43 - -
            sStrValues[03] = null;//43
            //44 - -
            sStrValues[04] = null;//44
            //45 - -
            sStrValues[05] = null;//45
            //46 - -
            sStrValues[06] = null;//46
            //47 - -
            sStrValues[07] = null;//47
            //48 - chequeSuma (double)
            sStrValues[08] = string.Format(SiMask, sValues[8]);//48 - chequeSuma
            //49 - realSuma (double)
            sStrValues[09] = string.Format(SiMask, sValues[9]);//49 - realSuma
            //50 - -
            sStrValues[10] = null;//_MSG["PAYMENT_CASH"];//50
            //51 - -
            sStrValues[11] = null;//_MSG["PAYMENT_CARD"];//51
            //52 - -
            sStrValues[12] = null;//_MSG["PAYMENT_CREDIT"];//52
            //53 - -
            sStrValues[13] = null;//_MSG["PAYMENT_CHEQUE"];//53
            //54 - buyers money [cash] (double)
            sStrValues[14] = string.Format(SiMask, (paymentTypes != null && buyersMoney != null && paymentTypes.IndexOf((byte)3) >= 0) ? buyersMoney[paymentTypes.IndexOf((byte)3)] : 0);//54
            //55 - buyers money [card] (double)
            sStrValues[15] = string.Format(SiMask, (paymentTypes != null && buyersMoney != null && paymentTypes.IndexOf((byte)0) >= 0) ? buyersMoney[paymentTypes.IndexOf((byte)0)] : 0);//55
            //56 - buyers money [credit] (double)
            sStrValues[16] = string.Format(SiMask, (paymentTypes != null && buyersMoney != null && paymentTypes.IndexOf((byte)1) >= 0) ? buyersMoney[paymentTypes.IndexOf((byte)1)] : 0);//56
            //57 - buyers money [cheque] (double)
            sStrValues[17] = string.Format(SiMask, (paymentTypes != null && buyersMoney != null && paymentTypes.IndexOf((byte)2) >= 0) ? buyersMoney[paymentTypes.IndexOf((byte)2)] : 0);//57
            //58 - -
            sStrValues[18] = null;//58
            //59 - -
            sStrValues[19] = null;//59
            //60 - buyersCash (double)
            sStrValues[20] = string.Format(SiMask, sValues[20]);//60 -
            //61 - buyersRest (double)
            sStrValues[21] = string.Format(SiMask, (paymentTypes != null && buyersMoney != null && buyersMoney.Count == 1 && paymentTypes[0] == 3) ? data[9] : 0);//61 -
            //62 - -
            sStrValues[22] = null;//62
            //63 - discountPercent (double)
            sStrValues[23] = string.Format(SiMask, sValues[23]);//63 -
            //64 - [-discountPercent] (double)
            sStrValues[24] = string.Format(SiMask, sValues[24]);//64 -
            //65 - discountCash (double)
            sStrValues[25] = string.Format(SiMask, sValues[25]);//65 -
            //66 - [-discountCash] (double)
            sStrValues[26] = string.Format(SiMask, sValues[26]);//66 -
            //67 - discountConstPercent (double)
            sStrValues[27] = string.Format(SiMask, data[13]);//67 -
            //68 - -
            sStrValues[28] = null;//68
            //69 - E_discountPercent[] (double)
            sStrValues[29] = string.Format(SiMask, data[15]);//69 -
            //70 - E_discountCash[] (double)
            sStrValues[30] = string.Format(SiMask, data[16]);//70 -
            //71 - discountCommonPercent (double)
            sStrValues[31] = string.Format(SiMask, data[17]);//71 -
            //72 - discountCommonCash (double)
            sStrValues[32] = string.Format(SiMask, data[18]);//72 -
            //73 - -
            sStrValues[33] = null;//73 -
            //74 - -
            sStrValues[34] = null;//74 -
            //75 - -
            sStrValues[35] = null;//75 -
            //76 - -
            sStrValues[36] = null;//76 -
            //77 - -
            sStrValues[37] = null;//77 -
            //78 - -
            sStrValues[38] = null;//78 -
            //79 - -
            sStrValues[39] = null;//79 -

            Array.Resize<object>(ref infoV, infoV.Length + sStrValues.Length);
            Array.Copy(sStrValues, 0, infoV, infoV.Length - sStrValues.Length, sStrValues.Length);

            //Info values (type parsed to string (used DiMaks)).
            object[] sDynStrValues = new object[40];
            //80 - -
            sDynStrValues[00] = null;//80
            //81 - -
            sDynStrValues[01] = null;//81
            //82 - -
            sDynStrValues[02] = null;//82
            //83 - -
            sDynStrValues[03] = null;//83
            //84 - -
            sDynStrValues[04] = null;//84
            //85 - -
            sDynStrValues[05] = null;//85
            //86 - -
            sDynStrValues[06] = null;//86
            //87 - -
            sDynStrValues[07] = null;//87
            //88 - chequeSuma (double)
            sDynStrValues[08] = null;//88 - chequeSuma (double)
            //89 - realSuma (double)
            sDynStrValues[09] = null;//89 - realSuma (double)
            //90 - -
            sDynStrValues[10] = null;//_MSG["PAYMENT_CASH"];//90
            //91 - -
            sDynStrValues[11] = null;//_MSG["PAYMENT_CARD"];//91
            //92 - -
            sDynStrValues[12] = null;//_MSG["PAYMENT_CREDIT"];//92
            //93 - -
            sDynStrValues[13] = null;//_MSG["PAYMENT_CHEQUE"];//93
            //94 - buyers money [cash] (double)
            sDynStrValues[14] = string.Format(DiMask, (paymentTypes != null && buyersMoney != null && paymentTypes.IndexOf((byte)3) >= 0) ? buyersMoney[paymentTypes.IndexOf((byte)3)] : 0);//94
            //95 - buyers money [card] (double)
            sDynStrValues[15] = string.Format(DiMask, (paymentTypes != null && buyersMoney != null && paymentTypes.IndexOf((byte)0) >= 0) ? buyersMoney[paymentTypes.IndexOf((byte)0)] : 0);//95
            //96 - buyers money [credit] (double)
            sDynStrValues[16] = string.Format(DiMask, (paymentTypes != null && buyersMoney != null && paymentTypes.IndexOf((byte)1) >= 0) ? buyersMoney[paymentTypes.IndexOf((byte)1)] : 0);//96
            //97 - buyers money [cheque] (double)
            sDynStrValues[17] = string.Format(DiMask, (paymentTypes != null && buyersMoney != null && paymentTypes.IndexOf((byte)2) >= 0) ? buyersMoney[paymentTypes.IndexOf((byte)2)] : 0);//97
            //98 - billNumber (string)
            sDynStrValues[18] = data[19] != null && data[19].ToString() == string.Empty ? "!ZeRo!" : data[19];//98
            //99 - billComment (string)
            sDynStrValues[19] = data[20] != null && data[20].ToString() == string.Empty ? "!ZeRo!" : data[20];//99
            //100 - buyersCash (double)
            sDynStrValues[20] = null;//100 -
            //101 - buyersRest (double)
            sDynStrValues[21] = string.Format(DiMask, (paymentTypes != null && buyersMoney != null && buyersMoney.Count == 1 && paymentTypes[0] == 3) ? data[9] : 0);//101 -
            //102 - -
            sDynStrValues[22] = null;//102
            //103 - discountPercent (double)
            sDynStrValues[23] = string.Format(DiMask, sValues[23]);//103 -
            //104 - [-discountPercent] (double)
            sDynStrValues[24] = string.Format(DiMask, sValues[24]);//104 -
            //105 - discountCash (double)
            sDynStrValues[25] = string.Format(DiMask, sValues[25]);//105 -
            //106 - [-discountCash] (double)
            sDynStrValues[26] = string.Format(DiMask, sValues[26]);//106 -
            //107 - discountConstPercent (double)
            sDynStrValues[27] = string.Format(DiMask, data[13]);//107 -
            //108 - -
            sDynStrValues[28] = null;//108
            //109 - E_discountPercent[] (double)
            sDynStrValues[29] = string.Format(DiMask, data[15]);//109 -
            //110 - E_discountCash[] (double)
            sDynStrValues[30] = string.Format(DiMask, data[16]);//110 -
            //111 - discountCommonPercent (double)
            sDynStrValues[31] = string.Format(DiMask, data[17]);//111 -
            //112 - discountCommonCash (double)
            sDynStrValues[32] = string.Format(DiMask, data[18]);//112 -
            //113 - -
            sDynStrValues[33] = null;//113 -
            //114 - -
            sDynStrValues[34] = null;//114 -
            //115 - -
            sDynStrValues[35] = null;//115 -
            //116 - -
            sDynStrValues[36] = null;//116 -
            //117 - -
            sDynStrValues[37] = null;//117 -
            //118 - -
            sDynStrValues[38] = null;//118 -
            //119 - -
            sDynStrValues[39] = null;//119 -

            Array.Resize<object>(ref infoV, infoV.Length + sDynStrValues.Length);
            Array.Copy(sDynStrValues, 0, infoV, infoV.Length - sDynStrValues.Length, sDynStrValues.Length);

            #endregion

            // additional data (delete bill's rows)

            //Creating output file
            string chqTxtName = string.Format("{0:X2}{1:X2}_{2:yyMMdd}_{2:HHmmss.fff}.txt", AppConfig.APP_SubUnit, AppConfig.APP_PayDesk, DateTime.Now);
            StreamWriter streamWr = new StreamWriter(AppConfig.Path_Temp + "\\" + chqTxtName, false, Encoding.Default);
            chqTxtName = AppConfig.Path_Temp + "\\" + chqTxtName;

            //Load template
            StreamReader streamRd = File.OpenText(tplFile);

            //Fill data by loaded template
            string template = string.Empty;
            while ((template = streamRd.ReadLine()) != null)
            {
                if (template == string.Empty)
                    template = " ";

                template = template.Replace("\\r", "\r");
                template = template.Replace("\\n", "\n");
                template = template.Replace("\\t", "\t");
                template = template.Replace("\\v", "\v");
                template = template.Replace("\\b", "\b");

                switch (template[0])
                {
                    #region Info values [S]
                    case 'S':
                        {
                            template = template.Remove(0, 1);
                            template = string.Format(template, infoV);

                            if (!template.Contains("!ZeRo!"))
                            {
                                template = GetHEX(template, _separators);
                                streamWr.WriteLine(template);
                            }
                            break;
                        }
                    #endregion
                    #region Articles [W]
                    case 'W':
                        {
                            //Output Format [W]
                            //00 - articleName (string)
                            //01 - articleDecription (string)
                            //02 - articleUnit (string)
                            //03 - articleTaxChar (char)
                            //04 - articlePrice (double)
                            //05 - articleDose (double)
                            //06 - articleTaxValue (double)
                            //07 - articleDiscount (double)
                            //08 - articleSuma (doulble)
                            //09 - articleActualSum (double)
                            //10 - articleTaxMoney (double)
                            //11 - articleCashDiscount (double)
                            //12 - articleDoseDiff (double)

                            //static values parsed as string [Program decimal correction]
                            //20 - articlePrice (double)
                            //21 - articleDose (double)
                            //22 - articleTaxValue (double)
                            //23 - articleDiscount (double)
                            //24 - articleSuma (double)
                            //25 - articleActualSum (double)
                            //26 - articleTaxMoney (double)
                            //27 - articleCashDiscount (double)
                            //28 - articleDoseDiff (double)

                            string articleTemplate = template.Remove(0, 1);
                            string art_name = "";
                            string art_desc = "";
                            double quantityDiff = 0.0;
                            bool printThisRecord = true;
                            DataRow dRow = ((DataTable)data[0]).NewRow();
                            for (int i = 0; i < ((DataTable)data[0]).Rows.Count; i++)
                            {
                                dRow.ItemArray = ((DataTable)data[0]).Rows[i].ItemArray;

                                // checking PrMk and PrBcMk
                                // Product Id Mask and Product Barcode Mask
                                // if some one is empty it will be ignored.
                                if (PrMk.Length != 0 || PrBcMk.Length != 0)
                                {
                                    printThisRecord = false;

                                    if (PrMk.Length != 0 &&
                                        PrBcMk.Length != 0 &&
                                        dRow["ID"].ToString().StartsWith(PrMk) &&
                                        dRow["BC"].ToString().StartsWith(PrBcMk))
                                        printThisRecord = true;

                                    if (PrMk.Length != 0 && dRow["ID"].ToString().StartsWith(PrMk))
                                        printThisRecord = true;

                                    if (PrBcMk.Length != 0 && dRow["BC"].ToString().StartsWith(PrBcMk))
                                        printThisRecord = true;
                                }

                                if (!printThisRecord)
                                    continue;

                                art_name = ((DataTable)data[0]).Rows[i]["NAME"].ToString();
                                art_desc = ((DataTable)data[0]).Rows[i]["DESC"].ToString();

                                if (art_name.Length > LoAN)
                                    art_name = art_name.Substring(0, LoAN);

                                if (art_desc.Length > LoAD)
                                    art_desc = art_desc.Substring(0, LoAD);

                                quantityDiff = CoreLib.GetRoundedDose(CoreLib.GetDouble(((System.Data.DataTable)data[0]).Rows[i]["TOT"]) - (double)((System.Data.DataTable)data[0]).Rows[i]["PRINTCOUNT"]);

                                try
                                {
                                    template = string.Format(articleTemplate,
                                        //0
                                        art_name,
                                        art_desc,
                                        ((DataTable)data[0]).Rows[i]["UNIT"],
                                        ((DataTable)data[0]).Rows[i]["VG"],
                                        ((DataTable)data[0]).Rows[i]["PRICE"],
                                        ((DataTable)data[0]).Rows[i]["TOT"],
                                        ((DataTable)data[0]).Rows[i]["TAX_VAL"],
                                        data[10] != null && (bool)data[10] ? 0 : (double)((DataTable)data[0]).Rows[i]["DISC"] / 100,
                                        ((DataTable)data[0]).Rows[i]["SUM"],
                                        ((DataTable)data[0]).Rows[i]["ASUM"],
                                        //10
                                        ((DataTable)data[0]).Rows[i]["TAX_MONEY"],
                                        CoreLib.GetRoundedMoney((double)((System.Data.DataTable)data[0]).Rows[i]["SUM"] - (double)((System.Data.DataTable)data[0]).Rows[i]["ASUM"]),//11
                                        quantityDiff,//12
                                        (quantityDiff > 0) ? 1 : (quantityDiff == 0 ? 0 : -1),//13
                                        null,//14
                                        null,//15
                                        null,//16
                                        null,//17
                                        null,//18
                                        null,//19
                                        string.Format("{0:F" + AppConfig.APP_MoneyDecimals + "}", ((DataTable)data[0]).Rows[i]["PRICE"]),
                                        string.Format("{0:F" + AppConfig.APP_DoseDecimals + "}", ((DataTable)data[0]).Rows[i]["TOT"]),
                                        string.Format("{0:F" + AppConfig.APP_MoneyDecimals + "}", ((DataTable)data[0]).Rows[i]["TAX_VAL"]),
                                        data[10] != null && (bool)data[10] ? "" : string.Format("{0:-0." + dCor + "%;+0." + dCor + "%;0." + dCor + "%}", (double)((DataTable)data[0]).Rows[i]["DISC"] / 100),
                                        string.Format("{0:F" + AppConfig.APP_MoneyDecimals + "}", ((DataTable)data[0]).Rows[i]["SUM"]),
                                        string.Format("{0:F" + AppConfig.APP_MoneyDecimals + "}", ((DataTable)data[0]).Rows[i]["ASUM"]),
                                        string.Format("{0:F" + AppConfig.APP_MoneyDecimals + "}", ((DataTable)data[0]).Rows[i]["TAX_MONEY"]),
                                        string.Format("{0:F" + AppConfig.APP_MoneyDecimals + "}", CoreLib.GetRoundedMoney((double)((System.Data.DataTable)data[0]).Rows[i]["SUM"] - (double)((System.Data.DataTable)data[0]).Rows[i]["ASUM"])),
                                        string.Format("{0:F" + AppConfig.APP_DoseDecimals + "}", CoreLib.GetRoundedDose(CoreLib.GetDouble(((System.Data.DataTable)data[0]).Rows[i]["TOT"]) - (double)((System.Data.DataTable)data[0]).Rows[i]["PRINTCOUNT"]))
                                    );
                                }
                                catch (Exception ex) { CoreLib.WriteLog(ex, "FeetchTemplate(); at Generating row template for article."); }

                                if (!template.Contains("!ZeRo!"))
                                {
                                    if (i == 0)
                                        template = template.TrimStart(new char[] { '\n', '\r' });
                                    if (i + 1 == ((DataTable)data[0]).Rows.Count)
                                        template = template.TrimEnd(new char[] { '\n', '\r' });

                                    template = GetHEX(template, _separators);
                                    streamWr.WriteLine(template);
                                }
                            }

                            break;
                        }
                    #endregion
                    #region Deleted Rows [D]
                    case 'D':
                        {
                            string articleTemplate = template.Remove(0, 1);
                            try
                            {
                                Dictionary<string, object[]> deletedRows = (Dictionary<string, object[]>)DataWorkShared.ExtractBillProperty(((DataTable)data[0]), mdcore.Common.CoreConst.DELETED_ROWS);
                                int i = 0;
                                string art_name = string.Empty;
                                string art_desc = string.Empty;
                                DataRow dRow = ((DataTable)data[0]).NewRow();
                                bool printThisRecord = true;
                                foreach (KeyValuePair<string, object[]> deletedRecord in deletedRows)
                                {
                                    printThisRecord = true;

                                    try
                                    {
                                        dRow.ItemArray = deletedRecord.Value;

                                        // checking PrMk and PrBcMk
                                        // Product Id Mask and Product Barcode Mask
                                        // if some one is empty it will be ignored.
                                        if (PrMk.Length != 0 || PrBcMk.Length != 0)
                                        {
                                            printThisRecord = false;

                                            if (PrMk.Length != 0 &&
                                                PrBcMk.Length != 0 &&
                                                dRow["ID"].ToString().StartsWith(PrMk) &&
                                                dRow["BC"].ToString().StartsWith(PrBcMk))
                                                printThisRecord = true;

                                            if (PrMk.Length != 0 && dRow["ID"].ToString().StartsWith(PrMk))
                                                printThisRecord = true;

                                            if (PrBcMk.Length != 0 && dRow["BC"].ToString().StartsWith(PrBcMk))
                                                printThisRecord = true;
                                        }

                                        if (!printThisRecord)
                                            continue;

                                        art_name = dRow["NAME"].ToString();
                                        art_desc = dRow["DESC"].ToString();

                                        if (art_name.Length > LoAN)
                                            dRow["NAME"] = art_name.Substring(0, LoAN);

                                        if (art_desc.Length > LoAD)
                                            dRow["DESC"] = art_desc.Substring(0, LoAD);

                                        template = string.Format(articleTemplate, dRow.ItemArray);

                                        if (!template.Contains("!ZeRo!"))
                                        {
                                            if (i == 0)
                                                template = template.TrimStart(new char[] { '\n', '\r' });
                                            if (i + 1 == ((DataTable)data[0]).Rows.Count)
                                                template = template.TrimEnd(new char[] { '\n', '\r' });

                                            template = GetHEX(template, _separators);
                                            streamWr.WriteLine(template);
                                        }
                                        i++;
                                    }
                                    catch (Exception ex) { }
                                }// foreach
                            }
                            catch (Exception ex) { }
                            break;
                        }
                    #endregion
                    #region Directives [#]
                    case '#':
                        {
                            //Template variables
                            //LoAN - Limit of Article Name (byte)
                            //LoAD - Limit of Article Description (byte)
                            //TSpL - Total Symbols per Line (byte)

                            template = template.Remove(0, 1);
                            object[] var = template.Split('=');

                            try
                            {
                                switch (var[0].ToString())
                                {
                                    case "LoAN": LoAN = byte.Parse(var[1].ToString()); break;
                                    case "LoAD": LoAD = byte.Parse(var[1].ToString()); break;
                                    case "TSpL": TSpL = byte.Parse(var[1].ToString()); break;
                                    case "PrMk": PrMk = var[1].ToString(); break;
                                    case "PrBcMk": PrBcMk = var[1].ToString(); break;
                                }
                            }
                            catch { }

                            break;
                        }
                    #endregion
                    #region Messages [M]
                    case 'M':
                        {
                            template = template.Remove(0, 1).ToUpper();
                            string[] keys = new string[_MSG.Keys.Count];
                            string[] blocks = new string[0];
                            string newLine = string.Empty;
                            string cuttedLine = string.Empty;
                            int startIndex = 0;
                            int length = 0;
                            int i = 0;
                            int j = 0;

                            _MSG.Keys.CopyTo(keys, 0);

                            try
                            {
                                for (i = 0; i < _MSG.Keys.Count; i++)
                                    template = template.Replace(keys[i], _MSG[keys[i]]);
                            }
                            catch { }

                            //Aligment
                            for (i = 0; i < _alignBlocks[0].Length; i++)
                            {
                                while (template.Contains(_alignBlocks[0][i]) && template.Contains(_alignBlocks[1][i]))
                                {
                                    startIndex = template.IndexOf(_alignBlocks[0][i]) + _alignBlocks[0][i].Length;
                                    length = template.IndexOf(_alignBlocks[1][i]) - startIndex;

                                    newLine = cuttedLine = template.Substring(startIndex, length);
                                    blocks = newLine.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
                                    newLine = string.Empty;
                                    for (j = 0; j < blocks.Length; j++)
                                    {
                                        blocks[j] = blocks[j].Trim();
                                        switch (_alignBlocks[0][i])
                                        {
                                            case "[center]":
                                                if (blocks[j].Length % 2 == 0)
                                                    length = (TSpL - blocks[j].Length) / 2 + blocks[j].Length;
                                                else
                                                    length = (TSpL - (blocks[j].Length - 1)) / 2 + blocks[j].Length;
                                                break;
                                            case "[right]":
                                                length = TSpL;
                                                break;
                                        }
                                        blocks[j] = blocks[j].PadLeft(length);
                                        newLine += blocks[j];
                                        if (j + 1 < blocks.Length)
                                            newLine += "\r\n";
                                    }
                                    cuttedLine = _alignBlocks[0][i] + cuttedLine + _alignBlocks[1][i];
                                    template = template.Replace(cuttedLine, newLine);
                                }

                                //remove first single aligment's block
                                if (template.Contains(_alignBlocks[0][i]) && !template.Contains(_alignBlocks[1][i]))
                                    template = template.Replace(_alignBlocks[0][i], "");

                                //remove end single aligment's block
                                if (!template.Contains(_alignBlocks[0][i]) && template.Contains(_alignBlocks[1][i]))
                                    template = template.Replace(_alignBlocks[1][i], "");
                            }

                            template = template.Replace("\\r", "\r");
                            template = template.Replace("\\n", "\n");
                            template = GetHEX(template, _separators);
                            streamWr.WriteLine(template);

                            break;
                        }
                    #endregion
                    #region Comment [;]
                    case ';':
                        {
                            break;
                        }
                    #endregion
                    default:
                        {
                            template = GetHEX(template, _separators);
                            streamWr.WriteLine(template);
                            break;
                        }
                }
            }

            //End fill data
            streamWr.Close();
            streamWr.Dispose();
            streamRd.Close();
            streamRd.Dispose();

            //Path for txt file.
            return chqTxtName;
        }
Ejemplo n.º 42
0
        //Deze functie importeert een '.xml' bestandje die database gegevens heeft.
        private void gegevensImporterenToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                //Open een dialog om een bestand te kiezen voor het importeren
                OpenFileDialog fileDialog = new OpenFileDialog();
                fileDialog.Title = "Selecteer een bestand om te importeren";
                fileDialog.Filter = "Database gegevens|*.xml";

                //als er op OK geklikt wordt in het dialog dan gaan we wat doen
                if (fileDialog.ShowDialog() == DialogResult.OK)
                {
                    //open een FileStream op het bestand en een XMLTextReader
                    FileStream myFileStream = new FileStream(fileDialog.FileName, FileMode.Open);
                    System.Xml.XmlTextReader myXmlReader = new System.Xml.XmlTextReader(myFileStream);

                    //leeg de bestaande dataset
                    databaseDataSet.Clear();
                    //lees vervolgens het XML bestandje in het dataset
                    databaseDataSet.ReadXml(myXmlReader);
                    myXmlReader.Close();

                    //update de database
                    updateDatabase();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
Ejemplo n.º 43
0
        private string VerifyAdwaysAccount(string CustomerID, string AdwaysID, string AdwaysEmail)
        {
            try
            {
                string url = "http://club.pchome.net/union/icson/checkHashCode.php?code=" + txtPPCode.Text.Trim();
                System.Net.WebClient wc = new System.Net.WebClient();
                System.IO.Stream stream = wc.OpenRead(url);
                System.Xml.XmlReader xmlread = new System.Xml.XmlTextReader(stream);

                string ppResult = stream.ToString();

                stream.Close();
                wc.Dispose();

                while (xmlread.Read())
                {
                    if (xmlread.Name.ToUpper().Equals("RESULT"))
                    {
                        break;
                    }
                }

                string result = xmlread.GetAttribute(0).ToString();
                xmlread.Close();
                return result;
            }
            catch
            {
                return "-1";
            }
        }
Ejemplo n.º 44
0
        //=======================================================================
        // Sub/Function: identify
        // Description: Use this function to return the identifier information
        // from an OAI repository.
        //
        // example:
        // OAI objOAI = new OAI("http://memory.loc.gov/cgi-bin/oai2_0");
        // Identify objID = new Identify();
        //
        // objID = objOAI.identify();
        // Console.WriteLine("Base URL: " + objID.baseURL);
        // Console.WriteLine("Repository: " + objID.repositoryName);
        // Console.WriteLine("Deleted Records: "  + objID.deletedRecord);
        //=======================================================================
        public Identify identify()
        {
            System.IO.Stream objStream;
            Identify objID = new Identify();
            System.Net.HttpWebRequest wr;
            System.Xml.XmlTextReader rd;

            try
            {
                prequestURL = baseURL + "?verb=Identify";
                wr = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(prequestURL);
                wr.UserAgent = cUserAgent;
                System.Net.WebResponse response = wr.GetResponse();
                objStream = response.GetResponseStream();
                System.IO.StreamReader reader = new System.IO.StreamReader(objStream);
                prawXML = reader.ReadToEnd();
                reader.Close();
                rd = new System.Xml.XmlTextReader(prawXML, System.Xml.XmlNodeType.Document, null);
            }
            catch (Exception e)
            {
                error.errorName = e.ToString();
                error.errorDescription = e.Message + "\n<br>Unable to connect to " + baseURL;
                return null;
            }

            while (rd.Read())
            {
                if (rd.NodeType == System.Xml.XmlNodeType.Element)
                {
                    if (rd.Name == "responseDate")
                    {
                        presponseDate = rd.ReadString();
                    }
                    else if (rd.Name == "Identify")
                    {
                        while (rd.Read() && rd.NodeType != System.Xml.XmlNodeType.EndElement)
                        {
                            switch (rd.Name)
                            {
                                case "repositoryName":
                                    objID.repositoryName = ParseOAI(ref rd, "repositoryName");
                                    break;
                                case "baseURL":
                                    objID.baseURL = ParseOAI(ref rd, "baseURL");
                                    break;
                                case "protocolVersion":
                                    objID.protocolVersion = ParseOAI(ref rd, "protocolVersion");
                                    break;
                                case "earliestDatestamp":
                                    objID.earliestDatestamp = ParseOAI(ref rd, "earliestDatestamp");
                                    break;
                                case "deletedRecord":
                                    objID.deletedRecord = ParseOAI(ref rd, "deletedRecord");
                                    break;
                                case "granularity":
                                    objID.granularity = ParseOAI(ref rd, "granularity");
                                    break;
                                case "adminEmail":
                                    objID.adminEmail.Add(ParseOAI(ref rd, "adminEmail"));
                                    break;
                                case "compression":
                                    objID.compression.Add(ParseOAI(ref rd, "compression"));
                                    break;
                                case "description":
                                    objID.description.Add(ParseOAIContainer(ref rd, "description"));
                                    break;
                            }
                        }
                    }
                    else if (rd.Name == "error")
                    {
                        error.errorName = rd.GetAttribute("code");
                        error.errorDescription = rd.ReadString();
                        return null;
                    }
                }
            }

            rd.Close();

            return objID;
        }
Ejemplo n.º 45
0
        public ListSet ListSets(ResumptionToken objToken, ref Object objHandler)
        {
            System.IO.Stream objStream;
            OAI_LIST objRecord;
            ListSet objList = new ListSet();
            ResumptionToken myToken;
            string tmp = "";
            System.Net.HttpWebRequest wr;
            System.Xml.XmlTextReader rd;

            if (objToken == null)
            {
                prequestURL = baseURL + "?verb=ListSets";
            }
            else
            {
                prequestURL = baseURL + "?verb=ListSets&resumptionToken=" + objToken.resumptionToken;
                //This is where we handle the resumptionToken
            }
            //======================================================
            // If you wanted to support additional metadata formats,
            // you would just need to have additional handlers.
            //======================================================

            try
            {
                wr = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(prequestURL);
                wr.UserAgent = cUserAgent;
                System.Net.WebResponse response = wr.GetResponse();
                objStream = response.GetResponseStream();
                System.IO.StreamReader reader = new System.IO.StreamReader(objStream);
                prawXML = reader.ReadToEnd();
                reader.Close();
                rd = new System.Xml.XmlTextReader(prawXML, System.Xml.XmlNodeType.Document, null);
            }
            catch (Exception e)
            {
                error.errorName = e.ToString();
                error.errorDescription = e.Message + "\n<br>Unable to connect to " + baseURL;
                return null;
            }

            while (rd.Read())
            {
                if (rd.NodeType == System.Xml.XmlNodeType.Element)
                {
                    if (rd.Name == "responseDate")
                    {
                        presponseDate = rd.ReadString();
                    }
                    else if (rd.Name == "ListSets")
                    {
                        //while (rd.Read())
                        do
                        {
                            if (rd.Name == "set")
                            {
                                objRecord = new OAI_LIST(rd.ReadInnerXml(), ref objHandler);
                                objList.listset.Add(objRecord);
                                //return objRecord;
                            }
                            else if (rd.Name == "resumptionToken")
                            {
                                tmp = rd.ReadOuterXml();
                                myToken = new ResumptionToken(tmp);
                                objList.token = myToken;
                            }
                            else rd.Read(); // Added the Read() and will never occur with the ReadInnerXml()

                        } while (rd.Name != "ListSets"); // loop
                    }
                    else if (rd.Name == "error")
                    {
                        error.errorName = rd.GetAttribute("code");
                        error.errorDescription = rd.ReadString();
                        return null;
                    }
                }
            }

            rd.Close();
            return objList;
        }
Ejemplo n.º 46
0
        public static string Get_Definephrase(string tag)
        {
            try
            {
                string ffile = "/cmm/xhtml/Definephrase.xml";
                string fpath = HttpContext.Current.Server.MapPath(ffile);
                if (!System.IO.File.Exists(fpath)) return "";

                string vlreturn = "";
                System.Xml.XmlTextReader rdr = new System.Xml.XmlTextReader(fpath);
                while (rdr.Read())
                {
                    switch (rdr.NodeType)
                    {
                        case System.Xml.XmlNodeType.Element:
                            if (rdr.Name == LANG + tag)
                            {
                                vlreturn = rdr.ReadElementString();
                                goto lexit;
                            }
                            else if (rdr.Name != "phrase")
                                rdr.Skip();
                            break;
                        default:
                            break;
                    }
                }
            lexit:
                rdr.Close();
                return vlreturn;
            }
            catch
            {
                return "Cannot get phrase";
            }
        }
Ejemplo n.º 47
0
        /// <summary>
        /// Load embedded example
        /// </summary>
        /// <param name="name">Example file name</param>
        public void LoadExample(string name)
        {
            try
            {
                System.Xml.Serialization.XmlSerializer x = new System.Xml.Serialization.XmlSerializer(_model.GetType());
                using (System.Xml.XmlReader reader = new System.Xml.XmlTextReader(System.Windows.Application.GetResourceStream(new System.Uri("/examples/" + name, UriKind.Relative)).Stream))
                {
                    if (x.CanDeserialize(reader))
                        _model = x.Deserialize(reader) as SettingsModel;
                    reader.Close();
                }

                // update all properties
                InvokePropertyChanged(null);
            }
            catch
            {
                System.Windows.MessageBox.Show("Couldn't load L-System, please try again later.", "Error", System.Windows.MessageBoxButton.OK, System.Windows.MessageBoxImage.Error);
            }
        }
        public static void Read_Configuration_File( string config_file )
        {
            if (!File.Exists(config_file))
                return;

            System.IO.StreamReader reader = new System.IO.StreamReader(config_file);
            System.Xml.XmlTextReader xmlReader = new System.Xml.XmlTextReader(reader);
            while (xmlReader.Read())
            {
                if (xmlReader.NodeType == System.Xml.XmlNodeType.Element)
                {
                    string node_name = xmlReader.Name.ToLower();
                    switch (node_name)
                    {
                        case "connection_string":
                            if (xmlReader.MoveToAttribute("type"))
                            {
                                if (xmlReader.Value.ToString().ToLower() == "postgresql")
                                    sobekDatabaseType = SobekCM_Database_Type_Enum.PostgreSQL;

                            }
                            xmlReader.Read();
                            Database_Connection_String = xmlReader.Value;
                            break;

                        case "error_emails":
                            xmlReader.Read();
                            systemErrorEmail = xmlReader.Value;
                            break;

                        case "error_page":
                            xmlReader.Read();
                            System_Error_URL = xmlReader.Value;
                            break;

                        case "ghostscript_executable":
                            xmlReader.Read();
                            ghostscriptExecutable = xmlReader.Value;
                            break;

                        case "imagemagick_executable":
                            xmlReader.Read();
                            imageMagickExecutable = xmlReader.Value;
                            break;
                    }
                }
            }

            xmlReader.Close();
            reader.Close();
        }
Ejemplo n.º 49
0
        // Lecture de la configuration
        static void ReadConfig()
        {
            string config_file = "config.xml";
            if (!System.IO.File.Exists(config_file))
            {
                var newconf = new System.Xml.XmlTextWriter(config_file, null);
                newconf.WriteStartDocument();
                newconf.WriteStartElement("config");
                newconf.WriteElementString("last_update", "0");
                newconf.WriteElementString("auth_token", "");
                newconf.WriteEndElement();
                newconf.WriteEndDocument();
                newconf.Close();
            }

            var conf = new System.Xml.XmlTextReader(config_file);
            string CurrentElement = "";
            while (conf.Read())
            {
                switch(conf.NodeType) {
                    case System.Xml.XmlNodeType.Element:
                        CurrentElement = conf.Name;
                        break;
                    case System.Xml.XmlNodeType.Text:
                    if (CurrentElement == "last_update")
                        LastUpdate = DateTime.Parse(conf.Value);
                    if (CurrentElement == "auth_token")
                        AuthToken = conf.Value;
                        break;
                }
            }
            conf.Close();

            // On vérifie que le token est encore valide
            if (AuthToken.Length > 0)
            {
                var flickr = new Flickr(Program.ApiKey, Program.SharedSecret);
                try
                {
                    Auth auth = flickr.AuthCheckToken(AuthToken);
                    Username = auth.User.UserName;
                }
                catch (FlickrApiException ex)
                {
                    //MessageBox.Show(ex.Message, "Authentification requise",
                    //    MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                    AuthToken = "";
                }
            }
        }
Ejemplo n.º 50
0
		public void ProcessRequest( HttpContext context )
		{
			 if (!SiteSecurity.IsValidContributor()) 
			{
				context.Response.Redirect("~/FormatPage.aspx?path=SiteConfig/accessdenied.format.html");
			}

			SiteConfig siteConfig = SiteConfig.GetSiteConfig();

			string entryId = "";
			string author = "";
			string title = "";
			string textToSave = "";
			string redirectUrl = SiteUtilities.GetStartPageUrl();


			System.Xml.XmlTextReader xtr = new System.Xml.XmlTextReader(context.Request.InputStream);
			try
			{
				while (!xtr.EOF)
				{
					xtr.Read();
					if (xtr.Name=="entryid")
					{
						entryId = xtr.ReadInnerXml();
					}
					if (xtr.Name=="author")
					{
						author = xtr.ReadInnerXml();
					}
					if (xtr.Name=="title" && xtr.NodeType == System.Xml.XmlNodeType.Element)
					{
						// Ensure this is the start element before moving forward to the CDATA.
						xtr.Read();  // Brings us to the CDATA inside "title"
						title = xtr.Value;
					}
					if (xtr.Name=="posttext" && xtr.NodeType == System.Xml.XmlNodeType.Element)
					{
						xtr.Read();
						textToSave = xtr.Value;
					}
				}
			}
			finally
			{
				xtr.Close();
			}


			// make sure the entry param is there
			if (entryId == null || entryId.Length == 0) 
			{
				context.Response.Redirect(SiteUtilities.GetStartPageUrl(siteConfig));
				return;
			}
			else
			{
				ILoggingDataService logService = LoggingDataServiceFactory.GetService(SiteConfig.GetLogPathFromCurrentContext());
				IBlogDataService dataService = BlogDataServiceFactory.GetService(SiteConfig.GetContentPathFromCurrentContext(), logService );
			
				// First, attempt to get the entry.  If the entry exists, then get it for editing 
				// and save.  If not, create a brand new entry and save it instead.
				Entry entry = dataService.GetEntry(entryId);
				if ( entry != null )
				{
					entry = dataService.GetEntryForEdit( entryId );
					Entry modifiedEntry = entry.Clone();
					modifiedEntry.Content = textToSave;
					modifiedEntry.Title = title;
					modifiedEntry.Author = author;
					modifiedEntry.Syndicated = false;
					modifiedEntry.IsPublic = false;
					modifiedEntry.ModifiedUtc = DateTime.Now.ToUniversalTime();
					modifiedEntry.Categories = "";
					dataService.SaveEntry(modifiedEntry, null);

					//context.Request.Form["textbox1"];
					
					logService.AddEvent(
						new EventDataItem( 
						EventCodes.EntryChanged, entryId, 
						context.Request.RawUrl));
				}
				else
				{
					// This is a brand new entry.  Create the entry and save it.
					entry = new Entry();
					entry.EntryId = entryId;
					entry.CreatedUtc = DateTime.Now.ToUniversalTime();
					entry.ModifiedUtc = DateTime.Now.ToUniversalTime();
					entry.Title = title;
					entry.Author = author;
					entry.Content = textToSave;
					entry.Syndicated = false;
					entry.IsPublic = false;
					dataService.SaveEntry(entry, null);

					//context.Request.Form["textbox1"];
					
					logService.AddEvent(
						new EventDataItem( 
						EventCodes.EntryAdded, entryId, 
						context.Request.RawUrl));
				}
			}
		}
Ejemplo n.º 51
0
        /// <summary>
        /// Get some DataTable from RSS file.
        /// </summary>
        /// <param name="location"></param>
        /// <param name="address"></param>
        /// <param name="feedType"></param>
        /// <returns></returns>
        public static System.Data.DataTable GetRSSFeed(RSSLocation location, string address, RSSFeedType feedType)
        {
            int intIndex = 0;
            int intItemTableIndex = -1;

            System.IO.StreamReader oStreamReader = null;
            System.Xml.XmlTextReader oXmlTextReader = null;

            switch(location)
            {
                case RSSLocation.URL:
                    oXmlTextReader = new System.Xml.XmlTextReader(address);
                    break;

                case RSSLocation.Drive:
                    oStreamReader = new System.IO.StreamReader(address, System.Text.Encoding.UTF8);
                    oXmlTextReader = new System.Xml.XmlTextReader(oStreamReader);
                    break;
            }

            System.Data.DataSet oDataSet = new System.Data.DataSet();
            oDataSet.ReadXml(oXmlTextReader, System.Data.XmlReadMode.Auto);

            oXmlTextReader.Close();
            if(location == RSSLocation.Drive)
                oStreamReader.Close();

            while((intIndex <= oDataSet.Tables.Count - 1) && (intItemTableIndex == -1))
            {
                if(oDataSet.Tables[intIndex].TableName.ToUpper() == feedType.ToString().ToUpper())
                    intItemTableIndex = intIndex;

                intIndex++;
            }

            if(intItemTableIndex == -1)
                return(null);
            else
                return(oDataSet.Tables[intItemTableIndex]);
        }
Ejemplo n.º 52
0
		private void FillDataSet ()
		{
			// Create a FileStream object with the file path and name.
   			System.IO.FileStream myFileStream = new System.IO.FileStream ("programes.xsd",System.IO.FileMode.Open);
			System.Xml.XmlTextReader myXmlTextReader = new System.Xml.XmlTextReader (myFileStream);
   			dsSource.ReadXmlSchema (myXmlTextReader);
   			myXmlTextReader.Close ();

			// Read the XML document back in.
			System.IO.FileStream fsReadXml = new System.IO.FileStream ("programes.xml", System.IO.FileMode.Open);

			System.Xml.XmlTextReader myXmlReader = new System.Xml.XmlTextReader(fsReadXml);

			dsSource.ReadXml (myXmlReader);
			myXmlReader.Close ();

			programs = dsSource.Tables["programes"].Copy ();

			applications = dsSource.Tables["programes"].Copy ();
			applications.TableName = "applications";
			applications.Columns.RemoveAt (0);

			utilities = dsSource.Tables["programes"].Copy ();
			utilities.TableName = "utilities";
			utilities.Columns.RemoveAt (2);
			utilities.Columns.RemoveAt (3);
			utilities.Columns.RemoveAt (4);

			DataSet dataset = new DataSet ();
			dataset.Tables.Add (applications);
			dataset.Tables.Add (utilities);
			dataset.Tables.Add (programs);
			dataGrid.DataSource = dataset;
			dataGrid.DataMember = "programes";
		}
Ejemplo n.º 53
0
        public ListIdentifier ListIdentifiers(string sPrefix,
            string sset,
            string sfrom,
            string suntil,
            ResumptionToken objToken)
        {
            System.IO.Stream objStream;
            ListIdentifier objList = new ListIdentifier();
            Identifiers objRecord;
            ResumptionToken myToken;
            string tmp = "";
            System.Net.HttpWebRequest wr;
            System.Xml.XmlTextReader rd;

            if (sPrefix.Length == 0)
            {
                sPrefix = "oai_dc";
            }

            if (objToken == null)
            {
                if (sset.Length != 0)
                {
                    sset = "&set=" + sset;
                }
                if (sfrom.Length != 0)
                {
                    sfrom = "&from=" + sfrom;
                }
                if (suntil.Length != 0)
                {
                    suntil = "&until=" + suntil;
                }

                prequestURL = baseURL + "?verb=ListIdentifiers&metadataPrefix=" + sPrefix + sset + sfrom + suntil;

            }
            else
            {
                prequestURL = baseURL + "?verb=ListIdentifiers&resumptionToken=" + objToken.resumptionToken;
                //This is where we handle the resumptionToken
            }
            //======================================================
            // If you wanted to support additional metadata formats,
            // you would just need to have additional handlers.
            //======================================================
            //Console.Write(sURL);
            try
            {
                wr = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(prequestURL);
                wr.UserAgent = cUserAgent;
                System.Net.WebResponse response = wr.GetResponse();
                objStream = response.GetResponseStream();
                System.IO.StreamReader reader = new System.IO.StreamReader(objStream);
                prawXML = reader.ReadToEnd();
                reader.Close();
                rd = new System.Xml.XmlTextReader(prawXML, System.Xml.XmlNodeType.Document, null);
            }
            catch (Exception e)
            {
                error.errorName = "badConnection";
                error.errorDescription = e.Message + "<br>Unable to connect to " + baseURL;
                return null;
            }

            while (rd.Read())
            {
                if (rd.NodeType == System.Xml.XmlNodeType.Element)
                {
                    if (rd.Name == "responseDate")
                    {
                        presponseDate = rd.ReadString();
                    }
                    else if (rd.Name == "ListIdentifiers")
                    {
                        do
                        {
                            if (rd.Name == "header")
                            {
                                tmp = rd.ReadOuterXml();
                                //tmp += ParseOAIContainer(ref rd, "header", true);
                                //Console.WriteLine("In the Function: " + tmp);
                                objRecord = new Identifiers(tmp);
                                objList.record.Add(objRecord);
                                //return objRecord;
                            }
                            else if (rd.Name == "resumptionToken")
                            {
                                tmp = rd.ReadOuterXml();
                                myToken = new ResumptionToken(tmp);
                                objList.token = myToken;
                            }
                            else rd.Read(); // Added the Read() and will never occur with the ReadInnerXml()

                        } while (rd.Name != "ListIdentifiers"); // loop
                    }
                    else if (rd.Name == "error")
                    {
                        error.errorName = rd.GetAttribute("code");
                        error.errorDescription = rd.ReadString();
                        rd.Close();
                        return null;
                    }
                }
            }

            rd.Close();
            return objList;
        }
Ejemplo n.º 54
0
        public static string FormTxtBill(string tplFile, DataTable dTable)
        {
            if (!File.Exists(tplFile))
                return "";

            if (!Directory.Exists(AppConfig.Path_Temp))
                Directory.CreateDirectory(AppConfig.Path_Temp);

            string dCor = string.Empty;
            for (byte i = 0; i < AppConfig.APP_MoneyDecimals; i++)
                dCor += '0';

            //Set directives
            byte LoAN = 15;
            byte LoAD = 20;
            byte TSpL = 0;

            //Load messages
            Dictionary<string, string> _MSG = new Dictionary<string, string>();
            using (System.Xml.XmlTextReader xmlRd = new System.Xml.XmlTextReader(AppConfig.Path_Templates + "\\" + "Messages.xml"))
            {
                string varName = string.Empty;
                xmlRd.WhitespaceHandling = System.Xml.WhitespaceHandling.None;
                while (xmlRd.Read())
                    if (xmlRd.NodeType == System.Xml.XmlNodeType.Element && xmlRd.Name != null
                        && xmlRd.Name != string.Empty && xmlRd.Name.ToUpper() != "MESSAGES")
                    {
                        varName = xmlRd.Name;
                        xmlRd.Read();
                        _MSG.Add(varName.ToUpper(), xmlRd.Value.TrimStart('\r', '\n').TrimEnd('\r', '\n'));
                    }
                xmlRd.Close();
            }

            // Aligment blocks
            string[][] _alignBlocks = new string[2][];
            string[] _separators = new string[] { "[hex:", "[dec:" };
            _alignBlocks[0] = new string[] { "[right]", "[center]" };
            _alignBlocks[1] = new string[] { "[\\right]", "[\\center]" };
            // Separators

            //Making info values
            #region Info values
            object[] infoV = new object[7];
            //00 - subUnit (byte)
            infoV[00] = AppConfig.APP_SubUnit;//0
            //01 - subUnitName (string)
            infoV[01] = AppConfig.APP_SubUnitName;//1
            //02 - payDesk (byte)
            infoV[02] = AppConfig.APP_PayDesk;//2
            //03 - cashierName (string)
            infoV[03] = UserConfig.UserID;//3
            //04 - currentDateTime (DateTime)
            infoV[04] = DateTime.Now;//4
            //05 - billNumber (string)
            infoV[05] = dTable.ExtendedProperties["NOM"].ToString();//05
            //19 - billComment (string)
            infoV[06] = dTable.ExtendedProperties["CMT"].ToString();//06

            #endregion

            //Creating output file
            string chqTxtName = string.Format("{0:X2}{1:X2}_{2:yyMMdd}_{2:HHmmss}.txt", AppConfig.APP_SubUnit, AppConfig.APP_PayDesk, DateTime.Now);
            StreamWriter streamWr = new StreamWriter(AppConfig.Path_Temp + "\\" + chqTxtName, false, Encoding.Default);
            chqTxtName = AppConfig.Path_Temp + "\\" + chqTxtName;

            //Load template
            StreamReader streamRd = File.OpenText(tplFile);

            //Fill data by loaded template
            string template = string.Empty;
            while ((template = streamRd.ReadLine()) != null)
            {
                if (template == string.Empty)
                    template = " ";

                template = template.Replace("\\r", "\r");
                template = template.Replace("\\n", "\n");
                template = template.Replace("\\t", "\t");
                template = template.Replace("\\v", "\v");
                template = template.Replace("\\b", "\b");

                switch (template[0])
                {
                    #region Info values [S]
                    case 'S':
                        {
                            template = template.Remove(0, 1);
                            template = string.Format(template, infoV);

                            if (!template.Contains("!ZeRo!"))
                            {
                                template = GetHEX(template, _separators);
                                streamWr.WriteLine(template);
                            }
                            break;
                        }
                    #endregion
                    #region Articles [W]
                    case 'W':
                        {
                            //Output Format [W]
                            //00 - articleName (string)
                            //01 - articleDecription (string)
                            //02 - articleUnit (string)
                            //03 - articleTaxChar (char)
                            //04 - articlePrice (double)
                            //05 - articleDose (double)
                            //06 - articleTaxValue (double)
                            //07 - articleDiscount (double)
                            //08 - articleSuma (doulble)
                            //09 - articleActualSum (double)
                            //10 - articleTaxMoney (double)
                            //11 - articleCashDiscount (double)

                            //static values parsed as string [Program decimal correction]
                            //20 - articlePrice (double)
                            //21 - articleDose (double)
                            //22 - articleTaxValue (double)
                            //23 - articleDiscount (double)
                            //24 - articleSuma (double)
                            //25 - articleActualSum (double)
                            //26 - articleTaxMoney (double)
                            //27 - articleCashDiscount (double)

                            string articleTemplate = template.Remove(0, 1);
                            string art_name = "";
                            string art_desc = "";
                            double _pTotal = 0.0;

                            for (int i = 0; i < dTable.Rows.Count; i++)
                            {
                                art_name = dTable.Rows[i]["NAME"].ToString();
                                art_desc = dTable.Rows[i]["DESC"].ToString();

                                if (art_name.Length > LoAN)
                                    art_name = art_name.Substring(0, LoAN);

                                if (art_desc.Length > LoAD)
                                    art_desc = art_desc.Substring(0, LoAD);

                                _pTotal = Convert.ToDouble(dTable.Rows[i]["TOT"]) - (double)dTable.Rows[i]["PRINTCOUNT"];
                                _pTotal = CoreLib.GetRoundedDose(_pTotal);

                                if (_pTotal > 0.0)
                                {
                                    template = string.Format(articleTemplate,
                                        //0
                                        art_name,
                                        art_desc,
                                        dTable.Rows[i]["UNIT"],
                                        dTable.Rows[i]["VG"],
                                        dTable.Rows[i]["PRICE"],
                                        _pTotal,
                                        dTable.Rows[i]["TAX_VAL"],
                                        "!ZeRo!",
                                        dTable.Rows[i]["SUM"],
                                        dTable.Rows[i]["ASUM"],
                                        //10
                                        dTable.Rows[i]["TAX_MONEY"],
                                        CoreLib.GetRoundedMoney((double)dTable.Rows[i]["SUM"] - (double)dTable.Rows[i]["ASUM"]),//11
                                        null,//12
                                        null,//13
                                        null,//14
                                        null,//15
                                        null,//16
                                        null,//17
                                        null,//18
                                        null,//19
                                        string.Format("{0:F" + AppConfig.APP_MoneyDecimals + "}", dTable.Rows[i]["PRICE"]),
                                        string.Format("{0:F" + AppConfig.APP_DoseDecimals + "}", _pTotal),
                                        string.Format("{0:F" + AppConfig.APP_MoneyDecimals + "}", dTable.Rows[i]["TAX_VAL"]),
                                        "!ZeRo!",
                                        string.Format("{0:F" + AppConfig.APP_MoneyDecimals + "}", dTable.Rows[i]["SUM"]),
                                        string.Format("{0:F" + AppConfig.APP_MoneyDecimals + "}", dTable.Rows[i]["ASUM"]),
                                        string.Format("{0:F" + AppConfig.APP_MoneyDecimals + "}", dTable.Rows[i]["TAX_MONEY"]),
                                        string.Format("{0:F" + AppConfig.APP_MoneyDecimals + "}", CoreLib.GetRoundedMoney((double)dTable.Rows[i]["SUM"] - (double)dTable.Rows[i]["ASUM"]))
                                    );

                                    if (!template.Contains("!ZeRo!"))
                                    {
                                        if (i == 0)
                                            template = template.TrimStart(new char[] { '\n', '\r' });
                                        if (i + 1 == dTable.Rows.Count)
                                            template = template.TrimEnd(new char[] { '\n', '\r' });

                                        template = GetHEX(template, _separators);
                                        streamWr.WriteLine(template);
                                    }
                                }
                            }

                            break;
                        }
                    #endregion
                    #region Directives [#]
                    case '#':
                        {
                            //Template variables
                            //LoAN - Limit of Article Name (byte)
                            //LoAD - Limit of Article Description (byte)
                            //TSpL - Total Symbols per Line (byte)

                            template = template.Remove(0, 1);
                            object[] var = template.Split('=');

                            try
                            {
                                switch (var[0].ToString())
                                {
                                    case "LoAN": LoAN = byte.Parse(var[1].ToString()); break;
                                    case "LoAD": LoAD = byte.Parse(var[1].ToString()); break;
                                    case "TSpL": TSpL = byte.Parse(var[1].ToString()); break;
                                }
                            }
                            catch { }

                            break;
                        }
                    #endregion
                    #region Messages [M]
                    case 'M':
                        {
                            template = template.Remove(0, 1).ToUpper();
                            string[] keys = new string[_MSG.Keys.Count];
                            string[] blocks = new string[0];
                            string newLine = string.Empty;
                            string cuttedLine = string.Empty;
                            int startIndex = 0;
                            int length = 0;
                            int i = 0;
                            int j = 0;

                            _MSG.Keys.CopyTo(keys, 0);

                            try
                            {
                                for (i = 0; i < _MSG.Keys.Count; i++)
                                    template = template.Replace(keys[i], _MSG[keys[i]]);
                            }
                            catch { }

                            //Aligment
                            for (i = 0; i < _alignBlocks[0].Length; i++)
                            {
                                while (template.Contains(_alignBlocks[0][i]) && template.Contains(_alignBlocks[1][i]))
                                {
                                    startIndex = template.IndexOf(_alignBlocks[0][i]) + _alignBlocks[0][i].Length;
                                    length = template.IndexOf(_alignBlocks[1][i]) - startIndex;

                                    newLine = cuttedLine = template.Substring(startIndex, length);
                                    blocks = newLine.Split(new string[] { "\r\n" }, StringSplitOptions.RemoveEmptyEntries);
                                    newLine = string.Empty;
                                    for (j = 0; j < blocks.Length; j++)
                                    {
                                        switch (_alignBlocks[0][i])
                                        {
                                            case "[center]":
                                                if (blocks[j].Length % 2 == 0)
                                                    length = (TSpL - blocks[j].Length) / 2 + blocks[j].Length;
                                                else
                                                    length = (TSpL - (blocks[j].Length - 1)) / 2 + blocks[j].Length;
                                                break;
                                            case "[right]":
                                                length = TSpL;
                                                break;
                                        }
                                        blocks[j] = blocks[j].PadLeft(length);
                                        newLine += blocks[j];
                                        if (j + 1 < blocks.Length)
                                            newLine += "\r\n";
                                    }
                                    cuttedLine = _alignBlocks[0][i] + cuttedLine + _alignBlocks[1][i];
                                    template = template.Replace(cuttedLine, newLine);
                                }

                                //remove first single aligment's block
                                if (template.Contains(_alignBlocks[0][i]) && !template.Contains(_alignBlocks[1][i]))
                                    template = template.Replace(_alignBlocks[0][i], "");

                                //remove end single aligment's block
                                if (!template.Contains(_alignBlocks[0][i]) && template.Contains(_alignBlocks[1][i]))
                                    template = template.Replace(_alignBlocks[1][i], "");
                            }

                            template = GetHEX(template, _separators);
                            streamWr.WriteLine(template);

                            break;
                        }
                    #endregion
                    #region Comment [;]
                    case ';':
                        {
                            break;
                        }
                    #endregion
                    default:
                        {
                            template = GetHEX(template, _separators);
                            streamWr.WriteLine(template);
                            break;
                        }
                }
            }

            //End fill data
            streamWr.Close();
            streamWr.Dispose();
            streamRd.Close();
            streamRd.Dispose();

            //Path for txt file.
            return chqTxtName;
        }
Ejemplo n.º 55
0
		private void FillDataSet()
		{

			//ReadSchemaFromXmlTextReader
   			// Create a FileStream object with the file path and name.
   			System.IO.FileStream myFileStream = new System.IO.FileStream ("programes.xsd",System.IO.FileMode.Open);

			// Create a new XmlTextReader object with the FileStream.
			System.Xml.XmlTextReader myXmlTextReader=
			new System.Xml.XmlTextReader(myFileStream);
   			// Read the schema into the DataSet and close the reader.
   			dsSource.ReadXmlSchema(myXmlTextReader);
   			myXmlTextReader.Close();


			// Read the XML document back in.
			// Create new FileStream to read schema with.
			System.IO.FileStream fsReadXml = new System.IO.FileStream
			("programes.xml", System.IO.FileMode.Open);

			System.Xml.XmlTextReader myXmlReader = new System.Xml.XmlTextReader(fsReadXml);

			dsSource.ReadXml (myXmlReader);
			myXmlReader.Close();

			dataGrid.DataSource = dsSource.Tables["programes"];
		}
Ejemplo n.º 56
0
        public ListMetadataFormats listMetadataFormats(string sidentifier)
        {
            System.IO.Stream objStream;
            ListMetadataFormats objFormat = new ListMetadataFormats();
            System.Net.HttpWebRequest wr;
            System.Xml.XmlTextReader rd;

            if (sidentifier.Length == 0)
            {
                prequestURL = baseURL + "?verb=ListMetadataFormats";
            }
            else
            {
                prequestURL = baseURL + "?verb=ListMetadataFormats&identifier=" + sidentifier;
            }

            try
            {
                wr = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(prequestURL);
                wr.UserAgent = cUserAgent;
                System.Net.WebResponse response = wr.GetResponse();
                objStream = response.GetResponseStream();
                System.IO.StreamReader reader = new System.IO.StreamReader(objStream);
                prawXML = reader.ReadToEnd();
                reader.Close();
                rd = new System.Xml.XmlTextReader(prawXML, System.Xml.XmlNodeType.Document, null);
            }
            catch (Exception e)
            {
                error.errorName = e.ToString();
                error.errorDescription = e.Message + "\n<br>Unable to connect to " + baseURL;
                return null;
            }

            while (rd.Read())
            {
                if (rd.NodeType == System.Xml.XmlNodeType.Element)
                {
                    if (rd.Name == "responseDate")
                    {
                        presponseDate = rd.ReadString();
                    }
                    else if (rd.Name == "ListMetadataFormats")
                    {
                        while (rd.Read())  // && rd.NodeType != System.Xml.XmlNodeType.EndElement)
                        {
                            switch (rd.Name)
                            {
                                case "metadataPrefix":
                                    objFormat.metadataPrefix.Add(ParseOAI(ref rd, "metadataPrefix"));
                                    break;
                                case "schema":
                                    objFormat.schema.Add(ParseOAI(ref rd, "schema"));
                                    break;
                                case "metadataNamespace":
                                    objFormat.metadataNamespace.Add(ParseOAI(ref rd, "metadataNamespace"));
                                    break;
                                default:
                                    break;
                            }
                        }
                    }
                    else if (rd.Name == "error")
                    {
                        error.errorName = rd.GetAttribute("code");
                        error.errorDescription = rd.ReadString();
                        return null;
                    }
                }
            }

            rd.Close();
            return objFormat;
        }
Ejemplo n.º 57
0
 public static void FromXml (System.IO.Stream stream, PackageMatchDelegate callback)
 {
     System.Xml.XmlTextReader reader = new System.Xml.XmlTextReader (stream);
     FromXml (reader, callback);
     reader.Close ();
     stream.Close ();
 }
Ejemplo n.º 58
0
		private void RefreshCapabilities( Stream capabilitiesStream ) 
		{
			System.Xml.XmlReader capReader = null;
			try 
			{
				capReader = new System.Xml.XmlTextReader(capabilitiesStream);

				capabilities_1_3_0.capabilities_1_3_0Doc doc = new capabilities_1_3_0.capabilities_1_3_0Doc();
				capabilities_1_3_0.wms.WMS_CapabilitiesType root = new capabilities_1_3_0.wms.WMS_CapabilitiesType(
					doc.Load( capReader ));

				if(root.HasCapability()) 
				{
					capabilities_1_3_0.wms.LayerType rootLayer = root.Capability.GetLayer();
					for(int i = 0; i < rootLayer.LayerCount; i++) 
					{
						capabilities_1_3_0.wms.LayerType curLayer = (capabilities_1_3_0.wms.LayerType)rootLayer.GetLayerAt(i);
						TreeNode tn = this.getTreeNodeFromLayerType(curLayer);
						this.treeViewLayers.BeginInvoke(new UpdateTreeDelegate(UpdateTree), new object[] {tn});
					}
					updateStatusBar("Download successful.");
				}
				else 
				{
					updateStatusBar("Invalid table of contents. Please try again later.");
				}
			} 
			catch(Exception caught)
			{
				// Ignore all problems
				updateStatusBar(caught.Message);
			}
			finally
			{
				// The dude at MS writing the XmlReader class was so high on XML he forgot IDisposable? :-P
				if(capReader != null)
					capReader.Close();
			}
		}
        /// <summary> Reads the inficated configuration file </summary>
        /// <param name="ConfigFile"> Configuration file to read </param>
        /// <exception>File is checked for existence first, otherwise all encountered exceptions will be thrown</exception>
        public static void Read_Configuration_File(string ConfigFile)
        {
            if (!File.Exists(ConfigFile))
                return;

            databaseInfo.Clear();

            StreamReader reader = new StreamReader(ConfigFile);
            System.Xml.XmlTextReader xmlReader = new System.Xml.XmlTextReader(reader);
            while (xmlReader.Read())
            {
                if (xmlReader.NodeType == System.Xml.XmlNodeType.Element)
                {
                    string node_name = xmlReader.Name.ToLower();
                    switch (node_name)
                    {
                        case "connection_string":
                            Database_Instance_Configuration newDb = new Database_Instance_Configuration();
                            if (xmlReader.MoveToAttribute("type"))
                            {
                                if (xmlReader.Value.ToLower() == "postgresql")
                                    newDb.Database_Type = SobekCM_Database_Type_Enum.PostgreSQL;
                            }
                            if (xmlReader.MoveToAttribute("active"))
                            {
                                if (xmlReader.Value.ToLower() == "false")
                                    newDb.Is_Active = false;
                            }
                            if (xmlReader.MoveToAttribute("canAbort"))
                            {
                                if (xmlReader.Value.ToLower() == "false")
                                    newDb.Can_Abort = false;
                            }
                            if (xmlReader.MoveToAttribute("isHosted"))
                            {
                                if (xmlReader.Value.ToLower() == "true")
                                    isHosted = true;
                            }
                            if (xmlReader.MoveToAttribute("name"))
                                newDb.Name = xmlReader.Value.Trim();

                            xmlReader.Read();
                            newDb.Connection_String = xmlReader.Value;
                            if (newDb.Name.Length == 0)
                                newDb.Name = "Connection" + (databaseInfo.Count + 1);
                            databaseInfo.Add(newDb);
                            break;

                        case "erroremails":
                            xmlReader.Read();
                            systemErrorEmail = xmlReader.Value;
                            break;

                        case "errorpage":
                            xmlReader.Read();
                            System_Error_URL = xmlReader.Value;
                            break;

                        case "ghostscript_executable":
                            xmlReader.Read();
                            ghostscriptExecutable = xmlReader.Value;
                            break;

                        case "imagemagick_executable":
                            xmlReader.Read();
                            imageMagickExecutable = xmlReader.Value;
                            break;

                        case "pause_between_polls":
                            xmlReader.Read();
                            int testValue;
                            if (Int32.TryParse(xmlReader.Value, out testValue))
                                Builder_Override_Seconds_Between_Polls = testValue;
                            break;

                        case "publish_logs_directory":
                            xmlReader.Read();
                            Builder_Logs_Publish_Directory = xmlReader.Value;
                            break;

                    }
                }
            }

            xmlReader.Close();
            reader.Close();
        }
Ejemplo n.º 60
0
		public ProjectConfig Load(string filename)
		{
			XmlSerializer xs = new XmlSerializer(typeof(ProjectConfig));
			// TODO: Exceptions...
			System.Xml.XmlTextReader xtr = new System.Xml.XmlTextReader(filename);
			ProjectConfig pc = (ProjectConfig)xs.Deserialize(xtr);
			xtr.Close();
			return pc;
		}