Display data from SQL into chart via WCF service - c#

I'm doing an assignment in inserting and displaying data from SQL into a chart (using Web Form or Highchart) via WCF service. I was able to get the data from SQL to WCF service but I don't know how to display it into a chart. I know using Web Form I can directly bind the data from SQL to the chart but the purpose of the assignment is to display the data via WCF service. Here are my code:
TempService:
public DataSet GetTemp()
{
SqlConnection con = new SqlConnection();
con.ConnectionString = "server=DUCPC\\SQLEXPRESS;database=Temprature;user=sa;password=123456";
SqlDataAdapter da = new SqlDataAdapter("select * from RoomTemp",con);
DataSet ds = new DataSet();
da.Fill(ds);
return ds;
}
Code to bind the data to the chart in Web Form:
protected void Page_Load(object sender, EventArgs e)
{
TempService.TempServiceClient tsc = new TempService.TempServiceClient();
DataSet ds = tsc.GetTemp();
TempChart.DataSource = ds;
TempChart.DataBind();
}
Of course the above code not working. Can anyone help to fix the code above? Is there a simple way to insert the data into the SQL database? Any help is appreciated :)

Related

How to Connect DataGridView in C# To an SQL Database?

I'm trying to pass data from DataGridView to a Database SqlClient I opened especially for this. When the program runs, it tells me this error:
An attempt to attach an auto-named database for file failed. A database with the same name exists, or specified file cannot be opened, or it is located on UNC share.
I made a form with 2 buttons, one for adding data to the DataGridView (works fine) and another one to pass the data to a database table.
the not working button's code is this:
private void button3_Click(object sender, EventArgs e)
{
string connectionString = "Data Source=.\\SQLEXPRESS;AttachDbFilename=.;Integrated Security=True;Connect Timeout=30;User Instance=True";
string sql = "SELECT * FROM Authors";
SqlConnection con = new SqlConnection(connectionString);
SqlDataAdapter dataadapter = new SqlDataAdapter(sql, con);
DataSet ds = new DataSet();
con.Open();
dataadapter.Fill(ds, "Authors_table");
con.Close();
dataGridView1.DataSource = ds;
dataGridView1.DataMember = "Authors_table";
}
What can I do to fix it?
I tried choosing a data source to the DataGridView but it still didn't work out.
Thanks in advance!

An error occurred while receiving DataTable in wcf service response

I am developing a windows form application in c#. My database is handled in a wcf application. In my wcf application I have a class called lecturer which has a method called view lecturers() as follows. My purpose is to view the lecturers table in a grid view.
public DataTable viewLec()
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["resourceAlloc"].ToString());
DataTable dt = new DataTable();
string vw = "select * from lecturers";
SqlCommand cmd = new SqlCommand(vw,con);
SqlDataAdapter adp = new SqlDataAdapter(cmd);
adp.Fill(dt);
return dt;
}
In my IService1.cs:
[OperationContract]
DataTable viewLecturer();
Service1.svc.cs:
public DataTable viewLecturer()
{
Lecturer lec = new Lecturer();
return lec.viewLec();
}
in my windows form application button click event,
private void button2_Click(object sender, EventArgs e)
{
Service1Client obj = new Service1Client();
dataGridView1.DataSource = obj.viewLecturer();
}
When I click the view button the above error occurs, I cannot understand why?
I don't know the exact error of your code, but first thing I want to mention is that using DataTable object as your Data Contract is not the best idea as it contains certain amount of extra data which usually is not consumed by the end applications. But anyway, in your particular case WCF will not be able to serialize your your object as it will not have table name which is mandatory for this class to perform serialization. Try to follow this way:
DataTable dt = new DataTable();
// Must set name for serialization to succeed.
dt.TableName = "lecturers";
I don't see the actual error you have (you should post it to make your answer more clear), but at least this will help you to avoid serialization error.

adding crystal report via code

i successfully designed and filled my Crystal report via code not via wizard.
i added Crystal report via addNEWITEM
i added dataset in aap_code via addNEWITEM
i added datatable into dataset via addNEWITEM
Via code i made report and filled dataset and table with data
Run and display. Successfully done.
but my question is that how to do it fully via code like for steps 1,2,3 ? I don't want to add it via AddNewItem etc, isn't there any way to add these via code ? i did, i created some datasets and table via code like we do for Gridview etc but that doesn't appear in DATA connections of crystal report etc.
String conStr =WebConfigurationManager.ConnectionStrings["LoginDatabaseConnectionString"].ConnectionString;
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
Dataset_load();
}
}
protected void Dataset_load()
{
SqlConnection sqlcon = new SqlConnection(conStr);
SqlCommand sqlCom = new SqlCommand("select * from Login", sqlcon);
SqlDataAdapter sqlDA = new SqlDataAdapter(sqlCom);
// DataSet ds = new DataSet("CRDataSet");
try
{
sqlcon.Open();
//sqlCom.ExecuteNonQuery();
//sqlDA.Fill(ds,"Login");
DataSet1 ds = new DataSet1();
DataTable dt = new DataTable("DT_CR");
sqlDA.Fill(dt);
ds.Tables[0].Merge(dt);
ReportDocument rd = new ReportDocument();
rd.Load(Server.MapPath("CrystalReport.rpt"));
rd.SetDataSource(ds);
CrystalReportViewer1.ReportSource = rd;
}
catch (Exception exc)
{
Response.Write(exc.Message);
}
finally
{
sqlcon.Close();
}
I'm not sure why you would make it harder on yourself by trying to create all the code from scratch rather than using the functionality of VS. If you really want to do it though, I would create everything using the built-in functionality. Then I would look at all the code that gets added and see what does what.
There are some tutorials out there that tell you how to do it using the features. Create one and then read through the code.
That's how I would do it.
Hope that helps,
Chris

GetData() does not exist in the current context

So I was trying follow along some asp.net tutorials on filling a Gridview with ajax.
On Microsoft's msdn example it has
DataSet ds = GetData(queryString);
which I found here.
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.basedataboundcontrol.datasource.aspx
they are including
<%# import namespace="System.Data" %>
<%# import namespace="System.Data.SqlClient" %>
and my C# codebehind already has
using System.Data;
using System.Data.SqlClient;
using System.Data.Sql;
On this example here he is using GetData() as well.
http://www.aspsnippets.com/Articles/GridView---Add-Edit-Update-Delete-and-Paging-the-AJAX-way.aspx
GridView1.DataSource = GetData(cmd);
GridView1.DataBind();
But anyway I am getting the error
GetData() does not exist in the current context
when I try it in my C# codebehind
SqlCommand sql = new SqlCommand(command);
AddressContactSource.SelectCommandType = SqlDataSourceCommandType.Text;
AddressContactSource.SelectCommand = command;
DataSet ds= new DataSet;
ds= GetData(sql);
So what am I missing?
A GetData() method could be
DataSet GetData(String queryString)
{
// Retrieve the connection string stored in the Web.config file.
String connectionString = ConfigurationManager.ConnectionStrings["NorthWindConnectionString"].ConnectionString;
DataSet ds = new DataSet();
try
{
// Connect to the database and run the query.
SqlConnection connection = new SqlConnection(connectionString);
SqlDataAdapter adapter = new SqlDataAdapter(queryString, connection);
// Fill the DataSet.
adapter.Fill(ds);
}
catch(Exception ex)
{
// The connection failed. Display an error message.
Message.Text = "Unable to connect to the database.";
}
return ds;
}
Its standard procedure:
1 You provide the sql queryString to the function
2 connect to your database
3 create and fill a DataSet with the result of the query and return the DataSet. Then assign the DataSet to the DataSource.
You have to implement functions like GetData(yourQueryString) yourself.
As connection string you take the string to your database (here are some examples: connectionstrings).
(Note: The above code example GetData() is just copied from the link you provided.)

Binding textboxes to database (C# web developer)

I am using Microsoft Visual Web Developer 2010 Express. I have been trying to enter my textbox input into a database table I created. I ran into a problem using the DataBinding property (located under the BindTextBoxes method at the bottom). I searched the internet and found out that the DataBinding property does not exist in Web Developer. Is there an alternate way to transfer the textbox input into a database table?
Here is database part of my code (in C#):
namespace WebApplication2
{
public partial class _Default : System.Web.UI.Page
{
//used to link textboxes with database
BindingSource bsUserDetails = new BindingSource();
//info stored in tables
DataSet dsUserDetails = new DataSet();
//manages connection between database and application
SqlDataAdapter daUserDetails = new SqlDataAdapter();
//create new SQL connection
SqlConnection connUserDetails = new SqlConnection("Data Source=.\SQLEXPRESS;AttachDbFilename=D:\Users\synthesis\Documents\Visual Studio 2010\Projects\Practical\Practical\App_Data\UserDetails.mdf;Integrated Security=True;User Instance=True");
protected void Page_Load(object sender, EventArgs e)
{
//link textboxes to relevant fields in the dataset
bsUserDetails.DataSource = dsUserDetails;
bsUserDetails.DataMember = dsUserDetails.Tables[0].ToString();
//call BindTextBoxes Method
BindTextBoxes();
private void BindTextBoxes()
{
txtBoxCell.DataBindings.Add(new Binding("Name entered into txtBox", bsUserDetails,
"Name column in database table", true));
}
}
}
You could always write your own SQL for inserting data from your text boxes. You'll need to setup a SqlConnection and SqlCommand object. Then you'll need to define the SQL on the command and set up the parameters to prevent SQL injection. Something like this:
StringBuilder sb = new StringBuilder();
sb.Append("INSERT INTO sometable VALUES(#text1,#text2)");
SqlConnection conn = new SqlConnection(connStr);
SqlCommand command = new SqlCommand(sb.ToString());
command.CommandType = CommandType.Text;
command.Parameters.AddWithValue("text1", text1.Text);
command.Parameters.AddWithValue("text2", text2.Text);
command.ExecuteNonQuery();

Categories