Inheritance: INullable, IXmlSerializable
Beispiel #1
1
 [Fact] // .ctor (Stream)
 public void Constructor2_Stream_Empty()
 {
     MemoryStream ms = new MemoryStream();
     SqlXml xmlSql = new SqlXml(ms);
     Assert.False(xmlSql.IsNull);
     Assert.Equal(string.Empty, xmlSql.Value);
 }
    public static String XMLRecordNewAttribute(SqlXml DataXml, String ATag, String AAttributeName, String AAttributeValue)
    {
        if (DataXml.IsNull) return null;

        if(String.IsNullOrWhiteSpace(ATag))
          throw new System.Exception("Parameter @Tag can't be null or empty");

        if(String.IsNullOrWhiteSpace(AAttributeName))
          throw new System.Exception("Parameter @AttributeName can't be null or empty");

        if(AAttributeValue == null) //return DataXml.Value;
          throw new System.Exception("Parameter @AttributeValue can't be null");

        XmlDocument UpdateDoc = new XmlDocument();
        XmlNode UpdateRoot = UpdateDoc.CreateElement("RECORDS");
        UpdateRoot.InnerXml = DataXml.Value;

        for(int I = 0; I < UpdateRoot.ChildNodes.Count; I++)
        {
          XmlNode UpdateNode = UpdateRoot.ChildNodes[I];
          if(UpdateNode.LocalName == ATag)
          {
        XmlAttribute Attribute = UpdateDoc.CreateAttribute(AAttributeName);
        Attribute.Value = AAttributeValue;
        UpdateNode.Attributes.Append(Attribute);
          }
        }

        return UpdateRoot.ChildNodes.Count == 0 ? null : UpdateRoot.InnerXml;
    }
    public static String XMLRecordInnerXml(SqlXml AXml, String ATag)
    {
        XmlReader LReader = AXml.CreateReader();
        LReader.Read();
        while(!LReader.EOF)
        {
          if(LReader.NodeType == XmlNodeType.Element)
          {
        if (LReader.Name == ATag)
        {
          String LInnerXml = LReader.ReadInnerXml();
          if (String.IsNullOrWhiteSpace(LInnerXml))
            return null;
          else
            return LInnerXml;
        }
        else
        {
          if (!LReader.IsEmptyElement)
            LReader.Skip();
          else
            LReader.Read();
        }
          }
          else
        LReader.Read();
        }

        return null;
    }
 /// <summary>
 /// Return XML for an array of items
 /// </summary>
 /// <param name="List">List of items</param>
 /// <param name="ListName">Name of the list</param>
 /// <param name="ItemName">Name of the item in the list.</param>
 /// <returns></returns>
 public static SqlXml GetXml(IEnumerable List, string ListName, string ItemName)
 {
     //We don't use 'using' or dispose or close the stream,
     //since it leaves in the return variable
     MemoryStream stream = new MemoryStream();
     SqlXml Result = null;
     try
     {
         using (XmlWriter writer = XmlWriter.Create(stream))
         {
             writer.WriteStartElement(ListName);
             foreach (object obj in List)
             {
                 writer.WriteElementString(ItemName, obj.ToString());
             }
             writer.WriteEndElement();
             Result = new SqlXml(stream);
         }
     }
     catch (Exception ex)
     {
         throw (ex);
     }
     finally
     {
     }
     return Result;
 }
		internal SqlTriggerContext (TriggerAction triggerAction, bool[] columnsUpdated, 
					SqlXml eventData)
		{
			this.triggerAction = triggerAction;
			this.columnsUpdated = columnsUpdated;
			this.eventData = eventData;
		}
