Link to home
Start Free TrialLog in
Avatar of Stealthrt
StealthrtFlag for United States of America

asked on

Calling local WFC service from ASP.net AJAX

Hey all I am using the following code on my local machine to give me a temporary WCF service:
    using System;
    using System.Windows.Forms;
    using System.ServiceModel;
    using TestService;
    
    namespace TestClient
    {
        public partial class Form1 : Form
        {
            IService1 patientSvc = null;
    
            public Form1()
            {
                InitializeComponent();
            }
    
            private void Form1_Load(object sender, EventArgs e)
            {
                EndpointAddress address = new EndpointAddress(new Uri("net.tcp://localhost:2202/PatientService"));
                NetTcpBinding binding = new NetTcpBinding();
                ChannelFactory<IService1> factory = new ChannelFactory<IService1>(binding, address);
                patientSvc = factory.CreateChannel();
            }
        }
    }

Open in new window

And the class1:
    using System;
    using System.Collections.Generic;
    using System.Text;
    using System.ServiceModel;
    using System.Runtime.Serialization;
    
    namespace TestService
    {
        [ServiceContract()]
        public interface IService1
        {
            [OperationContract]
            Patient GetPatient(Int32 index);
    
            [OperationContract]
            void SetPatient(Int32 index, Patient patient);
        }
    
        [ServiceBehavior(IncludeExceptionDetailInFaults = true)]
        public class PatientService : IService1
        {
            Patient[] pat = null;
    
            public PatientService()
            {
                pat = new Patient[3];
    
                pat[0] = new Patient();
                pat[0].FirstName = "Bob";
                pat[0].LastName = "Chandler";
    
                pat[1] = new Patient();
                pat[1].FirstName = "Joe";
                pat[1].LastName = "Klink";
    
                pat[2] = new Patient();
                pat[2].FirstName = "Sally";
                pat[2].LastName = "Wilson";
            }
    
            public Patient GetPatient(Int32 index)
            {
                if (index <= pat.GetUpperBound(0) && index > -1)
                    return pat[index];
                else
                    return new Patient();
            }
    
            public void SetPatient(Int32 index, Patient patient)
            {
                if (index <= pat.GetUpperBound(0) && index > -1)
                    pat[index] = patient;
            }
        }
    
        [DataContract]
        public class Patient
        {
            string firstName;
            string lastName;
    
            [DataMember]
            public string FirstName
            {
                get { return firstName; }
                set { firstName = value; }
            }
    
            [DataMember]
            public string LastName
            {
                get { return lastName; }
                set { lastName = value; }
            }
        }
    }

Open in new window

This works just fine if I have the call to **PatientService** with a "1". It shows me the values **Joe** and **Klink**.

However, doing the same on my ASP.net website page with the following:

.cs page:
    @{
        ViewBag.Title = ViewBag.Message;
        Layout = "~/Views/Shared/_Layout.cshtml";
    }
    
    <div class="col-sm-offset-2 col-sm-8" style="margin-bottom: 10px; margin-top: 10px; text-align: center;">
        <Button class="tips btn btn-success btn-outline" style="margin-right: 10px;" id="WCF" data-tooltip="@Html.Raw(tips["Continue"])">WCF TEST</Button>
    </div>

Open in new window

And the JavaScript:
    $(document).ready(function () {    
        $("#WCF").on("click", function () {
            $.ajax({
                type: "POST",
                url: ajaxDirPath + "WCF",
                data: '{"patNum": "1"}',
                contentType: "application/json", // content type sent to server
                success: ServiceSucceeded,
                error: ServiceFailed
            });
        });
    });

    function ServiceFailed(result) {
        console.log('Service call failed: ' + result.status + '  ' + result.statusText);
    }

    function ServiceSucceeded(result) {
        resultObject = result.MyFunctionResult;
        console.log("Success: " + resultObject);
    }

Open in new window

And the code behind:
    [HttpPost]
    public string WCF(string patNum)
    {
        Dictionary<string, string> resultsBack = new Dictionary<string, string>();
        EndpointAddress address = new EndpointAddress(new Uri("net.tcp://localhost:2202/PatientService"));
        NetTcpBinding binding = new NetTcpBinding();
        ChannelFactory<IService1> factory = new ChannelFactory<IService1>(binding, address);
        IService1 patientSvc = factory.CreateChannel();

        Patient patient = patientSvc.GetPatient(Convert.ToInt32(patNum));

        if (patient != null)
        {
            resultsBack.Add("dback", "GOOD");
            resultsBack.Add("return1", patient.FirstName);
            resultsBack.Add("return2", patient.LastName);
        }

        return JsonConvert.SerializeObject(resultsBack, Formatting.Indented);
    }

Open in new window

The **patient** variable is **NULL** for everything it returns back.

What would I be doing incorrectly?

This is the steps in debugging from both the javascript and the WCF service:
User generated image
Next -->
User generated image
Next -->
User generated image
Next -->
User generated image
Next -->
User generated image
Next -->
User generated image
Avatar of Curtis Shull
Curtis Shull
Flag of United States of America image

I didn't see where you delcare the patientSvc reference?

Try "newing up" the patientSvc object before using like:     PatientService patientSvc = new PatientService();    

or newing up Patient patient = new Patient();    

if in fact it's a Class Object and not from a Static Class
This question needs an answer!
Become an EE member today
7 DAY FREE TRIAL
Members can start a 7-Day Free trial then enjoy unlimited access to the platform.
View membership options
or
Learn why we charge membership fees
We get it - no one likes a content blocker. Take one extra minute and find out why we block content.