Click here to Skip to main content
14,738,318 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I need your help to solve my issue please give me a solution for this

I am trying a Serialize and Deserialize the Dynamic XML Data but the data was not Deserialized

These are my methods and i am using.

**Button Click Method**

    protected void btnCreateSession_Click(object sender, EventArgs e)
    {
        //System.Threading.Thread.Sleep(2000);
        tbodyException.Visible = false;//changes 9/10/12
        try
        {
            CreateSessionRequest request = new CreateSessionRequest();
            //ucClientInfo uc = 
            (ucClientInfo)LoadControl("~Shared/UserControls/ucClientInfo.ascx");
            request.applicationId = ucClientInfo1.txtApplicationID.Text;
            request.accountType = ddlAccountType.SelectedValue;
            request.salesOffice =
                ddlSalesoffice.SelectedItem.ToString();//txtSalesOffice.Text;
            request.salesAgentId = txtAgentId.Text;
            // Thiyagu 10/10/2012 added for deriving metrics by Agent and Outlet details 
            request.salesAgentName = txtAgentName.Text;
            request.outletLocationId = txtOutletID.Text;
            request.outletLocationName = txtOutletName.Text;
            // Thiyagu 10/10/2012 added for deriving metrics by Agent and Outlet details 

            Dictionary<string, string> agentDetails = new Dictionary<string, string>();

            agentDetails.Add("SubClientId", request.salesOffice);
            agentDetails.Add("SalesAgentId", request.salesAgentId);
            agentDetails.Add("SalesAgentName", request.salesAgentName);
            Session.Add("AgentDetails", agentDetails);

            ClientInfo clientinfo = new ClientInfo();
            // Thiyagu 10/04/12 populating dummy app server details in client else schema 
            clientinfo = PreOrderingHelper.mapClientInfoDetails(clientinfo);
            clientinfo.name = ucClientInfo1.txtClientName.Text;
            clientinfo.clientId = ucClientInfo1.ddlClientID.SelectedValue;
            GlobalVariable.ServiceClientID = ucClientInfo1.ddlClientID.SelectedValue;
            request.client = clientinfo;

            CreateSessionResponse response = new CreateSessionResponse();


            string url = (Page.Master as TestBed).COAServiceUrl;
            var token = (Page as BasePage).Token;
            var _url = (Page as BasePage).AppUrl;
            var _action = (Page as BasePage).Action + CurrentFlow.ToString();
            bool localDebug = Convert.ToBoolean(System.Configuration.ConfigurationManager.AppSettings["localDebug"]);
            if (!localDebug)
            {
                //ServiceHelper<CreateSessionRequest, CreateSessionResponse> helper = new 
                ServiceHelper<CreateSessionRequest, CreateSessionResponse>(url);
                //response = helper.CallService(request, CurrentFlow.ToString(), TcId);
                var webRequest = (HttpWebRequest)CommonUtil.SendSOAPRequest(request, _url, CurrentFlow.ToString(), token, _action, false);
                string result;
                using (WebResponse resp = webRequest.GetResponse())
                {
                    using (StreamReader rd = new StreamReader(resp.GetResponseStream()))
                    {
                        result = rd.ReadToEnd();
                        response = CommonUtil.DeserializeInnerSoapObject < CreateSessionResponse(result);
                    }
                }
            }
            else
            {
                TextReader tr = new StreamReader(@"C:\SampleXmls\CreateSessionResp.xml");
                System.Xml.Serialization.XmlSerializer xs = new System.Xml.Serialization.XmlSerializer(typeof(CreateSessionResponse), "http://verizon.com/CoFEEAnywhere/CoAServices/v1");
                //response = xs.Deserialize(tr) as SoapResponse.CreateSessionResponse;
                response = xs.Deserialize(tr) as CreateSessionResponse;
            }

            if (response != null && response.output != null &&
              !string.IsNullOrEmpty(response.output.sessionId))
            {

                Session["sessionId"] = response.output.sessionId;  // Saving it in session - Can be used elsewehere in later flows
                (Page.Master.FindControl("lblGlobalSessionIDValue") as Label).Text = response.output.sessionId; // setting the bottom session area in Preordering.aspx                    
                var masterPage = Page.Master as TestBed;
                masterPage.SessionIdUpdatePanel.Update();
                (Page as BasePage).SessionID = response.output.sessionId;
                lblCreatedSession.Text = (Page as BasePage).SessionID;
                lblSalesProfileResult.Text = "SUCCESS";

                Session["ClientId"] = ucClientInfo1.ddlClientID.SelectedValue;
                Session["ClientName"] = ucClientInfo1.txtClientName.Text;
                Session["AppId"] = ucClientInfo1.txtApplicationID.Text;
                Session["OrderType"] = ddlOrderType.SelectedValue;
                Session["AccountType"] = ddlAccountType.SelectedValue;
            }
        }
        catch (Exception ex)
        {
            tbodyException.Visible = true;
            aExcpetion.InnerText = ex.Message + "  |  " + ex.InnerException != null ?
           ex.InnerException.Message : string.Empty;//aExcpetion.Attributes.Add("onclick", 
            "OpenExceptionWindow('" + ex.InnerException + "');
         }
        finally
        {
            if (!string.IsNullOrEmpty(Session["ClientId"].ToString()) &&
            Session["ClientId"].ToString() == "CETC")
            {
                var masterPage = Page.Master as TestBed;
                masterPage.NextFlow.CommandName = FlowType.Recommended.ToString();
                masterPage.NextFlow.Text = "Next";
                masterPage.NextFlow.Visible = true;
            }
            else
            {
                var masterPage = Page.Master as TestBed;
                masterPage.NextFlow.Visible = true;
            }
        }
    }


** SOAP Request**
<pre>public static object SendSOAPRequest(object req, string _url, string methodName, string token, string _action, bool useSOAP12)
    {
        ServicePointManager.ServerCertificateValidationCallback = new

          RemoteCertificateValidationCallback
                                                       (
                                                          delegate { return true; }
                                                       );
        // Create the SOAP envelope
        var formXml = new XmlDocument();
        string soapXml = "";
        soapXml = WsdlRequestToSOAP(req);
        if (methodName == "GetBroadbandAvailability")
        {
            soapXml = soapXml.Remove(0, 21).Replace(methodName + "Request",
              "gbbRequest");
        }
        else if (methodName == "GetQualifiedProducts")
        {
            soapXml = soapXml.Remove(0, 21).Replace(methodName + "Request",
            "productsrequest");
        }
        else
        {
            soapXml = soapXml.Remove(0, 21).Replace(methodName + "Request", "req" +
         methodName);
        }

        formXml.LoadXml(soapXml);

        var newXml = new XmlDocument();
        var rootTag = String.Format("<{0}></{0}>", methodName);
        newXml.LoadXml(rootTag);

        XmlNode rootNode = newXml.ImportNode(formXml.DocumentElement, true);
        newXml.DocumentElement.AppendChild(rootNode);

        var stringXml = @"<?xml version=""1.0"" encoding=""utf-8""?>
                            <soap:Envelope xmlns:soap=""http://schemas.xmlsoap.org/soap/envelope/"" 
                                xmlns=""http://some link""
                                xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" 
                       xmlns:xsd=""http://www.w3.org/2001/XMLSchema"">
                                <soap:Body>
                                   {0}
                                </soap:Body>
                            </soap:Envelope>";
        var s = String.Format(stringXml, newXml.InnerXml);
        formXml.LoadXml(s);
        // Create the web request
        HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(_url);
        webRequest.Headers.Add("SOAPAction", _action ?? _url);
        webRequest.ContentType = (useSOAP12) ? "application/soap+xml;charset=\"utf-8\"" :
          "text/xml; encoding=utf-8";
        webRequest.Accept = (useSOAP12) ? "application/soap+xml" : "text/xml";
        webRequest.Method = "POST";
        webRequest.Headers.Add("Authorization", "Bearer " + token);
        webRequest.Headers.Add("X-CLIENT-CERT-STATUS", "ok");
        webRequest.Headers.Add("X-SUBJECT-NAME", "C=US, ST=Florida, L=Temple Terrace, O =\"Verizon Data Services.LLC\", OU=GTSAP, CN=apigee.coasvcs.verizon.com");

        // Insert SOAP envelope
        using (Stream stream = webRequest.GetRequestStream())
        {
            formXml.Save(stream);
        }

        return webRequest;
    }


