Пример #1
0
    static public FooBar Deserialize(XmlReader reader)
    {
        var fooBar =
            (FooBar) new DataContractSerializer(typeof(FooBar)).ReadObject(reader);

        fooBar.OriginalXml = reader.ToString();
        return(fooBar);
    }
Пример #2
0
        /// <summary>
        /// Parse an object from <paramref name="r"/> using the type hint <paramref name="t"/>
        /// </summary>
        /// <param name="r">The reader to read from</param>
        /// <param name="t">The type hint for the formatter</param>
        /// <returns>A structured result</returns>
        public IFormatterParseResult Parse(XmlReader r, Type t)
        {
            // Get the struct attribute
            IDatatypeFormatter formatter = null;
            Type cType = t;

            // Don't check for XSI type if the type is a GTS or iterable
            // This is because the XSI type on these classes will mislead the formatter selector
            if (t == typeof(GTS) || t.GetInterface(typeof(IEnumerable).FullName, false) != null && !t.IsAbstract)
            {
                formatter = GetFormatter(t);
            }
            else
            {
                // Force processing as an XSI:Type
                if (r.GetAttribute("type", NS_XSI) != null)
                {
                    cType = Util.ParseXSITypeName(r.GetAttribute("type", NS_XSI));
                }

                formatter = GetFormatter(cType);
            }

            if (formatter == null)
            {
                return(null);
            }

            // Set host and parse
            DatatypeFormatterParseResult result = new DatatypeFormatterParseResult(this.CompatibilityMode, ResultCode.Accepted, null, this.ValidateConformance);

            formatter.Host = (IXmlStructureFormatter)(this.Host ?? this);


#if WINDOWS_PHONE
            bool hasErrors = s_unsupportedNames.Exists(o => (t.IsGenericType ? t.GetGenericTypeDefinition() : t).Equals(o));
#else
            bool hasErrors = Array.Exists(s_unsupportedNames, o => (t.IsGenericType ? t.GetGenericTypeDefinition() : t).Equals(o));
#endif
            // Errors
            if (hasErrors)
            {
                var structAtt = t.GetCustomAttributes(typeof(StructureAttribute), false);
                if (structAtt.Length > 0)
                {
                    result.AddResultDetail(new UnsupportedDatatypeR1PropertyResultDetail(
                                               ResultDetailType.Warning,
                                               "All",
                                               (structAtt[0] as StructureAttribute).Name,
                                               r.ToString()
                                               ));
                }
            }
            // Structure graph
            result.Structure = formatter.Parse(r, result) as IGraphable;

            return(result);
        }
Пример #3
0
        public void xmlToList()
        {
            List <gameItem> lst2 = new List <gameItem>();

            using (XmlReader reader = XmlReader.Create("c:\\1.xml"))
            {
                XmlSerializer xz = new XmlSerializer(lst2.GetType());
                lst2 = (List <gameItem>)xz.Deserialize(reader);
                Console.WriteLine(reader.ToString());
            }
        }
        void Failure2()
        {
            XmlReader reader = null;

            try {
                reader = XmlReader.Create("foo.xml");
                Console.WriteLine(reader.ToString());
            } catch (InvalidOperationException e) {
                Console.WriteLine(e.Message);
            }
            ((IDisposable)reader).Dispose();
        }
        /// <summary>
        /// Parse an object from <paramref name="r"/> using the type hint <paramref name="t"/>
        /// </summary>
        /// <param name="r">The reader to read from</param>
        /// <param name="t">The type hint for the formatter</param>
        /// <returns>A structured result</returns>
        public IFormatterParseResult Parse(XmlReader r, Type t)
        {
            // Get the struct attribute
            IDatatypeFormatter formatter = null;
            Type cType = t;

            //if (formatter != null && t != typeof(GTS) && formatter.GenericArguments == null )
            //    formatter.GenericArguments = t.GetGenericArguments();
            if (t == typeof(GTS) || t.GetInterface(typeof(IEnumerable).FullName) != null && !t.IsAbstract)
            {
                formatter = GetFormatter(t);
            }
            else
            {
                // Force processing as an XSI:Type
                if (r.GetAttribute("type", NS_XSI) != null)
                {
                    cType = Util.ParseXSITypeName(r.GetAttribute("type", NS_XSI));
                }

                formatter = GetFormatter(cType);
            }

            if (formatter == null)
            {
                return(null);
            }

            // Set host and parse
            DatatypeFormatterParseResult result = new DatatypeFormatterParseResult(this.CompatibilityMode, ResultCode.Accepted, null, this.ValidateConformance);

            formatter.Host = (IXmlStructureFormatter)(this.Host ?? this);

            // Errors
            if (Array.Exists(s_unsupportedNames, o => (t.IsGenericType ? t.GetGenericTypeDefinition() : t).Equals(o)))
            {
                var structAtt = t.GetCustomAttributes(typeof(StructureAttribute), false);
                if (structAtt.Length > 0)
                {
                    result.AddResultDetail(new UnsupportedDatatypeR1PropertyResultDetail(
                                               ResultDetailType.Warning,
                                               "All",
                                               (structAtt[0] as StructureAttribute).Name,
                                               r.ToString()
                                               ));
                }
            }

            // Structure graph
            result.Structure = formatter.Parse(r, result) as IGraphable;

            return(result);
        }
        static void Main(string[] args)
        {
            XmlReader         reader     = XmlReader.Create(INPUT_FILENAME);
            string            xml        = reader.ToString();
            XmlSerializer     serializer = new XmlSerializer(typeof(DataRoot));
            DataRoot          root       = (DataRoot)serializer.Deserialize(reader);
            XmlWriterSettings settings   = new XmlWriterSettings();

            settings.Indent = true;
            XmlWriter writer = XmlWriter.Create(OUTPUT_FILENAME, settings);

            serializer.Serialize(writer, root);
        }
