Use AJAX to send array of JavaScript objects to database - c#

In this project the user will have the opportunity to create an array of objects with properties and those properties match up with a database table, with the properties of the object being the same as the columns in the database cable. The SQL looks like:
create table ServiceData
(ServiceId int
,ServiceDescription varchar(50)
)
go
create type ServiceType as table
(ServiceId int
,ServiceDescription varchar(50)
)
go
create proc spInsertService
#service ServiceType readonly
as
begin
insert into ServiceData(ServiceId,ServiceDescription)
select * from #service
end
Here I create a custom type and pass that custom type to a stored procedure in the form of a table valued parameter. The SQL and the following C# code execute and work fine:
[WebMethod]
public void InsertServiceData()
{
List<ServiceData> sdList = new List<ServiceData>();
ServiceData sd1 = new ServiceData(1, "first");
ServiceData sd2 = new ServiceData(2, "second");
sdList.Add(sd1);
sdList.Add(sd2);
DataTable dt = new DataTable();
dt.Columns.Add("ServiceId");
dt.Columns.Add("ServiceDescription");
foreach (var data in sdList)
{
dt.Rows.Add(data.ServiceId, data.ServiceDescription);
}
string cs = ConfigurationManager.ConnectionStrings["dbcs"].ConnectionString;
using (var con = new SqlConnection(cs))
{
using (var cmd = new SqlCommand("spInsertService",con))
{
con.Open();
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#service", dt);
cmd.ExecuteNonQuery();
}
}
}
You can see that in this working example I'm not using any AJAX call to send data to the web method. This code currently works and inserts the data from that hardcoded list fine. So when I change the code to actually try to take a JavaScript array like so:
$(document).ready(function ()
{
sd1 = {};
sd1.ServiceId = 1;
sd1.ServiceDescription = "test";
sd2 = {};
sd2.ServiceId = 2;
sd2.ServiceDescription = "other test";
//create array which is meant to mirror the List<ServiceData> in the
//earlier example
service = new Array();
service.push(sd1);
service.push(sd2);
//wrap the array in a data transfer object
var dto = {'sdList': service};
$('#btnSubmit').click(function ()
{
$.ajax(
{
type: "POST",
url: "WebService.asmx/InsertServiceData",
contentType: "application/json",
dataType: "json",
//stringify the dto
data: JSON.stringify(dto),
success: function(data)
{
console.log('success');
},
error: function(thrownError)
{
console.log(thrownError);
}
});
});
});
new C#
[WebMethod]
//this attempts to deserialize the DTO into a list of ServiceData objects
//which are then inserted into the TVP and then to the database
public void InsertServiceData(string sdList)
{
var jss = new JavaScriptSerializer();
List<ServiceData> list = jss.Deserialize<List<ServiceData>>(sdList);
DataTable dt = new DataTable();
dt.Columns.Add("ServiceId");
dt.Columns.Add("ServiceDescription");
foreach (var data in list)
{
dt.Rows.Add(data.ServiceId, data.ServiceDescription);
}
string cs = ConfigurationManager.ConnectionStrings["dbcs"].ConnectionString;
using (var con = new SqlConnection(cs))
{
using (var cmd = new SqlCommand("spInsertService",con))
{
con.Open();
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#service", dt);
cmd.ExecuteNonQuery();
}
}
}
Currently that code gives me the error: Type\u0027System.String\u0027isnotsupportedfordeserializationofanarray
If I don't wrap the array in a DTO object, but still stringify it I get
`System.Collections.Generic.IDictionary`2[[System.String,mscorlib,Version=4.0.0.0,Culture=neutral,PublicKeyToken`
I would like to not have to use SessionState of ViewState for this. Since I know the code works fine if I'm not passing a JavaScript array to the WebMethod, it has to been somewhere in the serialization and deserialization of the array that's breaking it. How can I fix this? It's been driving me nuts for days now

Please note following steps and then change your code lines.
Dont create sd1={} and sd2{}.
Create var list = []; at top then push json object like list.push({"ServiceId":1,"ServiceDescription":"test"}, {"ServiceId":2,"ServiceDescription":"other test"})
Create ajax parameter like var data = "{'sdLists':" +JSON.stringify(list)+"}"; and pass date as param.
Create a bean with variables to map json object as added in list above. see blow.
public class SdList{
private int Serviceid;
public int Serviceid
{
get { return Serviceid; }
set { Serviceid= value; }
}
private string ServiceDescription;
public string ServiceDescription
{
get { return ServiceDescription; }
set { ServiceDescription= value; }
}
}
Now Pass List<SdList> sdLists as parameter list to method as under
var data = "{'sdLists':"+JSON.stringify(list)+"}";
public void InsertServiceData(List sdLists)
Then Convert Json List in to generic list using java script serializer as under,
JavaScriptSerializer jss= new JavaScriptSerializer();
List<SdList> list = jss.ConvertToType<List<SdList>>(sdLists);
I have followed above steps and it is working fine.

Related

How To Pass a List Object From C# to an Oracle Stored Procedure?

I'm trying to send a List Object from my C# WebService method over to my stored procedure in Oracle.
Before posting here, I've tried all suggested duplicate links. Here's what I've accomplished so far:
Success: In C#, I can pass my List values from my HTML page over to my WebService method.
Success: In Oracle, I have created a Table, Object Type, Table Type, and Stored Procedure to accept the List values. I was able to test this using an Anonymous block and sample data.
Problem: I cannot get to pass my List values from my C# WebMethod over to my Oracle Stored Procedure.
I'm currently using the following setup:
Visual Studio 2017
.NET Framework 4.6.1
Oracle.ManagedDataAccess 18.6.0
Keep in mind that the version of Oracle.ManagedDataAccess 18.6.0 does NOT contain the OracleDbType.Array as suggested in the older examples.
public class Automobile
{
public string Make { get; set; }
public string Model { get; set; }
public string Year { get; set; }
public string Country { get; set; }
}
using Oracle.ManagedDataAccess.Client;
using Oracle.ManagedDataAccess.Types;
[WebMethod(EnableSession = true)]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string InsertCars(List<Automobile> myCars, int userID)
{
DataSet dataSet = new DataSet();
using (OracleConnection sqlConnection = new OracleConnection(OracleDBConnection))
{
using (OracleCommand sqlCommand = new OracleCommand("sp_InsertCars", sqlConnection))
{
sqlConnection.Open();
sqlCommand.CommandType = CommandType.StoredProcedure;
sqlCommand.Parameters.Add(
new OracleParameter
{
CollectionType = OracleCollectionType.PLSQLAssociativeArray,
Direction = ParameterDirection.Input,
ParameterName = "p_CarList",
UdtTypeName = "tt_Automobile",
Size = myCars.Count,
Value = myCars.ToArray()
}
);
sqlCommand.Parameters.Add(
new OracleParameter
{
OracleDbType = OracleDbType.Int32,
Direction = ParameterDirection.Input,
ParameterName = "p_UserID",
Value = userID
}
);
sqlCommand.Parameters.Add(
new OracleParameter
{
OracleDbType = OracleDbType.RefCursor,
Direction = ParameterDirection.Output,
ParameterName = "o_Cursor"
}
);
using (OracleDataAdapter sqlAdapter = new OracleDataAdapter(sqlCommand))
{
sqlAdapter.SelectCommand = sqlCommand;
sqlAdapter.Fill(dataSet);
}
}
return JsonConvert.SerializeObject(dataSet);
}
}
CREATE TABLE tblCars
(
RecordID INT GENERATED BY DEFAULT AS IDENTITY NOMINVALUE NOMAXVALUE INCREMENT BY 1 START WITH 1 NOCACHE NOCYCLE NOORDER,
Make NVARCHAR2(100) NULL,
Model NVARCHAR2(100) NULL,
Year NVARCHAR2(4) NULL,
Country NVARCHAR2(100) NULL,
UserID INT NULL
);
CREATE OR REPLACE TYPE ot_Automobile AS OBJECT
(
Make varchar2(100),
Model varchar2(100),
Year varchar2(4),
Country varchar2(100)
);
CREATE OR REPLACE TYPE tt_Automobile AS TABLE OF ot_Automobile;
CREATE OR REPLACE PROCEDURE sp_InsertCars
(
p_CarList In tt_Automobile,
p_UserID In integer,
o_Cursor Out Sys_RefCursor
)
AS
BEGIN
DBMS_Output.Enable;
For RowItem In (Select * From Table(p_CarList))
Loop
Insert Into tblCars
(
Make,
Model,
Year,
Country,
UserID
)
Values(
RowItem.Make,
RowItem.Model,
RowItem.Year,
RowItem.Country,
p_UserID
);
End Loop;
-- Return our results after insert
Open o_Cursor For
Select Make, Model, Year, Country From tblCars Where UserID = p_UserID;
EXCEPTION
When Others Then
DBMS_Output.Put_Line('SQL Error: ' || SQLERRM);
END sp_InsertCars;
COMMIT
/
The result should allow me to pass my array Object from my WebService WebMethod over to my Oracle stored procedure and then loop through each item of the array to perform an Insert.
Here's an example of the data I'm trying to pass in.
this answer depends on commercial package, but if you're as desperate as i am, it's a lifesaver for very reasonable $300 (circa 2020-Q4)... scouts honor, i'm no shill
DevArt's Oracle provider makes elegant work of passing lists of objects to stored procs... it really works... .net core 3.1 compatible, tested on linux, no dependencies on native oracle client ... see my take on a working console app sample below based on the linked forum post
DevArt's "OracleType.GetObjectType()" API makes the UDT marshalling part of this incredibly trivial for us... way less to grok than the existing unmanaged ODP table type support samples i've seen out there for years
strategic consideration - if you already have a sizable code base on an oracle provider, consider just leaving all that code as-is and only take on regression testing this new dependency where the specialized table type support is actually needed
short and sweet sample for quick digestion
using System;
using System.Data;
using Devart.Data.Oracle;
namespace ConsoleApp1
{
class Program
{
private static int oraTable;
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
//good docs:
//direct connection: https://www.devart.com/dotconnect/oracle/docs/StoredProcedures-OracleCommand.html
//linux licensing: https://www.devart.com/dotconnect/oracle/docs/?LicensingStandard.html
using OracleConnection db = new OracleConnection("{insert yours}");
//devart trial licensing nutshell... on WINDOWS, download & run their installer...
//the only thing you really need from that install is the license key file dropped here:
// %programdata%\DevArt\License\Devart.Data.Oracle.key
// then just go nuget the "Devart.Data.Oracle" package reference
//on Windows, the trial license file gets automatically picked up by their runtime
//if you're on Linux, basically just read their good instructions out there
//i've just tested it on WSL so far and plan to try on Azure linux app svc within next day
//db.ConnectionString = "license key=trial:Devart.Data.Oracle.key;" + db.ConnectionString;
db.Direct = true; //nugget: crucial!! https://www.devart.com/dotconnect/oracle/docs/DirectMode.html
db.Open();
var cmd = db.CreateCommand("UserPermissions_u", CommandType.StoredProcedure);
cmd.DeriveParameters();
//tblParm.OracleDbType = OracleDbType.Table;
//passing "table" type proc parm example: https://forums.devart.com/viewtopic.php?t=22243
var obj = new OracleObject(OracleType.GetObjectType("UserPerm", db));
var tbl = new OracleTable(OracleType.GetObjectType("UserPerms", db));
obj["UserPermissionId"] = "sR1CKjKYSKvgU90GUgqq+w==";
obj["adv"] = 1;
tbl.Add(obj);
cmd.Parameters["IN_Email"].Value = "banderson#kingcounty.gov";
cmd.Parameters["IN_Permissions"].Value = tbl;
cmd.ExecuteNonQuery();
//"i can't believe it's not butter!" -me, just now =)
}
}
}
corresponding oracle db definitions:
create or replace type UserPerm as object ( UserPermissionId varchar2(24), std number(1), adv number(1) );
create or replace type UserPerms as table of UserPerm;
create or replace PROCEDURE UserPermissions_u (
IN_Email IN varchar2,
IN_Permissions IN UserPerms
) is
dummyvar number default 0;
begin
select count(*) into dummyvar from table(IN_Permissions);
end;
/
more elaborate shot at generically reflecting on an inbound object to hydrate the proc parms like the OP's request... take with caution, needs testing/bullet-proofing ... i'd love to get better alternatives if anybody cares to share
using System;
using System.Data;
using Devart.Data.Oracle;
using System.Linq;
using System.Collections.Generic;
using System.Text.RegularExpressions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System.Collections;
namespace ConsoleApp1
{
public class User
{
public string Email { get; set; }
public List<UserPermissionEffective> Permissions { get; set; }
}
public class UserPermissionEffective
{
public string UserPermissionId { get; set; }
public string Email { get; set; }
public bool Std { get; set; }
public bool Adv { get; set; }
public string Mod { get; set; }
}
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
var dto = new User { Email = "testy#mctesterson.com", Permissions = new List<UserPermissionEffective> {
new UserPermissionEffective { UserPermissionId = "1", Std = false, Adv = true },
new UserPermissionEffective { UserPermissionId = "2", Std = true, Adv = false }
} };
if (dto == null) return;
//good docs:
//direct connection: https://www.devart.com/dotconnect/oracle/docs/StoredProcedures-OracleCommand.html
//linux licensing: https://www.devart.com/dotconnect/oracle/docs/?LicensingStandard.html
var dbstring = Environment.GetEnvironmentVariable("dbstring");
using OracleConnection db = new OracleConnection(dbstring);
db.ConnectionString = "license key=trial:Devart.Data.Oracle.key;" + db.ConnectionString;
db.Direct = true; //nugget: crucial!! https://www.devart.com/dotconnect/oracle/docs/DirectMode.html
db.Open();
var cmd = db.CreateCommand("UserPermissions_u", CommandType.StoredProcedure);
cmd.DeriveParameters();
//regex gets everything following the last underscore. e.g. INOUT_PARMNAME yields PARMNAME
var regex = new Regex(#"([^_\W]+)$", RegexOptions.Compiled);
//get the inboud model's root properties
var dtoProps = dto.GetType().GetProperties();
//loop over all parms assigning model properties values by name
//going by parms as the driver versus object properties to favor destination over source
//since we often ignore some superfluous inbound properties
foreach (OracleParameter parm in cmd.Parameters)
{
var cleanParmName = regex.Match(parm.ParameterName).Value.ToUpper();
var dtoPropInfo = dtoProps.FirstOrDefault(prop => prop.Name.ToUpper() == cleanParmName);
//if table type, then drill into the nested list
if (parm.OracleDbType == OracleDbType.Table)
{
//the type we're assigning from must be a list
//https://stackoverflow.com/questions/4115968/how-to-tell-whether-a-type-is-a-list-or-array-or-ienumerable-or/4115970#4115970
Assert.IsTrue(typeof(IEnumerable).IsAssignableFrom(dtoPropInfo.PropertyType));
var listProperty = (dtoPropInfo.GetValue(dto) as IEnumerable<Object>).ToArray();
//don't bother further logic if the list is empty
if (listProperty.Length == 0) return;
//get the oracle table & item Udt's to be instanced and hydrated from the inbound dto
var tableUdt = OracleType.GetObjectType(parm.ObjectTypeName, db);
var itemUdt = OracleType.GetObjectType(tableUdt.ItemObjectType.Name, db);
var dbList = new OracleTable(tableUdt);
//and the internal list item objects
var subPropInfos = dtoPropInfo.PropertyType.GenericTypeArguments[0].GetProperties().ToDictionary(i=>i.Name.ToUpper(), i=>i);
//for every item passed in...
foreach (var dtoSubItem in listProperty) {
//create db objects for every row of data we want to send
var dbObj = new OracleObject(itemUdt);
//and map the properties from the inbound dto sub items to oracle items by name
//using reflection to enumerate the properties by name
foreach (OracleAttribute field in itemUdt.Attributes)
{
var val = subPropInfos[field.Name.ToUpper()].GetValue(dtoSubItem);
//small tweak to map inbound booleans to 1's & 0's on the db since oracle doesn't support boolean!?!
var isDbBool = field.DbType == OracleDbType.Integer && field.Precision == 1;
dbObj[field] = isDbBool ? ((bool)val ? 1 : 0) : val;
}
//lastly add the db obj to the db table
dbList.Add(dbObj);
}
parm.Value = dbList;
}
else {
parm.Value = dtoPropInfo.GetValue(dto);
}
}
cmd.ExecuteNonQuery();
}
}
}
Please refer following link to setup ODAC
Setup Ref and use follwing link to get the ODAC
using Oracle.DataAccess.Client;
using Oracle.DataAccess.Types;
using System;
using System.Data;
namespace Strace_CustomTypes
{
class Program
{
static void Main(string[] args)
{
// Setup Ref - https://o7planning.org/en/10509/connecting-to-oracle-database-using-csharp-without-oracle-client
// ODAC 64bit ODAC122010Xcopy_x64.zip - https://www.oracle.com/technetwork/database/windows/downloads/index-090165.html
// .Net Framework 4
// 'Connection string' to connect directly to Oracle.
string connString = "Data Source=(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=0.0.0.0)(PORT=1521))(CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME=SIT)));Password=PASSWORD;User ID=USERID";
OracleConnection straceOracleDBConn = new OracleConnection(connString);
OracleCommand cmd = new OracleCommand("PKG_TEMP.TEST_ARRAY", straceOracleDBConn);
cmd.CommandType = CommandType.StoredProcedure;
try
{
straceOracleDBConn.Open();
CustomVarray pScanResult = new CustomVarray();
pScanResult.Array = new string[] { "hello", "world" };
OracleParameter param = new OracleParameter();
param.OracleDbType = OracleDbType.Array;
param.Direction = ParameterDirection.Input;
param.UdtTypeName = "USERID.VARCHAR2_ARRAY";
param.Value = pScanResult;
cmd.Parameters.Add(param);
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
Console.WriteLine($"Error: {ex.Message} {Environment.NewLine} {ex.StackTrace}");
}
finally
{
straceOracleDBConn.Close();
cmd.Dispose();
straceOracleDBConn.Dispose();
}
Console.WriteLine("Press any key to exit");
Console.ReadLine();
}
}
//Ref https://www.codeproject.com/Articles/33829/How-to-use-Oracle-11g-ODP-NET-UDT-in-an-Oracle-Sto
public class CustomVarray : IOracleCustomType, INullable
{
[OracleArrayMapping()]
public string[] Array;
private OracleUdtStatus[] m_statusArray;
public OracleUdtStatus[] StatusArray
{
get
{
return this.m_statusArray;
}
set
{
this.m_statusArray = value;
}
}
private bool m_bIsNull;
public bool IsNull
{
get
{
return m_bIsNull;
}
}
public static CustomVarray Null
{
get
{
CustomVarray obj = new CustomVarray();
obj.m_bIsNull = true;
return obj;
}
}
public void FromCustomObject(OracleConnection con, IntPtr pUdt)
{
OracleUdt.SetValue(con, pUdt, 0, Array, m_statusArray);
}
public void ToCustomObject(OracleConnection con, IntPtr pUdt)
{
object objectStatusArray = null;
Array = (string[])OracleUdt.GetValue(con, pUdt, 0, out objectStatusArray);
m_statusArray = (OracleUdtStatus[])objectStatusArray;
}
}
[OracleCustomTypeMapping("USERID.VARCHAR2_ARRAY")]
public class CustomVarrayFactory : IOracleArrayTypeFactory, IOracleCustomTypeFactory
{
public Array CreateArray(int numElems)
{
return new string[numElems];
}
public IOracleCustomType CreateObject()
{
return new CustomVarray();
}
public Array CreateStatusArray(int numElems)
{
return new OracleUdtStatus[numElems];
}
}
}

IBM db2Command SQL SELECT * FROM IN #namedParameter

When using the C# code below to construct a DB2 SQL query the result set only has one row. If I manually construct the "IN" predicate inside the cmdTxt string using string.Join(",", ids) then all of the expected rows are returned. How can I return all of the expected rows using the db2Parameter object instead of building the query as a long string to be sent to the server?
public object[] GetResults(int[] ids)
{
var cmdTxt = "SELECT DISTINCT ID,COL2,COL3 FROM TABLE WHERE ID IN ( #ids ) ";
var db2Command = _DB2Connection.CreateCommand();
db2Command.CommandText = cmdTxt;
var db2Parameter = db2Command.CreateParameter();
db2Parameter.ArrayLength = ids.Length;
db2Parameter.DB2Type = DB2Type.DynArray;
db2Parameter.ParameterName = "#ids";
db2Parameter.Value = ids;
db2Command.Parameters.Add(db2Parameter);
var results = ExecuteQuery(db2Command);
return results.ToArray();
}
private object[] ExecuteQuery(DB2Command db2Command)
{
_DB2Connection.Open();
var resultList = new ArrayList();
var results = db2Command.ExecuteReader();
while (results.Read())
{
var values = new object[results.FieldCount];
results.GetValues(values);
resultList.Add(values);
}
results.Close();
_DB2Connection.Close();
return resultList.ToArray();
}
You cannot send in an array as a parameter. You would have to do something to build out a list of parameters, one for each of your values.
e.g.: SELECT DISTINCT ID,COL2,COL3 FROM TABLE WHERE ID IN ( #id1, #id2, ... #idN )
And then add the values to your parameter collection:
cmd.Parameters.Add("#id1", DB2Type.Integer).Value = your_val;
Additionally, there are a few things I would do to improve your code:
Use using statements around your DB2 objects. This will automatically dispose of the objects correctly when they go out of scope. If you don't do this, eventually you will run into errors. This should be done on DB2Connection, DB2Command, DB2Transaction, and DB2Reader objects especially.
I would recommend that you wrap queries in a transaction object, even for selects. With DB2 (and my experience is with z/OS mainframe, here... it might be different for AS/400), it writes one "accounting" record (basically the work that DB2 did) for each transaction. If you don't have an explicit transaction, DB2 will create one for you, and automatically commit after every statement, which adds up to a lot of backend records that could be combined.
My personal opinion would also be to create a .NET class to hold the data that you are getting back from the database. That would make it easier to work with using IntelliSense, among other things (because you would be able to auto-complete the property name, and .NET would know the type of the object). Right now, with the array of objects, if your column order or data type changes, it may be difficult to find/debug those usages throughout your code.
I've included a version of your code that I re-wrote that has some of these changes in it:
public List<ReturnClass> GetResults(int[] ids)
{
using (var conn = new DB2Connection())
{
conn.Open();
using (var trans = conn.BeginTransaction(IsolationLevel.ReadCommitted))
using (var cmd = conn.CreateCommand())
{
cmd.Transaction = trans;
var parms = new List<string>();
var idCount = 0;
foreach (var id in ids)
{
var parm = "#id" + idCount++;
parms.Add(parm);
cmd.Parameters.Add(parm, DB2Type.Integer).Value = id;
}
cmd.CommandText = "SELECT DISTINCT ID,COL2,COL3 FROM TABLE WHERE ID IN ( " + string.Join(",", parms) + " ) ";
var resultList = new List<ReturnClass>();
using (var reader = cmd.ExecuteReader())
{
while (reader.Read())
{
var values = new ReturnClass();
values.Id = (int)reader["ID"];
values.Col1 = reader["COL1"].ToString();
values.Col2 = reader["COL2"].ToString();
resultList.Add(values);
}
}
return resultList;
}
}
}
public class ReturnClass
{
public int Id;
public string Col1;
public string Col2;
}
Try changing from:
db2Parameter.DB2Type = DB2Type.DynArray;
to:
db2Parameter.DB2Type = DB2Type.Integer;
This is based on the example given here

Printing Json data as Html Table

I am using PageMethod to retrieve Table data in Json format using the following C# Code
[WebMethod]
public static string GetJson2()
{
StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
JsonWriter jsonWriter = new JsonTextWriter(sw);
try
{
string connstr = "server=localhost;user=root;database=cm_users;port=3306;password=root";
MySqlConnection conn = new MySqlConnection(connstr);
conn.Open();
string sql = "select * from users";
MySqlCommand cmd = new MySqlCommand(sql, conn);
MySqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
int fieldcount = reader.FieldCount; // count how many columns are in the row
object[] values = new object[fieldcount]; // storage for column values
reader.GetValues(values); // extract the values in each column
jsonWriter.WriteStartObject();
for (int index = 0; index < fieldcount; index++)
{ // iterate through all columns
jsonWriter.WritePropertyName(reader.GetName(index)); // column name
jsonWriter.WriteValue(values[index]); // value in column
}
jsonWriter.WriteEndObject();
}
reader.Close();
}
catch (MySqlException mySqlException)
{ // exception
return mySqlException + "error";
}
// END of method
// the above method returns sb and another uses it to return as HTTP Response...
string jsonString = sb.ToString();
return jsonString; ;
}
Now I am Catching the out put of the method into an html Page using an Java Scipt
Using Ajax JavaScript I am consuming the returned string which is in Json format.
function getUsers() {
$.ajax({
type: "POST",
url: "http://{address}:8078/Default.aspx/GetJson2",
data: "{}",
contentType: "application/json",
dataType: "json",
success: function (msg) {
$("#Result").text(msg.d);
var myTable1 = '';
myTable1 += '<table id="myTable1" cellspacing=0 cellpadding=2 border=1>';
myTable1 += "<tr><td><b>ID</b></td><td><b>UserName</b></td><td><b>Password</b></td><td><b>Email</b></td></tr>";
$.each(msg, function(i,v){
alert(i + v);
myTable1 += "<tr><td>" + v.id + "</td><td>" + v.username + "</td><td>" + v.password + "</td><td>" + v.Email + "</td></tr>";
});
$("#user_tb1").html(myTable1) ;
},
error: function () {
alert("error");
}
});
};
I am getting Json string as
{"id":1,"username":"karthik","password":"karthik","Email":"karthikdheeraj#gmail.com"}{"id":2,"username":"Lohith","password":"Lohith","Email":"lohith#cnonymn.com"}
and Html as
A table structure in which each cell is filled with "undefined"
What might be the Issue in the above code.
It looks like the json being retrieved from the server is incorrect, it's not an array of objects.
The correct format should be:
[
{"id":1,"username":"karthik","password":"karthik","Email":"karthikdheeraj#gmail.com"},
{"id":2,"username":"Lohith","password":"Lohith","Email":"lohith#cnonymn.com"}
]
Here's a plnkr showing your table filling code working with correctly formatted data
There's something up with the JSON that you are getting back. The proper format needs to be:
var json = [{
"id": 1,
"username": "karthik",
"password": "karthik",
"Email": "karthikdheeraj#gmail.com"
}, {
"id": 2,
"username": "Lohith",
"password": "Lohith",
"Email": "lohith#cnonymn.com"
}];
Below is a fiddle I created showing that the loop now alerts the username properly.
http://jsfiddle.net/77YBq/
After more investigation:
To continue to drill into this issue I believe the root of your JSON problem "if the documentation is correct" JsonWriter Documentation
I beleive your server code needs to have
jsonWriter.WriteStartArray(); // Starts Json Array notation;
// This is your existing code
//================================================================================
while (reader.Read())
{
int fieldcount = reader.FieldCount; // count how many columns are in the row
object[] values = new object[fieldcount]; // storage for column values
reader.GetValues(values); // extract the values in each column
jsonWriter.WriteStartObject();
for (int index = 0; index < fieldcount; index++)
{ // iterate through all columns
jsonWriter.WritePropertyName(reader.GetName(index)); // column name
jsonWriter.WriteValue(values[index]); // value in column
}
jsonWriter.WriteEndObject();
}
reader.Close();
//================================================================================
// End of your existing code
jsonWriter.WriteEndArray(); // Ends Json Array notation;
The JsonTextWriter is not intended to be used in the way you are using it.
You should take advantage of a serialization library so that you aren't writing code to serialize JSON.
Here is a solution that uses JSON.NET.
Include the package at http://json.codeplex.com/ in your solution.
Add this using statement to your file:
using Newtonsoft.Json;
Add a class to map your records to.
public class User{
... properties here
}
[WebMethod]
public static string GetJson2()
{
StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
JsonWriter jsonWriter = new JsonTextWriter(sw);
var users = new List<User>();
try
{
string connstr = "server=localhost;user=root;database=cm_users;port=3306;password=root";
MySqlConnection conn = new MySqlConnection(connstr);
conn.Open();
string sql = "select * from users";
MySqlCommand cmd = new MySqlCommand(sql, conn);
MySqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
int fieldcount = reader.FieldCount; // count how many columns are in the row
object[] values = new object[fieldcount]; // storage for column values
reader.GetValues(values); // extract the values in each column
users.add(new User { id = reader["id"], username = reader["username"] ..});
}
reader.Close();
}
catch (MySqlException mySqlException)
{ // exception
return mySqlException + "error";
}
return JsonConvert.SerializeObject(users);
}
You should also consider naming your id, username etc as Id, Username etc so that you are following the correct naming conventions.

jQuery AJAX postback to WebMethod returning only first row of results

I have the following JQUERY code that I'm expecting to return 3 json results to the console. What's happening is I'm getting 3 copies of the results of the first return.
so for example I'm trying to see filename's, and I'm getting back "first name, first name, first name" instead of "first name, second name, third name"
here's my code:
$.ajax({
type: "POST",
url: "front.aspx/GetData",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
var obj = msg.d;
$.each(obj, function(index, value){
console.log(value);
});
}
});
what am I doing wrong with the each function?
I don't think you need my CS code to tell me what I'm doing wrong, but incase you do, here it is:
public class LoadData {
public string filename;
public string date;
public string filetype;
public Int32 height;
public Int32 width;
public string uploadGroup;
public string title;
public string uniqueID;
public string uploader;
public string uniqueIDnoExt;
}
[WebMethod]
public static List<LoadData> GetData() {
LoadData b = new LoadData();
List<LoadData> info = new List<LoadData>();
SqlDataReader reader;
string connectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();
SqlConnection connection = new SqlConnection(connectionString);
connection.Open();
SqlCommand command = new SqlCommand("SELECT * FROM uploads ORDER BY id DESC", connection);
command.Parameters.Add(new SqlParameter("uploader", "anonymous"));
reader = command.ExecuteReader();
while (reader.Read()) {
b.filename = reader.GetString(1);
b.date = reader.GetSqlDateTime(3).ToString();
b.filetype = reader.GetString(4);
b.height = (Int32)reader.GetSqlInt32(5);
b.width = (Int32)reader.GetSqlInt32(6);
b.uploadGroup = reader.GetString(7);
b.title = reader.GetString(8);
b.uniqueID = reader.GetString(9);
b.uploader = reader.GetString(10);
b.uniqueIDnoExt = reader.GetString(12);
info.Add(b);
}
return info;
}
Move this line
LoadData b = new LoadData();
inside the loop.
while (reader.Read()) {
LoadData b = new LoadData();
b.filename = reader.GetString(1);
b.date = reader.GetSqlDateTime(3).ToString();
b.filetype = reader.GetString(4);
b.height = (Int32)reader.GetSqlInt32(5);
b.width = (Int32)reader.GetSqlInt32(6);
b.uploadGroup = reader.GetString(7);
b.title = reader.GetString(8);
b.uniqueID = reader.GetString(9);
b.uploader = reader.GetString(10);
b.uniqueIDnoExt = reader.GetString(12);
info.Add(b);
}
The way you have it now you make only one line of data. The List<> holds the reference, it does not recreate them. So if you're not making new data, you're not inserting any new data (as it is now). You're just adding first one in memory, and then changing the values.
Also you can read :
http://en.wikipedia.org/wiki/Linked_list
By the way.
You have left open many things, you will soon end up without resources. Use the using keyword on the objects that need to be closed. And, for speed, use a static string (to read only) on the connection string.
You are creating list in wrong way.. Follow #Aristos way to add object correctly.
and at your ajax request sucess: section..
Loop Throuh d.data. Check this JQuery Ajax with Class Arrays
for (var i in d.data) { }
And you can Manually convert result dataset to JSON

Returning multiple values to be used in jQuery from a WebMethod

I have jquery using ajax/json to grab an elements ID and then hits:
[System.Web.Services.WebMethod]
public static string EditPage(string nodeID)
{
DataTable dt = new DataTable();
using (SqlConnection con = new SqlConnection(Global.conString))
using (SqlCommand cmd = new SqlCommand("contentPageGetDetail", con))
{
cmd.Parameters.Add("#ID", SqlDbType.UniqueIdentifier).Value = Global.SafeSqlLiteral(nodeID, 1);
cmd.CommandType = CommandType.StoredProcedure;
cmd.ExecuteNonQuery();
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
{
da.Fill(dt);
}
}
if (dt.Count > 0)
{
string pageTitle = dt.Rows[0]["Title"].toString();
string contentID = dt.Rows[0]["ContentID"].toString();
return pageTitle, contentID, nodeID;
}
else
{
return "Failed";
}
}
When it's time to return I want to grab all content returned from the stored procedure back to the jquery method in the success section and set a hiddenfield, dropdown value, and a title in a textfield.
In the jQuery I tried using "pageTitle" but it came up undefined. What do I need to do jQuery side to grab whats being returned and populate fields in my Web Form before showing the form?
You'll need to create a struct or class to return:
public struct TheStruct
{
public string pageTitle;
public int contentID,
public int nodeID;
}
[System.Web.Services.WebMethod]
public static TheStruct EditPage(string nodeID)
{
<your code here>
var result = new TheStruct();
result.pageTitle = "Test";
result.contentID = 1;
return result;
}
If you pass:
contentType: "application/json; charset=utf-8",
in the AJAX call, you'll get a JSON reply, which you can parse like:
var obj = jQuery.parseJSON(webserviceReply);
alert(obj.pageTitle);
public class stuff {
string pagetitle;
string contentID;
string nodeID;
}
[System.Web.Services.WebMethod]
public static stuff EditPage(string nodeID) {
... get the stuff
stuff returnme = new stuff();
returnme.pagetitle = ...
returnme.contentid = ...
return returnme;
}
==== jquery side:
Assuming you're using the AJAX call of jquery do something like this:
.ajax({ type: "GET", url: "./return.asmx", async: true, dataType: "xml",
success: function (respons, status) {
$(respons).find("WebServiceCallName stuff pagetitle").text();
}});
You'll need to look at the webservice output directly (just navigate to it as if it were a webpage) to make sure your jQuery selector is correct.
If you want to use the string you return from jquery try:
success: function(msg) {
alert(msg.d);
}
msg.d will hold the string you return from your webservice call. If you want to return multiple strings, try to add a predefined string between them and split them in your jquery success function. like:
yourfirststring||##||yoursecondstring||##||yourthirdstring
var strings = msg.d.split("||##||");

Categories