Beispiel #6
0
        public static SqlXml ExecScript(SqlString Sql, SqlXml Options, SqlXml Input)
        {
            var XOutput = new XDocument(
                new XElement("root",
                    new XElement("content")));

            try
            {
                using (var q = new SqlCommand())
                {
                    q.Connection = new SqlConnection("context connection=true");
                    q.CommandType = CommandType.Text;

                    q.CommandText = Sql.Value;
                    q.InitOptions(Options.Value);
                    q.Parameters.SetInput(Input.Value);

                    q.Connection.Open();
                    q.ExecuteNonQuery();
                    XOutput.Root.Add(q.Parameters.GetOutput());
                    q.Connection.Close();
                }
            }
            catch (Exception ex)
            {
                XOutput.Root.Add(ex.ExceptionSerialize());
            }

            return new SqlXml(XOutput.CreateReader());
        }
Beispiel #7
0
        public static SqlXml ExecQuery(SqlString Sql, SqlXml Options, SqlXml Input)
        {
            var XOutput = new XDocument(new XElement("root"));

            try
            {
                using (var q = new SqlCommand())
                {
                    q.Connection = new SqlConnection("context connection=true");
                    q.CommandType = CommandType.Text;

                    q.CommandText = Sql.Value;
                    q.InitOptions(Options.Value);
                    q.Parameters.SetInput(Input.Value);

                    q.Connection.Open();
                    var Result = q.ExecuteXmlReader();
                    if (Result.Read())
                        XOutput.Root.Element("content").Add(
                            XElement.Load(Result, LoadOptions.None));
                    q.Connection.Close();
                }
            }
            catch (Exception ex)
            {
                XOutput.Root.Add(ex.ExceptionSerialize());
            }

            return new SqlXml(XOutput.CreateReader());
        }
 public static SqlDateTime ParamDateTimeTemp(SqlXml Xml, SqlString Name)
 {
     String ValueType;
       String Value = GetValueFromXMLAttribute(Xml, Name, out ValueType);
       if (Value == null) return new SqlDateTime();
       SqlDateTime Result;
       try
       {
     Result = new SqlDateTime(XmlConvert.ToDateTime(Value, XmlDateTimeSerializationMode.RoundtripKind));
       }
       catch (Exception Error)
       {
     throw new System.Exception("Error convert Param = \"" + Name.Value.ToString() + "\" Value = \"" + Value.ToString() + "\" to DateTime: " + Error.Message);
       }
       if (ValueType != null && ValueType != "")
       {
     // year, month, day, hour, minute, second
     switch (ValueType)
     {
       case "1": return Result.Value.Date.AddDays(1);
       default: return Result;
     }
       }
       return Result;
 }
 override public void SetCapacity(int capacity) {
     SqlXml[] newValues = new SqlXml[capacity];
     if (null != values) {
         Array.Copy(values, 0, newValues, 0, Math.Min(capacity, values.Length));
     }
     values = newValues;
 }
 /// <summary>
 /// Constructs the storage representation from client side objects.
 /// </summary>
 /// <param name="name">Schema info name.</param>
 /// <param name="shardingSchemaInfo">Schema info represented in XML.</param>
 internal DefaultStoreSchemaInfo(
     string name,
     SqlXml shardingSchemaInfo)
 {
     this.Name = name;
     this.ShardingSchemaInfo = shardingSchemaInfo;
 }
Beispiel #11
0
        public static void CreateActivity(SqlString url, SqlString username, SqlString password, SqlString token, SqlString employeeId, SqlXml messageBlob)
        {
            IChatterService service = new ChatterService(url.Value);
            service.AllowUntrustedConnection();
            service.Login(username.Value, password.Value, token.Value);

            CreateProfileActivity(service, employeeId.Value, messageBlob.Value);
        }
Beispiel #12
0
		public void Constructor2_Stream_ASCII ()
		{
			string xmlStr = "<Employee><FirstName>Varadhan</FirstName><LastName>Veerapuram</LastName></Employee>";
			MemoryStream stream = new MemoryStream (Encoding.ASCII.GetBytes (xmlStr));
			SqlXml xmlSql = new SqlXml (stream);
			Assert.IsFalse (xmlSql.IsNull, "#1");
			Assert.AreEqual (xmlStr, xmlSql.Value, "#2");
		}
