WCF giving error 400 bad request when calling using AJAX or from SharePoint 2013 Workflow

Problem Statement:-

I was getting the error 400 Bad Request, when trying to call the WCF web service using AJAX or from SharePoint 2013 Workflow.

Solution:-

I have figured out the issue and resolved by the following code:

  1. In your service Interface where you will define the OperationContact, you need to use the WebInvoke with the following Method = “GET” or “POST” depends upon your requirement, ResponseFormat = WebMessageFormat.Json,BodyStyle = WebMessageBodyStyle.Bare.

Example:-

[OperationContract]
[WebInvoke(Method = “GET”,
ResponseFormat = WebMessageFormat.Json,
BodyStyle = WebMessageBodyStyle.Bare)]
string HelloWorld();

 

2.  Add Factory=”System.ServiceModel.Activation.WebScriptServiceHostFactory” in the .svc file like this:

<%@ ServiceHost Language=”C#” Debug=”true” Service=”WcfService1.Service1″     CodeBehind=”Service1.svc.cs” Factory=”System.ServiceModel.Activation.WebScriptServiceHostFactory” %>

 

Download the Source code:-

WcfService1

First rename the above .doc file to .zip and extract it

Calling Cross Domain Web Services in AJAX

Problem Statement:-

I have a web service which is deployed on a domain A. I want to call this web service from another domain, but cross domain calling is not allowed.

Solution:-

We can achieve this thing with JSONP. In this approach we will wrap the JSON string into a callback function. And in the script from where we are calling this service method, we will define the Callback function which will be called by browser on success.

Steps:-

  1. Create a class Student

[Serializable]
public class Student
{
public string ID { get; set; }
}

2. Write the following code above the Web Service Class

[System.Web.Script.Services.ScriptService]

public class WebService1 : System.Web.Services.WebService

3. Following is the WebMethod

[WebMethod()]
[System.Web.Script.Services.ScriptMethod(UseHttpGet = true, ResponseFormat =             System.Web.Script.Services.ResponseFormat.Json)]
public void GetStudentData(string callback)
{

List<Student> students= new List<Student>();
Student S = new Student();
S.ID = “100”;
students.Add(S);

StringBuilder sb = new StringBuilder();
JavaScriptSerializer js = new JavaScriptSerializer();
sb.Append(callback + “(“);
sb.Append(js.Serialize(students));
sb.Append(“);”);

Context.Response.Clear();
Context.Response.ContentType = “application/json”;
Context.Response.Write(sb.ToString());
Context.Response.End();
}

4. Following is the Client side code

function CallAjaxCall() {
$.ajax({
crossDomain: true,
contentType: “application/json; charset=utf-8”,
url: “http://localhost:2952/WebService1.asmx/GetStudentData&#8221;,
dataType: “jsonp”,
success: onDataReceived
});
}

function onDataReceived(data) {
alert(JSON.stringify(data));
}

 

 

Infinite Session in Web Applications

Problem Statement:-

We were the facing the problem that session was getting timeout after every 20 minutes.

Solution:-

To resolve this issue. I wrote a web service method which is returning the string. We will call this method using ajax after every 15 minutes, so the session will not be timeout.

Example with explanation:-

Step # 1:-

Create a web service method in your web page:

[System.Web.Services.WebMethod]
public static String SessionAliveRequest()
{
return “”;
}

Step # 2:-

Call this method from master page so that it will be applied to all the pages which are inheriting the particular master page.

function SessionAliveRequest() {

$.ajax({
type: “POST”,
url: “AuthorizeRequest.aspx/SessionAliveRequest”,
contentType: “application/json; charset=utf-8”,
dataType: “json”,
success: function (response) {
setTimeout(function () {
console.log(“Calling in success”);
SessionAliveRequest();
}, 900000);
},
failure: function (response) {

},
error: function (response) {

var SessionAliveCount = document.getElementById(‘HDSessionAlive’).value;
SessionAliveCount = parseInt(SessionAliveCount) + 1;
document.getElementById(‘HDSessionAlive’).value = SessionAliveCount;
if (parseInt(SessionAliveCount) < 5) {
setTimeout(function () {
console.log(“Calling in failure try # ” + SessionAliveCount);
SessionAliveRequest();
}, 900000);
}
else {
alert(‘Connectivity problem’);
}
}
});

}

SessionAliveRequest();

 

You can notice that in the success event i am recalling the web service method. So it will recursively call the server.

Step # 3:-

In the web form create a server side hidden variable which you have to sent to 0 in the page_load event:

<asp:HiddenField ID=”HDSessionAlive” runat=”server” ClientIDMode=”Static” />

protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
HDSessionAlive.Value = “0”;

}

}

 

Step # 4 :-

In this error event i will increment the hidden variable so that after 5 attempts i will not call the server in case of error.

 

 

Populate a Dropdown using JQUERY AJAX in ASP.NET MVC

Step # 1 : Create a Model

public class StateModel

{

public Int64 StateCode { get; set; }

public string StateName { get; set; }

public string Abbreviation { get; set; }

public Int64 CountryCode { get; set; }

}

Step # 2 : Create an Action which will return the State List in the form of JSONResult

public JsonResult GetStateByCountry(int CountryCode)

{

List<StateModel> states = (from c in dbContext.States

where c.CountryCode.Equals(CountryCode)

orderby c.StateName

select new StateModel

{

StateCode = c.StateCode,

StateName = c.StateName

}).ToList();

JsonResult JSResult = Json(states);

return JSResult;

}

Step # 3 : Create a Java Script function which will call the action and get the State List in the form of JSONResult

CountryCode = Select Country code from Country Dropdown, on the basis of we will get the states.

function GetStateByCountry(CountryCode) {

    $.ajax({

url: “GetStateByCountry”, // Action name on the same controller

data: { CountryCode: CountryCode },

dataType: “json”,

type: “POST”,

error: function () {

        },

success: function (data) {

var items = “”;

items += “<option value=\”\”>” + “-Select-” + “</option>”;

$.each(data, function (i, item) {

items += “<option value=\”” + item.StateCode + “\”>” + item.StateName + “</option>”;

});

            $(#ddlState”).html(items);

        }

});

}

Implement AJAX using javaScript

Page1:-

<html>
<head>
<script type=”text/javascript”>
function stateChanged()
{

// readyState  = 4 means, page processed 

if (xmlHttp.readyState == 4)
{
document.getElementById(“divResult”).innerHTML = xmlHttp.responseText;
}
}
function GetDataFromPage2() {
xmlHttp = GetXmlHttpObject();
if (xmlHttp == null) {
alert(“Your browser does not support AJAX!”);
return;
}

// calling Page2.html

var url = “page2.html”;

xmlHttp.onreadystatechange = stateChanged;
xmlHttp.open(“GET”, url, true);
xmlHttp.send(null);
}

 

 

// Function to create XMLHttpRequest

function GetXmlHttpObject() {
var xmlHttp = null;
try {
// Firefox, Opera 8.0+, Safari
xmlHttp = new XMLHttpRequest();
}
catch (e) {
// Internet Explorer
try {
xmlHttp = new ActiveXObject(“Msxml2.XMLHTTP”);
}
catch (e) {
xmlHttp = new ActiveXObject(“Microsoft.XMLHTTP”);
}
}
return xmlHttp;
}
</script>
</head>
<body>
<input type=”button” value=”click” onclick=”GetDataFromPage2()”/>
<div id=”divResult”></div>
</body>
</html>

Page2:-

This is page2.html … Thanks …………