Google Soap Parsing in Windows Phone 8 c# | SubramanyamRaju Xamarin & Windows App Dev Tutorials

Tuesday 10 December 2013

Soap Parsing in Windows Phone 8 c#

Introduction

SOAP, originally defined as Simple Object Access Protocol, is a protocol specification for exchanging structured information in the implementation of Web Services in computer networks. It relies on XML Information Set for its message format, and usually relies on other Application Layer protocols, most notably Hypertext Transfer Protocol (HTTP) or Simple Mail Transfer Protocol(SMTP), for message negotiation and transmission.

Source File at :  Soap parsing in wp8

Building the Sample

No need of any other external dll's or library.We just need to add following helper class for removing the extra name spaces from soap reponce 
1)Removing soap name space's and making the proper xml nodes
                   (or)
Removing the namespaces from SOAP request in windows phone 8 c#

                   (or)

How to parse soap responce into xml nodes in windows phone 8 c#

C#

 public class RemoveNameSpace 
    { 
 
        public static string RemoveAllNamespaces(string xmlDocument) 
        { 
            XElement xmlDocumentWithoutNs = RemoveAllNamespaces(XElement.Parse(xmlDocument)); 
 
            return xmlDocumentWithoutNs.ToString(); 
        } 
 
        private static XElement RemoveAllNamespaces(XElement xmlDocument) 
        { 
            if (!xmlDocument.HasElements) 
            { 
                XElement xElement = new XElement(xmlDocument.Name.LocalName); 
                xElement.Value = xmlDocument.Value; 
                return xElement; 
            } 
            return new XElement(xmlDocument.Name.LocalName, xmlDocument.Elements().Select(el => RemoveAllNamespaces(el))); 
        } 
 
    }
 Example for use this class:
 string Notificationdata = RemoveNameSpace.RemoveAllNamespaces(reader.ReadToEnd()); 

2)Creating Ui for showing responce data

XAML
<Grid x:Name="ContentPanel" Grid.Row="1" Margin="12,0,12,0"            <ListBox HorizontalAlignment="Left" Name="aboutlist" Height="696" VerticalAlignment="Top" Width="456"                <ListBox.ItemTemplate                    <DataTemplate                        <Grid Width="456"                            <Grid.RowDefinitions                                <RowDefinition Height="Auto"/> 
                                <RowDefinition Height="Auto"/> 
                                <RowDefinition Height="Auto"/> 
                                <RowDefinition Height="Auto"/> 
                            </Grid.RowDefinitions> 
                            <TextBlock TextWrapping="Wrap" Grid.Row="0" Text="{Binding Text3}"/> 
                            <TextBlock TextWrapping="Wrap" Grid.Row="1" Text="{Binding Text2}"/> 
                            <TextBlock TextWrapping="Wrap" Grid.Row="2" Text="{Binding Text1}"/> 
                            <Rectangle Fill="White" Height="10" Grid.Row="3"/> 
                        </Grid> 
                    </DataTemplate> 
                </ListBox.ItemTemplate> 
            </ListBox> 
        </Grid>

3)ScreenShot

Description
Note: Here i am using "HttpWebRequest" for requesting the web service.You may also try to request the web service using WebClient. However in this sample i had taken Url is "http://sygnetinfosol.com/webservice.asmx".and i don't give guarantee for this url will work in future.And so please replace this url with your own web service url
We have to follow some little bit steps to parse the soap response
1)Creating HttpWebRequest object request
C#

HttpWebRequest spAuthReq = HttpWebRequest.Create("http://sygnetinfosol.com/webservice.asmx"as HttpWebRequest;
2)Need to mention Soap action

C#
spAuthReq.Headers["SOAPAction"] = "http://tempuri.org/HelloWorld";//here i want call the hellworld method so i kept this soap action
 3)Need to mention content type

C#
 spAuthReq.ContentType = "text/xml; charset=utf-8";
4)Generating the soap request
C#
string AuthEnvelope = 
                          @"<?xml version=""1.0"" encoding=""utf-8""?> 
            <soap:Envelope xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"" xmlns:soap=""http://schemas.xmlsoap.org/soap/envelope/""> 
            <soap:Body> 
            <HelloWorld xmlns=""http://tempuri.org/"" /> 
          </soap:Body> 
            </soap:Envelope>";