Beispiel #13
0
 [Fact] // .ctor (Stream)
        //[Category ("NotDotNet")] // Name cannot begin with the '.' character, hexadecimal value 0x00. Line 1, position 2
 public void Constructor2_Stream_Unicode()
 {
     string xmlStr = "<Employee><FirstName>Varadhan</FirstName><LastName>Veerapuram</LastName></Employee>";
     MemoryStream stream = new MemoryStream(Encoding.Unicode.GetBytes(xmlStr));
     SqlXml xmlSql = new SqlXml(stream);
     Assert.False(xmlSql.IsNull);
     Assert.Equal(xmlStr, xmlSql.Value);
 }
Beispiel #14
0
    public static void SaveXMLTofile(SqlXml XMLData, String DestFile, Boolean Append)
    {
        StreamWriter writer = new StreamWriter(DestFile, Append, System.Text.Encoding.UTF8);
        writer.Write(@"<?xml version=""1.0"" encoding=""utf-8"" ?>");
        writer.Write(XMLData.Value);
        writer.Close();

        SqlContext.Pipe.Send(String.Format("XML text successfully saved to file '{0}'", DestFile));
    }
        public void TestCreateActivityWithMissingBody()
        {
            string xml =
                "<activity xmlns=\"http://ns.opensocial.org/2008/opensocial\"><postedTime>1310597396000</postedTime><title>Edited their narrative</title></activity>";
            var xmlReader = XmlTextReader.Create(new System.IO.StringReader(xml));

            SqlXml messageBlob = new SqlXml(xmlReader);

            //ChatterSqlProcedures.CreateActivity(_url, _username, _password, _token, _employeeId, messageBlob, _pmid, _title, _body);
        }
Beispiel #16
0
        private static void AddXmlParameter(string paramName, SqlCommand oCmd, XmlDocument oXd)
        {
            using (XmlNodeReader xnr = new XmlNodeReader(oXd))
            {
                System.Data.SqlTypes.SqlXml sx = new System.Data.SqlTypes.SqlXml(xnr);

                oCmd.Parameters.Add(paramName, SqlDbType.Xml);
                oCmd.Parameters[paramName].Value = sx;
            }
        }
Beispiel #17
0
 public void TestRandomUnicodeGeneration_ExecutesSuccessfully()
 {
     XmlDocument xmlDocument = new XmlDocument();
     XmlElement xmlNode = xmlDocument.CreateElement("TestNode");
     // ReSharper disable once AssignNullToNotNullAttribute
     xmlNode.InnerText = Random.RandomString(100000);
     xmlDocument.AppendChild(xmlNode);
     XmlNodeReader xmlNodeReader = new XmlNodeReader(xmlDocument);
     // The SqlXml constructor applies stricter tests to Unicode strings than Encoding.Unicode:
     // ReSharper disable once UnusedVariable
     SqlXml dummy = new SqlXml(xmlNodeReader);
 }
        private void buttonSend_Click(object sender, EventArgs e)
        {
            richTextBoxResponseHeader.Text = "";
            richTextBoxResponseBody.Text = "";
            var header = richTextBoxHeader.Text.Length > 0 ? new SqlXml(XmlReader.Create(new StringReader(richTextBoxHeader.Text))) : SqlXml.Null;
            var body = new SqlXml(XmlReader.Create(new StringReader(richTextBoxBody.Text)));

            Sql.UDF.SOAPRequest.SOAP.SOAPRequest((SqlString)textBoxUri.Text, ref header, ref body);

            richTextBoxResponseHeader.Text = header.IsNull == false ? header.Value : "" ;
            richTextBoxResponseBody.Text = body.IsNull == false ? body.Value : "";
        }