Пример #7
0
        public static object GetIpLocation(string IpAddress)
        {
            XmlSerializer serializer = new XmlSerializer(typeof(Responsee));
            XmlReader     reader     = XmlReader.Create(new StringReader(GetIpData(IpAddress)));

            // object oo = (Responsee)serializer.Deserialize(reader);
            //     return reader.Value.ToString(); ;
            foreach (var a in reader.ToString())
            {
            }
            return(reader);
            //  return (Responsee)serializer.Deserialize(reader);
        }
Пример #8
0
 public static bool Import(string xmlPath) //从Xml文件导入
 {
     try
     {
         using (XmlReader reader = XmlReader.Create(xmlPath))
         {
             XmlSerializer xz = new XmlSerializer(myOrders.GetType());
             myOrders = (List <Order>)xz.Deserialize(reader);
             Console.WriteLine(reader.ToString());
         }
         return(true);
     }
     catch
     {
         return(false);
     }
 }
Пример #9
0
        /// <summary>
        /// Parse an object from <paramref name="s"/>
        /// </summary>
        public T Parse <T>(XmlReader r, DatatypeR2FormatterParseResult result) where T : ANY, IPrimitiveDataValue, IQuantity, new()
        {
            // Prepare QTY formatting
            QTYFormatter baseFormatter = new QTYFormatter();

            baseFormatter.Host = this.Host;

            // Parse attributes part of QTY
            T retVal = this.ParseAttributes <T>(r, result);

            // Parse the elements
            baseFormatter.ParseElements <T>(r, retVal, result);

            // Validate
            new ANYFormatter().Validate(retVal, r.ToString(), result);

            return(retVal);
        }
Пример #10
0
        // Strips MathML tags from the source and replaces the equations with the content
        // found in the <!-- eqn: :--> comments in the docs.
        // Todo: Some simple MathML tags do not include comments, find a solution.
        // Todo: Some files include more than 1 function - find a way to map these extra functions.
        public string ProcessFile(string file)
        {
            string text = File.ReadAllText(file);

            Match m = remove_mathml.Match(text);

            while (m.Length > 0)
            {
                string removed = text.Substring(m.Index, m.Length);
                text = text.Remove(m.Index, m.Length);
                int equation = removed.IndexOf("eqn");
                if (equation > 0)
                {
                    text = text.Insert(m.Index,
                                       "<![CDATA[" +
                                       removed.Substring(equation + 4, removed.IndexOf(":-->") - equation - 4) +
                                       "]]>");
                }
                m = remove_mathml.Match(text);
            }

            XmlReader doc = null;

            try
            {
                // The pure XmlReader is ~20x faster than the XmlTextReader.
                doc = XmlReader.Create(new StringReader(text), settings);
                //doc = new XmlTextReader(new StringReader(text));

                using (StringWriter sw = new StringWriter())
                {
                    xslt.Transform(doc, null, sw);
                    return(sw.ToString());
                }
            }
            catch (XmlException e)
            {
                Console.WriteLine(e.ToString());
                Console.WriteLine(doc.ToString());
                return(String.Empty);
            }
        }
Пример #11
0
        protected T Parse <T>(XmlReader xr, DatatypeFormatterParseResult result) where T : ANY, new()
        {
            T retVal = base.Parse <T>(xr, result);


            PropertyInfo pi = typeof(T).GetProperty("Value");

            try
            {
                // Value
                if (xr.GetAttribute("value") != null)
                {
                    pi.SetValue(retVal, Util.FromWireFormat(xr.GetAttribute("value"), pi.PropertyType), null);
                }
            }
            catch (Exception e)
            {
                result.AddResultDetail(new ResultDetail(ResultDetailType.Error, e.Message, xr.ToString(), e));
            }

            return(retVal);
        }
Пример #12
0
 public override string ToString()
 {
     return(_innerReader.ToString());
 }
    protected void btnSearchSM_Click(object sender, EventArgs e)
    {
        string searchBasicURL = "http://api.musescore.com/services/rest/score?oauth_consumer_key=fRWBMQeNaqrBfnckEjfbkH4634jtidSy&text=";
        string searchTxt      = TextBox1.Text;
        string searchURL      = searchBasicURL + searchTxt;

        DataSet   ds = new DataSet();
        DataTable dt = new DataTable();

        dt.Columns.Add(new DataColumn("MSuid", typeof(Int32)));
        dt.Columns.Add(new DataColumn("MSsid", typeof(Int32)));
        dt.Columns.Add(new DataColumn("MSurl", typeof(string)));
        dt.Columns.Add(new DataColumn("Title", typeof(string)));

        var request  = (HttpWebRequest)WebRequest.Create(searchURL);
        var response = (HttpWebResponse)request.GetResponse();

        var receiveStream = response.GetResponseStream();

        //var mySourceDoc = new XmlDocument();
        //mySourceDoc.Load(receiveStream);
        receiveStream.Close();


        XmlReader reader = XmlReader.Create(receiveStream);

        reader.MoveToContent();
        while (reader.Read())
        {
            if (reader.IsStartElement())
            {
                DataRow dr = dt.NewRow();
                switch (reader.Name.ToString())
                {
                case "id":
                    int MSsid = Convert.ToInt32(reader.ReadString());
                    dr["MSsid"] = MSsid;
                    Console.WriteLine("MSsid " + MSsid);
                    break;

                case "uri":
                    string MSurl = reader.ReadString();
                    dr["MSurl"] = MSurl;
                    Console.WriteLine("MSurl " + MSurl);
                    break;

                case "uid":
                    int MSuid = Convert.ToInt32(reader.ReadString());
                    dr["MSuid"] = MSuid;
                    Console.WriteLine("MSuid " + MSuid);
                    break;

                case "title":
                    string title = reader.ToString();
                    dr["Title"] = title;
                    Console.WriteLine("title " + title);
                    break;
                }
                dt.Rows.Add(dr);
            }
        }
        dlSearch.DataSource = dt;
        dlSearch.DataBind();
    }
