Json object inside object via asp.net c# from sql server - c#

I am using jstree plugin, and I need json format that is inside object.
this is my output:
[{"id":"1","text":"Document Management","parent":"#","icon":"fa fa-table","selected":1}
,{"id":"2","text":"Document List","parent":"1","icon":"fa fa-list","selected":1}
,{"id":"7","text":"Hazard","parent":"#","icon":"fa fa-file-text","selected":1}]
this is what I need:
[{"id":"1","text":"Document Management","parent":"#","icon":"fa fa-table",state: { opened: true, selected: true }}}
,{"id":"2","text":"Document List","parent":"1","icon":"fa fa-list",state: { opened: true, selected: true }}}
,{"id":"7","text":"Hazard","parent":"#","icon":"fa fa-file-text",state: { opened: true, selected: true }}}]
and these are my c# and js codes which creates json serialising and treeview;
c#
[WebMethod]
public static string Menu()
{
ClassSystemAccessPolicy classDocumentPolicy = new ClassSystemAccessPolicy();
DataTable dt = new DataTable();
dt = classDocumentPolicy.Permission_Load().Tables[0];
System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();
Dictionary<string, object> row;
foreach (DataRow dr in dt.Rows)
{
row = new Dictionary<string, object>();
foreach (DataColumn col in dt.Columns)
{
row.Add(col.ColumnName, dr[col]);
}
rows.Add(row);
}
return serializer.Serialize(rows);
}
js
var MenuTree = function () {
$.ajax({
type: "POST",
url: "Permission.aspx/Menu",
contentType: "application/json",
dataType: "json",
success: function (data) {
var menu$json = JSON.parse(data.d);
$('#tree_menu').jstree({
'plugins': ["wholerow", "checkbox", "types"],
'core': {
"themes": {
"responsive": false
},
'data': menu$json
}
});
console.log(menu$json)
},
error: function () {
console.log('err')
}
});
How can I serialise like state: { selected: true } ?

You need to create your own DTO(Data Transfer Object) for this
public class JSTreeDTO
{
public string id{get;set;}
public string text{get;set;}
public string text{get;set;}
public string parent {get;set;}
public string icon{get;set;}
public StateDTO state{get;set;}
}
public class StateDTO
{
public bool opened{get;set;}
public bool selected{get;set;}
}
Then create it inside loop
List<JSTreeDTO> treeList=new List<JSTreeDTO>();
foreach (DataRow dr in dt.Rows)
{
JSTreeDTO node=new JSTreeDTO();
row = new Dictionary<string, object>();
foreach (DataColumn col in dt.Columns)
{
node.id=dr["id"];//etc
node.state=new StateDTO();
node.state.opened=true;//based on your logic
}
treeList.Add(node);
return serializer.Serialize(treeList);
}

Related

CsvActionResult not prompting file download in View - C# MVC4

I am calling a custom action from my view with a $.post and sending a couple user generated parameters with it:
$("#submitReport").click(function () {
var carData = $("#car-select").val();
var bikeData = $("#bike-select").val();
if (carData && bikeData !== null) {
$.post('/Reporting/ExportToExcel', $.param({ carData: carData, bikeData: bikeData }, true), function(data) {
console.log(data);
});
}
});
Csv Action Result:
[HttpPost]
public CsvActionResult ExportToExcel(string[] carData, string[] bikeData)
{
var dt = new DataTable();
// Add all the stuff into the datatable
return new CsvActionResult(dt) { FileDownloadName = "MyReport.csv" };
}
And the most important part, the CsvActionResult class:
public sealed class CsvActionResult : FileResult
{
private readonly DataTable _dataTable;
public CsvActionResult(DataTable dataTable)
: base("text/csv")
{
_dataTable = dataTable;
}
protected override void WriteFile(HttpResponseBase response)
{
var outputStream = response.OutputStream;
using (var memoryStream = new MemoryStream())
{
WriteDataTable(memoryStream);
outputStream.Write(memoryStream.GetBuffer(), 0, (int)memoryStream.Length);
}
}
private void WriteDataTable(Stream stream)
{
var streamWriter = new StreamWriter(stream, Encoding.Default);
WriteHeaderLine(streamWriter);
streamWriter.WriteLine();
WriteDataLines(streamWriter);
streamWriter.Flush();
}
private void WriteHeaderLine(StreamWriter streamWriter)
{
foreach (DataColumn dataColumn in _dataTable.Columns)
{
WriteValue(streamWriter, dataColumn.ColumnName);
}
}
private void WriteDataLines(StreamWriter streamWriter)
{
foreach (DataRow dataRow in _dataTable.Rows)
{
foreach (DataColumn dataColumn in _dataTable.Columns)
{
WriteValue(streamWriter, dataRow[dataColumn.ColumnName].ToString());
}
streamWriter.WriteLine();
}
}
private static void WriteValue(StreamWriter writer, String value)
{
writer.Write("\"");
writer.Write(value.Replace("\"", "\"\""));
writer.Write("\",");
}
}
When I look in the console, I can see that the data is being returned, but it doesn't prompt a file download in the browser. So I actually need to do something with the data when it is returned. I thought it would prompt a file download automatically.
Any help would be appreciated.

Set objects Property of type Dictionary while parsing dataset in foreach loop

So I have this problem. I have Project class with Name and Resource properties. I have DataSet and I want to set my Resource property values(of type Dictionary) from the DataSet. And tha's where I struggle.
Any ideas how I could solve this problem? Preferably not using LINQ/Lambdas.
I'm getting Invalid Initializer member declarator error. I hope there is a proper way to do it so error is not relevant. Thanks in advance!
public class FakeDataset
{
public static System.Data.DataTable TTable()
{
DataTable table = new DataTable("Resources");
table.Columns.Add("Name", typeof(string));
table.Columns.Add("Resource", typeof(string));
table.Columns.Add("Value", typeof(string));
table.Rows.Add("Project", "Resource1", "11");
table.Rows.Add("Project", "Resource2", "12");
table.Rows.Add("Project", "Resource3", "9");
table.Rows.Add("Project22", "Resource1", "1");
table.Rows.Add("Project22", "Resource2", "2");
return table;
}
public static DataSet CreateDataset()
{
DataSet dataset = new DataSet("ProjectDataset");
dataset.Tables.Add(TTable());
return dataset;
}
}
public class Project
{
public string Name { get; set; }
public Dictionary<string, string> Resource { get; set; }
}
class Program
{
public static void Main()
{
var dataset = FakeDataset.CreateDataset();
var projectList = new List<Project>();
foreach (DataTable table in dataset.Tables)
{
foreach (DataRow dataRow in table.Rows)
{
projectList.Add(new Project { Name = Convert.ToString(dataRow["Name"]), Resource.Add(dataRow["Resource"].ToString(), dataRow["Value"].ToString()) });
}
}
}
}
Writing your for loop like this will solve the issue
foreach (DataTable table in dataset.Tables)
{
foreach (DataRow dataRow in table.Rows)
{
var dict = new Dictionary<string, string>();
dict.Add(dataRow["Resource"].ToString(), dataRow["Value"].ToString());
projectList.Add(new Project { Name = Convert.ToString(dataRow["Name"]), Resource = dict });
}
}
Or, using collection initialize syntax
foreach (DataTable table in dataset.Tables)
{
foreach (DataRow dataRow in table.Rows)
{
projectList.Add(new Project {
Name = Convert.ToString(dataRow["Name"]),
Resource = new Dictionary<string, string> { { dataRow["Resource"].ToString(), dataRow["Value"].ToString() } } }
);
}
}
But, do you really need Resource as a Dictionary<,> ? As of now, it will contain only one entry per Project class. Maybe you just need two string properties instead?

Nunit c# csv testsource

I am trying pass an argument to a NUnit test after reading a CSV file i.e.
[Test, TestCaseSource(typeof(RegistrationData), "GetTestData")]
public void RegisterUserTest(RegistrationData registrationData)
{
RegisterNewUser registration = new RegisterNewUser(this.driver);
this.driver.Navigate().GoToUrl(baseURL + "/mercuryregister.php");
registration.registerNewUser(registrationData);
}
but I get the error:
System.InvalidCastException : Unable to cast object of type
'RegisterUser.RegistrationData' to type
'System.Collections.IEnumerable'.RegisterUser.UserRegistrationTest.RegisterUserTest
private RegistrationData GetTestData()
{
DataTable dt = DataTable.New.ReadCsv(#"C:\datafolder\regdata.csv");
RegistrationData registrationData = new RegistrationData();
foreach (Row row in dt.Rows)
{
registrationData.setfirstName(row["FirstName"]);
registrationData.setfirstName(row["LastName"]);
registrationData.setPhone(row["Phone"]);
registrationData.setUserName(row["UserName"]);
registrationData.setAddress1(row["Add1"]);
registrationData.setAddress2(row["Add2"]);
registrationData.setCity(row["City"]);
registrationData.setState(row["State"]);
registrationData.setPostalcode(row["Postalcode"]);
registrationData.setCountry(row["Country"]);
registrationData.setEmail(row["Email"]);
registrationData.setPassword(row["Password"]);
registrationData.setConfimPassword(row["Cpassword"]);
}
// return new RegistrationData[][] { { registrationData } };
return registrationData;
}
Example of the ModelTestCaseSource:
public class ModelTestCaseSource
{
public IEnumerable<TestCaseData> GetTestCases()
{
DataTable dt = DataTable.New.ReadCsv(#"C:\datafolder\regdata.csv");
foreach (Row row in dt.Rows)
{
var registrationData = new RegistrationData();
registrationData.setfirstName(row["FirstName"]);
registrationData.setfirstName(row["LastName"]);
registrationData.setPhone(row["Phone"]);
registrationData.setUserName(row["UserName"]);
registrationData.setAddress1(row["Add1"]);
registrationData.setAddress2(row["Add2"]);
registrationData.setCity(row["City"]);
registrationData.setState(row["State"]);
registrationData.setPostalcode(row["Postalcode"]);
registrationData.setCountry(row["Country"]);
registrationData.setEmail(row["Email"]);
registrationData.setPassword(row["Password"]);
registrationData.setConfimPassword(row["Cpassword"]);
yield return new TestCaseData(new object[] { registrationData });
}
}
}
Usage:
[Test, TestCaseSource(typeof(ModelTestCaseSource), "GetTestCases")]
public void RegisterUserTest(RegistrationData registrationData)
{
RegisterNewUser registration = new RegisterNewUser(this.driver);
this.driver.Navigate().GoToUrl(baseURL + "/mercuryregister.php");
registration.registerNewUser(registrationData);
}

Can't get data from GetJson method

Here is my code in Default.aspx:
$(function() {
var dataSource = {};
$("#MainTree,#SubTree").jstree({
"json_data": {
"ajax":{
type: "POST",
async: true,
url: "Default.aspx/GetJson",
contentType: "application/json; charset=utf-8",
dataType: "json",
cache: false,
success: function(msg) {
dataSource = msg;
},
error: function(err) {
alert(err);
},
data: dataSource,
},
},
"plugins": ["themes", "json_data", "ui", "dnd"]
});
});
And here is GetJson method in Default.aspx.cs:
[WebGet(ResponseFormat = WebMessageFormat.Json)]
[System.Web.Services.WebMethod]
public static string GetJson()
{
System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();
Dictionary<string, object> row = null;
DataTable dtEmployee = new DataTable();
dtEmployee.Columns.Add("EmpId", typeof(int));
dtEmployee.Columns.Add("Name", typeof(string));
dtEmployee.Columns.Add("Address", typeof(string));
dtEmployee.Columns.Add("Date", typeof(DateTime));
//
// Here we add five DataRows.
//
dtEmployee.Rows.Add(25, "Rk", "Gurgaon", DateTime.Now);
dtEmployee.Rows.Add(50, "Sachin", "Noida", DateTime.Now);
dtEmployee.Rows.Add(10, "Nitin", "Noida", DateTime.Now);
dtEmployee.Rows.Add(21, "Aditya", "Meerut", DateTime.Now);
dtEmployee.Rows.Add(100, "Mohan", "Banglore", DateTime.Now);
foreach (DataRow dr in dtEmployee.Rows)
{
row = new Dictionary<string, object>();
foreach (DataColumn col in dtEmployee.Columns)
{
row.Add(col.ColumnName, dr[col]);
}
rows.Add(row);
}
return serializer.Serialize(rows);
}
EDIT:
This is the result when i check GetJson method respone:
{"d":"[{\"EmpId\":25,\"Name\":\"Rk\",\"Address\":\"Gurgaon\",\"Date\":\"\/Date(1372999726975)\/\"},{\"EmpId\":50,\"Name\":\"Sachin\",\"Address\":\"Noida\",\"Date\":\"\/Date(1372999726975)\/\"},{\"EmpId\":10,\"Name\":\"Nitin\",\"Address\":\"Noida\",\"Date\":\"\/Date(1372999726975)\/\"},{\"EmpId\":21,\"Name\":\"Aditya\",\"Address\":\"Meerut\",\"Date\":\"\/Date(1372999726975)\/\"},{\"EmpId\":100,\"Name\":\"Mohan\",\"Address\":\"Banglore\",\"Date\":\"\/Date(1372999726975)\/\"}]"}
And the result is nothing..It just appeared "..Loading" flashly and then it return blank page..please help me to show what's the problem here is..Thanks a lot.
It seems that you've not read the documentation properly so I would suggest you do that first.
When you use json_data plugin, you need to follow basic structure as shown below and could be found here, that means you need to provide Json data in below format:
{
"data" : "node_title",
// omit `attr` if not needed; the `attr` object gets passed to the jQuery `attr` function
"attr" : { "id" : "node_identificator", "some-other-attribute" : "attribute_value" },
// `state` and `children` are only used for NON-leaf nodes
"state" : "closed", // or "open", defaults to "closed"
"children" : [ /* an array of child nodes objects */ ]
}
Taking response structure into consideration, you need to have server side class as shown below:
public class Emp
{
public EmpAttribute attr { get; set; }
public string data { get; set; }
}
public class EmpAttribute
{
public string id;
public bool selected;
}
And your pagemethod should look alike below:
[WebGet(ResponseFormat = WebMessageFormat.Json)]
[System.Web.Services.WebMethod]
public static List<Emp> GetJson()
{
List<Emp> empTreeArray = new List<Emp>();
Emp emp1 = new Emp()
{
attr = new EmpAttribute(){ id= "25",selected=false},
data = "Nitin-Gurgaon"
};
Emp emp2 = new Emp()
{
attr = new EmpAttribute(){ id="50",selected=false},
data = "Sachin-Noida"
};
empTreeArray.Add(emp1);
empTreeArray.Add(emp2);
return empTreeArray;
}
Your clientside binding code should be like below:
$(function() {
var dataSource = {};
$("#demo1").jstree({
"json_data": {
"ajax":{
"type": "POST",
"url": "Default2.aspx/GetJson",
"contentType": "application/json; charset=utf-8",
"dataType": "json",
success: function(msg) {
return msg.d;
},
error: function(err) {
alert(err);
}
}
},
"plugins": ["themes", "json_data", "ui", "dnd"]
});
});
Notice return msg.d in Success function that is missing from your code.
More examples could be found here
Please go through documentation of any plugin you use next time.
type http://Default.aspx/GetJson directly in browser and check whether correct data is coming or not.
Other two locations where you can add debugging code is
success: function(msg) {
dataSource = msg;
},
error: function(err) {
alert(err);
}
add breakpoints and debug the javascript.
The response is encapsulated in a property called "d". Instead of datasource = msg you should have datasource = msg.d

How can I access session in a webmethod?

Can i use session values inside a WebMethod?
I've tried using System.Web.Services.WebMethod(EnableSession = true) but i can't access Session parameter like in this example:
[System.Web.Services.WebMethod(EnableSession = true)]
[System.Web.Script.Services.ScriptMethod()]
public static String checaItem(String id)
{
return "zeta";
}
here's the JS who calls the webmethod:
$.ajax({
type: "POST",
url: 'Catalogo.aspx/checaItem',
data: "{ id : 'teste' }",
contentType: 'application/json; charset=utf-8',
success: function (data) {
alert(data);
}
});
You can use:
HttpContext.Current.Session
But it will be null unless you also specify EnableSession=true:
[System.Web.Services.WebMethod(EnableSession = true)]
public static String checaItem(String id)
{
return "zeta";
}
There are two ways to enable session for a Web Method:
1. [WebMethod(enableSession:true)]
2. [WebMethod(EnableSession = true)]
The first one with constructor argument enableSession:true doesn't work for me. The second one with EnableSession property works.
For enable session we have to use [WebMethod(enableSession:true)]
[WebMethod(EnableSession=true)]
public string saveName(string name)
{
List<string> li;
if (Session["Name"] == null)
{
Session["Name"] = name;
return "Data saved successfully.";
}
else
{
Session["Name"] = Session["Name"] + "," + name;
return "Data saved successfully.";
}
}
Now to retrive these names using session we can go like this
[WebMethod(EnableSession = true)]
public List<string> Display()
{
List<string> li1 = new List<string>();
if (Session["Name"] == null)
{
li1.Add("No record to display");
return li1;
}
else
{
string[] names = Session["Name"].ToString().Split(',');
foreach(string s in names)
{
li1.Add(s);
}
return li1;
}
}
so it will retrive all the names from the session and show.
You can try like this
[WebMethod]
public static void MyMethod(string ProductID, string Price, string Quantity, string Total)// Add new parameter Here
{
db_class Connstring = new db_class();
try
{
DataTable dt = (DataTable)HttpContext.Current.Session["aaa"];
if (dt == null)
{
DataTable dtable = new DataTable();
dtable.Clear();
dtable.Columns.Add("ProductID");// Add new parameter Here
dtable.Columns.Add("Price");
dtable.Columns.Add("Quantity");
dtable.Columns.Add("Total");
object[] trow = { ProductID, Price, Quantity, Total };// Add new parameter Here
dtable.Rows.Add(trow);
HttpContext.Current.Session["aaa"] = dtable;
}
else
{
object[] trow = { ProductID, Price, Quantity, Total };// Add new parameter Here
dt.Rows.Add(trow);
HttpContext.Current.Session["aaa"] = dt;
}
}
catch (Exception)
{
throw;
}
}
Take a look at you web.config if session is enabled. This post here might give more ideas.
https://stackoverflow.com/a/15711748/314373
In C#, on code behind page using web method,
[WebMethod(EnableSession = true)]
public static int checkActiveSession()
{
if (HttpContext.Current.Session["USERID"] == null)
{
return 0;
}
else
{
return 1;
}
}
And, in aspx page,
$.ajax({
type: "post",
url: "", // url here
contentType: "application/json; charset=utf-8",
dataType: "json",
data: '{ }',
crossDomain: true,
async: false,
success: function (data) {
returnValue = data.d;
if (returnValue == 1) {
}
else {
alert("Your session has expired");
window.location = "../Default.aspx";
}
},
error: function (request, status, error) {
returnValue = 0;
}
});

Categories

Resources