Beispiel #19
0
        public void Constructor2_Stream_Null()
        {
            SqlXml xmlSql = new SqlXml((Stream)null);
            Assert.True(xmlSql.IsNull);

            try
            {
                string value = xmlSql.Value;
                Assert.False(true);
            }
            catch (SqlNullValueException)
            {
            }
        }
 public static SqlBoolean ParamBit(SqlXml Xml, SqlString Name)
 {
     String Value = GetValueFromXML(Xml, Name);
       if (Value == null)
     return new SqlBoolean();
       else
     try
     {
       return new SqlBoolean(XmlConvert.ToBoolean(Value));
     }
     catch (Exception Error)
     {
       throw new System.Exception("Error convert Param = \"" + Name.Value.ToString() + "\" Value = \"" + Value.ToString() + "\" to Boolean: " + Error.Message);
     }
 }
 public static DateTime? ParamDateTime(SqlXml Xml, SqlString Name)
 {
     String Value = GetValueFromXML(Xml, Name);
       if (Value == null)
     return null;
       else
     try
     {
       return XmlConvert.ToDateTime(Value, XmlDateTimeSerializationMode.RoundtripKind);
     }
     catch (Exception Error)
     {
       throw new System.Exception("Error convert Param = \"" + Name.Value + "\" Value = \"" + Value + "\" to DateTime: " + Error.Message);
     }
 }
        public static void SOAPRequest(SqlString uri, ref SqlXml header, ref SqlXml body)
        {
            SqlString soapRequest = string.Empty;
            SqlString soapResponse;
            soapRequest += "<soap:Envelope ";
            soapRequest += "xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' ";
            soapRequest += "xmlns:xsd='http://www.w3.org/2001/XMLSchema' ";
            soapRequest += "xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/' ";
            soapRequest += "xmlns:encodingStyle='http://schemas.xmlsoap.org/soap/encoding' >";

            // Добавляем залоловок, если он передан
            if (!header.IsNull && header.Value != string.Empty)
                soapRequest += "<soap:Header>" + header.Value.ToString() + "</soap:Header>";

            soapRequest += "<soap:Body>";
            soapRequest += body.Value.ToString();
            soapRequest += "</soap:Body></soap:Envelope>";

            var req = WebRequest.Create(uri.ToString());

            req.Headers.Add("SOAPAction", "\"\"");
            req.ContentType = "text/xml;charset=\"utf-8\"";
            req.Method = "POST";

            // Отправляем запрос
            using (var stm = req.GetRequestStream())
            using (var stmw = new StreamWriter(stm))
                stmw.Write(soapRequest);

            // Получаем ответ
            using (var webResponse = req.GetResponse())
            using (var responseStream = new StreamReader(webResponse.GetResponseStream(), Encoding.UTF8))
                soapResponse = responseStream.ReadToEnd();

            // Удаляем неописанные namespace из ответа (ответы WEB сервисов не всегда правильны :-( )
            soapResponse = Regex.Replace(soapResponse.Value, "SOAP-ENV:", "", RegexOptions.IgnoreCase);
            soapResponse = Regex.Replace(soapResponse.Value, "SOAP:", "", RegexOptions.IgnoreCase);

            // Возвращаем данные из <Header>
            using (var r = XmlReader.Create(new StringReader(soapResponse.Value)))
                header = r.ReadToFollowing("Header") ? new SqlXml(XmlReader.Create(new StringReader(r.ReadInnerXml()))) : SqlXml.Null;

            // Возвращаем данные из <Body>
            using (var r = XmlReader.Create(new StringReader(soapResponse.Value)))
                body = r.ReadToFollowing("Body") ? new SqlXml(XmlReader.Create(new StringReader(r.ReadInnerXml()))) : SqlXml.Null;
        }
    public static SqlString fnXMLGetMessageValue(SqlXml doc, SqlInt32 lcid, SqlInt32 defaultLcid)
    {
        SqlString defaultValue = SqlString.Null;

        if (doc.IsNull)
        {
            return SqlString.Null;
        }

        using (XmlReader xr = doc.CreateReader())
        {
            while (xr.ReadToFollowing("message"))
            {
                int localLcid;
                if (xr.HasAttributes && int.TryParse(xr.GetAttribute("lcid"), out localLcid))
                {
                    if ((lcid == localLcid) && (!xr.IsEmptyElement))
                    {
                        xr.Read();
                        if (xr.NodeType == XmlNodeType.Text || xr.NodeType == XmlNodeType.Whitespace) //Message element contains text
                        {
                            return new SqlString(xr.Value);
                        }
                        return xr.NodeType == XmlNodeType.EndElement ? string.Empty : SqlString.Null;
                    }
                    if ((defaultLcid == localLcid) && (!xr.IsEmptyElement))
                    {
                        xr.Read();
                        if (xr.NodeType == XmlNodeType.Text || xr.NodeType == XmlNodeType.Whitespace) //Message element contains text
                        {
                            defaultValue = xr.Value;
                        }
                        else if (xr.NodeType == XmlNodeType.EndElement) //Message element contains no text
                        {
                            defaultValue = string.Empty;
                        }
                        else
                        {
                            defaultValue = SqlString.Null;
                        }
                    }
                }
            }
        }
        return defaultValue;
    }
 public static IEnumerable XMLRecordAttributes(SqlXml AXml)
 {
     if (AXml.IsNull) yield break;
     XmlReader LReader = AXml.CreateReader();
     XMLRecordAttribute LAttribute;
     if (LReader.Read() && LReader.NodeType == XmlNodeType.Element)
     {
       LAttribute.Index = 0;
       while (LReader.MoveToNextAttribute())
       {
     LAttribute.Index++;
     LAttribute.Name  = LReader.Name;
     LAttribute.Value = LReader.Value;
     yield return LAttribute;
       }
     }
 }
        public void TestCreateActivityWithIncorrectEmployee()
        {
            string xml =
                "<activity xmlns=\"http://ns.opensocial.org/2008/opensocial\"><postedTime>1304533194580</postedTime><title>This is Profiles test activity from ChatterSqlProceduresTest</title></activity>";
            var xmlReader = XmlTextReader.Create(new System.IO.StringReader(xml));

            SqlXml messageBlob = new SqlXml(xmlReader);

            try
            {
                //ChatterSqlProcedures.CreateActivity(_url, _username, _password, _token, "1221212", messageBlob, _pmid, _title, _body);
                Assert.Fail("CreateActivity method should throw and exception if user is not found by employee id");
            }
            catch (Exception ex)
            {
                Assert.AreEqual("Object not found, Salesforce.User, keys:1221212", ex.Message);
            }
        }
