Am getting statuss 500 error.Am not getting exactly where am doing wrong.
When i click on getcustomer button 'Getcustomers' method is called which retuns json .
Script:
<script>
var MyApp = angular.module("MyApp", []);
MyApp.controller("ctrl", function ($scope, $http) {
$scope.helloAngular = "hello";
$scope.GetCustomers = function () {
debugger;
$http.get("/Home/Getcustomers")
.success(function (data) {
$scope.customerDetails = data;
}).
error(function (data, status, thrownError) {
//alert(status);
//alert(data.responseText);
alert(thrownError);
});
}
});
</script>
Server side code:
I get json data from this function:
public ActionResult Getcustomers()
{
string query = "select top 10 * from Customers ";
ArrayList custArray = new ArrayList();
SqlCommand cmd = new SqlCommand(query, sqlcon);
sqlcon.Open();
var reader = cmd.ExecuteReader();
while (reader.Read())
{
custArray.Add(new
{
Name = reader["ContactName"],
City = reader["City"],
PostalCode = reader["PostalCode"],
Country = reader["Country"],
Phone = reader["Phone"],
});
}
var result= JsonConvert.SerializeObject(custArray);
sqlcon.Close();
return Json(result);
}
I have search ,but cant get where am going wrong.Plz help me.
Yes, At last got what i was missing.
As status 500 is server error.It was occuring because the reader was not closed
after reading the sqldatareader(I really make silly mistakes)
public ActionResult Getcustomers()
{
string query = "select top 10 * from Customers ";
ArrayList custArray = new ArrayList();
SqlCommand cmd = new SqlCommand(query, sqlcon);
sqlcon.Open();
var reader = cmd.ExecuteReader();
while (reader.Read())
{
custArray.Add(new
{
Name = reader["ContactName"],
City = reader["City"],
PostalCode = reader["PostalCode"],
Country = reader["Country"],
Phone = reader["Phone"],
});
}
//Clean sqldatareader here;
reader.Close();
reader.Dispose();
var result= JsonConvert.SerializeObject(custArray);
sqlcon.Close();
return Json(result);
}
Related
I am consuming Wcf REST Service into Angualar JS Application. I am facing some problems . As I know WCf REST Service allow GET ,POST,PUT and DELETE Operation. But I want to return a method true or flase from Wcf Service into Angular JS application. For Example if ueranme is exist into Database then i want to return true and displaying message in angular js application that username is exist otherwise the information will be stored in database . if is possible please provide an example with good explanation .
Here is the interface.
[OperationContract]
[WebInvoke(Method = "POST",
RequestFormat = WebMessageFormat.Json,
ResponseFormat = WebMessageFormat.Json,
//BodyStyle = WebMessageBodyStyle.WrappedRequest,
UriTemplate = "/AuthenticateUser")]
bool AuthenticateUser(UserLogin userLogin );
Here is the Implematation .
public bool AuthenticateUser(UserLogin userLogin)
{
string CS = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
using (SqlConnection con = new SqlConnection(CS))
{
SqlCommand cmd = new SqlCommand("spAuthenticateUser", con);
cmd.CommandType = CommandType.StoredProcedure;
string encryptedpassword = FormsAuthentication.HashPasswordForStoringInConfigFile(userLogin.Password, "SHA1");
SqlParameter paramUsername = new SqlParameter("#UserName", userLogin.Username);
SqlParameter paramPassword = new SqlParameter("#Password", encryptedpassword);
cmd.Parameters.Add(paramUsername);
cmd.Parameters.Add(paramPassword);
con.Open();
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
int RetryAttempts = Convert.ToInt32(rdr["RetryAttempts"]);
if (Convert.ToBoolean(rdr["AccountLocked"]))
{
return true;
}
else if (RetryAttempts > 0)
{
int AttemptsLeft = (4 - RetryAttempts);
return false;
}
else if (Convert.ToBoolean(rdr["Authenticated"]))
{
return true;
}
}
return false;
}
}
Here is the Script code ..
///// <reference path="../angular.min.js" />
var app = angular.module("WebClientModule", [])
.controller('Web_Client_Controller', ["$scope", 'myService', function ($scope, myService) {
$scope.OperType = 1;
//1 Mean New Entry
//To Clear all input controls.
function ClearModels() {
$scope.OperType = 1;
$scope.Username = "";
$scope.Password = "";
}
$scope.login = function () {
var User = {
Username: $scope.Username,
Password: $scope.Password,
};
myService.AuthenticateUser(User).then(function (pl) {
$scope.msg = "Username and password is correct ";
window.location.href = "/Welcome/Index";
ClearModels();
}, function (err) {
$scope.msg = "Password Incorrect !";
console.log("Some error Occured" + err);
});
};
}]);
app.service("myService", function ($http) {
// Create new record
this.AuthenticateUser = function (User) {
return $http.post("http://localhost:52098/HalifaxIISService.svc/AuthenticateUser", JSON.stringify(User));
}
})
I work on a webapp, i have a probleme to send data and i didn't find some example. I use AngularJS and JavaEE.
Now :
AngularJs :
quiz is an object.
roomFactory.create = function(quiz){
//item.idLesson = $stateParams.lessonid;
return $http.post("/api/private/room/create",quiz)
.then(function (response){
roomFactory.room = response.data;
return roomFactory.room;
},function (response){
$q.reject(response);
});
};
Servlet :
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//get the identity of the one who send the request
Map<String, Object> payload = AppConfig.getRequestPayload(request);
//objetMapper --> use to add request....
ObjectMapper objectMapper = new ObjectMapper();
Random randomGenerator;
// Number of question for the two sets
int nbQuestion = 0;
List<Question> questionsRandom = new ArrayList<>();
//Get object from request
//List<String> list = objectMapper.readValue(AppConfig.getJsonRequest(request), new TypeReference<List<String>>(){});
//List<Quiz> list2 = objectMapper.readValue(AppConfig.getJsonRequest(request), new TypeReference<List<Quiz>>(){});
//String name = list.get(0);
Quiz quiz = objectMapper.readValue(AppConfig.getJsonRequest(request),Quiz.class);
if (quiz.getDuration() == null) {
quiz.setDuration(-1);
}
//LOGGER.info("getIdLesson : ");
//Get list of question from datastore
List<Question> questions = ofy().load().type(Question.class).filter("idLesson", quiz.getIdLesson()).list();
//Take some questions from the list to make the quiz
if (!questions.isEmpty()) {
if (questions.size() < quiz.getNbQuestion()) {
nbQuestion = questions.size();
} else {
nbQuestion = quiz.getNbQuestion();
}
// we peek all the question randomly to the server and create a list of question
while (nbQuestion > 0) {
randomGenerator = new Random();
int index = randomGenerator.nextInt(questions.size());
questionsRandom.add(questions.get(index));
questions.remove(questions.get(index));
nbQuestion--;
}
if (!questionsRandom.isEmpty()) {
//Set the quiz
quiz.setQuestions(questionsRandom);
quiz.setNbQuestion(questionsRandom.size());
Lesson lesson = ofy().load().type(Lesson.class).id(Long.valueOf(quiz.getIdLesson())).now();
//Lesson lesson = ofy().load().type(Lesson.class).filter("idLesson", quiz.getIdLesson()).first().now();
//SET the room
//User user = ofy().load().type(User.class).id(Long.valueOf(jsonUserId.toString())).now();
User user = ofy().load().type(User.class).filter("email", payload.get("email").toString()).first().now();
//LOGGER.info("User : "+user.getFirstName());
Room room = new Room(user, quiz, 60);
room.calculTimeToFinishTheQuiz();
room.setName(lesson.getTitle() + RoomManager.roomNumber);
room.setId(quiz.getIdLesson() + RoomManager.roomNumber);
//Save the room in RoomManager
RoomManager.roomNumber++;
RoomManager.addNewRoom(quiz.getIdLesson(), room);
//Send the room in response
String json = objectMapper.writeValueAsString(room);
response.setContentType("application/json");
response.getWriter().write(json);
}
}
}
}
I need another parameter in my fonction create :
roomFactory.create = function(quiz, roomName){
I try this to send both data :
return $http.post("/api/private/room/create",quiz, roomName)
or
return $http.post("/api/private/room/create",[quiz, roomName])
Get data in Servlet :
first solution :
String roomName= objectMapper.readValue(AppConfig.getJsonRequest(request),String.class);
second solution :
List<String> list = objectMapper.readValue(AppConfig.getJsonRequest(request), new TypeReference<List<String>>(){});
String roomName = list.get(0);
roomName = roomName.replace("\"", "");
but the second didn't work because quiz is an object. I try to convert quiz but i didn't work as well.
You can pass multiple Data as follow
var Indata = {'pram1': 'value1', 'pram2': 'value2' };
$http.post("/api/private/room/create", Indata)
.then(function (response){
roomFactory.room = response.data;
return roomFactory.room;
},function (response){
$q.reject(response);
});
Here is the better example
For sending multiple list in the json to rest api use this code
var settings1 = {pram1: 'value1', pram2: 'value2',pram3: 'value3'};
var settings2 = {pram1: 'value1', pram2: 'value2',pram3: 'value3'};
var settings3 = {pram1: 'value1', pram2: 'value2',pram3: 'value3'};
var listObj = [settings1,settings2,settings3];
$http.post("/api/private/room/create",listObj)
.then(function (response){
roomFactory.room = response.data;
return roomFactory.room;
},function (response){
$q.reject(response);
});
and in the controller
#RequestMapping(value = "/api/private/room/create", method = RequestMethod.POST, produces = MediaType.APPLICATION_JSON_VALUE)
ResponseEntity createRequest(#RequestBody List<SettingsModel> settingsList) {
}
SeetingsModel class is like this
public class SettingsModel {
private String param1;
private String param2;
private String param3;
public String getParam1() {
return param1;
}
public void setParam1(String param1) {
this.param1 = param1;
}
public String getParam2() {
return param2;
}
public void setParam2(String param2) {
this.param2 = param2;
}
public String getParam3() {
return param3;
}
public void setParam3(String param3) {
this.param3 = param3;
}
}
This is my POST request:
$scope.TestPost = function (par1, par2) {
$http.post('EmployeeService.asmx/GetAllEmployees',
{
par1: par1,
par2: par2
})
.then(function (response) {
$scope.employees = response.data;
})
};
And this is code that gets called on the server side. Code is called correctly and json serialized object is written to response:
[WebMethod]
public void GetAllEmployees(string par1, string par2)
{
List<Employee> listEmployees = new List<Employee>();
string cs = ConfigurationManager.ConnectionStrings["connString"].ConnectionString;
using(SqlConnection con = new SqlConnection(cs))
{
List<Employee> _list = new List<Employee>();
SqlCommand cmd = new SqlCommand("SELECT * FROM tblEmployees", con);
con.Open();
SqlDataReader rdr = cmd.ExecuteReader();
while(rdr.Read())
{
Employee emp = new Employee
{
id = Convert.ToInt32(rdr["Id"]),
name = rdr["Name"].ToString(),
gender = rdr["Gender"].ToString(),
salary = Convert.ToInt32(rdr["Salary"])
};
listEmployees.Add(emp);
}
}
JavaScriptSerializer js = new JavaScriptSerializer();
Context.Response.Write(js.Serialize(listEmployees));
}
Response object is this - some strange line is appended at the end {"d":null} which I can not understand why. I am also receiving error on the client side: SyntaxError: Unexpected token:
"[{"id":1,"name":"Ben","gender":"Male","salary":55000},
{"id":2,"name":"Sara","gender":"Female","salary":68000},
{"id":3,"name":"Mark","gender":"Male","salary":57000},
{"id":4,"name":"Pam","gender":"Female","salary":53000},
{"id":5,"name":"Todd","gender":"Male","salary":60000}]{"d":null}"
Thanks to #82Tuskers and this post:
Differences between Response.End() and Response.Flush()
I've found the solution. I've changed code at the end of server side function to:
Context.Response.Clear();
Context.Response.Write(js.Serialize(listEmployees));
Context.Response.Flush();
Context.Response.End();
Response is now OK.
is there a javascript where I can populate a gridview from the database? For example is there a javascript for this code?
gvRFPCorpCode is the name of my gridview
private void fillCorpCode()
{
DataSet ds = new DataSet();
data.gRowId = this.txtROWID.Text;
ds = data.GetCorpCode();
if (ds != null)
{
if (ds.Tables[0].Rows.Count > 0)
{
this.gvRFPCorpCode.DataSource = ds.Tables[0];
this.gvRFPCorpCode.DataBind();
}
}
}
ds = data.GetCorpCode(); is equal to this:
public DataSet GetCorpCode()
{
DataSet ds = new DataSet();
SqlParameter[] sqlParam = new SqlParameter[]
{
new SqlParameter("#RowId",sRowId)
};
if (this.InitDataLayerObject() == true)
{
ds = this.ExecuteQuery("dbo.sp_ESS_RFP_GetCorpCode", sqlParam);
}
return ds;
}
It's a stored procedure, here is my stored procedure "dbo.sp_ESS_RFP_GetCorpCode"
ALTER PROCEDURE [dbo].[sp_ESS_RFP_GetCorpCode]
-- Add the parameters for the stored procedure here
#RowId varchar(max)
AS
BEGIN
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
declare #xml as xml
select
#xml =convert(xml,CORPCODE)
from Tbl_ESS_Request_For_Payment_Save
where ROWID=#RowId
select
tbl.col.value('CorpCode[1]', 'varchar(100)') as CorpCode,
tbl.col.value('Amount[1]', 'varchar(100)')as Amount
from #xml.nodes('/NewDataSet/Table1') tbl(col)
END
What I want is to have a javascript equivalent to private void fillCorpCode to populate it on my gridview, BTW, You might ask why I need a javascript if i already have a code in c#, It's because of some process in my program and it is difficult to explain. So please help me on this one, thank you in advance!
do like this
function getJSONData(selVal, callbackName) {
selVal = encodeURI(selVal);
var formdata = { };// any data you want to pass as input
$.ajax({
type: "POST",
url: "aspx",
data: formdata,
cache: false,
success: function (data) {
callbackName(data);
},
error: function (xhr, ajaxOptions, thrownError) {
alert('Error in processing data !!' + thrownError);
},
async: false
});
}
function createTable() {
mytable = $('<table Class="table table-striped table-bordered table-hover"></table>').attr({ id: "basicTable" });
// alert(rowData);
var rowobj = JSON.parse(rowData);
// To populate header
var firstrow;
var firstrow = $('<tr></tr>').appendTo(mytable);
$('<td></td>').text('Entity Name').appendTo(firstrow);
$('<td></td>').text('Attribute Name').appendTo(firstrow);
$('<td></td>').text(' Value').appendTo(firstrow);
// To populate rows
$.each(rowobj, function (i, obj) {
$('<td valign="middle"></td>').text(obj.ParentName).appendTo(row);
$('<td valign="middle"></td>').text(obj.ParentName1).appendTo(row);
$('<td valign="middle"></td>').text(obj.ParentName2).appendTo(row);});
}
//C# method
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json, UseHttpGet = true)]
public static string Mymethod(string entityName, string entityType, string filterValues)
{
List<MasterFields> fields = null;
ServiceWrapper<ILOSService>.Perform(svcClient =>
{
fields = getfields();
});
JavaScriptSerializer jss = new JavaScriptSerializer();
string output = jss.Serialize(fields);
return output;
}
//IService.cs
[WebInvoke(Method = "POST", ResponseFormat = WebMessageFormat.Json)]
String CheckAuth(String AccountID, String Password);
//Service.cs
public String CheckAuth(String AccountID, String Password)
{
String message="";
string StrCon = #"my conn string";
DataTable dt = new DataTable();
SqlConnection con = new SqlConnection(StrCon);
string qry = "select * from Account where AccountID='" + AccountID + "' and Password='"+Password+"'";
con.Open();
SqlCommand cmd = new SqlCommand(qry, con);
SqlDataAdapter adp = new SqlDataAdapter(cmd);
adp.Fill(dt);
if (dt.Rows.Count > 0)
{
message = "Authorized";
}
else
{
message = "unauthorized";
}
con.Close();
return message;
}
i want to know that what does the variable d: stands for and how can i change the d: to Message:..??
i need some suggestion thank you..
//GETTING output
{
d: "Authorized"
}
//expected output
{
Message: "Authorized"
}
i m new to wcf so it will be helpful if i get undertandable suggestion
thank you..
The variable d is there for security reasons.
But you can always return an object instead of a string
public object CheckAuth(String AccountID, String Password)
{
// .. snip
return new {
Message = message
};
}
If you call your service like this, it should return something like
{
"d" : {
"Message": "Authorized"
}
}
Not sure what you're using on the front-end, if you use jQuery you could make a wrapper around the ajax function:
function doAjax(url, data, cb) {
$.ajax({
url: url,
data: data,
success: function(data) {
cb(data.d);
}
});
}
and make use of your new defined function like this:
doAjax('/CheckAuth', yourDataObj, function result(data) {
console.log(data.Message);
});