how to get data table to json array in c# - asp.net

how i can get a json array return from data table in asmx service menthods.
am coded like this but am not getting in array
[WebMethod(CacheDuration = 500)]
[ScriptMethod(ResponseFormat = ResponseFormat.Json, XmlSerializeString = false)]
public String latency(int testId)
{
SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["DatabaseConnectionString"].ConnectionString);
SqlDataAdapter da = new SqlDataAdapter("GetValues", conn);
da.SelectCommand.CommandType = CommandType.StoredProcedure;
da.SelectCommand.Parameters.Add(new SqlParameter("TestId", testId));
DataTable dt=new DataTable();
da.Fill(dt);
string[][] JaggedArray = new string[dt.Rows.Count][];
int i = 0;
foreach (DataRow rs in dt.Rows)
{
JaggedArray[i] = new string[] { rs["Time"].ToString(), rs["minlatency"].ToString() };
i = i + 1;
}
string json = JsonConvert.SerializeObject(JaggedArray);
return json;
}
my response is
{"d":"[[\"2/3/2012 11:30:14 AM\",\"10\"],[\"2/3/2012 11:30:16 AM\",\"5\"],[\"2/3/2012 11:30:18 AM\",\"7\"]]"}

You may try .NET Framework's JavaScriptSerializer :
JavaScriptSerializer serializer = new JavaScriptSerializer();
var serialized = serializer.Serialize(
new int[][]
{
new []{1,2,3},
new []{4,5,6}
}
);
Console.WriteLine(serialized);
Console.ReadLine();
Output:
[[1,2,3],[4,5,6]]
NOTE:
JavaScriptSerializer has been reported to be slower than Json.NET.

Related

getting data from Web Services c#

I have an issue loading data in the correct format from web services.
Web Service code:
[WebMethod]
public string LoadLearrner(string id)
{
MyFunctions func = new MyFunctions();
DataSet ds;
DataSet dtsta = SQLServer.GetDsBySP("Load_Learner_ForCRM","learnerId", id.ToString());
string[] cntName = new string[dtsta.Tables[0].Rows.Count];
List<string> list = new List<string>();
int i = 0;
foreach (DataRow rdr in dtsta.Tables[0].Rows)
{
list.Add(rdr[0].ToString());
list.Add(rdr[1].ToString());
list.Add(rdr[2].ToString());
list.Add(rdr[3].ToString());
list.Add(rdr[5].ToString());
i++;
}
String[] str = list.ToArray();
string JSONString=string.Empty;
JSONString = JsonConvert.SerializeObject(str);
return JSONString;
}
Code that's used to call the above web service method is:
WebRequest request = (HttpWebRequest)WebRequest.Create("http://abc/Company/CrmLearner.asmx/LoadLearrner?id=" + item.learner_id);
request.Method = "GET";
request.ContentType = "application/text";
using (Stream dataStream = response.GetResponseStream())
{
StreamReader reader = new StreamReader(dataStream);
responseFromServer = reader.ReadToEnd();
Console.WriteLine(responseFromServer);
}
Result is:
I don't want the result like that. I want to load proper XML or JSON and store it in an object.

Are BinaryFormatter Serialization dotnet core and framework compatible?

I have 2 programs, one written in .Net Framework 4.7.x and another app that is dot net core 2.1.
Program 1, written in .Net Framework. takes a Dataset and using BinaryFormatter writes it to a database field as a byte[].
Program 2, written in dot net core, then takes that record and attempts to Deserialize the field using BinaryFormatter. I'm getting an exception "ArgumentException: Type 'System.Byte' is not deserializable."
Program 1
static void Main(string[] args)
{
var connectionString = ConfigurationManager.ConnectionStrings["CDPMetadataModelContext"].ConnectionString;
byte[] binaryFormattedDs;
using (var connection = new SqlConnection(connectionString))
{
connection.Open();
using (var da = new SqlDataAdapter("Select * from Code_Job_Status", connection))
{
var ds = new DataSet();
da.Fill(ds);
binaryFormattedDs = SerializeBinaryDataContract(ds);
}
string query = "INSERT INTO dbo.Result_Cache (Result_Binary_Data, Run_DateTime) output inserted.Result_Cache_ID VALUES";
string insertQuery = "(#binaryValue, getdate())";
using (SqlCommand cmd = new SqlCommand(query + insertQuery, connection))
{
cmd.Parameters.AddWithValue("#binaryValue", SqlDbType.VarBinary).Value = binaryFormattedDs;
var newId = (int)cmd.ExecuteScalar();
Console.WriteLine("New Id= "+ newId);
Debug.WriteLine("New Id= " + newId);
}
connection.Close();
}
Console.ReadKey();
var ds2 = DeSerialize<DataSet>(binaryFormattedDs);
Console.WriteLine("Row Count=" + ds2.Tables[0].Rows.Count);
Console.ReadKey();
}
public static T DeSerialize<T>(byte[] bytes)
{
var serializer = new BinaryFormatter();
using (var ms = new MemoryStream())
{
ms.Write(bytes, 0, bytes.Length);
ms.Seek(0, SeekOrigin.Begin);
return (T)serializer.Deserialize(ms);
}
}
public static byte[] SerializeBinaryDataContract(DataSet dataSet)
{
BinaryFormatter binaryFormatter = new BinaryFormatter();
byte[] buffer;
using (MemoryStream memoryStream = new MemoryStream())
{
dataSet.RemotingFormat = SerializationFormat.Binary;
binaryFormatter.Serialize((Stream)memoryStream, (object)dataSet);
buffer = new byte[memoryStream.Length];
memoryStream.Seek(0L, SeekOrigin.Begin);
memoryStream.Read(buffer, 0, buffer.Length);
}
return buffer;
}
Program 2
static void Main(string[] args)
{
Console.WriteLine("Result_Cache_ID:");
var reportIds = Console.ReadLine();
if (int.TryParse(reportIds, out var resultCacheId))
{
GetDS(resultCacheId);
}
Console.ReadKey();
}
private static void GetDS(int resultCacheId)
{
using (var connection = new SqlConnection(ConnectionString))
{
connection.Open();
using (var da = new SqlDataAdapter("Select * from Result_Cache where Result_Cache_ID="+ resultCacheId, connection))
{
var ds = new DataSet();
da.Fill(ds);
var binaryFormattedDs =(byte[]) ds.Tables[0].Rows[0]["Result_Binary_Data"];
var ds2 = DeSerialize<DataSet>(binaryFormattedDs);
Console.WriteLine("Row Count=" + ds2.Tables[0].Rows.Count);
}
}
}
public static T DeSerialize<T>(byte[] bytes)
{
var serializer = new BinaryFormatter();
using (var ms = new MemoryStream())
{
ms.Write(bytes, 0, bytes.Length);
ms.Seek(0, SeekOrigin.Begin);
return (T)serializer.Deserialize(ms);
}
}
am I doing something wrong?

JsonConvert in ASP.Net

I'm working in ASP.Net, JsonConvert doesn't work.How can I use JsonConvert?
I have already download NewtonSoft and write this string(using Newtonsoft;) to my project.
public void FillDataGrid()
{
DataTable dt = new DataTable();
string json;
string url = "http://192.168.0.111:2903/MigraPlus.asmx/GetDataJson";
using (WebClient client = new WebClient())
{
json = client.DownloadString(url);
}
string[] json1 = json.Split('>');
string[] json2 = json1[2].Split('<');
json = json2[0];
dt = (DataTable)JsonConvert.DeserializeObject(json, typeof(DataTable));
GridView1.DataSource = dt;
GridView1.DataBind();
}

session gets cleared once method finish