Beispiel #26
0
        public static SqlXml ExecXQuery(SqlXml Source, SqlString XQuery)
        {
            using (var q = new SqlCommand())
            {
                q.Connection = new SqlConnection("context connection=true");
                q.CommandType = CommandType.Text;

                q.CommandText =
                    String.Format("SELECT @X.query('{0}')",
                                  XQuery.Value.Replace("'", "''"));

                q.Parameters.Add("@X", SqlDbType.Xml).Direction = ParameterDirection.Input;
                q.Parameters["@X"].Value = Source.Value;

                q.Connection.Open();
                return new SqlXml(q.ExecuteXmlReader());
            }
        }
Beispiel #27
0
    public static void XMLExport(SqlXml InputXml, SqlString OutputFile)
    {
        try
            {
                if (!InputXml.IsNull && !OutputFile.IsNull)
                {

                    XmlDocument doc = new XmlDocument();
                    doc.LoadXml(InputXml.Value);

                    StringWriterWithEncoding sw = new StringWriterWithEncoding(System.Text.Encoding.GetEncoding("ISO-8859-1"));
                    XmlWriterSettings settings = new XmlWriterSettings
                    {
                        Indent = true,
                        IndentChars = "  ",
                        NewLineChars = "\r\n",
                        NewLineHandling = NewLineHandling.Replace,
                        Encoding = System.Text.Encoding.GetEncoding("ISO-8859-1")
                    };

                    using (XmlWriter writer = XmlWriter.Create(sw, settings))
                    {
                        doc.Save(writer);
                    }

                    System.IO.File.WriteAllText(OutputFile.ToString(), sw.ToString(), System.Text.Encoding.GetEncoding("ISO-8859-1"));
                }
                else
                {
                    throw new Exception("Parameters must be set");
                }
            }
            catch
            {
                throw;
            }
    }