Пример #14
0
        // Strips MathML tags from the source and replaces the equations with the content
        // found in the <!-- eqn: :--> comments in the docs.
        // Todo: Some simple MathML tags do not include comments, find a solution.
        // Todo: Some files include more than 1 function - find a way to map these extra functions.
        public string[] ProcessFile(string file)
        {
            string text;

            if (LastFile == file)
            {
                return(Text);
            }

            LastFile = file;
            text     = File.ReadAllText(file);

            Match m = remove_mathml.Match(text);

            while (m.Length > 0)
            {
                string removed = text.Substring(m.Index, m.Length);
                text = text.Remove(m.Index, m.Length);
                int equation = removed.IndexOf("eqn");
                if (equation > 0)
                {
                    // Find the start and end of the equation string
                    int eqn_start = equation + 4;
                    int eqn_end   = removed.IndexOf(":-->") - equation - 4;
                    if (eqn_end < 0)
                    {
                        // Note: a few docs from man4 delimit eqn end with ": -->"
                        eqn_end = removed.IndexOf(": -->") - equation - 4;
                    }
                    if (eqn_end < 0)
                    {
                        Console.WriteLine("[Warning] Failed to find equation for mml.");
                        goto next;
                    }

                    string eqn_substring = removed.Substring(eqn_start, eqn_end);
                    text = text.Insert(m.Index, "<![CDATA[" + eqn_substring + "]]>");
                }

next:
                m = remove_mathml.Match(text);
            }

            XmlReader doc = null;

            try
            {
                // The pure XmlReader is ~20x faster than the XmlTextReader.
                doc = XmlReader.Create(new StringReader(text), settings);
                //doc = new XmlTextReader(new StringReader(text));

                using (StringWriter sw = new StringWriter())
                {
                    xslt.Transform(doc, null, sw);
                    Text = sw.ToString().Split(new char[] { '\r', '\n' },
                                               StringSplitOptions.RemoveEmptyEntries);

                    // Remove unecessary whitespace
                    // Indentation is handled by BindStreamWriter
                    for (int i = 0; i < Text.Length; i++)
                    {
                        Text[i] = Text[i].Trim();
                    }
                    return(Text);
                }
            }
            catch (XmlException e)
            {
                Console.WriteLine(e.ToString());
                Console.WriteLine(doc.ToString());
                return(new string[0]);
            }
        }
Пример #15
0
 public override string ToString()
 {
     return(reader.ToString());
 }
Пример #16
0
        /// <summary>
        /// Parse elements
        /// </summary>
        public void ParseElements <T>(XmlReader s, T retVal, DatatypeR2FormatterParseResult result) where T : ANY, IQuantity, new()
        {
            if (retVal == null)
            {
                throw new ArgumentNullException("retVal");
            }

            // Elements
            #region Elements
            if (!s.IsEmptyElement)
            {
                int    sDepth = s.Depth;
                string sName  = s.Name;

                s.Read();
                // string Name
                while (!(s.NodeType == System.Xml.XmlNodeType.EndElement && s.Depth == sDepth && s.Name == sName))
                {
                    string oldName = s.Name; // Name
                    try
                    {
                        ParseElementsInline(s, retVal, result);
                    }
                    catch (VocabularyException e)
                    {
                        result.AddResultDetail(new VocabularyIssueResultDetail(ResultDetailType.Error, e.Message, e));
                    }
                    catch (MessageValidationException e)
                    {
                        result.AddResultDetail(new MARC.Everest.Connectors.ResultDetail(MARC.Everest.Connectors.ResultDetailType.Error, e.Message, s.ToString(), e));
                    }
                    finally
                    {
                        if (s.Name == oldName)
                        {
                            s.Read();
                        }
                    }
                }
            }
            #endregion
        }
Пример #17
0
 /// <summary>
 /// Parse elements inline (meaning the element exit criteria has already been handled
 /// </summary>
 protected void ParseElementsInline(XmlReader s, ST retVal, DatatypeR2FormatterParseResult result)
 {
     if (s.LocalName == "translation") // Translation
     {
         var hostResult = Host.Parse(s, typeof(ED));
         result.Code = hostResult.Code;
         result.AddResultDetail(hostResult.Details);
         if (retVal.Translation == null)
         {
             retVal.Translation = new SET <ST>();
         }
         retVal.Translation.Add((ST)hostResult.Structure);
     }
     else if (s.NodeType == System.Xml.XmlNodeType.Element)
     {
         result.AddResultDetail(new NotImplementedElementResultDetail(ResultDetailType.Warning, s.LocalName, s.NamespaceURI, s.ToString(), null));
     }
 }
Пример #18
0
        /// <summary>
        /// Parse an object from <paramref name="s"/>
        /// </summary>
        public T ParseAttributes <T>(XmlReader r, DatatypeR2FormatterParseResult result) where T : ANY, IPrimitiveDataValue, IQuantity, new()
        {
            string val = null;

            // Get the value
            if (r.GetAttribute("value") != null)
            {
                val = r.GetAttribute("value");
            }

            // Parse the QTY part
            QTYFormatter baseFormatter = new QTYFormatter();

            baseFormatter.Host = this.Host;

            // Parse attributes part of QTY
            T retVal = baseFormatter.ParseAttributes <T>(r, result);

            IRealValue rvRetVal = retVal as IRealValue;

            // If the value was interpreted
            if (!String.IsNullOrEmpty(val))
            {
                try
                {
                    retVal.Value = Util.FromWireFormat(val, retVal.GetType().GetProperty("Value").PropertyType);
                    if (rvRetVal != null && val.Contains(DatatypeR2Formatter.FormatterCulture.NumberFormat.NumberDecimalSeparator))
                    {
                        rvRetVal.Precision = val.Length - val.IndexOf(DatatypeR2Formatter.FormatterCulture.NumberFormat.NumberDecimalSeparator) - 1;
                    }
                }
                catch (Exception e)
                {
                    result.Code = ResultCode.Error;
                    result.AddResultDetail(new ResultDetail(ResultDetailType.Error, e.Message, r.ToString(), e));
                }
            }

            // REturn the retVal
            return(retVal);
        }
Пример #19
0
        // Strips MathML tags from the source and replaces the equations with the content
        // found in the <!-- eqn: :--> comments in the docs.
        // Todo: Some simple MathML tags do not include comments, find a solution.
        // Todo: Some files include more than 1 function - find a way to map these extra functions.
        public string ProcessFile(string file)
        {
            if (LastFile == file)
            {
                return(Text);
            }

            LastFile = file;
            Text     = File.ReadAllText(file);

            Match m = remove_mathml.Match(Text);

            while (m.Length > 0)
            {
                string removed = Text.Substring(m.Index, m.Length);
                Text = Text.Remove(m.Index, m.Length);
                int equation = removed.IndexOf("eqn");
                if (equation > 0)
                {
                    // Find the start and end of the equation string
                    int eqn_start = equation + 4;
                    int eqn_end   = removed.IndexOf(":-->") - equation - 4;
                    if (eqn_end < 0)
                    {
                        // Note: a few docs from man4 delimit eqn end with ": -->"
                        eqn_end = removed.IndexOf(": -->") - equation - 4;
                    }
                    if (eqn_end < 0)
                    {
                        Console.WriteLine("[Warning] Failed to find equation for mml.");
                        goto next;
                    }

                    string eqn_substring = removed.Substring(eqn_start, eqn_end);
                    Text = Text.Insert(m.Index, "<![CDATA[" + eqn_substring + "]]>");
                }

next:
                m = remove_mathml.Match(Text);
            }

            XmlReader doc = null;

            try
            {
                // The pure XmlReader is ~20x faster than the XmlTextReader.
                doc = XmlReader.Create(new StringReader(Text), settings);
                //doc = new XmlTextReader(new StringReader(text));

                using (StringWriter sw = new StringWriter())
                {
                    xslt.Transform(doc, null, sw);
                    Text = sw.ToString().TrimEnd('\n');
                    return(Text);
                }
            }
            catch (XmlException e)
            {
                Console.WriteLine(e.ToString());
                Console.WriteLine(doc.ToString());
                return(String.Empty);
            }
        }
Пример #20
0
        public virtual IGraphable ParseObject(XmlReader r, Type useType, Type interactionContext, XmlIts1FormatterParseResult resultContext)
        {
            ThrowIfDisposed();


            // Find a helper
            string typeName = GetStructureName(useType);

            IXmlStructureFormatter ixsf = null;
            
            // xsi type? - We want to adjust the type based on this value
            try
            {
                string xsiType = r.GetAttribute("type", NS_XSI);
                // Is this model / type registered somewhere ?
                if ((this.Settings & SettingsType.AlwaysCheckForOverrides) != 0 && xsiType == null &&
                    !typeof(ANY).IsAssignableFrom(useType))
                    xsiType = this.CreateXSITypeName(useType, interactionContext, r as IXmlNamespaceResolver);

                if (xsiType != null)
                {
                    if (useType.IsInterface || typeof(ANY).IsAssignableFrom(useType)) // HACK: We don't override the use type for ANY derivatives as some types are special and require special typing
                        ixsf = this.GetAdjustedFormatter(xsiType); //Util.ParseXSITypeName(r.GetAttribute("type", NS_XSI));
                    else
                        useType = this.ParseXSITypeName(xsiType, r as IXmlNamespaceResolver);
                }
                else
                    ixsf = (IXmlStructureFormatter)this.GraphAides.Find(t => t.HandleStructure.Contains(typeName));
            }
            catch (Exception e)
            {
                resultContext.AddResultDetail(new ResultDetail(ResultDetailType.Error, e.Message, r.ToString(), e));
            }

            string currentPath = r is XmlStateReader ? (r as XmlStateReader).CurrentPath : r.Name;
            // Does a helper have it?
            if (ixsf != null)
            {
                ixsf.Host = this;
                var aideResult = ixsf.Parse(r, useType);
                resultContext.AddResultDetail(aideResult.Details);
                return aideResult.Structure;
            }

#if WINDOWS_PHONE
            ITypeFormatter formatter = m_codeGeneratorFormatter.GetFormatter(useType);
            if (formatter == null)
                formatter = new ReflectFormatter();
#else
            ITypeFormatter formatter = m_codeGeneratorFormatter.GetFormatter(useType);
            // Is there a formatter and if there is not a formatter 
            // can we create one?
            if (formatter == null && (Settings & SettingsType.UseGeneratorFormat) == SettingsType.UseGeneratorFormat)
                s_threadPool.QueueUserWorkItem((WaitCallback)delegate(object state)
                {
                    BuildCache(new Type[] { (Type)state });
                }, useType);
            // If there is no connector can we use reflection?
            if (formatter == null && (Settings & SettingsType.UseReflectionFormat) == SettingsType.UseReflectionFormat)
                formatter = new ReflectFormatter();
            else if (formatter == null && (Settings & SettingsType.UseGeneratorFormat) == SettingsType.UseGeneratorFormat)
            {
                s_threadPool.WaitOne();
                formatter = m_codeGeneratorFormatter.GetFormatter(useType);
            }
#endif
            if (formatter == null)
                throw new InvalidOperationException(string.Format("Couldn't format '{0}' at {1}, verify formatter settings", useType.FullName, r.ToString()));

            // Parse using the formatter
            formatter.Host = this;

            // Parse the object
            IGraphable result = (IGraphable)formatter.Parse(r, useType, interactionContext, resultContext);

            IResultDetail[] details = null;
            if (details != null && result == null || ValidateConformance && (!formatter.Validate(result, currentPath, out details)))
                resultContext.AddResultDetail(details.Length > 0 ? details : new IResultDetail[] { new ResultDetail(ValidateConformance ? ResultDetailType.Error : ResultDetailType.Warning, String.Format("Couldn't parse type '{0}'", useType.ToString()), currentPath) });

            
            return result;
        }
Пример #21
0
        public T Parse <T>(XmlReader xr, DatatypeFormatterParseResult result) where T : ANY, new()
        {
            ANYFormatter baseFormatter = new ANYFormatter(); // Base formatter
            T            retVal        = baseFormatter.Parse <T>(xr, result);

            // If it is null return the null flavor
            if (retVal.NullFlavor != null)
            {
                return(retVal);
            }

            PropertyInfo pi = typeof(T).GetProperty("Value");

            try
            {
                // Value
                if (xr.GetAttribute("value") != null)
                {
                    pi.SetValue(retVal, Util.FromWireFormat(xr.GetAttribute("value"), pi.PropertyType), null);
                }
            }
            catch (Exception e)
            {
                result.AddResultDetail(new ResultDetail(ResultDetailType.Error, e.Message, xr.ToString(), e));
            }
            return(retVal);
        }
