1

In this web application I want to send an sms to a mobile ann. This is my code of aspx.cs file:

protected void buttonSendOnClick(object sender, EventArgs e)
{
    //are required fields filled in:
    if (textboxRecipient.Text == "")
    {
         textboxError.Text += "Recipient(s) field must not be empty!\n";
         textboxError.Visible = true;
         return;
    }
        //we creating the necessary URL string:
    string ozSURL = "http://127.0.0.1"; //where Ozeki NG SMS Gateway is running
    string ozSPort = "9501"; //port number where Ozeki NG SMS Gateway is listening
    string ozUser = HttpUtility.UrlEncode("admin"); //username for successful login
    string ozPassw = HttpUtility.UrlEncode("abc123"); //user's password
    string ozMessageType = "SMS:TEXT"; //type of message
    string ozRecipients = HttpUtility.UrlEncode( textboxRecipient.Text); //who will        

 //get the message
    string ozMessageData = HttpUtility.UrlEncode(textboxMessage.Text); //body of  
 //message

     string createdURL = ozSURL + ":" + ozSPort + "/httpapi" +
          "?action=sendMessage" +
            "&username=" + ozUser +
            "&password=" + ozPassw +
            "&messageType=" + ozMessageType +
            "&recipient=" + ozRecipients +
            "&messageData=" + ozMessageData;

   try
   {
            //Create the request and send data to Ozeki NG SMS Gateway Server by HTTP 
connection
            HttpWebRequest myReq = (HttpWebRequest)WebRequest.Create(createdURL);

            //Get response from Ozeki NG SMS Gateway Server and read the answer
            HttpWebResponse myResp = (HttpWebResponse)myReq.GetResponse();
            System.IO.StreamReader respStreamReader = new 
 System.IO.StreamReader(myResp.GetResponseStream());
            string responseString = respStreamReader.ReadToEnd();
            respStreamReader.Close();
            myResp.Close();

            //inform the user
            string result = Regex.Replace(responseString, @"<[^>]*>", string.Empty);
            textboxError.Text = Server.HtmlEncode( result);
            textboxError.Visible = true;
        }
        catch (Exception)
        {
            //if sending request or getting response is not successful Ozeki NG SMS                 
  Gateway Server may do not run
            textboxError.Text = "Ozeki NG SMS Gateway Server is not running!";
            textboxError.Visible = true;
        }

    }

After I run I got text as xml doc like this

<Responses>
<Response0>
    <Action>sendMessage</Action>
    <Data>
        <AcceptReport>
            <StatusCode>0</StatusCode>
            <StatusText>Message accepted for delivery</StatusText>
            <MessageID>89c8011c-e291-44c3-ac72-cd35c76cb29d</MessageID>
            <Recipient>+85568922903</Recipient>
        </AcceptReport>
    </Data>
</Response0>
</Responses>

but I want it diplay as

Message accepted for delivery Message ID: IEUHSHIL Recipient: +441234567

So how can I do this?

Toon Krijthe
  • 52,876
  • 38
  • 145
  • 202
Toeur Tenh
  • 71
  • 4
  • 14

5 Answers5

1

with regards to one of the suggested methods in the comments, use something like this;

        XmlDocument doc = new XmlDocument();
        doc.LoadXml(load your xml document or string here);
        XmlNodeList xnList = doc.SelectNodes("Response0/Data/AcceptReport");
        foreach (XmlNode xn in xnList)
                            {
                                string status = xn["StatusTest"].InnerText;
                                string messageID = xn["MessageID"].InnerText;
                                string recipient = xn["Recipient"].InnerText;
                            }
        string finalString = string.Format("{0} Message ID: {1} Recipient {2}", status, messageID, recipient);

This will create an XML document based on the document or string you load into it. XmlNodeList allows you to basically pick out any XmlElements that you want, and in this case you format a string with the node information, in the format that you requested

Kestami
  • 2,045
  • 3
  • 32
  • 47
0

Try something like this

       string stext = @"<Responses>
    <Response0>
     <Action>sendMessage</Action>
       <Data>
        <AcceptReport>
         <StatusCode>0</StatusCode>
         <StatusText>Message accepted for delivery</StatusText>
         <MessageID>89c8011c-e291-44c3-ac72-cd35c76cb29d</MessageID>
         <Recipient>+85568922903</Recipient>
       </AcceptReport>
      </Data>
    </Response0>
   </Responses>";
       XElement xm = XElement.Parse(stext);
       string sout="";
       sout = xm.Descendants("StatusText").First().Value + " Message ID:" + xm.Descendants("MessageID").First().Value + " Recipient:" + xm.Descendants("Recipient").First().Value;
Likurg
  • 2,742
  • 17
  • 22
0

How about using XmlDocument class with XPath?

Client code:

XmlDocument xmlDocument = new XmlDocument();
xmlDocument.Load(...);  // Load from file, stream, etc.
string status = GetDeliveryStatus(xmlDocument);

XML document processing:

private static string GetDeliveryStatus(XmlDocument xmlDocument)
{
    XmlNode reportNode = xmlDocument.SelectSingleNode("/Responses/Response0/Data/AcceptReport");
    if (reportNode == null)
        throw new ArgumentException("AcceptReport node is absent", xmlDocument);

    var messageIDNode = reportNode["MessageID"];
    if (messageIDNode == null)
        throw new ArgumentException("MessageID node is absent", xmlDocument);
    var messageID = messageIDNode.InnerText;

    var recipientNode = reportNode["Recipient"];
    if (recipientNode == null)
        throw new ArgumentException("Recipient node is absent", xmlDocument);
    var recipient = recipientNode.InnerText;

    var result = string.Format("Message accepted for delivery Message ID: {0} Recipient: {1}", messageID, recipient);
    return result;
}
0

you got a json result :

You converted it into string and then replaced braces with spaces , Thats why you got xml.

Recheck these lines :

 //inform the user
            string result = Regex.Replace(responseString, @"<[^>]*>", string.Empty);
            textboxError.Text = Server.HtmlEncode( result);

Check ResponseString and extract the required data from it.

Helpful links : reading HttpwebResponse json response, C# , how to split json format string in order to Deserialize is into .net object?

Community
  • 1
  • 1
abhinav pratap
  • 623
  • 8
  • 15
  • oh, i think your answer is right to my question but how to Check ResponseString and extract the required data from it? i just start with that. can you let me know? thanks – Toeur Tenh Aug 09 '12 at 08:36
  • May you help me? i really need your help much – Toeur Tenh Aug 09 '12 at 08:50
  • What you get in responseString? get it while debugging and paste it here. or get it by commenting line string result = Regex.Replace(responseString, @"<[^>]*>", string.Empty); and setting textboxError.Text = responseString; – abhinav pratap Aug 09 '12 at 09:08
  • in responseString, after i run my web application i got: sendMessage0Message accepted for delivery0e4e47f3-14d4-418c-a1ad-62d79d1ada75+85568922903. what is my problem? – Toeur Tenh Aug 09 '12 at 09:25
  • try this with your myreq, myreq.ContentType = "application/json"; – abhinav pratap Aug 09 '12 at 09:45
  • or you can extract the result from the responseString you pasted like string substrMsg = ab.Substring(responseString.IndexOf('0'), responseString.IndexOf("delivery")); string recepient = ab.Substring(responseString.IndexOf('+')); string messageId = ab.Substring(responseString.IndexOf("delivery"), responseString.IndexOf('+')); string result = substrMsg + " Message ID " + messageId + " Recipient " + recepient; textboxError.Text=result.(index of may be not right here, change according to result) – abhinav pratap Aug 09 '12 at 09:48
  • i put myReq.ContentType = "application/json"; like this HttpWebRequest myReq = (HttpWebRequest)WebRequest.Create(createdURL); myReq.ContentType = "application/json"; and i still this error message: sendMessage0Message accepted for deliveryae2914f1-9116-4bc7-bb9f-95c30017d7f4+85568922903. How to do more? – Toeur Tenh Aug 09 '12 at 09:52
  • can't say. you can extract the required message from responseString. "sendMessage, 0, Message accepted for delivery, ae2914f1-9116-4bc7-bb9f-95c30017d7f4, +85568922903" – abhinav pratap Aug 09 '12 at 09:55
  • Oops, replace ab with responseString – abhinav pratap Aug 09 '12 at 10:03
  • what do you mean this line: textboxError.Text=result.(index of may be not right here, change according to result) – Toeur Tenh Aug 09 '12 at 10:08
  • i write codes like this: string substrMsg = responseString.Substring(responseString.IndexOf('0'), responseString.IndexOf("delivery")); string recepient = responseString.Substring(responseString.IndexOf('+')); string messageId = responseString.Substring(responseString.IndexOf("delivery"), responseString.IndexOf('+')); string result = substrMsg + " Message ID " + messageId + " Recipient " + recepient; textboxError.Text = Server.HtmlEncode(result); after run i get error: Ozeki NG SMS Gateway Server is not running! – Toeur Tenh Aug 09 '12 at 10:11
  • but actually Ozeki NG SMS Gateway Server service is running on my pc. so is this because Ozeki NG SMS Gateway Server? – Toeur Tenh Aug 09 '12 at 10:13
0

Use XSLT. The reason is that it makes it easy to store the transform in a file. This means if the message format ever changes, it is easy to update your transform to cope.

Add a function like

public void XslTransformer(string source, string stylesheet, string output)
{
    XslTransform xslt = new XslTransform();
    xslt.Load(stylesheet);
    xslt.Transform(source, output);                
}

And call it, passing your XML, and a transform like:

<?xml version="1.0" encoding="ISO-8859-1"?>
<!-- Edited by XMLSpy® -->
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:template match="/">
<html>
Message accepted for delivery
    <table border="0">
      <tr>
        <td>Message ID:</td>
        <td><xsl:value-of select="Responses/Response0/Data/AcceptReport/MessageID"/></td>
        <td>Recipient:</td>
        <td><xsl:value-of select="Responses/Response0/Data/AcceptReport/Recipient"/></td>
        <td>StatusCode:</td>
        <td><xsl:value-of select="Responses/Response0/Data/AcceptReport/MessageID"/></td>
      </tr>
    </table>
</html>
</xsl:template>
</xsl:stylesheet>

Change this format as you like.

Justin Harvey
  • 14,446
  • 2
  • 27
  • 30