Beispiel #28
0
        public static void DequeueMessage(
            SqlString accountName, SqlString sharedKey, SqlBoolean useHTTPS,
            SqlString queueName,
            SqlInt32 visibilityTimeoutSeconds, // we won't support peek so we should do it fast
            SqlInt32 timeoutSeconds,
            SqlGuid xmsclientrequestId)
        {
            ITPCfSQL.Azure.AzureQueueService aqs = new AzureQueueService(accountName.Value, sharedKey.Value, useHTTPS.Value);
            ITPCfSQL.Azure.Queue q = aqs.GetQueue(queueName.Value);
            Message msg = q.Get(visibilityTimeoutSeconds.Value, timeoutSeconds.Value,
                xmsclientrequestId.IsNull ? (Guid?)null : xmsclientrequestId.Value);

            if (msg == null) // empty queue
                return;

            msg.Delete(timeoutSeconds.Value,
                 xmsclientrequestId.IsNull ? (Guid?)null : xmsclientrequestId.Value);

            try // try to convert it to XML, if it fails, return a simple string
            {
                SqlXml xml;
                using (System.IO.StringReader sr = new System.IO.StringReader(msg.Body))
                {
                    using (System.Xml.XmlReader reader = System.Xml.XmlReader.Create(sr))
                    {
                        xml = new SqlXml(reader);
                    }
                }

                Utils.PushSingleRecordResult(xml.Value, System.Data.SqlDbType.Xml);
            }
            catch (Exception exce)
            {
                SqlContext.Pipe.Send("Cannot parse as XML:" + exce.Message);
                Utils.PushSingleRecordResult(msg.Body, System.Data.SqlDbType.NVarChar);
            }
        }
 public static SqlString fnXMLGetContextValue(SqlXml context, SqlString param)
 {
     if (context.IsNull || param.IsNull)
     {
         return SqlString.Null;
     }
     using (XmlReader xr = context.CreateReader())
     {
         while (xr.ReadToFollowing("contextparam"))
         {
             //                if(true) return xr.GetAttribute("key").Equals(Param.Value).ToString();
             if (xr.HasAttributes && xr.GetAttribute("key") == param.Value)
             {
                 xr.Read();
                 if (xr.NodeType == XmlNodeType.Text || xr.NodeType == XmlNodeType.Whitespace) //Message element contains text
                 {
                     return new SqlString(xr.Value);
                 }
                 return xr.NodeType == XmlNodeType.EndElement ? string.Empty : SqlString.Null;
             }
         }
     }
     return SqlString.Null;
 }
Beispiel #30
0
        public static void InsertOrReplaceEntity(
            SqlString accountName, SqlString sharedKey, SqlBoolean useHTTPS,
            SqlString tableName,
            SqlString partitionKey,
            SqlString rowKey,
            SqlXml AttributeList,
            SqlString xmsclientrequestId)
        {
            ITPCfSQL.Azure.AzureTableService ats = new AzureTableService(accountName.Value, sharedKey.Value, useHTTPS.Value);
            ITPCfSQL.Azure.Table table = ats.GetTable(tableName.Value);

            ITPCfSQL.Azure.TableEntity te = new TableEntity(partitionKey.Value, rowKey.Value);

            System.Xml.XmlDocument doc = new System.Xml.XmlDocument();
            doc.LoadXml(AttributeList.Value);

            foreach (System.Xml.XmlNode nAttrib in doc.FirstChild.ChildNodes)
            {
                te.Attributes[nAttrib.Name] = nAttrib.InnerText;
            }

            table.InsertOrUpdate(te,
                xmsclientrequestId != null ? xmsclientrequestId.Value : null);
        }
Beispiel #31
0
 public SqlXml Adjust(SqlXml value)
 {
     if (SqlDbType.Xml != SqlDbType)
         ThrowInvalidType();
     return value;
 }
Beispiel #32
0
 protected override string GetTSqlLiteral(System.Data.SqlTypes.SqlXml value, SqlVersion sqlVersion)
 {
     return(value == null ? NULL : value.Value.ToTSqlLiteral(true));
 }
