Convert data to JSON format - asp.net

i have used the Newtonsoft.Json for converting data into json format.
I have write the below code:
[WebMethod(EnableSession = true)]
[ScriptMethod(UseHttpGet = false, ResponseFormat = ResponseFormat.Json)]
public string DataTableToJSONWithJSONNet()
{
DataTable dt = new DataTable();
dt.Columns.Add("id", typeof(Int32));
DataSet ds = new DataSet();
ds = cls.ReturnDataSet("Get_data",
new SqlParameter("#Yourid", "5"));
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
dt.Rows.Add(Convert.ToInt32(ds.Tables[0].Rows[i]["id"].ToString()));
}
string JSONString = string.Empty;
JSONString = "{" + "''mydata''"+":" + JsonConvert.SerializeObject(dt) + "}";
return JSONString;
}
So it gives me the below output:
But i want the output like :
{"mydata":[{"id":125},{"id":137},{"id":249},{"id":201},{"id":124},
{"id":173},{"id":160},{"id":153},{"id":146},{"id":168}]}
So how can i convert to it from xml to json. ?

I run your solution in a console application and I can clearly see the problem. If you avoid building json manually, the problem will go away. As I don't have database, I have added my data rows manually. Hope that will help.
using Newtonsoft.Json;
using System;
using System.Data;
namespace Test
{
class MyDataContainer
{
public DataTable mydata { get; set; }
}
class Program
{
static void Main(string[] args)
{
Console.Write(DataTableToJSONWithJSONNet());
Console.Read();
}
static string DataTableToJSONWithJSONNet()
{
DataTable dt = new DataTable();
dt.Columns.Add("id", typeof(Int32));
dt.Rows.Add(1);
dt.Rows.Add(2);
MyDataContainer cont = new MyDataContainer();
cont.mydata = dt;
string JSONString = string.Empty;
JSONString = JsonConvert.SerializeObject(cont);
//to see your attempt uncomment the blow lines
//Console.Write("{" + "''mydata''"+":" + JsonConvert.SerializeObject(dt) + "}");
//Console.WriteLine();
return JSONString;
}
}
}

Looking into your codes, you are already declared that your output is type of JSON, so on the response data it will return a JSON string.
[ScriptMethod(UseHttpGet = false, ResponseFormat = ResponseFormat.Json)]
And you also declared that this is a ScriptMethod. My thought is you are testing your app by running your code and accessing the url of the web service - for example http://localhost/test.asmx and clicking the invoke button on your DataTableToJSONWithJSONNet method. This approach will really display JSON result enclosed on XML format. The best way to test your own code is to invoke the web service using something like jQuery Ajax or equivalent (client scripts).
You can change your code to something like this to achieve the output you are looking for:
[WebMethod(EnableSession = true)]
[ScriptMethod(UseHttpGet = false, ResponseFormat = ResponseFormat.Json)]
public MyResponse DataTableToJSONWithJSONNet()
{
DataTable dt = new DataTable();
dt.Columns.Add("id", typeof(Int32));
DataSet ds = new DataSet();
ds = cls.ReturnDataSet("Get_data",
new SqlParameter("#Yourid", "5"));
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
dt.Rows.Add(Convert.ToInt32(ds.Tables[0].Rows[i]["id"].ToString()));
}
MyResponse result = new MyResponse();
result.mydata = dt;
return result;
}
class MyResponse
{
private object _mydata;
public object mydata { get { return this._mydata; } set { this._mydata = value; } }
public MyResponse() { }
}

Related

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();
}

Web API to query SQL Server and return result is not working as expected

