0

OK I have been working on this for a few days now an it is starting to annoy me.

I have a page where the user can change the colour scheme. And choose a logo for the page.

Using jquery to loop round all the items that can be changed ($(".brand").each)

and build up the data and finally send it to a wcf service as a json object, see below

$(".brand").each(function () {
    //use the title attribute to list the css properties 
    // you want for that element 

    //use the id with a prefix to represent the actual element
    // you want to brand, 
    //matching up with the item in the site's css

    //prefix 'c-' = css class so replace with '.'
    //prefix 'id-' = element id so replace with '#'
    //prefix 'e-' = element so just remove the prefix

    var id = $(this).attr("id").replace("c-", ".").replace("id-", "#").replace("e-", "");
    var title = $(this).attr("title");
    var values = title.split(',');
    var property = "";
    var value = "";
    for (var i = 0; i < values.length; i++) {
      selector = values[i]
      value = $(this).css(values[i]);
    }
    var item = {};
    item["id"] = "";
    item["selector"] = id;
    item["css_property"] = property;
    item["property_value"] = value;
    json.push(item);
  });
  if ($(".imgbase").val().length > 0) {
    var logoUrl = $(".imgbase").val();
    logoUrl = logoUrl.replace(new RegExp("^data:image/[a-z]*;base64,", ""));
    var item = {};
    item["id"] = 1;
    item["selector"] = "";
    item["css_property"] = "";
    item["property_value"] = logoUrl;
    json.push(item);
  }

$.ajax({
    type: "POST",
    contentType: "application/json",
    url: "http://localhost:64177/BrandingService.svc/DoBranding",
    data: JSON.stringify({ CSS: json }),
    dataType: "json",

    success: function (msg) {
      if (msg.hasOwnProperty("d"))
        alert(msg.d);
    },
    error: function (result) {
      alert("Failed to call service: (" + result.status + ") \n" + result.statusText);
    }
  });

Now this seems to create an array object, so my question is, what on earth should my service be expecting, and how do I read it? Assuming I am sending it correctly? If I receive it as an object there is no error but the service has no idea what it is and cannot deserialize it. I can't receive it as a List(Of BrandingCSS), this causes a 500 error, I have a class (see bottom), That I am trying to use as a List(Of BrandingCSS), so how do I get the "CSS Object" into that? I have tried the JavaScriptSerializer and Json.net, I am open to either to get a result, so if anyone can help, please do before I go insane.

    <OperationContract()>
  Public Function DoBranding(ByVal CSS As Object) As String
    Try
      Return "FOO"

    Catch ex As Exception
      Return "BAR: " & ex.Message
    End Try
    End Function

Class I am using

    <DataContract([Namespace]:="")> _
  Public Class BrandingCSS
    <DataMember>
    Public Property ServiceID() As Integer
      Get
        Return m_ServiceID
      End Get
      Set(value As Integer)
        m_ServiceID = value
      End Set
    End Property
    Private m_ServiceID As Integer
    <DataMember>
    Public Property selector() As String
      Get
        Return m_selector
      End Get
      Set(value As String)
        m_selector = value
      End Set
    End Property
    Private m_selector As String
    <DataMember>
    Public Property css_property() As String
      Get
        Return m_property
      End Get
      Set(value As String)
        m_property = value
      End Set
    End Property
    Private m_property As String
    <DataMember>
    Public Property property_value() As String
      Get
        Return m_value
      End Get
      Set(value As String)
        m_value = value
      End Set
    End Property
    Private m_value As String
    <DataMember>
    Public ReadOnly Property logo() As Byte()
      Get
        Return img
      End Get
    End Property
    Private img As Byte() = Nothing
    Public Sub New()
      Try
        img = Convert.FromBase64String(property_value)
      Catch ex As Exception
        img = Nothing
      End Try
    End Sub
  End Class

If you are wanting to see the services section in the web.config it is this

<system.serviceModel>
    <services>
      <service name="BrandingService">
        <endpoint address="" behaviorConfiguration="BrandingServiceAspNetAjaxBehavior"
          binding="webHttpBinding" contract="BrandingService" />
      </service>
    </services>
    <behaviors>
      <endpointBehaviors>
        <behavior name="BrandingServiceAspNetAjaxBehavior">
          <enableWebScript />
        </behavior>
      </endpointBehaviors>
      <serviceBehaviors>
        <behavior name="">
          <serviceMetadata httpGetEnabled="true" httpsGetEnabled="true" />
          <serviceDebug includeExceptionDetailInFaults="true" />
        </behavior>
      </serviceBehaviors>
    </behaviors>
    <serviceHostingEnvironment aspNetCompatibilityEnabled="true"
      multipleSiteBindingsEnabled="true" />
  </system.serviceModel>
  <system.web.extensions>
    <scripting>
      <webServices>
        <jsonSerialization maxJsonLength="5000000" />
      </webServices>
    </scripting>
  </system.web.extensions>

and a sample of the json sent is here

"[
    {\"id\":\"1\",\"selector\":\".mp-level\",\"css_property\":\"background\",\"property_value\":\"\"},
    {\"id\":\"1\",\"selector\":\".mp-level\",\"css_property\":\"color\",\"property_value\":\"\"},
    {\"id\":\"1\",\"selector\":\"#header\",\"css_property\":\"background\",\"property_value\":\"\"},
    {\"id\":\"1\",\"selector\":\"#header\",\"css_property\":\"color\",\"property_value\":\"\"},
    {\"id\":\"1\",\"selector\":\"#header\",\"css_property\":\"border-bottom-color\",\"property_value\":\"\"},
    {\"id\":\"1\",\"selector\":\"headerinput\",\"css_property\":\"background\",\"property_value\":\"\"},
    {\"id\":\"1\",\"selector\":\"headerbutton\",\"css_property\":\"background\",\"property_value\":\"\"},
    {\"id\":\"1\",\"selector\":\"footer\",\"css_property\":\"background\",\"property_value\":\"\"},
    {\"id\":\"1\",\"selector\":\"footer\",\"css_property\":\"color\",\"property_value\":\"\"}
]"

1 Answers1

0

First of all, add

contentType: "application/json;charset=utf-8"

in your POST request header.

I haven't seen RequestFormat = WebMessageFormat.Json in your service contract.

C# Code

[OperationContract]
    [WebInvoke(Method = "POST", UriTemplate = "CSSBranding",
        RequestFormat = WebMessageFormat.Json,
        BodyStyle = WebMessageBodyStyle.Bare)]
    string DoBranding(BrandingCSS[] css);

Note that your JSON and BrandingCSS class should have same parameters. For example, for "selector" in JSON, you must have "selector" property in BrandingCSS class.

[DataContract(Namespace = "")]
public class BrandingCSS
{
   [DataMember]
   public string selector {get; set;}
   [DataMember]
   public string id {get; set;}
   //Remaining properties here.
}

I hope you understood C# code.

EDIT If you want to check what JSON your service should accept, override the ToString() method for your BrandingCSS class.

public override string ToString()
{
    JavaScriptSerializer js = new JavaScriptSerializer(); // Available in System.Web.Script.Serialization;           
    return js.Serialize(this);
}

Now make an object of class BrandingCSS.

BrandingCSS bcss = new BrandingCSS();
string acceptedJson = bcss.ToString();
Console.WriteLine(acceptedJson);

or you can make a temp OperationContract and call these line of codes. Hit a break point there and see the JSON. After that, make a JSON that you just have seen in debugger and send request. See 500 Internal Server Error.. And also you haven't shown your Web.Config file.

Faizan Mubasher
  • 4,427
  • 11
  • 45
  • 81