Пример #22
0
        private void button1_Click(object sender, EventArgs e)
        {
            //useKleber(1, 200);
            lbl_Result.Text = msg_InProgress;
            var excel = new ExcelQueryFactory(sourceFile)
            {
                DatabaseEngine          = LinqToExcel.Domain.DatabaseEngine.Ace,
                TrimSpaces              = LinqToExcel.Query.TrimSpacesType.Both,
                UsePersistentConnection = true,
                ReadOnly = true
            };
            var address        = from p in excel.Worksheet <Address>(0) select p;
            int combi          = 0;
            int lowerLimit     = 1;
            int CountOfRecords = address.Count();//get count of records in excell sheet

            //the records require to be divide by 50 - as Kleber can process only 50 records at a time.

            int remainder = CountOfRecords % 20;

            int quotient = CountOfRecords / 20;

            try
            {
                InitializeExcel();
            }
            catch (Exception ex)
            {
                lbl_Result.Text = msg_Failure;
            }

            if (quotient > 0) //the quotitent is more than 1 -meaning the number of cycles loop
            {
                for (int j = 1; j <= quotient; j++)
                {
                    useKleber(counter, (counter + 19));
                    counter = counter + 20;
                }

                if (remainder > 0)
                {
                    useKleber(((quotient * 20) + 1), ((quotient * 20) + remainder));
                }
            }
            else
            {
                useKleber(1, remainder);
            }

            FinalDtResponseXml = "<EmbeddedByVinnies>" + FinalDtResponseXml + "</EmbeddedByVinnies>";

            StringBuilder XmlResponseStringBuilder = new StringBuilder();
            int           ResultCounter            = 0;
            string        responseFetchedReqId     = null;
            string        responseFetchedValue     = null;
            string        resultFetchedName        = null;
            string        resultFetchedValue       = null;

            int position = 1;

            XmlReader XmlReader = XmlReader.Create(new StringReader(FinalDtResponseXml));

            try
            {
                while (XmlReader.Read())
                {
                    lastRow += 1;
                    if (XmlReader.IsStartElement())
                    {
                        switch (XmlReader.Name)
                        {
                        case "DtResponse":
                            //Console.WriteLine("DT RESPONSE");
                            if (XmlReader.HasAttributes)
                            {
                                position = 1;
                                while (XmlReader.MoveToNextAttribute())
                                {
                                    switch (XmlReader.Name)
                                    {
                                    case "RequestId":
                                        responseFetchedReqId = XmlReader.Value;

                                        break;
                                    }
                                }
                                XmlReader.MoveToElement();
                            }
                            //Console.WriteLine(DisplayDoubleDividerString);
                            break;

                        case "Result":

                            //Console.WriteLine("RESULT " + ResultCounter);
                            position = Convert.ToInt32(responseFetchedReqId); position++;
                            if (XmlReader.HasAttributes)
                            {
                                //position = 1 ;
                                while (XmlReader.MoveToNextAttribute())
                                {
                                    string DPIDFetched = XmlReader["DPID"].ToString();;

                                    if (DPIDFetched != String.Empty)
                                    {
                                        switch (XmlReader.Name)
                                        {
                                        case "AddressLine":

                                            resultFetchedName  = XmlReader.Name;
                                            resultFetchedValue = XmlReader.Value;

                                            MySheet.Cells[position, 10] = resultFetchedValue;
                                            break;

                                        case "City":

                                            resultFetchedName  = XmlReader.Name;
                                            resultFetchedValue = XmlReader.Value;

                                            MySheet.Cells[position, 13] = resultFetchedValue;
                                            break;

                                        case "Postcode":

                                            resultFetchedName  = XmlReader.Name;
                                            resultFetchedValue = XmlReader.Value;

                                            MySheet.Cells[position, 15] = resultFetchedValue;
                                            break;

                                        case "State":

                                            resultFetchedName  = XmlReader.Name;
                                            resultFetchedValue = XmlReader.Value;

                                            MySheet.Cells[position, 14] = resultFetchedValue;
                                            break;

                                        case "DPID":

                                            resultFetchedName           = XmlReader.Name;
                                            resultFetchedValue          = XmlReader.Value;
                                            MySheet.Cells[position, 16] = resultFetchedValue;
                                            ResultCounter++;
                                            break;
                                        }
                                    }
                                }
                                XmlReader.MoveToElement();
                            }
                            //Console.WriteLine(DisplayDividerString);
                            break;
                        }
                    }
                    MyBook.Save();
                    ResultCounter++;
                }

                MyBook.Save();
                string XMLReaderDump = XmlReader.ToString();
                XmlReader.Dispose();

                MyBook.Saved = true;
                MyBook.Close();
                //MySheet.Unprotect();
                MyApp.Quit();
                lbl_Result.Text = msg_Success;//"Job completed succesfully";
            }
            catch (Exception ex)
            {
                XmlReader.Dispose();

                //MyBook.Saved = true;
                MyBook.Close();
                //MySheet.Unprotect();
                MyApp.Quit();
                lbl_Result.Text = msg_Failure;// "Job couldnt be completed . Encountered errors";
            }
        }
Пример #23
0
 public void Load(XmlReader reader)
 {
     SettingsXml = reader.ToString();
 }
Пример #24
0
        private void ParseProduct(XmlReader reader)
        {
            /*
             * There are 2380 products in the Fusepump feed and only 861 in our catalogue table
             * I need to introduce a flag that will restrict the updating of products to only those in the catalogue
             * At present all products in the Fusepump feed will be created
             */
            string strProductSKU = "";
            string strCareInstructions = "abc";
            try
            {
                //reader.ReadToDescendant("careInstructions");
                string strProduct = reader.ToString();
                reader.ReadToFollowing("productsku");
                strProductSKU = reader.ReadElementContentAsString();
                reader.ReadToFollowing("product_info");
                strCareInstructions = reader.ReadElementContentAsString();
                recordsRead++;

            /*                reader.ReadToNextSibling("sku");
                var sku = reader.ReadString(); // asin
                int intProductID = -1;
                intProductID = fetchProductID(sku);*/

            /*                // Create a new Product if not present
                string strSQL = "";
                if (intProductID == -1)
                {
                    // Need to create and amend as the parseOptions() routine needs to update an existing product
                    SqlConnection con3DB = new SqlConnection(MS.DHC.Configuration.Database.WorkerConnection);
                    con3DB.Open();
                    SqlCommand sqlComm3 = new SqlCommand();
                    sqlComm3 = con3DB.CreateCommand();
                    strSQL = "insert into product (ASIN) values ("
                                + "'" + sku + "')";
                    productsCreated++;
                    sqlComm3.CommandText = strSQL;

                    try
                    {
                        sqlComm3.ExecuteNonQuery();
                    }
                    catch (Exception e)
                    {
                        throw new Exception("oops!");
                    }
                    con3DB.Close();
                    intProductID = fetchProductID(sku);
                }*/

                // TODO <delivery_services> entity present with data = true
                // Now in MS Web service
                reader.ReadToDescendant("delivery_services");
            //                reader.ReadToNextSibling("dlv");
            //                string strDeliveryAvailable = reader.ReadString();

                // TODO Promotions entity. Now in MS Web service
            //                reader.ReadToNextSibling("promotion");
            //                var promotion = reader.ReadString();

                this.ParseSKUs(reader, strProductSKU);

                reader.ReadToNextSibling("storeCollection");
                string strStoreCollection = reader.ReadElementContentAsString();

                reader.ReadToNextSibling("safetyInformation");
                string strSafetyInformation = reader.ReadElementContentAsString();

                reader.ReadToNextSibling("returns");
                string strReturns = reader.ReadElementContentAsString();

                reader.ReadToNextSibling("returnsPolicy");
                string strReturnsPolicy = reader.ReadElementContentAsString();

                // Update the Product information
            /*                SqlConnection con2DB = new SqlConnection(MS.DHC.Configuration.Database.WorkerConnection);
                con2DB.Open();
                SqlCommand sqlComm = new SqlCommand();
                sqlComm = con2DB.CreateCommand();
                strSQL = "UPDATE product SET " +
                                        "CareInstructions = '" + careInstructions + "'"
                                        + ", TCode = '" + productCode + "'"
                                        + ", deliveryAvailable = '" + deliveryAvailable + "'"
                                        + ", promotion = '" + promotion + "'"
                                        + ", storeCollection = '" + storeCollection + "'"
                                        + ", safetyInformation = '" + safetyInformation + "'"
                                        + ", returns = '" + returns + "'"
                                        + ", returnsPolicy = '" + returnsPolicy + "'";*/

                /*            if (strCareInstruction != null)
                            {
                                strSQL = strSQL + ", CareInstructions = '" + strCareInstruction + "'";
                            }*/

            /*                strSQL = strSQL + " where ID = '" + intProductID + "'";
                productsAmended++;

                sqlComm.CommandText = strSQL;

                try
                {
                    sqlComm.ExecuteNonQuery();
                }
                catch (Exception e)
                {
                    throw new Exception("oops!");
                }
                con2DB.Close();*/
            }
            catch (Exception ex)
            {
                throw new Exception("help");
            }
        }