Beispiel #33
0
        private static XmlDocument getXmlRecord(string connection, string keyId, string contentType, DeletedOptions deleted)
        {
            if (connection.Length <= 0)
            {
                throw new Exception("missing or invalid connection string");
            }
            if (keyId.Length <= 0)
            {
                throw new Exception("missing or invalid keyID");
            }
            if (contentType.Length <= 0)
            {
                throw new Exception("contentType must be specified");
            }

            try
            {
                XmlDocument xdOutput = new XmlDocument {
                    XmlResolver = null
                };
                StringBuilder sb = new StringBuilder();

                using (SqlCommand oCmd = new SqlCommand("getXmlRecord", new SqlConnection(connection)))
                {
                    oCmd.CommandType = CommandType.StoredProcedure;

                    oCmd.Parameters.AddWithValue("@id", keyId);
                    oCmd.Parameters.AddWithValue("@contentType", contentType);
                    oCmd.Parameters.AddWithValue("@deleted", deleted);

                    oCmd.Connection.Open();

                    System.Data.SqlClient.SqlDataReader oRdr = oCmd.ExecuteReader();



                    if (!oRdr.HasRows)
                    {
                        return(null);
                    }

                    while (oRdr.Read())
                    {
                        System.Data.SqlTypes.SqlXml sx = oRdr.GetSqlXml(0);
                        //XmlReader xr = sx.CreateReader();
                        //xr.Read();

                        sb.Append(sx.Value);
                    }


                    oRdr.Close();
                    oCmd.Connection.Close();
                }

                xdOutput.LoadXml(sb.ToString());

                return(xdOutput);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
Beispiel #34
0
        private static XmlDocument getXmlRecords(string connection, XmlDocument searchIds, string contentType, DeletedOptions deleted)
        {
            if (connection == null || connection.Length <= 0)
            {
                throw new Exception("missing or invalid connection string");
            }
            if (searchIds == null)
            {
                throw new Exception("missing or invalid searchIds Xml");
            }
            if (contentType.Length <= 0)
            {
                throw new Exception("contentType must be specified");
            }

            XmlDocument xdOutput = new XmlDocument {
                XmlResolver = null
            };
            string rootNode = contentType + "s";

            // no IDs, so save time by aborting now
            if (!searchIds.DocumentElement.HasChildNodes)
            {
                xdOutput.LoadXml(string.Format("<{0}/>", rootNode));
                return(xdOutput);
            }

            try
            {
                StringBuilder sbXml = new StringBuilder();

                using (SqlCommand oCmd = new SqlCommand("getXmlRecords", new SqlConnection(connection)))
                {
                    oCmd.CommandType = CommandType.StoredProcedure;

                    using (XmlNodeReader xnr = new XmlNodeReader(searchIds))
                    {
                        SqlXml sx = new SqlXml(xnr);

                        oCmd.Parameters.Add("@ids", SqlDbType.Xml);
                        oCmd.Parameters["@ids"].Value = sx;
                    }

                    oCmd.Parameters.AddWithValue("@contentType", contentType);
                    oCmd.Parameters.AddWithValue("@version", null);
                    oCmd.Parameters.AddWithValue("@deleted", deleted);

                    oCmd.Connection.Open();

                    System.Data.SqlClient.SqlDataReader oRdr = oCmd.ExecuteReader();

                    if (!oRdr.HasRows)
                    {
                        sbXml.Append("<" + rootNode + "/>");
                    }
                    else
                    {
                        sbXml.Append("<" + rootNode + ">");
                        while (oRdr.Read())
                        {
                            System.Data.SqlTypes.SqlXml sx = oRdr.GetSqlXml(0);
                            //XmlReader xr = sx.CreateReader();
                            //xr.Read();

                            sbXml.Append(sx.Value);
                        }
                        sbXml.Append("</" + rootNode + ">");

                        oRdr.Close();
                        oCmd.Connection.Close();
                    }
                }

                xdOutput.LoadXml(sbXml.ToString());

                return(xdOutput);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }