How to convert datatable to json string in c# - javascript

Its work perfect when data in the datatable is small i.e 10 columns and 300 rows. But when the amount of data in datatable is large it did not work.
Here is my code
[WebMethod]
public static string getData()
{
string _cs = "";
string _query = "";
OleDbConnection _conn = new OleDbConnection();
OleDbCommand _cmd = new OleDbCommand();
OleDbDataAdapter _da = new OleDbDataAdapter();
DataTable _dt = new DataTable();
try
{
_cs = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + _path + ";Extended Properties= \"Excel 8.0;HDR=Yes;IMEX=1\";";
//_query = "SELECT * FROM [3123121288$A1:L290]"; work perfect
_query = "SELECT * FROM [3123121288$]"; //did not work
_conn.ConnectionString = _cs;
_cmd.Connection = _conn;
_cmd.CommandText = _query;
_da.SelectCommand = _cmd;
_da.Fill(_dt);
}
catch (Exception ex)
{ }
return JsonConvert.SerializeObject(_dt);
}

Related

Call function on ButtonClick

I am trying to call function from .aspx to my JavaScript.
I try something like this
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Filter" Width="224px" OnClientClick="return BindToData();" />
And here is my JavaScript
<script type="text/javascript">
function GetSelectedReportName() {
return
document.getElementById('<%=ddlReportName.ClientID%>').options[document.getElementById('<%=ddlReportName.ClientID%>').selectedIndex].value;
}
function ShowReport() {
var reportName = GetSelectedReportName();
ASPxWebDocumentViewer1.OpenReport(reportName);
}
</script>
And here is my function which I need to call in ButtonClick
public void BindToData()
{
try
{
string connString = #"Data Source=(LocalDb)\MSSQLLocalDB;Initial Catalog=DesignSaoOsig1;Integrated Security=True";
SqlConnection conn = new SqlConnection(connString);
string strproc = "TestReport";
using (SqlDataAdapter sda = new SqlDataAdapter(strproc, connString))
{
DataSet ds = new DataSet();
SqlCommand cmd = new SqlCommand();
sda.SelectCommand.CommandType = CommandType.StoredProcedure;
sda.SelectCommand.Parameters.Add("#Status", SqlDbType.Bit).Value = ddlStatus.SelectedValue == "1" ? true : false;
sda.SelectCommand.Parameters.Add("#OrgJed", SqlDbType.Int).Value = ddlOrgUnit.SelectedValue;
sda.Fill(ds);
XtraReport report = new XtraReport
{
DataSource = ds,
DataMember = ds.Tables[0].TableName
};
string[] arrvalues = new string[ds.Tables[0].Rows.Count];
for (int loopcounter = 0; loopcounter < ds.Tables[0].Rows.Count; loopcounter++)
{
//assign dataset values to array
arrvalues[loopcounter] = ds.Tables[0].Rows[loopcounter]["PrezimeIme"].ToString();
arrvalues[loopcounter] = ds.Tables[0].Rows[loopcounter]["NetworkLogin"].ToString();
arrvalues[loopcounter] = ds.Tables[0].Rows[loopcounter]["Status"].ToString();
arrvalues[loopcounter] = ds.Tables[0].Rows[loopcounter]["OrgUnitID"].ToString();
arrvalues[loopcounter] = ds.Tables[0].Rows[loopcounter]["DT_Creat"].ToString();
arrvalues[loopcounter] = ds.Tables[0].Rows[loopcounter]["DT_Modif"].ToString();
}
ASPxWebDocumentViewer1.OpenReport(report);
ASPxWebDocumentViewer1.DataBind();
//gridview1.DataSource = ds;
//gridview1.DataBind();
}
}
catch (Exception)
{
throw;
}
}
I need to load filtered report in button click, since in JS I only load report, when I click in button I get only unfiltered data, when I debug application I see that I get filtered data, but problem can be only in JS. Any help will be appreciate
Here is reference page which I check:
Link 1
Link 2
Link 3

Google Sheet Connection to SQL Server

I am hoping that someone can help me with this connection issue, I am trying to connect a Google Sheet to a SQL Server 2014 database and pull the data via a View.
Below is a piece of code that I have taken from the :-
https://learn.microsoft.com/en-us/sql/connect/jdbc/connection-url-sample
import java.sql.*;
public class connectURL {
public static void main(String[] args) {
// Create a variable for the connection string.
String connectionUrl = "jdbc:sqlserver://localhost:1433;" +
"databaseName=AdventureWorks;user=UserName;password=*****";
// Declare the JDBC objects.
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
try {
// Establish the connection.
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
con = DriverManager.getConnection(connectionUrl);
// Create and execute an SQL statement that returns some data.
String SQL = "SELECT TOP 10 * FROM Person.Contact";
stmt = con.createStatement();
rs = stmt.executeQuery(SQL);
// Iterate through the data in the result set and display it.
while (rs.next()) {
System.out.println(rs.getString(4) + " " + rs.getString(6));
}
}
// Handle any errors that may have occurred.
catch (Exception e) {
e.printStackTrace();
}
finally {
if (rs != null) try { rs.close(); } catch(Exception e) {}
if (stmt != null) try { stmt.close(); } catch(Exception e) {}
if (con != null) try { con.close(); } catch(Exception e) {}
}
}
}
I have amended the connection string with the relevant SQL connection username and password but I am getting the following error :-
Missing ; before statement. (line 1, file "Code")Dismiss
I am very new to this so please if possible keep the answers as simple as possible.
Thanks PD
After some time I cut down the original code and it looks a lot more like what I am after but still having some connection issues, can anyone see what the error might be
// Read up to 1000 rows of data from the table and log them.
function readFromTable() {
var conn = Jdbc.getConnection("jdbc:sqlserver://IP ADDRESS:1433;databaseName=name;user=user;password=password");
var start = new Date();
var stmt = conn.createStatement();
stmt.setMaxRows(1000);
var results = stmt.executeQuery('SELECT * FROM table');
var numCols = results.getMetaData().getColumnCount();
while (results.next()) {
var rowString = '';
for (var col = 0; col < numCols; col++) {
rowString += results.getString(col + 1) + '\t';
}
Logger.log(rowString)
}
results.close();
stmt.close();
var end = new Date();
Logger.log('Time elapsed: %sms', end - start);
}

DateTime is not displayed as expected [duplicate]

This question already has answers here:
Javascript serialization of DateTime in asp.net is not giving a javascript date object?
(10 answers)
Closed 6 years ago.
I have a C# code to get some dates from a Sql Table, these dates are filled by mssql getdate() the problem here is that my dates are displayed in the following structure:
/Date(1480343496517)/
And what I expect is this:
2016-11-28 08:13:23.820 //This is what I get executing my query in MSSQL
This is my full code:
C# Class
public MyDate(DateTime date)
{
Date = date;
}
public DateTime Date { get; set; }
WebMethod
[WebMethod]
public string ShowDate()
{
DataTable dt = new DataTable();
dt = conn.CheckTable("date");
MyDate fch;
List<MyDate> list = new List<MyDate>();
for (int i = 0; i < dt.Rows.Count; i++)
{
fch = new Fecha();
fch.Date = Convert.ToDateTime(dt.Rows[i]["Date"]);
list.Add(fch);
fch = null;
}
JavaScriptSerializer js = new JavaScriptSerializer();
string lines = js.Serialize(list);
return lines;
}
CheckTable
public DataTable CheckTable(string table)
{
dt = new DataTable();
ds = new DataSet();
string sql = "";
switch (table)
{
case "date":
sql = "SELECT Date FROM dbo.Table_1";
break;
}
try
{
Open();
SqlDataAdapter da = new SqlDataAdapter(sql, conn);
da.Fill(ds);
dt = ds.Tables[0];
}
catch (Exception ex)
{
}
finally
{
Close();
}
return dt;
}
And my JS function:
$.ajax({
type: 'POST', //POST | GET
url: "WebService.asmx/ShowDate", //Direccion del ws
dataType: 'json',
contentType: 'application/json',
timeout: 600000,
error: function (xhr) {
$('#dates').html('<option>Error</option>');
},
success: function (data) {
var datas = JSON.parse(data.d);
for (var i = 0; i < datos.length; i++) {
var myDate= datas[i].Date;
options += '<option value ="' + myDate+ '">';
options += myDate;
options += '</option>';
}
$('#dates').html(options);
}
});
What I'm doing wrong and what can I do to solve it?
I don't know what the other classes you're using are, but if you just want a list of dates from the query then this should do it...
[WebMethod]
public string ShowDate()
{
DataTable dt = new DataTable();
dt = conn.CheckTable("date");
List<DateTime> list = new List<DateTime>();
for (int i = 0; i < dt.Rows.Count; i++)
{
list.Add(Convert.ToDateTime(dt.Rows[i]["Date"]).ToString());
}
JavaScriptSerializer js = new JavaScriptSerializer();
string lines = js.Serialize(list);
return lines;
}
then in the JavaScript, change this one line...
var myDate = datas[i];
The web method will now just return a serialised list of dates, so no need to get a .date property of the list objects any more.

C# in javascript executes only once

When I try to read the data from Azure Database code does so correctly on page load/refresh but then it repeats the very same data, even though I call a function to get a new one.
C# Code for fetching data.
public static class GetSensorData
{
public static List<Reading> GetTemperatureSensorData(int quantity)
{
decimal TemperatureCelcius;
DateTime TimeOfAReading;
string ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["rpiDB"].ConnectionString.ToString();
List<Reading> TempTemperatureList = new List<Reading> { };
SqlConnection Connection = new SqlConnection(ConnectionString);
SqlCommand GetTemperature = new SqlCommand("SELECT TOP " + quantity + " * FROM tbl_temp ORDER BY time DESC;", Connection);
Connection.Open();
SqlDataAdapter TempAdapter = new SqlDataAdapter(GetTemperature);
DataTable TempereatureSensorDataTable = new DataTable();
TempAdapter.Fill(TempereatureSensorDataTable);
for (int i = 0; i < quantity; i++)
{
TemperatureCelcius = (decimal)TempereatureSensorDataTable.Rows[i][0];
//gotta change the culture from within
TemperatureCelcius = decimal.Parse(TemperatureCelcius.ToString(), CultureInfo.InvariantCulture);
TimeOfAReading = (DateTime)TempereatureSensorDataTable.Rows[i][1];
TempTemperatureList.Add(new Reading(TemperatureCelcius, TimeOfAReading.ToString("HH/mm")));
}
Connection.Close();
return TempTemperatureList;
}
}
And here's how I use it in CSHTML
var updateData = function (oldData) {
var labels = oldData["labels"];
var dataSetA = oldData["datasets"][0]["data"];
#{
List<Reading> SingleReading = new List<Reading>(GetSensorData.GetTemperatureSensorData(1));
}
var datetime = #SingleReading[0].TimeOfReading
labels.push(String(datetime));
labels.shift();
var Temperature = #(SingleReading[0].TemperatureCelcius);
dataSetA.push(Temperature / 100);
dataSetA.shift();
};
setInterval(function () {
updateData(data);
myLineChart.data = data;
myLineChart.update();
}, 5000
);
The function in setInterval is being executed every 5 seconds but with the data, I got on the page load.
You need to create a web service in your C# project so that you can make AJAX calls to GetTemperatureSensorData. I recommend putting this into its own Web API project. https://msdn.microsoft.com/en-us/library/hh833994(v=vs.108).aspx
Next, you will need to create an AJAX call to the web service in your javascript code. To make this easier to do, I recommend using the jQuery library, specifically the get command: https://api.jquery.com/jquery.get/
Thanks everyone for your help, I've figured it out.
This is my CS code from HomeController.cs
public ActionResult GetTemp(int quantity)
{
decimal TemperatureCelcius;
DateTime TimeOfReading;
string ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["rpiDB"].ConnectionString.ToString();
List<Reading> TempTemperatureList = new List<Reading> { };
SqlConnection Connection = new SqlConnection(ConnectionString);
SqlCommand GetTemperature = new SqlCommand("SELECT TOP " + quantity + " * FROM tbl_temp ORDER BY time DESC;", Connection);
Connection.Open();
SqlDataAdapter TempAdapter = new SqlDataAdapter(GetTemperature);
DataTable TempereatureSensorDataTable = new DataTable();
TempAdapter.Fill(TempereatureSensorDataTable);
for (int i = 0; i < quantity; i++)
{
TemperatureCelcius = (decimal)TempereatureSensorDataTable.Rows[i][0];
TimeOfReading = (DateTime)TempereatureSensorDataTable.Rows[i][1];
TempTemperatureList.Add(new Reading(TemperatureCelcius, TimeOfReading.ToString("HH:mm")));
}
Connection.Close();
return Json(TempTemperatureList, JsonRequestBehavior.AllowGet);
}
And Ajax:
setInterval(function () {
$.ajax({
type: 'GET',
url: '/Home/GetTemp',
contentType: 'application/json; charset=utf-8',
data: { 'quantity': 1 },
success: function (response) {
var _Temperature = response[0].TemperatureCelcius;
var _TimeOfReading = response[0].TimeOfReading;
console.log(_Temperature);
updateData(data, _Temperature, _TimeOfReading);
myLineChart.data = data;
myLineChart.update();
},
error: function(req, err){ console.log('my message ' + err); }
});
}, 5000
);

The SmartSource Data collector JavaScript Tag, could be inserted from Java?

I'm totally new in Webtrends, I have read that The SmartSource Data collector JavaScript Tag, could be inserted from Java or HTML. does anyone know how to inser it from Java, I found the below class, is this class does the job? please provide some samples. Thanks in advance
public class DC {
public DC() {
super();
}
public String post_url(String connUrl, Map<String, String> bodyref) {
String response = "";
String responseCode = "";
try {
HttpURLConnection conn = null;
// construct data
String data = "";
Iterator<String> i = bodyref.keySet().iterator();
boolean ampersand = false;
while (i.hasNext()) {
if (ampersand) {
data += "&";
} else {
ampersand = true;
}
String b = i.next();
data += b + "=" + bodyref.get(b);
}
System.out.println();
System.out.println("[Request]");
System.out.println("(Url)");
System.out.println(connUrl);
System.out.println("(Body)");
System.out.println(data);
// send data
URL url = new URL(connUrl);
conn = (HttpURLConnection) url.openConnection();
conn.setUseCaches(false);
conn.setDoOutput(true);
OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(data);
wr.flush();
try {
// get the response
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
String line;
while ((line = rd.readLine()) != null) {
response += line;
response += "\n";
}
rd.close();
} catch (IOException e1) {
if (conn != null) {
// get the response
BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getErrorStream()));
String line;
while ((line = rd.readLine()) != null) {
response += line;
response += "\n";
}
}
}
System.out.println();
System.out.println("[Response]");
System.out.println("(Status)");
System.out.printf("%s %s\n", conn.getResponseCode(), conn.getResponseMessage());
System.out.println("(Message)");
System.out.println(conn.getResponseMessage());
System.out.println("(Body)");
System.out.println(response);
System.out.flush();
wr.close();
} catch (Exception e) {
System.out.println();
System.out.println("[Response]");
System.out.println("(Status)");
System.out.println(e.toString());
System.out.println("(Message)");
System.out.println(e.getMessage());
System.out.flush();
}
return response;
}
public static void main(String[] args) {
DC dc = new DC();
// customer-specific DCSID
String dcsid = "dcslbiart00000gwngvpqkrcn_2u3z";
// base portion of DC API url
String base_url = "http://dc.webtrends.com/v1/" + dcsid;
// post body
Map<String, String> body1 = new HashMap();
// post query string
String querystring = "";
// compose urls
String id_url = base_url + "/ids.svc" + querystring;
String event_url = base_url + "/events.svc" + querystring;
// get visitor identifier
String id = dc.post_url(id_url, body1);
// post body
Map<String, String> body = new HashMap();
// initialize post body
body.put("dcsuri", "/MyJavaTest");
body.put("dcssip", "localhost");
body.put("WT.ti", "MyJavaTest");
body.put("WT.co_f", id);
body.put("dcsverbose", "true");
// submit event data
dc.post_url(event_url, body);
}

Categories

Resources