5)Removing the namespace from soap response with above helper class name is "RemoveNameSpace"
C#

 string Notificationdata = RemoveNameSpace.RemoveAllNamespaces(reader.ReadToEnd()); 
 6)Total code is
C#
using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Net; 
using System.Windows; 
using System.Windows.Controls; 
using System.Windows.Documents; 
using System.Windows.Input; 
using System.Windows.Media; 
using System.Windows.Media.Animation; 
using System.Windows.Shapes; 
using Microsoft.Phone.Controls; 
using System.Text; 
using System.IO; 
using System.Net.NetworkInformation; 
using MihirCampusMate; 
using System.Xml.Linq; 
 
namespace SoapParsing 
{ 
    public partial class MainPage : PhoneApplicationPage 
    { 
        GetAboutUs GAbt = new GetAboutUs(); 
        GetAboutUsList GAbtList = new GetAboutUsList(); 
        string responseString = ""; 
        public MainPage() 
        { 
            InitializeComponent(); 
            GetSampleString(); 
        } 
        public void GetSampleString() 
        { 
 
            HttpWebRequest spAuthReq = HttpWebRequest.Create("http://sygnetinfosol.com/webservice.asmx"as HttpWebRequest; 
            spAuthReq.Headers["SOAPAction"] = "http://tempuri.org/HelloWorld"; 
            spAuthReq.ContentType = "text/xml; charset=utf-8"; 
            spAuthReq.Method = "POST"; 
            spAuthReq.BeginGetRequestStream(new AsyncCallback(SelectedGGetSampleString), spAuthReq); 
        } 
 
        private void SelectedGGetSampleString(IAsyncResult asyncResult) 
        { 
 
            string AuthEnvelope = 
                          @"<?xml version=""1.0"" encoding=""utf-8""?> 
            <soap:Envelope xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"" xmlns:soap=""http://schemas.xmlsoap.org/soap/envelope/""> 
            <soap:Body> 
            <HelloWorld xmlns=""http://tempuri.org/"" /> 
          </soap:Body> 
            </soap:Envelope>"; 
            UTF8Encoding encoding = new UTF8Encoding(); 
            HttpWebRequest request = (HttpWebRequest)asyncResult.AsyncState; 
            System.Diagnostics.Debug.WriteLine("REquest is :" + request.Headers); 
            Stream _body = request.EndGetRequestStream(asyncResult); 
            string envelope = string.Format(AuthEnvelope); 
            System.Diagnostics.Debug.WriteLine("Envelope is :" + envelope); 
            byte[] formBytes = encoding.GetBytes(envelope); 
            _body.Write(formBytes, 0, formBytes.Length); 
            _body.Close(); 
            request.BeginGetResponse(new AsyncCallback(GetAllGetAllPhotosByProfileICallback1), request); 
        } 
 
        private void GetAllGetAllPhotosByProfileICallback1(IAsyncResult asyncResult) 
        { 
 
            try 
            { 
                if (NetworkInterface.GetIsNetworkAvailable()) 
                { 
                    System.Diagnostics.Debug.WriteLine("Async Result is :" + asyncResult); 
                    HttpWebRequest request = (HttpWebRequest)asyncResult.AsyncState; 
                    HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(asyncResult); 
                    if (request != null && response != null) 
                    { 
                        if (response.StatusCode == HttpStatusCode.OK) 
                        { 
                             
                            StreamReader reader = new StreamReader(response.GetResponseStream()); 
                            string Notificationdata = RemoveNameSpace.RemoveAllNamespaces(reader.ReadToEnd()); 
                            XDocument doc = XDocument.Parse(Notificationdata); 
                            foreach (var r in doc.Descendants("HelloWorldResult")) 
                            { 
                                foreach (var r1 in doc.Descendants("FormModel")) 
                                { 
                                    GAbtList.Add(new GetAboutUs { Text3 = r1.Element("Text3") == null ? "" : r1.Element("Text3").Value.ToString(), Text2 = r1.Element("Text2") == null ? "" : r1.Element("Text2").Value.ToString(), Text1 = r1.Element("Text1") == null ? "" : r1.Element("Text1").Value.ToString() }); 
                                    responseString = r1.Element("Text3") == null ? "" : r1.Element("Text3").Value.ToString(); 
                                } 
                              
 
                            } 
 
                            Dispatcher.BeginInvoke(() => aboutlist.ItemsSource = GAbtList); 
                        } 
                    } 
                } 
                else 
                { 
                    Dispatcher.BeginInvoke(()=>MessageBox.Show(" There is no newtwork available")); 
                     
                } 
            } 
            catch 
            { 
                Dispatcher.BeginInvoke(()=>MessageBox.Show(" There is a problem with webservice")); 
            } 
        } 
    } 
    public class GetAboutUs 
    { 
        public string Text3 
        { 
            get; 
            set; 
 
        } 
        public string Text2 
        { 
            get; 
            set; 
 
        } 
        public string Text1 
        { 
            get; 
            set; 
 
        } 
 
    } 
 