** AuthorizeRequest**
<pre>public static string AuthorizeRequest()
    {
        string client_id = "t1ehVqcAGYmWC8yvPapwgdZOqOjQd5oO";
        string client_secret = "ICo3o8Da8BCpmXk0";
        var restClient = new RestClient("https://some link / oauth / client_credential / accesstoken ? grant_type = client_credentials");

        var restRequest = new RestRequest(Method.POST);
        restRequest.AddHeader("Cache-Control", "no-cache");
        restRequest.AddHeader("Content-Type", "application/json");
        restRequest.AddParameter("client_id", client_id);
        restRequest.AddParameter("client_secret", client_secret);
        IRestResponse restResponse = restClient.Execute(restRequest);
        var responseJson = restResponse.Content;
        var token = JsonConvert.DeserializeObject<Dictionary<string, object>>
         (responseJson)["access_token"].ToString();

        return token;
    }

** WsdlRequestToSOAP**

  public static string WsdlRequestToSOAP(object Object)
    {
        if (Object == null)
        {
            throw new ArgumentException("Object can not be null");
        }
        try
        {
            var serxml = new System.Xml.Serialization.XmlSerializer(Object.GetType());
            var ms = new MemoryStream();
            serxml.Serialize(ms, Object);
            return Encoding.UTF8.GetString(ms.ToArray());
        }
        catch { throw; }
    }


** IndentXMLString**

public static string IndentXMLString(string xml)
    {
        string outXml = string.Empty;
        MemoryStream ms = new MemoryStream();
        // Create a XMLTextWriter that will send its output to a memory stream (file)
        XmlTextWriter xtw = new XmlTextWriter(ms, Encoding.Unicode);
        XmlDocument doc = new XmlDocument();
        StreamReader sr = null;`enter code here`
         try
        {
            // Load the unformatted XML text string into an instance 
            // of the XML Document Object Model (DOM)
            doc.LoadXml(xml);

            // Set the formatting property of the XML Text Writer to indented
            // the text writer is where the indenting will be performed
            xtw.Formatting = System.Xml.Formatting.Indented;

            // write dom xml to the xmltextwriter
            doc.WriteContentTo(xtw);
            // Flush the contents of the text writer
            // to the memory stream, which is simply a memory file
            xtw.Flush();

            // set to start of the memory stream (file)
            ms.Seek(0, SeekOrigin.Begin);
            // create a reader to read the contents of 
            // the memory stream (file)
            sr = new StreamReader(ms);
            // return the formatted string to caller                
        }
        catch (Exception ex)
        {

        }
        return sr.ReadToEnd();
    }
<pre>** Finally this is the DeserializeInnerSoapObject method**
<pre>public static T DeserializeInnerSoapObject<T>(string soapResponse)
    {
        XmlDocument xmlDocument = new XmlDocument();
        xmlDocument.LoadXml(soapResponse);

        var soapBody = xmlDocument.GetElementsByTagName("s:Body")[0];
        string innerObject = IndentXMLString(soapBody.InnerXml); //soapBody.InnerXml;

        XmlSerializer deserializer = new XmlSerializer(typeof(T), "http://some link");


        using (TextReader reader = new StringReader(innerObject))
        {
            return (T)deserializer.Deserialize(reader);
        }
    }




Finally the output came like this

<pre><soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<CreateSessionResponse xmlns="http://Some Link">
      <CreateSessionResult>
        <output>
          <sessionId>some ID</sessionId>
        </output>
      </CreateSessionResult>
    </CreateSessionResponse>
  </soap:Body>
</soap:Envelope>




What I have tried:

I need your help to resolve this issue
Posted
Comments
ZurdoDev 28-Jan-20 8:28am
   
What error do you get?
Aditya Thota 31-Jan-20 2:39am
   
No error i have got but the data was not deserilized when i trying to deserilize
ZurdoDev 31-Jan-20 6:54am
   
What does that mean? If you call deserialize it will only do one of 2 things. Deserialize or throw an error. Nothing else.
Aditya Thota 3-Feb-20 1:42am
   
throw an error : Object reference not set to an instance of object
Its shown Null value in response
ZurdoDev 3-Feb-20 6:52am
   
Which means something is null. It's very simple to fix this and only you can because we can't run your code. Just debug it and find what is null and then fix it. Very easy.
Aditya Thota 4-Feb-20 2:46am
   
No Zurdo i have tried in multiple ways to resolve this issue here the main issue is Soap Response XML data File format is wrong its my thinking

We are getting the soap response XML format data having both XSD and XSI tags are added to inside theSoap Body at the end of the soap response created

And you can see once the above methods then u can understand what happening here

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900