Пример #25
0
        public void XML2ON(XmlReader xmlReader, double dtdVersion, bool checkMissingArguments)
        {
            string XMLTAG = "";

            // Check the elements arguments of the request
            try
            {
                if ((!xmlReader.IsStartElement(ONXml.XMLTAG_ARGUMENTS)) && (!xmlReader.IsStartElement(ONXml.XMLTAG_FILTERVARIABLES)))
                {
                    throw new ONXMLNavFilterException(null, xmlReader.ToString(), ONXml.XMLTAG_ARGUMENTS, ONXml.XMLTAG_FILTERVARIABLES);
                }
            }
            catch
            {
                throw new ONXMLNavFilterException(null, xmlReader.ToString(), ONXml.XMLTAG_ARGUMENTS, ONXml.XMLTAG_FILTERVARIABLES);
            }

            if (xmlReader.IsEmptyElement)             // Service dont have arguments
            {
                xmlReader.ReadElementString();
                return;
            }

            if (xmlReader.IsStartElement(ONXml.XMLTAG_ARGUMENTS))
            {
                xmlReader.ReadStartElement(ONXml.XMLTAG_ARGUMENTS);
                XMLTAG = ONXml.XMLTAG_ARGUMENT;
            }
            else if (xmlReader.IsStartElement(ONXml.XMLTAG_FILTERVARIABLES))
            {
                xmlReader.ReadStartElement(ONXml.XMLTAG_FILTERVARIABLES);
                XMLTAG = ONXml.XMLTAG_FILTERVARIABLE;
            }

            // While there are arguments to solve ...
            string lName;

            while (xmlReader.IsStartElement(XMLTAG))
            {
                string lXmlType;
                try
                {
                    if (dtdVersion <= 2.0)
                    {
                        lName = xmlReader.GetAttribute(ONXml.XMLATT_NAME_DTD20);
                    }
                    else
                    {
                        lName = xmlReader.GetAttribute(ONXml.XMLATT_NAME);
                    }

                    lXmlType = xmlReader.GetAttribute(ONXml.XMLATT_TYPE);

                    if ((mIdClass == "") && (mIdService == ""))
                    {
                        string             lClass = "";
                        DataTypeEnumerator lType  = new DataTypeEnumerator();
                        if (string.Compare(lXmlType, "autonumeric", true) == 0)
                        {
                            lType = DataTypeEnumerator.Autonumeric;
                        }
                        else if (string.Compare(lXmlType, "int", true) == 0)
                        {
                            lType = DataTypeEnumerator.Int;
                        }
                        else if (string.Compare(lXmlType, "bool", true) == 0)
                        {
                            lType = DataTypeEnumerator.Bool;
                        }
                        else if (string.Compare(lXmlType, "blob", true) == 0)
                        {
                            lType = DataTypeEnumerator.Blob;
                        }
                        else if (string.Compare(lXmlType, "date", true) == 0)
                        {
                            lType = DataTypeEnumerator.Date;
                        }
                        else if (string.Compare(lXmlType, "datetime", true) == 0)
                        {
                            lType = DataTypeEnumerator.DateTime;
                        }
                        else if (string.Compare(lXmlType, "nat", true) == 0)
                        {
                            lType = DataTypeEnumerator.Nat;
                        }
                        else if (string.Compare(lXmlType, "real", true) == 0)
                        {
                            lType = DataTypeEnumerator.Real;
                        }
                        else if (string.Compare(lXmlType, "password", true) == 0)
                        {
                            lType = DataTypeEnumerator.Password;
                        }
                        else if (string.Compare(lXmlType, "string", true) == 0)
                        {
                            lType = DataTypeEnumerator.String;
                        }
                        else if (string.Compare(lXmlType, "text", true) == 0)
                        {
                            lType = DataTypeEnumerator.Text;
                        }
                        else if (string.Compare(lXmlType, "time", true) == 0)
                        {
                            lType = DataTypeEnumerator.Time;
                        }
                        else
                        {
                            lType = DataTypeEnumerator.OID;
                        }

                        xmlReader.ReadStartElement(XMLTAG);
                        if (lType == DataTypeEnumerator.OID)
                        {
                            lClass = xmlReader.GetAttribute("Class");
                        }

                        mArgumentList.Add(lName, new ONArgumentInfo(lName, true, lType, 1000, lClass, "", ""));
                    }
                    else
                    {
                        xmlReader.ReadStartElement(XMLTAG);
                    }
                }
                catch (Exception e)
                {
                    throw new ONXMLStructureException(e, ONXml.XMLATT_NAME);
                }

                try
                {
                    ReadArgument(xmlReader, dtdVersion, lName, lXmlType);
                }
                catch (Exception e)
                {
                    if (e.GetType() == typeof(ONInstanceNotExistException))
                    {
                        throw;
                    }
                    else
                    {
                        throw new ONArgumentException(e, lName);
                    }
                }
                xmlReader.ReadEndElement();                 // Argument
            }

            xmlReader.ReadEndElement();             // Arguments

            // Check the change detection items of the request
            if (xmlReader.IsStartElement(ONXml.XMLTAG_CHANGEDETECTIONITEMS))
            {
                if (xmlReader.IsEmptyElement)                 // Service dont have change detection items
                {
                    xmlReader.ReadElementString();
                    return;
                }

                if (xmlReader.IsStartElement(ONXml.XMLTAG_CHANGEDETECTIONITEMS))
                {
                    xmlReader.ReadStartElement(ONXml.XMLTAG_CHANGEDETECTIONITEMS);
                    XMLTAG = ONXml.XMLTAG_CHANGEDETECTIONITEM;
                }

                // While there are change detection items to solve ...
                while (xmlReader.IsStartElement(XMLTAG))
                {
                    try
                    {
                        lName = xmlReader.GetAttribute(ONXml.XMLATT_NAME);
                        xmlReader.ReadStartElement(XMLTAG);
                    }
                    catch (Exception e)
                    {
                        throw new ONXMLStructureException(e, ONXml.XMLATT_NAME);
                    }

                    try
                    {
                        ReadChangeDetectionItem(xmlReader, dtdVersion, lName);
                    }
                    catch (Exception e)
                    {
                        throw new ONArgumentException(e, lName);
                    }
                    xmlReader.ReadEndElement();                     // ChangeDetectionItem
                }

                xmlReader.ReadEndElement();                 // ChangeDetectionItems
            }

            // Comprobations over the arguments
            foreach (DictionaryEntry lElem in mArgumentList)
            {
                ONArgumentInfo lArg = (ONArgumentInfo)lElem.Value;

                // Check if it is all the arguments
                if (lArg.Value == null)
                {
                    if (checkMissingArguments)
                    {
                        throw new ONMissingArgumentException(null, lArg.IdArgument, lArg.Alias);
                    }
                    else
                    {
                        continue;
                    }
                }

                if (lArg.Value.Value == null && lArg.Null == false)
                {
                    throw new ONNotNullArgumentException(null, mIdService, mIdClass, lArg.IdArgument, mAlias, mClassAlias, lArg.Alias);
                }

                if (lArg.MaxLength > 0)
                {
                    ONString lString = lArg.Value as ONString;
                    //MARTA DEFECT 3766
                    //ONText lText = lArg.Value as ONText;
                    if (((object)lString != null) && (lString.TypedValue != null) && (lString.TypedValue.Length > lArg.MaxLength))
                    {
                        throw new ONMaxLenghtArgumentException(null, lArg.IdArgument, lArg.Alias, lArg.MaxLength.ToString());
                    }
                    //MARTA DEFECT 3766
                    //if (((object) lText != null) && (lText.TypedValue != null) && (lText.TypedValue.Length > lArg.MaxLength))
                    //	throw new ONMaxLenghtArgumentException(null, lArg.IdArgument, lArg.Alias, lArg.MaxLength.ToString());
                }
            }
        }
