Understanding Difference between ToArray and JSON - c#

I'm working on jquery to get data bind it to the dropdownlists & also I used web service method, and its working great but I'm not getting some clarification I,e for binding data to one dropdownlist I'm getting data from web method which is returns To Array objects and for another dropdownlist I'm getting data from web method which is returns in terms of JSON object, but in the front end I'm not getting any difference. most of them telling serialised json good method to work on, so what actually happens here? I'm bit confuse
please help me
thank you
**here is my code**
Default.aspx
<html>
<head runat="server">
<title>JsonAndToArray</title>
<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
ddlActivityType = document.getElementById("<%=ddlActivity.ClientID %>");
$.ajax({
type: "POST",
contentType: "application/json;charset/utf-8",
url: "Visit.asmx/GetActivityByJSON",
dataType: "json",
success: function(results) {
results = eval(results.d);
$('#ddlActivity').get(0).options.length = 0;
$('#ddlActivity').get(0).options[0] = new Option(' --select-- ', '0');
$.each(results, function(val, text) {
$('#ddlActivity').append($('<option></option>').val(text[1]).html(text[0]));
});
}
});
ddlActivityType1 = document.getElementById("<%=ddlActivity2.ClientID %>");
$.ajax({
type: "POST",
contentType: "application/json;charset/utf-8",
url: "Visit.asmx/GetActivity",
dataType: "json",
success: function(results) {
results = eval(results.d);
$('#ddlActivity2').get(0).options.length = 0;
$('#ddlActivity2').get(0).options[0] = new Option('--select--', '0');
$.each(results, function(val, text) {
$('#ddlActivity2').append($('<option></option>').val(text[1]).html(text[0]));
});
}
});
});
</script>
</head>
<body>
<form id="form1" runat="server">
Json-Activity :
<select id="ddlActivity" runat="server">
</select>
<br />
<br />
ToArray-Activity :
<select id="ddlActivity2" runat="server">
</select>
<br />
<br />
<asp:Button ID="btnJson" runat="server" Text="Json" OnClick="Json_click"/>
</form>
</body>
</html>
Defalut.aspx.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Web.Script.Serialization;
public partial class Defalut: System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Json_click(object sender,EventArgs e)
{
}
}
**webservices**
**
- Visit.asmx
**
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Data;
using System.Data.SqlClient;
using System.Web.Script.Serialization;
using Facade;
/// <summary>
/// Summary description for Visit
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
[System.Web.Script.Services.ScriptService]
public class Visit : System.Web.Services.WebService
{
public Visit()
{
//Uncomment the following line if using designed components
//InitializeComponent();
}
[WebMethod]
public string HelloWorld()
{
return "Hello World";
}
[WebMethod]
public IList<string[]> GetActivity()
{
IList<string[]> values = new List<string[]>();
//string value = "";
try
{
SqlConnection con_New = new SqlConnection(#"Data Source=SQLEXPRESS;Initial Catalog="Database";Integrated Security=True;");
con_New.Open();
SqlCommand cmdSelect_ST = new SqlCommand("select id,name from table", con_New);
SqlDataAdapter da_ST = new SqlDataAdapter(cmdSelect_ST);
DataSet ds = new DataSet();
da_ST.Fill(ds);
DataTable dt = ds.Tables[0];
for (int i = 0; i < dt.Rows.Count; i++)
{
string[] ActivityType = new string[2];
ActivityType[0] = dt.Rows[i]["name"].ToString();
ActivityType[1] = dt.Rows[i]["id"].ToString();
values.Add(ActivityType);
}
}
catch (Exception ex)
{
}
return values;
}
[WebMethod]
public string GetActivityByJSON()
{
IList<string[]> values = new List<string[]>();
string value = "";
try
{
SqlConnection con_New = new SqlConnection(#"Data Source=SQLEXPRESS;Initial Catalog="Database";Integrated Security=True;");
con_New.Open();
SqlCommand cmdSelect_ST = new SqlCommand("select name,id from table", con_New);
SqlDataAdapter da_ST = new SqlDataAdapter(cmdSelect_ST);
DataSet ds = new DataSet();
da_ST.Fill(ds);
DataTable dt = ds.Tables[0];
for (int i = 0; i < dt.Rows.Count; i++)
{
string[] ActivityType = new string[2];
ActivityType[0] = dt.Rows[i]["name"].ToString();
ActivityType[1] = dt.Rows[i]["id"].ToString();
values.Add(ActivityType);
}
JavaScriptSerializer js = new JavaScriptSerializer();
value = js.Serialize(values);
}
catch (Exception ex)
{
}
return value;
}
}

In the first call you are returning an array which is converted to a json array by the system. You return this:
IList<string[]> values = new List<string[]>();
In the second call you convert to a jsaon array and return it as a string. Here is the code that does the conversion:
JavaScriptSerializer js = new JavaScriptSerializer();
value = js.Serialize(values);
Since json is just a string formatted in a certain way -- there is no difference. Just when the string to send back is created and who (your code or the system code) creates it.

Related

How to display a google bar chart, instead of data table only?

This is asp.net coding website page coding page in here I insert the JavaScript and retrieve data by ID just I set height and weight only
<h1 class="style2"> Channeling Paid and UnPaid Monthly</h1>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<asp:GridView ID="Ch_Data_Monthly" runat="server" BackColor="White"
BorderColor="#3366CC" BorderStyle="None" BorderWidth="1px" CellPadding="4">
</asp:GridView>
<asp:Literal ID="ltScriptsDataMonthly" runat="server"></asp:Literal>
<div id="Ch_BarChart_Monthly" style="width: 900px; height: 300px;" />
This is the C# coding. I'm getting data by SQL Server R2 stored procedure.
i have connecting my data bases by web config called "connectionString"
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Configuration;
using System.Text;
using System.Data;
using System.Web.Security;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
// Monthly Bind Gridview
Bind_Ch_Data_Monthly();
// Monthly Bind Charts
BindChart_Monthly();
}
}
//Monthly Channeling Paid and UnPaid
private void Bind_Ch_Data_Monthly()
{
Ch_Data_Monthly.DataSource = GetChartDataMonthly();
Ch_Data_Monthly.DataBind();
}
private void BindChart_Monthly()
{
DataTable dsChartDataMonthly = new DataTable();
StringBuilder strScriptDataMonthly = new StringBuilder();
try
{
dsChartDataMonthly = GetChartDataMonthly();
strScriptDataMonthly.Append(#"<script type='text/javascript'>
google.charts.load('visualization', '1', {packages: ['bar']});
google.charts.setOnLoadCallback(drawChart);</script>
<script type='text/javascript'>
function drawChart() {
var data = google.visualization.arrayToDataTable([
['Months', 'Paid', 'UnPaid'],");
foreach (DataRow row in dsChartDataMonthly.Rows)
{
strScriptDataMonthly.Append("['" + row["Months"] + "'," + row["Paid"] + "," + row["UnPaid"] + "],");
}
strScriptDataMonthly.Remove(strScriptDataMonthly.Length - 1, 1);
strScriptDataMonthly.Append("]);");
strScriptDataMonthly.Append("var options = {chart: {title: 'Company Performance',subtitle: 'Sales, Expenses, and Profit: 2014-2017',}};");
strScriptDataMonthly.Append("var chart = new google.charts.Bar(document.getElementById(document.getElementById('Ch_BarChart_Monthly')); chart.draw(data, options); } google.setOnLoadCallback(drawChart)");
strScriptDataMonthly.Append(" </script>");
ltScriptsDataMonthly.Text = strScriptDataMonthly.ToString();
}
catch
{
}
finally
{
dsChartDataMonthly.Dispose();
strScriptDataMonthly.Clear();
}
}
/// <summary>
/// fetch data from mdf file saved in app_data
/// </summary>
/// <returns>DataTable</returns>
private DataTable GetChartDataMonthly()
{
DataSet dsData = new DataSet();
try
{
SqlConnection sqlCon = new SqlConnection(ConfigurationManager.ConnectionStrings["connectionString"].ConnectionString);
SqlDataAdapter sqlCmd = new SqlDataAdapter("DSB_Ch_MonthWise_Paid&UnPaid", sqlCon);
sqlCmd.SelectCommand.CommandType = CommandType.StoredProcedure;
sqlCon.Open();
sqlCmd.Fill(dsData);
sqlCon.Close();
}
catch
{
throw;
}
return dsData.Tables[0];
}
}
only need one document.getElementById
replace this...
var chart = new google.charts.Bar(document.getElementById(document.getElementById('Ch_BarChart_Monthly')); chart.draw(data, options); } google.setOnLoadCallback(drawChart)
with this...
var chart = new google.charts.Bar(document.getElementById('Ch_BarChart_Monthly')); chart.draw(data, options); } google.setOnLoadCallback(drawChart);
Please fix this line and try
document.getElementById(document.getElementById('Ch_BarChart_Monthly'))
Try this
document.getElementById('Ch_BarChart_Monthly'));
chart.draw(data, options);
google.setOnLoadCallback(drawChart)

ASP.NET AJAX: How to get a JSON response obtained using also Session?

I'm new to ASP.NET but I've to deal with it quickly and powerfully (I know I'm asking the sky but I have to ;) ).
I have a page that uses google maps to show many markers. So I would like to ask to the server asynchronously the coordinates. I consider the best way to do this is to ask them json-serialized via AJAX and keeping track via ASP session the portions of the map already sent to the client and sending only those new.
I tryied in many ways but I found always issues that broke the magic.
My JS code is:
function map2Json() {
return JSON.stringify({ "categories": $("#typeSelector input:checked").map(function () {
return $(this).val();
}).get(),
"bounds": boundsDecorator(map.getBounds())
})
};
function getMarkers() {
$.ajax({
type: "POST",
url: "GetMarkers",
data: map2Json(),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
failure: OnFailure
});
}
While my ASP.NET C# code (WebService.cs) is:
[WebMethod(EnableSession = true)]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string GetMarkers(List<string> categories, Bounds bounds)
{
System.Diagnostics.Debug.WriteLine(categories.ToString());
System.Diagnostics.Debug.WriteLine(bounds.SouthWest.lat);
return JsonConvert.SerializeObject(getMarkers(categories, bounds));
}
private string getRectangle(Bounds bounds)
{
return string.Format("polygon(({0} {1}, {2} {1}, {2} {3}, {0} {3}, {0} {1}))", bounds.NorthEast.lng.ToString(CultureInfo.InvariantCulture), bounds.NorthEast.lat.ToString(CultureInfo.InvariantCulture), bounds.SouthWest.lng.ToString(CultureInfo.InvariantCulture), bounds.SouthWest.lat.ToString(CultureInfo.InvariantCulture));
}
private string STpolygon(string polygon)
{
return string.Format("geography :: STGeomFromText('{0}', 4326)", polygon);
}
private string typologiesListString(List<string> typologies)
{
return string.Format("({0})", string.Join(",", typologies));
}
private string formatMapNew(List<MapViewed> maps)
{
return string.Join(" OR ", maps.Select(x => string.Format("{0}.STIntersects(GeoLocation) = 1 and Tipologia = {1}", x.lastPatch.ToString(), x.typology)));
}
private DataSet getCoordinatesInPolygon(List<MapViewed> maps)
{
SqlCommand Command_coord = new SqlCommand();
Command_coord.CommandType = CommandType.Text;
SqlConnection conn = new SqlConnection("Server=localhost\\SQLEXPRESS;Database=geotagging;Trusted_Connection=Yes;Integrated Security=SSPI;");
Command_coord.Connection = conn;
string query = string.Format(#"
select [Ragione sociale], GeoLocation, Tipologia, Dettagli
from GEOTAG
where {0}", formatMapNew(maps));
Command_coord.CommandText = query;
DataSet coordinatesDS = new DataSet();
SqlDataAdapter coordinatesDA = new SqlDataAdapter();
coordinatesDA.SelectCommand = Command_coord;
try
{
coordinatesDA.Fill(coordinatesDS);
}
catch (System.Data.SqlClient.SqlException e)
{
System.Diagnostics.Debug.WriteLine("Error query: \n{0}\n Message = {1}", query, e.Message);
}
return coordinatesDS;
}
private bool IsEmpty(DataSet dataSet)
{
foreach (DataTable table in dataSet.Tables)
if (table.Rows.Count != 0) return false;
return true;
}
private List<Marker> getDBMarkers(DataSet coordinatesDS)
{
List<Marker> markers = new List<Marker>();
SqlGeography point;
Marker marker;
if (!IsEmpty(coordinatesDS))
{
foreach (DataRow row in coordinatesDS.Tables[0].Rows)
{
point = (SqlGeography)row[1];
marker = new Marker((string)row[0], new Point(point.Lat.Value, point.Long.Value), (string)row[2], (string)row[3]);
markers.Add(marker);
}
}
return markers;
}
private List<Marker> getMarkers(List<string> typologies, Bounds bounds)
{
return getDBMarkers(getCoordinatesInPolygon(updatedMaps(bounds, typologies)));
}
private List<MapViewed> updatedMaps(Bounds bounds, List<string> typologies)
{
List<MapViewed> maps = new List<MapViewed>();
MapViewed map;
foreach (string typology in typologies)
{
if (Session["mapViewed-" + typology] == null) Session["mapViewed-" + typology] = new MapViewed(typology);
map = (MapViewed)Session["mapViewed-" + typology];
map.mergeAndGetDiff(getRectangle(bounds));
maps.Add(map);
}
return maps;
}
Please don't focus too much on the ugliness of my code. I tryied also to use almost the same code in the code behind of my page but each method I use should be static so I can't use Session variables.
Question
What would you do?
Notes
I didn't put the code to insert markers on the map because there is no need.
Solution
Thank you all for the advices. Following your suggests I put this code in the code behind and it works well:
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Drawing;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Globalization;
using Microsoft.SqlServer.Types;
using System.Data.SqlTypes;
using System.Text;
public partial class _Default : System.Web.UI.Page
{
static SqlConnection conn = new SqlConnection("Server=localhost\\SQLEXPRESS;Database=geotagging;Trusted_Connection=Yes;Integrated Security=SSPI;");
protected void Page_Load(object sender, EventArgs e)
{
string[] typologies = new string[] { "Ricambi", "Concessionario", "Motocicli", "Officina" };
foreach (string typology in typologies)
{
HttpContext.Current.Session["mapViewed-"+typology] = new MapViewed(typology);
}
}
private static string getRectangle(Bounds bounds)
{
return string.Format("polygon(({0} {1}, {2} {1}, {2} {3}, {0} {3}, {0} {1}))", bounds.NorthEast.lng.ToString(CultureInfo.InvariantCulture), bounds.NorthEast.lat.ToString(CultureInfo.InvariantCulture), bounds.SouthWest.lng.ToString(CultureInfo.InvariantCulture), bounds.SouthWest.lat.ToString(CultureInfo.InvariantCulture));
}
private static string STpolygon(string polygon)
{
return string.Format("geography :: STGeomFromText('{0}', 4326)", polygon);
}
private string typologiesListString(List<string> typologies)
{
return string.Format("({0})", string.Join(",", typologies));
}
private static string formatMapNew(List<MapViewed> maps)
{
return string.Join(" OR ", maps.Select(x => string.Format("{0}.STIntersects(GeoLocation) = 1 and Tipologia = '{1}'", STpolygon(x.lastPatch.ToString()), x.typology)));
}
private static DataSet getCoordinatesInPolygon(List<MapViewed> maps)
{
SqlCommand Command_coord = new SqlCommand();
Command_coord.CommandType = CommandType.Text;
Command_coord.Connection = conn;
string query = string.Format(#"
select [Ragione sociale], GeoLocation, Tipologia, Dettagli
from GEOTAG
where {0}", formatMapNew(maps));
Command_coord.CommandText = query;
DataSet coordinatesDS = new DataSet();
SqlDataAdapter coordinatesDA = new SqlDataAdapter();
coordinatesDA.SelectCommand = Command_coord;
try
{
coordinatesDA.Fill(coordinatesDS);
}
catch (System.Data.SqlClient.SqlException e)
{
System.Diagnostics.Debug.WriteLine("Error query: \n{0}\n Message = {1}", query, e.Message);
}
return coordinatesDS;
}
private static bool IsEmpty(DataSet dataSet)
{
foreach (DataTable table in dataSet.Tables)
if (table.Rows.Count != 0) return false;
return true;
}
private static List<Marker> getDBMarkers(DataSet coordinatesDS)
{
List<Marker> markers = new List<Marker>();
SqlGeography point;
Marker marker;
if (!IsEmpty(coordinatesDS))
{
foreach (DataRow row in coordinatesDS.Tables[0].Rows)
{
point = (SqlGeography)row[1];
marker = new Marker((string)row[0], new Point(point.Lat.Value, point.Long.Value), (string)row[2], (string)row[3]);
markers.Add(marker);
}
}
return markers;
}
private static List<Marker> getMarkers(List<string> typologies, Bounds bounds)
{
return getDBMarkers(getCoordinatesInPolygon(updatedMaps(bounds, typologies)));
}
private static List<MapViewed> updatedMaps(Bounds bounds, List<string> typologies)
{
List<MapViewed> maps = new List<MapViewed>();
MapViewed map;
foreach (string typology in typologies)
{
map = (MapViewed)HttpContext.Current.Session["mapViewed-" + typology];
map.mergeAndGetDiff(getRectangle(bounds));
maps.Add(map);
}
return maps;
}
[System.Web.Services.WebMethod(EnableSession = true)]
public static List<Marker> GetMarkers(List<string> categories, Bounds bounds)
{
return getMarkers(categories, bounds);
}
}
You can use session in static methods like this
//Store value in session
HttpContext.Current.Session["mysession"]=value;
//Get value from session
var sessionvaue=HttpContext.Current.Session["mysession"];
use the static HttpContext.Current property to access the Session variables:
HttpContext.Current.Session

Why does an asmx file have to have a webservice with just an int as a parameter?

I have an asmx web service which requires a string and two ints to return data. When I run the asmx page directly and invoke it, I get a 500 error and on chrome get the following:
System.IndexOutOfRangeException: Index was outside the bounds of the array.
at System.Web.Services.Protocols.HttpServerType..ctor(Type type)
at System.Web.Services.Protocols.HttpServerProtocol.Initialize()
at System.Web.Services.Protocols.ServerProtocolFactory.Create(Type type, HttpContext context, HttpRequest request, HttpResponse response, Boolean& abortProcessing)
But, when I add the following web service to the asmx.cs file along side my actual web service, it works.
[WebMethod]
[ScriptMethod(UseHttpGet = true)]
public string getBlah(int blah)
{
return "blah";
}
I then went to a few older sites I've worked on, all of which had at least one web service that just had an int for input, and when I removed the int only web service, the rest failed. So why does asmx web services require a web service with only an int as a parameter for the other web services to work?
This is happening on .Net 4. Haven't tested any other versions.
EDIT:
I was able to create a mockup that is broken, but even adding the int doesn't seem to fix this one. I created a new web forms .net 4 project and added the following asmx file to it. Commenting out AMethod causes Owners to break instead of returning nothing. I'm using values a, 1, 1 for the three fields of the Owner webservice.
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Script.Serialization;
using System.Web.Script.Services;
using System.Web.Services;
namespace WebApplication2
{
/// <summary>
/// Summary description for WebService1
/// </summary>
[WebService(Namespace = "http://www.mysite.com/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
[System.Web.Script.Services.ScriptService]
public class WebService1 : System.Web.Services.WebService
{
[WebMethod]
[ScriptMethod(UseHttpGet = true)]
public string AMethod(int page)
{
return "blah";
}
[WebMethod]
[ScriptMethod(UseHttpGet = true)]
public void Owners(string searchTerm, int pageSize, int page)
{
string retJson = "";
Context.Response.Write(retJson);
}
[WebMethod]
[ScriptMethod(UseHttpGet = true)]
public string Results(List<string> counties, List<string> field2, List<string> field3, string owners, int pageSize, int page)
{
return "[\"test\":\"hi\",\"test2\":\"bye\"]";
}
}
}
500 is Internal server error it indicates about ur logic error.
This will help u to understand how to work with WebService.asmx.
.aspx side
fetching input by scripting.
function InsertDetail() {
var prhid = $("#<%=PRHId.ClientID%>").val();
var item = $("#<%=TextBox1.ClientID%>").val();
var Quantity = $("#<%=TextBox2.ClientID%>").val();
var Price = $("#<%=TextBox3.ClientID%>").val();
var Make = $("#<%=TextBox4.ClientID%>").val();
var Discription = $("#<%=TextBox5.ClientID%>").val();
var d = [];
d.push(prhid);
d.push(item);
d.push(Quantity);
d.push(Price);
d.push(Make);
d.push(Discription);
var jsnDta = JSON.stringify({ d: d });
alert(jsnDta);
$.ajax({
type: "POST",
url: "InsertRequestDetail.asmx/InsertDetail",
data: jsnDta,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (r) {
var rtnData = r.d; //all returned data...
var respDta = [];
$.map(rtnData, function (item, index) {
var j = [
item.status,
item.msg,
];
respDta.push(j);
});
$.each(respDta, function (key, value) {
var status = value[0];
var msg = value[1];
if (status == true) {
alert(msg);
} else {
alert("Error" + msg);
}
});
.asmx side
now all we need to do is call values of fetched inputs and save it in Db table.
public class InsertRequestDetail : System.Web.Services.WebService
{
[ScriptMethod(UseHttpGet = true)]
[WebMethod]
public List<RequestResponse> InsertDetail(List<string> d)
{
List<RequestResponse> list = new List<RequestResponse>();
string prhid = d[0];
string item = d[1];
string Quantity = d[2];
string Price = d[3];
string Make = d[4];
string Discription = d[5];
Pro_DbCon obj2 = new Pro_DbCon();
string constr = obj2.dbconnection();
SqlConnection con = new SqlConnection(constr);
try
{
con.Open();
string select = "Select * From Pro_Detail where PRHId = #prhid AND Item = #item AND Quantity = #quantity AND Price = #price AND Make = #make AND Discription = #dis";
SqlCommand cmd1 = new SqlCommand(select, con);
cmd1.Parameters.AddWithValue("#prhid", prhid);
cmd1.Parameters.AddWithValue("#item", item);
cmd1.Parameters.AddWithValue("#quantity", Quantity);
cmd1.Parameters.AddWithValue("#price", Price);
cmd1.Parameters.AddWithValue("#make", Make);
cmd1.Parameters.AddWithValue("#dis", Discription);
SqlDataReader dr = cmd1.ExecuteReader();
if (dr.Read())
{
dr.Close();
RequestResponse r = new RequestResponse();
r.status = false;
r.msg = "Duplicate";
list.Add(r);
}
else
{
dr.Close();
string insertquery = "Insert into Pro_Detail (PRHId,Item,Quantity,Price,Make,Discription ) values (#prhid,#item,#quantity,#price,#make,#dis)";
SqlCommand cmd = new SqlCommand(insertquery, con);
cmd1.Parameters.AddWithValue("#prhid", prhid);
cmd1.Parameters.AddWithValue("#item", item);
cmd1.Parameters.AddWithValue("#quantity", Quantity);
cmd1.Parameters.AddWithValue("#price", Price);
cmd1.Parameters.AddWithValue("#make", Make);
cmd1.Parameters.AddWithValue("#dis", Discription);
int affectedrows = cmd.ExecuteNonQuery();
if (affectedrows > 0)
{
RequestResponse r = new RequestResponse();
r.status = true;
r.msg = "success";
list.Add(r);
}
else
{
RequestResponse r = new RequestResponse();
r.status = false;
r.msg = "error on adding";
list.Add(r);
}
}
}
catch (Exception ex)
{
RequestResponse r = new RequestResponse();
r.status = false;
r.msg = "Error !" + ex.ToString();
list.Add(r);
}
finally
{
con.Close();
}
return list;
}
}
In case u get 500 internal Server error Related .asmx is the place to look for logic errors or mistyping.

Cant get data to list the five latest messages by using JSON and Webapi

I want to list the five latest messages in a listbox by using JSON and WebApi.
Somehow it doesn't show any data on the listbox
JQuery method:
<script>
function get_latest_messages(Namn) {
// Handle your incomming data from the api
function handleJson (messages) {
// the data parameter is supposed to be your json
for (var i = 0; i < messages.length; i++) {
$("#MessList").append(data[i].UIdFrom);
$("#MessList").append(data[i].Text);
}
}
// Call
$.getJSON('http://localhost:51486/api/message/get?username=' + Namn, handleJson);
}
</script>
The listbox the messages is shown in:
<div runat="server" id="SenastDiv">
<asp:Label ID="Text" runat="server" Text="Dina fem senaste meddelanden"></asp:Label>
<asp:ListBox ID="MessList" runat="server" Width="250 px"></asp:ListBox>
</div>
The api Controller:
namespace MvcApplication1.Controllers
public class MessageController : Controller
{
DALLager d = new DALLager();
public IEnumerable<GetFiveLatest> Get(string username)
{
IEnumerable<GetFiveLatest> messages = d.getFiveLatest(username);
return messages;
}
}
The method in the datalayer:
public List<GetFiveLatest> getFiveLatest(string userName)
{
try
{
SqlConnection conn = new SqlConnection(WebConfigurationManager.ConnectionStrings["InstabandDBEntities"].ConnectionString);
conn.Open();
Meddelande mess = new Meddelande();
List<GetFiveLatest> lista = new List<GetFiveLatest>();
SqlCommand cmd = new SqlCommand("SELECT TOP 5 UIdFrom, Text FROM Message WHERE UIdTo='" + userName + "'ORDER BY Text DESC", conn);
SqlDataReader dataReader = cmd.ExecuteReader();
while (dataReader.Read())
{
GetFiveLatest message = new GetFiveLatest();
message.Text = (dataReader["Text"].ToString());
message.UIdFrom = (dataReader["UIdFrom"].ToString());
lista.Add(message);
}
conn.Close();
return lista;
}
catch (Exception ex)
{
throw new Exception(exe = "Följande fel inträffade: " + ex.Message.ToString());
}
}
You're using a MVC Controller. You should be using an ApiController.

ASP.NET page crashes with MySql connection

I am trying to write a dashboard with information about the website's hits and where people come from etc.
I wrote the following page:
<%# Page Language="C#" Inherits="Daschboard.Board" MasterPageFile="~/site.master" %>
<asp:Content id="main" runat="server" ContentPlaceHolderID="main">
<asp:UpdatePanel runat="server" id="updateableWidgets">
<ContentTemplate>
<asp:ContentPlaceHolder id="WidgetsTable">
</asp:ContentPlaceHolder>
</ContentTemplate>
</asp:UpdatePanel>
</asp:Content>
With the following code behind:
using Widgets;
using System;
using System.Text;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Configuration;
using MySql.Data.MySqlClient;
namespace Daschboard
{
public partial class Board : System.Web.UI.Page
{
protected List<IWidget> widgets;
private MySqlConnection db = new MySqlConnection (ConfigurationManager.AppSettings ["mySql"]);
protected void Page_Load(object sender, EventArgs e)
{
widgets = new List<IWidget>();
BuildWidgtTable();
var WidgetThread = new System.Threading.Thread(new System.Threading.ThreadStart(this.InitWidgets));
WidgetThread.Start();
}
private string BuildWidgtTable ()
{
StringBuilder sb = new StringBuilder ();
db.Open ();
var tableName = ConfigurationManager.AppSettings ["DatabaseSiteName"];
var query = "SELECT * FROM " + tableName + ", Widget WHERE " + tableName + ".WidgetID = Widget.WidgetID";
var command = new MySqlCommand (query, db);
var result = command.ExecuteReader ();
while (result.Read()) {
widgets.Add(getWidget(result.GetString(4)));
}
db.Close ();
sb.Append("<table>\n");
sb.Append("</table>");
result.Close();
return sb.ToString();
}
private void InitWidgets ()
{
db.Open();
foreach (var widget in widgets) {
var siteId = ConfigurationManager.AppSettings["siteID"];
var query = "SELECT * FROM Values, Widget WHERE Widget.WidgetID = Values.WidgetID AND SiteID = " + siteId;
var command = new MySqlCommand(query, db);
var result = command.ExecuteReader();
while(result.Read()){
Console.WriteLine(result);
}
result.Close();
widget.Init ("1");
}
db.Close();
}
private IWidget getWidget (string fileName)
{
IWidget widget = null;
switch (fileName) {
case "PageHits":
widget = new PageHits();
break;
case "SiteHits":
widget = new SiteHits();
break;
}
return widget;
}
}
}
When I run this something goes wrong; the debugger stops working without a good error.
It does load the widgets from the database but it doesn't get the values from the database.
I am using Monodevelop on a Mac.
You are running the widget initialization method in a separate thread (InitWidgets method). The page might have already finished rendering when this method executes. If you want to use asynchronous operations in ASP.NET I would recommend you reading about Asynchronous Pages on MSDN. The idea is to mark your WebForm as asynchronous by setting Async="true" in your Page directive (<%# Page Async="true" ... %>) and then use the RegisterAsyncTask method on your web form.

Categories

Resources