I have two methods in my webservice.cs page like below.
[WebMethod(EnableSession = true)]
public void checkEmployee(string emailId, string password)
{
List<Employee> ListEmp = new List<Employee>();
string cs = ConfigurationManager.ConnectionStrings["rushDB"].ConnectionString;
using (SqlConnection con = new SqlConnection(cs))
{
SqlCommand cmd = new SqlCommand("select * from Employees where Email='" + emailId + "' AND Password='" + password + "'", con);
string personName = null;
string personEmail = null;
string personDeptName = null;
con.Open();
SqlDataReader rdr = cmd.ExecuteReader();
if (rdr.HasRows == true)
{
while (rdr.Read())
{
Employee empChild = new Employee();
empChild.ID = Convert.ToInt16(rdr["ID"]);
empChild.Name = rdr["Name"].ToString();
empChild.Email = rdr["Email"].ToString();
empChild.Password = rdr["Password"].ToString();
empChild.DepartName = rdr["DepartName"].ToString();
personName = rdr["Name"].ToString();
personEmail = rdr["Email"].ToString();
personDeptName = rdr["DepartName"].ToString();
ListEmp.Add(empChild);
}
HttpContext.Current.Session["NamePerson"] = personName;
HttpContext.Current.Session["EmailPerson"] = personEmail;
HttpContext.Current.Session["DepartPerson"] = personDeptName;
JavaScriptSerializer js = new JavaScriptSerializer();
Context.Response.Write(js.Serialize(ListEmp));
}
}
}
[WebMethod(EnableSession = true)]
public void GetCurrentData()
{
Employee ListEmp = new Employee();
if (HttpContext.Current.Session["NamePerson"] != null)
ListEmp.Name = HttpContext.Current.Session["NamePerson"].ToString();
if (HttpContext.Current.Session["EmailPerson"] != null)
ListEmp.Email = HttpContext.Current.Session["EmailPerson"].ToString();
if (HttpContext.Current.Session["DepartPerson"] != null)
ListEmp.DepartName = HttpContext.Current.Session["DepartPerson"].ToString();
JavaScriptSerializer js = new JavaScriptSerializer();
Context.Response.Write(js.Serialize(ListEmp));
}
My issue is that the session created in checkEmployee gets vanished after that method checkEmployee finishes its execution.
I want to retrieve the session values in GetCurrentData but i am unable to do so. Any solution would help me. i have googled it but that didn't helped.
You need a cookie-jar to be able to retain session-state on Web Services. Depending on how you're consuming the service it can get quite complicated if you haven't done it before...
Have at look at the following articles:
http://www.codeproject.com/Articles/322436/RestSessionState
http://www.codeproject.com/Articles/188749/WCF-Sessions-Brief-Introduction

Getting a JSON string response from web method

In my web application there is a WCF web service. In the following method
public string GetPolicyDetails(GetPolicyDetails_ML ml)
{
var strFileName = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
"log.xml");
DataTable dt = new DataTable();
DataSet ds = new DataSet();
try
{
con = new SqlConnection(connectionString);
con.Open();
cmd = new SqlCommand("sp_GetPolicyDetails", con) { CommandType = CommandType.StoredProcedure };
cmd.Parameters.AddWithValue("#policy_id", ml.policyID);
adp = new SqlDataAdapter(cmd);
adp.Fill(dt);
string json = JsonConvert.SerializeObject(dt,Formatting.Indented);
return json;
}
catch (SqlException ex)
{
return "fail";
}
finally
{
con.Close();
con.Dispose();
}
}
will return a json string inWCF Test Client. I need to access this method from my tab application. The code i used is
ServiceReference1.Service1Client client = new ServiceReference1.Service1Client();
var ds = await client.GetPolicyInfoAsync(Convert.ToInt16(txtPolicyNumber.Text));
This will get the response in to the #var ds#. My question is what is the type of this var ds and how to get the Json data out of this variable ds. Thanks in advance.

Resources