    public class GetAboutUsList : List<GetAboutUs> 
    { 
 
 
    } 
}

Windows Phone tutorials for beginners key points

This section is included for only windows phone beginners.However this article can covers following questions.Off course these key words are more helpful for getting more best results about this topic in search engines like google/bing/yahoo.. 

1. How to parse the soap response in windows phone 8 c#

2. How to parse Soap XML in Windows Phone 8 c#

3. Xml parsing in c# windows phone 8

4. How convert soap response into xml nodes  in windows phone 8 c#

4. Soap parsing example  in windows phone 8 c#

Have a nice day by: 

2 comments:

  1. foreach (var r1 in doc.Descendants("get_category_items_v2Result"))
    {
    GAbtList.Add(new Response { item_category_desc = r1.Element("item_category_desc") == null ? "" : r1.Element("item_category_desc").Value.ToString(), sub_category_image = r1.Element("sub_category_image") == null ? "" : r1.Element("sub_category_image").Value.ToString() });
    responseString = r1.Element("item_category_desc") == null ? "" : r1.Element("item_category_desc").Value.ToString(); }
    }
    Dispatcher.BeginInvoke(() => aboutlist.ItemsSource = GAbtList);


    in r1 i have following values, I tried to get only category_id_desc but it doesn't worked out. can you sort this out.

    {"Method":"MAINCATEGORY","ResponseCode":0,"ResponseText":"","Response":[{"item_category_uid":2625,"item_category_desc":"PATRIOT 15.3 INGROUND SOLID WINTER COVERS","Total":16,"sub_category_image":"CAT_PAT_L.jpg","sub_category_thumb":"CAT_PAT_S.jpg"},{"item_category_uid":2624,"item_category_desc":"Patriot 15.3 Solid Winter Cover","Total":19,"sub_category_image":"CAT_PAT_L.jpg","sub_category_thumb":"CAT_PAT_S.jpg"},{"item_category_uid":2015,"item_category_desc":"Aquador Closure System","Total":16,"sub_category_image":"aqd1010_l.jpg","sub_category_thumb":"aqd1010_l.jpg"},{"item_category_uid":2016,"item_category_desc":"Aquador Replacement Lids","Total":6,"sub_category_image":"aqd71010_l.jpg","sub_category_thumb":"aqd71010_l.jpg"},{"item_category_uid":3245,"item_category_desc":"Chemicals - WSL","Total":19,"sub_category_image":"","sub_category_thumb":""},{"item_category_uid":3249,"item_category_desc":"Controls - WSL","Total":5,"sub_category_image":"","sub_category_thumb":""},{"item_category_uid":3247,"item_category_desc":"Filters - WSL","Total":4,"sub_category_image":"","sub_category_thumb":""},{"item_category_uid":3246,"item_category_desc":"Heaters - WSL","Total":1,"sub_category_image":"","sub_category_thumb":""},{"item_category_uid":3248,"item_category_desc":"Pumps - WSL","Total":0,"sub_category_image":"","sub_category_thumb":""},{"item_category_uid":3252,"item_category_desc":"Lights - WSL","Total":4,"sub_category_image":"","sub_category_thumb":""},{"item_category_uid":3251,"item_category_desc":"Alternate Sanitizers - WSL","Total":4,"sub_category_image":"","sub_category_thumb":""},{"item_category_uid":3133,"item_category_desc":"Big Sticky Spray Adhesive","Total":3,"sub_category_image":"","sub_category_thumb":""}]}

    ReplyDelete
    Replies
    1. Your webservcie response is like a 'Json' fromat .You need to parse your Json response .And the above article code is not work for Json and it is only work for xml .

      Delete

Search Engine Submission - AddMe