I am trying to connect to SQL Server from the Web API and return a result set as JSON. But my code shown here is not working as expected. I am trying to return the entire query response as a JSON:
[HttpGet]
public HttpResponseMessage Getdetails(string ROOM)
{
string commandText = "SELECT * from [TDB].[dbo].[results_vw] where ROOM = #ROOM_Data";
string connStr = ConfigurationManager.ConnectionStrings["TDBConnection"].ConnectionString;
var jsonResult = new StringBuilder();
using (SqlConnection connection = new SqlConnection(connStr))
{
SqlCommand command = new SqlCommand(commandText, connection);
command.Parameters.Add("#ROOM_Data", SqlDbType.VarChar);
command.Parameters["#ROOM_Data"].Value = ROOM;
connection.Open();
var reader = command.ExecuteReader();
if (!reader.HasRows)
{
jsonResult.Append("[]");
}
else
{
while (reader.Read())
{
jsonResult.Append(reader.GetValue(0).ToString());
}
}
var response = new HttpResponseMessage(System.Net.HttpStatusCode.OK);
response.Content = new StringContent(jsonResult.ToString());
connection.Close();
return response;
}
}
This code returns this result:
333838362692368203368203368203362692368203359544362692368203362692368203362692368203368203
Where I am expecting the JSON as
{"data":
[
{"R_ID":"368203","ROOM":"K2"},
{"R_ID":"368203","ROOM":"K2"}
]}
Now I created a model class called DatabaseResult to store the response but I am not sure how I can store the result in to the model class in the controller
public class DatabaseResult
{
public int r_id { get; set; }
public string room { get; set; }
}
The current result is because you are only return the the value from the first column of each row and adding it to the string builder.
Create a new instance of the model and populate it using the values from the reader for each row.
[HttpGet]
public IHttpActionResult Getdetails(string ROOM) {
string commandText = "SELECT * from [TDB].[dbo].[results_vw] where ROOM = #ROOM_Data";
string connStr = ConfigurationManager.ConnectionStrings["TDBConnection"].ConnectionString;
var jsonResult = new StringBuilder();
using (SqlConnection connection = new SqlConnection(connStr)) {
using (SqlCommand command = new SqlCommand(commandText, connection)) {
command.Parameters.Add("#ROOM_Data", SqlDbType.VarChar);
command.Parameters["#ROOM_Data"].Value = ROOM;
connection.Open();
List<DatabaseResult> records = new List<DatabaseResult>();
using (var reader = command.ExecuteReader()) {
while (reader.Read()) {
var row = new DatabaseResult {
r_id = (int)reader["r_id"],
room = (string)reader["room"],
//...other properties.
};
records.Add(row);
}
return Ok(records);
}
}
}
}
The above uses the column names as the indexer to get the values from the reader.

How to cache global information for all users?

I have my first bigger asp.net website and there are userlists of all user online - of course this list is the same for every user, but as a normal online list I update this with PageMethod / WebMethod every 10 seconds.
So if 100 users online that means 10x6x100 = 6000 database querys each minute.
How can I avoid that?
Can I save this information for all user in something like a session / querystring / cookie but global for all users to avoid querys?
The Simplest way is to create an Application Variable or DataTable, which will hold your Required Information.
After each 10 minutes, when you update the records, Just update the Application Datatable you created above. This DataTable is common for all the users and that will decrease your load drastically.
Let me know if you need code.
You may us static variable for this. If you are having more than 1 app-pool to serverpages
then use asp.net caching since static variable are not thread safe.
Here is my code that i use for something similar it has 2 class.
class1
using System;
public class onlineuser
{
public string sessionid = "";
public string username = "";
public string currentpage = "";
public DateTime time = DateTime.Now;
public onlineuser()
{
//
// TODO: Add constructor logic here
//
}
}
class2
using System;
using System.Collections;
using System.Data;
public class user
{
public static ArrayList online;
public static void adduser(string sessionid,string username,string currentpage)
{
removeunused();
remove(sessionid);
onlineuser ou = new onlineuser();
ou.sessionid = sessionid;
ou.username = username;
ou.currentpage = currentpage;
ou.time = DateTime.Now;
if (online==null)
{
online = new ArrayList();
}
online.Add(ou);
online.TrimToSize();
}
public static void remove(string sessionid)
{
if (online==null)
{
return;
}
onlineuser ou = new onlineuser();
for (int i = 0; i < online.Count; i++)
{
ou = (onlineuser)online[i];
if (ou.sessionid == sessionid)
{
online.RemoveAt(i);
online.TrimToSize();
return;
}
}
}
public static void removeunused()
{
if (online == null)
{
return;
}
onlineuser ou = new onlineuser();
for (int i = 0; i < online.Count; i++)
{
ou = (onlineuser)online[i];
if (ou.time < DateTime.Now.AddMinutes(-2))
{
online.RemoveAt(i);
online.TrimToSize();
return;
}
}
}
public static DataTable totable()
{
DataTable dt = new DataTable();
DataColumn dc = new DataColumn("SessionId", typeof(string));
DataColumn dc1 = new DataColumn("UserName", typeof(string));
DataColumn dc2 = new DataColumn("currentpage", typeof(string));
DataColumn dc3 = new DataColumn("Time", typeof(DateTime));
dt.Columns.Add(dc);
dt.Columns.Add(dc1);
dt.Columns.Add(dc2);
dt.Columns.Add(dc3);
if (online!=null)
{
onlineuser ou = new onlineuser();
for (int i = 0; i < online.Count; i++)
{
ou = (onlineuser)online[i];
dt.Rows.Add(new object[] {ou.sessionid,ou.username,ou.currentpage,ou.time});
}
}
return dt;
}
}
following code is placed in mymaster page which update userlist
try
{
string uname= "N/A";
if (Session["uname"]!=null)
{
uname = Session["uname"].ToString();
}
string page = Path.GetFileName(Request.PhysicalPath).Trim().ToLower();
if (Request.QueryString!=null)
{
page += "?"+Request.QueryString.ToString();
}
user.adduser(Session.SessionID, uname, page);
}
catch (Exception)
{
}

