Asked by:
post wcf json input AND JSON OUTPUT REMOTE SERVER ERROR

Question
-
User-1451335618 posted
public Status CalculateSelf_Checksum(string empsapid, string wef, string deletionremarks)
{Status res = new Status();
string result_checksum = string.Empty;
try
{
Status.selfcal obj1 = new Status.selfcal()
{
_s_esapid = empsapid,
_s_wef = wef,
_s_deletionmsg = deletionremarks
};
Functions fobj = new WcfService2.Functions();
result_checksum = fobj.CalculateCheckSumSelfDelete(empsapid, wef, deletionremarks);
DataContractJsonSerializer ser =
new DataContractJsonSerializer(typeof(Status.selfcal));
MemoryStream mem = new MemoryStream();
ser.WriteObject(mem, obj1);string data =
Encoding.UTF8.GetString(mem.ToArray(), 0, (int)mem.Length);
System.Net.WebClient webClient = new System.Net.WebClient();
webClient.Headers["Content-type"] = "application/json";
webClient.Encoding = Encoding.UTF8;
string outputJson =
webClient.UploadString("http://localhost:50932/Service2.svc/CalculateSelf_Checksum", "POST", "hh");//SHOWING ERRRO
//Status objStatus = Newtonsoft.Json.JsonConvert.DeserializeObject<Status>(outputJson);
}
catch (Exception ex)
{
string s = ex.Message;
}
return new Status()
{
_esapid = empsapid,
_wef = wef,
_deletionmsg = deletionremarks,
_ReturnChecksum = result_checksum
};
}Thursday, May 18, 2017 10:27 AM
All replies
-
User475983607 posted
It looks like you are trying to consume a WCF service which uses SOAP yet you are forcing JSON. Simply create a service reference then invoke the service methods. If you want to use RESTful services then take a look at Web API.
https://msdn.microsoft.com/en-us/library/bb628652.aspx
https://msdn.microsoft.com/en-us/library/bb386386.aspx
In the future, post the errors you are receiving; otherwise we have to guess...
Thursday, May 18, 2017 11:38 AM -
User-1451335618 posted
I want input as json string and output aslo json string . want to use this url in postman
Friday, May 19, 2017 5:29 AM -
User-1451335618 posted
webform1.aspx.cs
try
{
string inputJson = Newtonsoft.Json.JsonConvert.SerializeObject(new { objEMPLOYEE_DATA_HCL123 = GetInputObject() });
System.Net.WebClient webClient = new System.Net.WebClient();
webClient.Headers["Content-type"] = "application/json";
webClient.Encoding = System.Text.Encoding.UTF8;
//Service1 CO = new Service1();
//CO.CalculateSelf_Checksum("1234","TEST","2017-05-12");
string outputJson = webClient.UploadString("http://localhost:61917/Service1.svc/CalculateSelf_Checksum", "POST", objEMPLOYEE_DATA_HCL123.ToString());
Status objStatus = Newtonsoft.Json.JsonConvert.DeserializeObject<Status>(outputJson);
}
catch (Exception ex)
{}.
E_EMPLOYEE_DATA_HCL1234 objEMPLOYEE_DATA_HCL123 = new E_EMPLOYEE_DATA_HCL1234();
private E_EMPLOYEE_DATA_HCL1234 GetInputObject()
{
try
{
objEMPLOYEE_DATA_HCL123.CHKo = new CHK_old()
{
ESAPID = "1234",
DELMARK = "TEST",
WEF = "2017-05-10"
};
}
catch (Exception ex)
{}
return objEMPLOYEE_DATA_HCL123;
}
}error whn control goes to service1.svc.cs while debugging mode , null valkues are passing to method mentioned bellow---kindly help??
service1.svc.cs
public Status CalculateSelf_Checksum(string empsapid, string wef, string deletionremarks)
{
Status result = new Status();
Status obj1 = new Status();
try
{
string chk = CalculateCheckSumDepDelete(empsapid, wef, deletionremarks);obj1 = new Status
{ReturnMessage = wef,
ReturnValue = Convert.ToInt32(empsapid),
CHK = chk
};
}
catch (Exception ex)
{}`
return obj1;
}Friday, May 19, 2017 11:16 AM -
User475983607 posted
swat123
I want input as json string and output aslo json string . want to use this url in postman
You are using the wrong technology. Use Web API as that's what Web API is for.
WCF is a SOAP service. To get WCF to work with JSON, you need to configure the WCF service. There is no indication in your post that you have properly configure the WCF service for REST requests.
I've build many REST/JSON WCF services and can tell you first hand it is NOT worth the effort. Web API is much much easier as Web API is a REST service whereas WCF is not.
Otherwise, use WCF as intended - a SOAP service. Create a web reference in your project as explained (and linked) in my previous thread.
Here are a few references if you insist on going down the rabbit hole and mangling WCF to be a REST service.
https://msdn.microsoft.com/en-us/library/bb472488(v=vs.110).aspx
https://msdn.microsoft.com/en-us/library/bb924552(v=vs.110).aspx
https://msdn.microsoft.com/en-us/library/bb885100(v=vs.110).aspx
Friday, May 19, 2017 11:28 AM -
User-1451335618 posted
Ok Thank You for valuable rply
Friday, May 19, 2017 11:39 AM -
User-1451335618 posted
I have to build a rest service and have to test it in postman app with json input and json output. no wcf soap . please help??
Friday, May 19, 2017 11:56 AM -
User475983607 posted
swat123
I have to build a rest service and have to test it in postman app with json input and json output. no wcf soap . please help??
I'm not sure how to help you! Your example code is using service1.svc with is a WCF service. To make this a REST service you need to do fairly extensive configuration. There is no indication that you have properly configured the WCF service to use JSON. I doubt you could have read the posted documentation and implemented a solution within the time it took you to post this response.
If you have decided to go with Web API and are not sure how to proceed then see the following reference documentation on this site.
Friday, May 19, 2017 12:13 PM -
User-1451335618 posted
i have coded a get rest service and it is working properly using
https://www.codeproject.com/Articles/201901/CREATE-RESTful-WCF-Service-API-Using-POST-Step-By link
now trying for post method .. this can help you to specify what i am coding??
Thanks again for replies
Thank You so much
Friday, May 19, 2017 12:17 PM -
User475983607 posted
i have coded a get rest service and it is working properly using
https://www.codeproject.com/Articles/201901/CREATE-RESTful-WCF-Service-API-Using-POST-Step-By link
now trying for post method .. this can help you to specify what i am coding??
Thanks again for replies
Thank You so much
The article shows how to build a XML service not JSON. Anyway, another forum member asked a similar question recently you can find the source code at the following link.
https://forums.asp.net/p/2121787/6138870.aspx?p=True&t=636307699847839670
Again, consider Web API as Web API is a REST service. REST was added to WCF at a later time and it requires a fair amount of configuration to get it to work. As you've seen so far..
Friday, May 19, 2017 12:59 PM -
User-1451335618 posted
ok tHANK You .
One more favor,
I have server 400 error in following code
at string outputJson = webClient.UploadString("http://localhost:63275/GetService.svc/InsertRecords", "POST", inputJson); line
public void callservice()
{
//try
//{string inputJson = Newtonsoft.Json.JsonConvert.SerializeObject(new { E_EMPLOYEE_DATA_HCL = GetInputObject() });
inputJson = inputJson.Replace("\"E_EMPLOYEE_DATA_HCL\":{\"E_EMP_HCL\":", "");
inputJson = inputJson.Replace("}", "");
System.Net.WebClient webClient = new System.Net.WebClient();
webClient.Headers["Content-type"] = "application/json";
webClient.Encoding = System.Text.Encoding.UTF8;
string outputJson = webClient.UploadString("http://localhost:63275/GetService.svc/InsertRecords", "POST", inputJson);
Student objStatus = Newtonsoft.Json.JsonConvert.DeserializeObject<Student>(outputJson);}
Monday, May 22, 2017 6:47 AM -
User-1451335618 posted
And aslo my value passing through postman app are going null to the method written in serice file ..kindly help
Monday, May 22, 2017 8:15 AM -
User-1451335618 posted
how to pass an object to webclient.uploadstring ?? my object values are going null
Tuesday, May 23, 2017 10:00 AM -
User475983607 posted
swat123
how to pass an object to webclient.uploadstring ?? my object values are going null
So the service is being hit but the parameters are null? Or the arguments are not sent in the request?
It could be the service method parameter do not do not match the arguments. It could also be the WCF service is not properly configured. It could be the client code is not working correctly. It's hard to provided assistance without the source code.
The biggest issue you are facing is you are NOT using the technology correctly. All you have do is create a service reference and all the complexity goes away. you'll be done in 10 minutes.
If you want a REST service then use Web API. Again very easy to do and well documented.
If you insist on not using the technology correctly, you will continue to have problems.
Tuesday, May 23, 2017 11:04 AM -
User-1451335618 posted
Yes, Thank You for your valuable response.
I have understood my mistake.
I wanna create REST web API with POST method.
I have successfully created 4 methods with localhost URL and tested in postman app.But when I pass string values it works means i.e. postman app input as string .its working properly but when I am trying to send an object (i.e. postman app input as object-object values is passing null.)
webform1.aspx.cs file code on page load
GetInputObject();
DataContractJsonSerializer ser =
new DataContractJsonSerializer(typeof(E_EMPLOYEE_DATA_HCL));
MemoryStream mem = new MemoryStream();
ser.WriteObject(mem, objEMPLOYEE_DATA_HCL);
string data =
Encoding.UTF8.GetString(mem.ToArray(), 0, (int)mem.Length);
WebClient webClient = new WebClient();
webClient.Headers["Content-type"] = "application/json";
webClient.Encoding = Encoding.UTF8;
webClient.UploadString("http://localhost:63275/GetService.svc/IIRMSingleInsert", "POST", data);
i want to pass string data as object
mt IGetservice.cs file code
[OperationContract]
[WebInvoke(Method = "POST",
UriTemplate = "/IIRMSingleInsert", BodyStyle = WebMessageBodyStyle.Wrapped, RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
CommonResults SingleInsert(E_EMPLOYEE_DATA_HCL oE_EMP_HCL);
My GetService.svc.cs code
public CommonResults SingleInsert(E_EMPLOYEE_DATA_HCL oE_EMP_HCL) // this object is going null whenever i hit the service url in postman app
{
string str1 = GetHash(string.Format("{0}{1}{2}", oE_EMP_HCL.E_EMP_HCL.ein/* E_EMP_HCL.insuredname, E_EMP_HCL.dob*/ ));
CommonResults OBJIEM = new CommonResults()
{
_dRES = str1,
//_EsapId = E_EMP_HCL.ein,
};
return OBJIEM;
}
Thank You,
(i.e. postman app input as object) object values is passing null.
Tuesday, May 23, 2017 12:12 PM -
User-1451335618 posted
I have successfully implemented rest application in my web app. I was sending parameter names wrong .
Thank You so much for ur valuable and quick reply .
Thanks
Wednesday, May 24, 2017 1:03 PM -
User-1451335618 posted
My Updated Code
IGetService.cs code
[OperationContract]
[WebInvoke(Method = "POST",
UriTemplate = "/NaturalAdditionByObject", BodyStyle = WebMessageBodyStyle.Wrapped, RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
CommonResults NaturalAdditionByObject(E_EMPLOYEE_DATA_HCL NatObj);[OperationContract]
[WebInvoke(Method = "POST",
UriTemplate = "/DepDeleteData", BodyStyle = WebMessageBodyStyle.Wrapped, RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)]
CommonResults DepDeleteData(string empsapid, long hcldepid, string wef, string deletionremarks);GetService.svc.cs code
public CommonResults DepDeleteData(string empsapid, long hcldepid, string wef, string deletionremarks)
{string str1 = GetHash(string.Format("{0}{1}{2}{3}", empsapid, hcldepid, wef, deletionremarks));
CommonResults OBJIEM = new CommonResults()
{
_dRES = str1,
_EsapId = empsapid,
};
return OBJIEM;
}public CommonResults NaturalAdditionByObject(E_EMPLOYEE_DATA_HCL NatObj)
{
string str1 = GetHash(NatObj.E_EMP_HCL.empsapid + NatObj.E_EMP_HCL.hcldepid + NatObj.E_EMP_HCL.depname+ NatObj.E_EMP_HCL.dob+ NatObj.E_EMP_HCL.relationcode+ NatObj.E_EMP_HCL.dom+ NatObj.E_EMP_HCL.maritalstatus + NatObj.E_EMP_HCL.gender+ NatObj.E_EMP_HCL.bloodgroup);
CommonResults OBJIEM = new CommonResults()
{
_dRES = str1,
_EsapId = NatObj.E_EMP_HCL.empsapid,
};
return OBJIEM;}
private string GetHash(string MyString)
{
byte[] ByteData = Encoding.ASCII.GetBytes(MyString);System.Security.Cryptography.SHA1 oMd5 = System.Security.Cryptography.SHA1.Create();
byte[] HashData = oMd5.ComputeHash(ByteData);
StringBuilder oSb = new StringBuilder();
for (int x = 0; x < HashData.Length; x++)
{
oSb.Append(HashData[x].ToString("x2"));
}return oSb.ToString();
}CommonResults.cs common class
public class CommonResults
{
//private string DelMarks;
//private string DWEF;
private string EsapId;private string dRES;
//public string _DelMarks
//{
// get { return DelMarks; }
// set { DelMarks = value; }
//}
public string _EsapId
{
get { return EsapId; }
set { EsapId = value; }
}
//public string _DWEF
//{
// get { return DWEF; }
// set { DWEF = value; }
//}
public string _dRES
{
get { return dRES; }
set { dRES = value; }
}
public CommonResults()
{
//DelMarks = string.Empty;
EsapId = string.Empty;
//DWEF = string.Empty;
dRES = string.Empty;
}}
webform1.aspx.cs code
pageLoad()
{
callService()l;
}
callService()
{
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(E_EMPLOYEE_DATA_HCL));
MemoryStream mem = new MemoryStream();
ser.WriteObject(mem, objEMPLOYEE_DATA_HCL);
string data = Encoding.UTF8.GetString(mem.ToArray(), 0, (int)mem.Length);
data = Newtonsoft.Json.JsonConvert.SerializeObject(new { NatObj = GetInputObject() });
WebClient webClient = new WebClient();
webClient.Headers["Content-type"] = "application/json";
webClient.Encoding = Encoding.UTF8;
webClient.UploadString("http://localhost:63275/GetService.svc/NaturalAddition", "POST", data);Label1.Text = "manual input - " +" "+ data;
}
E_EMPLOYEE_DATA_HCL objEMPLOYEE_DATA_HCL = new E_EMPLOYEE_DATA_HCL();
private E_EMPLOYEE_DATA_HCL GetInputObject()
{
try
{
objEMPLOYEE_DATA_HCL.E_EMP_HCL = new E_EMP_HCL()
{
ein= "90080",
empsapid = "90080",
insuredname="ramesh",
hcldepid = "404056",
depname = "Ramesh",
dob = "1989-09-21",
relationcode = "7",
dom = "2017-05-15",
maritalstatus = "M",
gender = "F",
bloodgroup = "0",};
}
catch (Exception ex)
{}
return objEMPLOYEE_DATA_HCL;}
Thursday, May 25, 2017 4:50 AM -
User1967761114 posted
Hi swat123,
Could you sure the type E_EMPLOYEE_DATA_HCL ‘s namespace is same as with your server? Otherwise they can’t mapped.
And I’m not sure the way you used is available.
You could use ChannelFactory to invoke the WCF service.
https://msdn.microsoft.com/en-us/library/ms734681(v=vs.110).aspx
Also you could invoke the WCF service by visual studio’s feature(add service reference),it will auto generate client proxy.
https://msdn.microsoft.com/en-us/library/bb386386.aspx
If you have any other questions, please feel free to contact me any time.
Best Regards
Even
Friday, May 26, 2017 9:43 AM -
User-1451335618 posted
Thank You so much.
My new query is realted to oracle .. i an trying to convert excel sheet data into xml and try to insert into oracle server.
My sheer contains date column. i have done coding for check of valid date -
public bool CheckDate(string input_date, string input_formt, ref StringBuilder message)
{
string MyDtFormat = string.Empty;
string[] Dates;
try
{
bool b = DateTime.TryParseExact(input_date, input_formt, null, DateTimeStyles.None, out exdate);if (input_formt == "dd-mm-yyyy" && DateTime.TryParseExact(input_date, input_formt, null, DateTimeStyles.None, out exdate) == true)
{
Dates = input_date.Split('-');
MyDtFormat = Dates[0] + '-' + (Dates[1]) + '-' + Dates[2];
int max_daays = DateTime.DaysInMonth(Convert.ToInt32(Dates[2]), Convert.ToInt32(Dates[1]));
if (Convert.ToInt32(Dates[1]) > 12 || Convert.ToInt32(Dates[1]) < 1)
{
Check_Date = false;
message.Append("invalid month...");
log.Error(message.ToString());}
else if (Convert.ToInt32(Dates[0]) > max_daays || (Convert.ToInt32(Dates[0]) < 1))
{
Check_Date = false;
message.Append("invalid days in month...");
log.Error(message.ToString());
}
else if (Convert.ToInt32(Dates[2]) == 0000)
{
Check_Date = false;
message.Append("invalid year...");
log.Error(message.ToString());
}
else
{
Check_Date = true;
}
}else if (input_formt == "dd/mm/yyyy" && DateTime.TryParseExact(input_date, input_formt, null, DateTimeStyles.None, out exdate) == true)
{
Dates = input_date.Split('/');
MyDtFormat = Dates[0] + '/' + (Dates[1]) + '/' + Dates[2];
int max_daays = DateTime.DaysInMonth(Convert.ToInt32(Dates[2]), Convert.ToInt32(Dates[1]));
if (Convert.ToInt32(Dates[1]) > 12 || Convert.ToInt32(Dates[1]) < 1)
{
Check_Date = false;
message.Append("invalid month...");
log.Error(message.ToString());}
else if (Convert.ToInt32(Dates[0]) >(max_daays) || Convert.ToInt32(Dates[0]) < 1)
{
Check_Date = false;
message.Append("invalid days in month51...");
log.Error(message.ToString());
}
else if (Convert.ToInt32(Dates[2]) == 0000)
{
Check_Date = false;
message.Append("invalid year...");
log.Error(message.ToString());
}
else
{
Check_Date = true;
}
}
else if (input_formt == "mm-dd-yyyy" && DateTime.TryParseExact(input_date, input_formt, null, DateTimeStyles.None, out exdate) == true)
{
Dates = input_date.Split('-');
MyDtFormat = Dates[0] + '-' + (Dates[1]) + '-' + Dates[2];
int max_daays = DateTime.DaysInMonth(Convert.ToInt32(Dates[2]), Convert.ToInt32(Dates[0]));
if (Convert.ToInt32(Dates[1]) > (max_daays) || Convert.ToInt32(Dates[1]) < 1)
{
Check_Date = false;
message.Append("invalid days in month...");
log.Error(message.ToString());}
else if (Convert.ToInt32(Dates[0]) > 12 || Convert.ToInt32(Dates[0]) < 1)
{
Check_Date = false;
message.Append("invalid month5555...");
log.Error(message.ToString());
}
else if (Convert.ToInt32(Dates[2]) == 0000)
{
Check_Date = false;
message.Append("invalid year...");
log.Error(message.ToString());
}
else
{
Check_Date = true;
}}
else if (input_formt == "mm/dd/yyyy" && DateTime.TryParseExact(input_date, input_formt, null, DateTimeStyles.None, out exdate) == true)
{
Dates = input_date.Split('/');
MyDtFormat = Dates[0] + '/' + (Dates[1]) + '/' + Dates[2];
int max_daays = DateTime.DaysInMonth(Convert.ToInt32(Dates[2]), Convert.ToInt32(Dates[0]));
if (Convert.ToInt32(Dates[1]) > (max_daays) || Convert.ToInt32(Dates[1]) < 1)
{
Check_Date = false;
message.Append("invalid days in month...");
log.Error(message.ToString());}
else if (Convert.ToInt32(Dates[0]) > 12 || Convert.ToInt32(Dates[0]) < 1)
{
Check_Date = false;
message.Append("invalid month...");
log.Error(message.ToString());
}
else if (Convert.ToInt32(Dates[2]) == 0000)
{
Check_Date = false;
message.Append("invalid year...");
log.Error(message.ToString());
}
else
{
Check_Date = true;
}
}
else
{
Check_Date = false;
message.Append("invalid date...");
log.Error(message.ToString());
}
}
catch (Exception ex)
{
Check_Date = false;
log.Error("Error in CheckDate. " + ex.Message);
}
return Check_Date;
}
public string CheckNullDate(string selected_date, string selected_dateformat)
{try
{
if (selected_date == "" && selected_dateformat == "dd-mm-yyyy")
{
selected_date = "01-01-1900";
}
else if (selected_date == "" && selected_dateformat == "dd/mm/yyyy")
{
selected_date = "01/01/1900";
}
else if (selected_date == "" && selected_dateformat == "mm-dd-yyyy")
{
selected_date = "01-01-1900";
}
else if (selected_date == "" && selected_dateformat == "mm/dd/yyyy")
{
selected_date = "01/01/1900";
}
}
catch
{
log.Error("error in CheckNullDate...");
}
return selected_date;
}the xml is also going right .. error is when i am trying to enter date 31-03-2010 plsql developer is throwing error saying not a valid month package or procedure failed while trying to insert or update
Kindly help
Tuesday, May 30, 2017 7:59 AM -
User-1451335618 posted
hi,
public void callservie()
{
try
{
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(Acnt_User));
MemoryStream mem = new MemoryStream();
GetInputObject();
ser.WriteObject(mem, objui);
string data =
Encoding.UTF8.GetString(mem.ToArray(), 0, (int)mem.Length);
data = Newtonsoft.Json.JsonConvert.SerializeObject(new { Acnt_User = GetInputObject() });
WebClient webClient = new WebClient();
webClient.Headers["Content-type"] = "application/json";
webClient.Encoding = Encoding.UTF8;
webClient.UploadString("http://localhost:50201/Service1.svc/GetRows", "POST", data);
lblgetdata.Text = "manual input - " + " " + data;
}
catch (Exception ex)
{ lblgetdata.Text = ex.Message; }
}
}is my code to retrieve records from sql server and i m getting exception at
webClient.UploadString("http://localhost:50201/Service1.svc/GetRows", "POST", data);
please help
Monday, June 12, 2017 6:29 AM -
User475983607 posted
Create a WCF web reference.
https://msdn.microsoft.com/en-us/library/bb628652.aspx
Or use Web API not WCF.
is my code to retrieve records from sql server and i m getting exception at
webClient.UploadString("http://localhost:50201/Service1.svc/GetRows", "POST", data);
It is always best to post the error otherwise the community has to guess.
Monday, June 12, 2017 10:40 AM -
User-1451335618 posted
thank u so much
i hv another query
folowing is my code
user.js
function getalldata()
{
$.ajax({
type: "GET",
url: "http://localhost:49734/Service1.svc/GetUserDetails",
contentType: "json",
dataType: 'json',
success: onsuccess ,
error: function (xhr) {
alert("failed");
},
complete: function (xhr) {
alert("completed" + xhr);
}
});
function onsuccess(response) {
alert("ok" + arguments.valueOf() );}
}service1.avc.cs
private string strConnection = ConfigurationManager.ConnectionStrings["conString"].ToString();
public List<user> GetUserDetails()
{
List<user> userdetails = new List<user>();
using (SqlConnection con = new SqlConnection(strConnection))
{
con.Open();
SqlCommand cmd = new SqlCommand("select * from tbl_TempUsers", con);
//cmd.Parameters.AddWithValue("@Name", Username);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dtresult = new DataTable();
da.Fill(dtresult);
if (dtresult.Rows.Count > 0)
{
for (int i = 0; i < dtresult.Rows.Count; i++)
{
user userInfo = new user();
userInfo.Userid = dtresult.Rows[i]["User_Ids"].ToString();
userInfo.FirstName = dtresult.Rows[i]["User_FirstName"].ToString();
userInfo.LastName = dtresult.Rows[i]["User_LastNames"].ToString();
userInfo.Emial = dtresult.Rows[i]["User_Email"].ToString();
userdetails.Add(userInfo);
}
}
con.Close();
}
return userdetails;
}webform1.aspx
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript" src="custom/js/user.js" ></script>
<script type="text/javascript">
$(document).ready(function () {
$('#btncall').click(function () {
getalldata();
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button ID="btncall" runat="server" Text="Button" />
<br />
<table id="tbDetails" cellpadding="0" cellspacing="0">
<thead style="background-color:#DC5807; color:White; font-weight:bold">
<tr style="border:solid 1px #000000">
<td>UserId</td>
<td>UserName</td></tr>
</thead>
<tbody>
</tbody>
</table></div>
</form>
</body>
</html>when i run webform1.aspx alert message in success function should show the datat returning in service1.avc.cs file ??
i want output in form
{
"GetCustomersResult": [
{
"Emial": "",
"FirstName": "mina",
"LastName": "",
"Userid": ""
},
{
"Emial": "",
"FirstName": "nitish",
"LastName": "",
"Userid": ""
}
]
}in json
please help
Tuesday, June 13, 2017 8:20 AM -
User1967761114 posted
Hi swat123,
According to your last reply, I wrote an example for you.
I show some code at here, you could download the whole service project by the following link.
https://1drv.ms/u/s!AgdLRPNxESMTg1_VxyPWDO9fvenN
(1) Data Contract
[DataContract] public class User { [DataMember] public int Userid { get; set; } [DataMember] public string FirstName { get; set; } [DataMember] public string LastName { get; set; } [DataMember] public string Email { get; set; } }
(2) Service Contract
[ServiceContract] public interface IService1 { [OperationContract] [WebInvoke(UriTemplate = "/GetUserDetails", Method = "POST", BodyStyle = WebMessageBodyStyle.Bare, RequestFormat = WebMessageFormat.Json, ResponseFormat = WebMessageFormat.Json)] List<User> GetUserDetails(); }
(3) The implement of the service contract
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)] public class Service1 : IService1 { public List<User> GetUserDetails() { //For example,I wrote it by simulate data, in your case, you could read from DB. var result = new List<User>(); result.Add(new User() { Userid = 1, FirstName = "Lebron", LastName = "James", Email = "James@test.com" }); result.Add(new User() { Userid = 2, FirstName = "Steven", LastName = "Curry", Email = "Curry@test.com" }); result.Add(new User() { Userid = 3, FirstName = "Kevin", LastName = "Duran", Email = "Duran@test.com" }); return result; } }
(4) Client invoke
<form id="form1" runat="server"> <div> <asp:Button ID="btncall" runat="server" Text="Button" OnClientClick="return getalldata()" /> </div> </form> <script src="../Scripts/jquery-1.10.2.min.js"></script> <script type="text/javascript"> function getalldata() { $.ajax({ type: "POST", url: "http://localhost:56500/Service1.svc/GetUserDetails", contentType: "application/json; charset=utf-8", dataType: "json", success: function (result) { console.log(result); }, }); return false; } </script>
Then, the result as below:
If you have any other questions, please feel free to contact me any time.
Best Regards
Even
Tuesday, June 13, 2017 9:28 AM -
User-1451335618 posted
hi,thank
thank u so much again,
thank u so much again,
but i want to retrieve datta from database in sql server .
my table name is tbl_usertemp.
and want to show retrieved json data in jquery alert box.
my ser ice url is working correctly in web browser and local iis . but while trying it with jquery ajax call , the onsuccess function returning null.
my service url
http://localhost:49734/Service1.svc/GetUserDetails
output in web browser-this data retrieved from sql server database table tbl_usertemp
[{"Emial":"minap@gmail.com","FirstName":"mina","LastName":"pande","Userid":"1"},{"Emial":"nitish@yahoo.com","FirstName":"nitish","LastName":"joshi","Userid":"2"}]
Tuesday, June 13, 2017 10:20 AM -
User-1451335618 posted
HI,
I tries this code, but giving error as-
NetworkError: Failed to execute 'send' on 'XMLHttpRequest': Failed to load 'http://localhost:49734/Service1.svc/InsertObjects'.
how to overcome this.
kindly help
thank u
Wednesday, June 14, 2017 6:35 AM -
User475983607 posted
You are probably facing a CORS error.
Wednesday, June 14, 2017 10:32 AM -
User1967761114 posted
Hi swat123,
According to your last reply, there had another 2 key points in the example project which I post before, you could see it carefully~.
I recommend you could add your code in this example project, or also you could try to invoke the service in this example project.
(1) Global.asax, enable CORS in Application_BeginRequest
public class Global : System.Web.HttpApplication { protected void Application_BeginRequest(object sender, EventArgs e) { //enable CORS HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*"); if (HttpContext.Current.Request.HttpMethod == "OPTIONS") { HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "POST, PUT, DELETE"); HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept"); HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000"); HttpContext.Current.Response.End(); } } }
(2) web.config, add the following configuration into the configuration file.
<configuration> <system.serviceModel> <serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true"> <serviceActivations> <add factory="System.ServiceModel.Activation.WebServiceHostFactory" relativeAddress="Service1.svc" service="WcfService1.Service1"/> </serviceActivations> </serviceHostingEnvironment> </system.serviceModel> </configuration>
relativeAddress: the relative file path of the service.
service: the full name of the service.
If you have any other questions, please feel free to contact me any time.
Best Regards
Even
Thursday, June 15, 2017 1:31 AM -
User-1451335618 posted
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="WebApplication5.WebForm1" %>
<!DOCTYPE html>
<html>
<head>
<title>Hello jQuery</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js"></script>
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script src="hello.js"></script>
</head><body>
<div>
<p class="greeting-id">The ID is </p>
<p class="greeting-content">The content is </p>
</div>
</body>
</html>/// <reference path="http://localhost:54466/Service1.svc" />
$(document).ready(function () {
$.ajax({
//url: "http://rest-service.guides.spring.io/greeting"
type: "POST",
contentType: "application/json; charset=utf-8",
type:"json",
url: "http://localhost:54466/Service1.svc/Printname"
}).then(function (data) {
$('.greeting-id').append(data);
$('.greeting-content').append(data.content);
});
});when i run project $.ajax call is not getting hit . it is not going to then(function (data) { also.
kindly help
Thursday, June 15, 2017 5:19 AM -
User1967761114 posted
Hi swat123,
However, I’m unsure which error had happened with you, could you send the whole project to me? I will help you to find and solve the issue.
If you have any other questions, please feel free to contact me any time.
Best Regards
Even
Tuesday, June 20, 2017 8:12 AM -
User-1451335618 posted
Hi,
Thank u So much for ur help,
My another query is as follows-
i have comapnymaster table containing 72 records with company type.
I have to goup it by company type and each type having 2 or 4 types with description and different ids.
i have used linq group by clause on a generic list but i want to convert linq result into generic list,
Kindly help
My code-
using (SqlCommand sqlCmd = new SqlCommand("RW_SP_GET_TPADATA", sqlCon))
{
sqlCmd.CommandType = CommandType.StoredProcedure;
sqlCon.Open();
dr = sqlCmd.ExecuteReader();
if (dr.HasRows)
{
while (dr.Read())
{
count = count + 1;
cobj = new CompanyTPAMaster()
{
R_CompType = new R_CompType() { cmp_type = dr["TYPE"].ToString(), },
R_Type_DtlObJ = new List<R_Type_Dtl> { new R_Type_Dtl {
cmp_type = dr["TYPE"].ToString(),
DESC = dr["DESC"].ToString().Trim(),
DESCRIPTION = dr["DESCRIPTION"].ToString().Trim(),
ID = dr["ID"] == DBNull.Value ? 0 : Convert.ToInt32(dr["ID"].ToString().Trim()),
RECORD_STATUS = dr["RECORD_STATUS"] == DBNull.Value ? 0 : Convert.ToInt32(dr["RECORD_STATUS"].ToString().Trim()),} }
};
listmaster.Add(cobj);
}}
var results = listmaster.GroupBy(p => p.R_CompType.cmp_type,
(ID, DESC) => new { ID = ID, Des = DESC.ToList() })
.OrderBy(p => p.ID)
.Select(p => p.Des).ToList();Monday, July 3, 2017 5:29 AM