Пример #26
0
 /// <summary>
 /// Parse elements that are inline in the read loop
 /// </summary>
 public void ParseElementsInline(XmlReader s, IQuantity retVal, DatatypeR2FormatterParseResult result)
 {
     if (s.LocalName == "expression") // Format using ED
     {
         var hostResult = this.Host.Parse(s, typeof(ED));
         result.Code = hostResult.Code;
         result.AddResultDetail(hostResult.Details);
         retVal.Expression = hostResult.Structure as ED;
     }
     else if (s.LocalName == "originalText") // display name
     {
         var hostResult = this.Host.Parse(s, typeof(ED));
         result.Code = hostResult.Code;
         result.AddResultDetail(hostResult.Details);
         retVal.OriginalText = hostResult.Structure as ED;
     }
     else if (s.LocalName == "uncertainty") // Translation
     {
         var hostResult = Host.Parse(s, retVal.GetType());
         result.Code = hostResult.Code;
         result.AddResultDetail(hostResult.Details);
         retVal.Uncertainty = hostResult.Structure as IQuantity;
     }
     else if (s.LocalName == "uncertainRange") // Uncertainty range
     {
         var hostResult = Host.Parse(s, typeof(IVL <IQuantity>));
         result.Code = hostResult.Code;
         result.AddResultDetail(hostResult.Details);
         retVal.UncertainRange = hostResult.Structure as IVL <IQuantity>;
     }
     else if (s.NodeType == System.Xml.XmlNodeType.Element)
     {
         result.AddResultDetail(new NotImplementedElementResultDetail(ResultDetailType.Warning, s.LocalName, s.NamespaceURI, s.ToString(), null));
     }
 }