Pdf's fields should remain editable using itextsharp in asp.net

I have a fillable pdf. In which i have few textboxes.
I fill these fields by using following code(itextsharp).
DataTable dt = new DataTable();
String pdfPath1 = Server.MapPath("pdfs\\transmittal2.pdf");
if (File.Exists(pdfPath1))
{
dt = objClsTransmittal.GetTransmittal(jobid, cid);
String comment = "Correspondence generated for " + dt.Rows[0]["Recipient"].ToString();
var formfield = PDFHelper.GetFormFieldNames(pdfPath1);
formfield["DocDate"] = DateTime.Now.ToLongDateString();
formfield["Address1"] = dt.Rows[0]["Company"].ToString();
formfield["Address2"] = dt.Rows[0]["Address1"].ToString();
formfield["PropertyAddress"] = dt.Rows[0]["PropertyAddress"].ToString();
formfield["Job"] = dt.Rows[0]["JobID"].ToString();
formfield["Name"] = dt.Rows[0]["Recipient"].ToString();
formfield["CityStateZip"] = dt.Rows[0]["address2"].ToString();
formfield["E-mail"] = dt.Rows[0]["Email"].ToString();
var pdfcontent = PDFHelper.GeneratePDF(pdfPath1, formfield);
PDFHelper.ReturnPDF(pdfcontent, "Transmittal.pdf");
}
Currently its downloded as read only pdf.
when this pdf gets downloaded, i want that all fields still remain fillable, with the text i have filled in pdf. So that i can edit the text.
I'm looking forward for your replies.
Thanks.
EDIT
PdfHelper is my custom class. In which i have used following code:
using System;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
using System.Web;
using System.IO;
using iTextSharp.text.pdf;
public class PDFHelper
{
public static Dictionary<string, string> GetFormFieldNames(string pdfPath)
{
var fields = new Dictionary<string, string>();
var reader = new PdfReader(pdfPath);
foreach (DictionaryEntry entry in reader.AcroFields.Fields)
fields.Add(entry.Key.ToString(), string.Empty);
reader.Close();
return fields;
}
public static byte[] GeneratePDF(string pdfPath, Dictionary<string, string> formFieldMap)
{
var output = new MemoryStream();
var reader = new PdfReader(pdfPath);
var stamper = new PdfStamper(reader, output);
var formFields = stamper.AcroFields;
foreach (var fieldName in formFieldMap.Keys)
formFields.SetField(fieldName, formFieldMap[fieldName]);
stamper.FormFlattening = true;
stamper.Close();
reader.Close();
return output.ToArray();
}
public static string GetExportValue(AcroFields.Item item)
{
var valueDict = item.GetValue(0);
var appearanceDict = valueDict.GetAsDict(PdfName.AP);
if (appearanceDict != null)
{
var normalAppearances = appearanceDict.GetAsDict(PdfName.N);
if (normalAppearances != null)
{
foreach (var curKey in normalAppearances.Keys)
if (!PdfName.OFF.Equals(curKey))
return curKey.ToString().Substring(1); // string will have a leading '/' character, so remove it!
}
}
var curVal = valueDict.GetAsName(PdfName.AS);
if (curVal != null)
return curVal.ToString().Substring(1);
else
return string.Empty;
}
public static void ReturnPDF(byte[] contents)
{
ReturnPDF(contents, null);
}
public static void ReturnPDF(byte[] contents, string attachmentFilename)
{
var response = HttpContext.Current.Response;
if (!string.IsNullOrEmpty(attachmentFilename))
response.AddHeader("Content-Disposition", "attachment; filename=" + attachmentFilename);
response.ContentType = "application/pdf";
response.BinaryWrite(contents);
response.End();
}
Your code line
stamper.FormFlattening = true;
instructs iTextSharp to flatten the form fields, i.e. to integrate them into the page content and remove the form field annotations.
As you want to keep the form fields as editable fields, don't flatten the form.
Error: Cannot convert type in PDFHelper.cs
public static Dictionary<string, string> GetFormFieldNames(string pdfPath)
{
var fields = new Dictionary<string, string>();
var reader = new PdfReader(pdfPath);
foreach (DictionaryEntry entry in reader.AcroFields.Fields) //ERROR: 'System.Collections.Generic.KeyValuePair' to 'System.Collections.DictionaryEntry'
{
fields.Add(entry.Key.ToString(), string.Empty);
}
reader.Close();
return fields;
}
'System.Collections.Generic.KeyValuePair' to 'System.Collections.DictionaryEntry'

Manually converting result dataset to JSON

I have DataReader that holds the results from a stored procedure caal. The results consist of two fields ...
UserID
UserName
Normally I bind these results to an ASP.NET dropdownlist control ...
ddlUserList.DataSource = rdr // rdr is the DataReader
ddlUserList.DataTextField = "UserName"
ddlUserList.DataValueField = "UserID"
ddlUserList.DataBind()
However I am now trying to accomplish the same thing using jQuery AJAX. What I am stuck on is how to manually convert the dataset held in the DataReader to JSON. How are multiples values separated? Does this look correct?
{{"UserID":1, "UserName":"Bob"}, {"UserID":2, "UserName":"Sally"},{"UserID":3, "UserName":"Fred"}}
I realize there are libraries out there such as JSON.NET to handle the serialization but I am in the learning stage now and want to make sure I understand everything from the bottom up.
Was wondering if you have tried using System.Web.Script.Serialization.JavaScriptSerializer library?
You can look at Rick Stahl's blog on this:
http://www.west-wind.com/weblog/posts/737584.aspx
Or you could also do something like create a method that will pull out data from the datareader and place it in a list of objects. (See code below). These list of object will be serialized using the JavaScriptSerializer library.
Hope this helps!
public class User
{
public int UserId { get; set; }
public string UserName { get; set;}
}
public class DataLayer
{
public string GetUsers(string connString)
{
string result = null;
List<User> users = null;
// get data using SqlReader
using(var conn = new SqlConnection(connString))
{
using(var cmd = new SqlCommand{ Connection = conn, CommandText = "SELECT * FROM Users", CommandType = CommandType.Text })
{
conn.Open();
var reader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
if(!reader.HasRows)
return null;
//convert data reader to a list of user objects
users = (List<User>)ConvertToList<User>(ref reader);
conn.Close();
}
}
//convert list of objects in list to json objects
var jsonSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();
result = jsonSerializer.Serialize(users);
return result;
}
public static IList<T> ConvertToList<T>(ref SqlDataReader reader)
{
IList<T> result = null;
if (reader.IsClosed)
return result;
result = new List<T>();
T item = default(T);
while (reader.Read())
{
//create item instance
item = (T)Activator.CreateInstance<T>();
//get class property members
var propertyItems = item.GetType().GetProperties();
//populate class property members with data from data reader
for (int ctr = 0; ctr < reader.FieldCount; ctr++)
{
if(reader.GetName(ctr) == propertyItems[ctr].Name)
propertyItems[ctr].SetValue(item, UtilsHelper.GetValue<string>(reader[ctr]), null);
}
//add item to list
result.Add(item);
}
reader.Close();
reader.Dispose();
return result;
}
}

Resources