C# String to Dataset - c#

I've tried to find the answer to this but I've found no success. If it is possible how do you convert a string to a data set in C# so I can generate a JSON file from the data in my database table.
Here is my asmx file:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Script.Services;
using System.Web.Script.Serialization;
using System.Data;
using System.Data.SqlClient;
namespace Book
{
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
[ScriptService]
public class Service : System.Web.Services.WebService
{
SqlConnection con;
SqlDataAdapter adap;
DataSet ds;
[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public DataSet GetBookList()
{
con = new SqlConnection(#"Data Source=server;Initial Catalog=database;Persist Security Info=True;User ID=username;pwd=password;");
adap = new SqlDataAdapter("SELECT * FROM tblBookList", con);
ds = new DataSet();
adap.Fill(ds, "tblBookList");
var jsonString = new JavaScriptSerializer().Serialize(ds);
return jsonString;
}
}
}
Or is there a smarter way to export the data into a JSON file?
EDIT
The error that I am receiving is
Error: cannot implicitly convert type 'string' to 'System.Data.DataSet'
The error appears on the 'return jsonString;' statement.

Your function is defined as returning a DataSet.
You are returning a string.
Change the function definition to return a string.
public String GetBookList()

If you want to return the DataSet, just return the "ds" variable. Otherwise you are just returning a string that is a serialized version of the ds variable.

Related

XML to String from Database call - MVC

I'm trying to recycle an approach found here
to call a stored procedure from SQL Server, receive an XML response, render the response to a string variable, and process it against an XLST template. I can't seem to get the string variable created correctly. Here's what I'm doing in my controller:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Data.SqlClient;
using System.Configuration;
using Demo2.Models;
namespace Demo2.Controllers
{
public class CfsController : Controller
{
// GET: Cfs
public ActionResult Report()
{
{
SqlConnection con = new SqlConnection("data source=.; database=Test; integrated security=SSPI");
SqlCommand cmd = new SqlCommand("EXEC [TEST].[REPORTSERV].[CFSREPORT] #CFSNUMBER = N'010101-10';", con);
con.Open();
SqlDataReader rdr = cmd.ExecuteReader();
string response = rdr.ToString();
con.Close();
ViewBag.CurrentReport = response;
return View();
}
}
}
}
When I run the code I'm getting an error in the transform step in the tranformObj.Transform(reader, args, writer) step of the helper CS.
I believe the issue is caused by the string response variable not taking the XML response from the SQL Server as a string.
Since my stored procedure is going to return only one record (an XML response), I've changed ExecuteReader to ExecuteScalar and converted the response into a string. It's now working but it looks like some of the XML files I'm getting back are exceeding the size of the string variable.
string rdr = cmd.ExecuteScalar().ToString();
ViewBag.CurrentReport = rdr;
You never provided your SP source code... So it is assumed that it returns an XML data type.
You need to change the following two lines:
SqlDataReader rdr = cmd.ExecuteReader();
string response = rdr.ToString();
To the following:
using (XmlReader reader = cmd.ExecuteXmlReader())
{
XDocument xdoc = XDocument.Load(reader);
string response = xdoc.ToString();
}

An exception of type 'System.Data.SqlClient.SqlException' Instance failure

I'm a beginner with C# and I'm working with a web service. When I tried to test my service, this error message occurs:
An exception of type 'System.InvalidOperationException' occurred in System.Data.dll but was not handled in user code
Additional information: Instance failure.
Here is my connection string in web configuration:
<connectionStrings>
<add name="connection"
connectionString="Data Source=DESKTOP-CIRUCVV\\SQLEXPRESS;Initial Catalog=CustomerManagerment;Integrated Security=True;"/>
</connectionStrings>
Here is my code inside the web service class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Data.SqlClient;
using System.Data;
using System.Web.Configuration;
namespace WebService
{
/// <summary>
/// Summary description for CustomerService
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.ComponentModel.ToolboxItem(false)]
// 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 CustomerService : System.Web.Services.WebService
{
static string strcon = WebConfigurationManager.ConnectionStrings["connection"].ConnectionString;
public CustomerService() { }
[WebMethod(Description = "Show Customers")]
public DataSet showCustomer()
{
SqlConnection con = new SqlConnection(strcon);
string Sql = "select * from Customers";
SqlDataAdapter da = new SqlDataAdapter(Sql, con);
DataSet ds = new DataSet();
da.Fill(ds);
return ds;
}
}
}
Change DESKTOP-CIRUCVV\\SQLEXPRESS to DESKTOP-CIRUCVV\SQLEXPRESS

I would like to display data from a database in an MVC project using sql adapter

I am looking to use the SQL Data adapter feature inside of MVC to display the results from a query string inside of my project. I'm new to using the sql adapter feature but I would like to get used to it. Simply put, I need to know what to put in my controller, and if i need to create a model, and what to put in my view.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
namespace NewHoyaIntranet.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
DataSet data;
DataTable table;
using (SqlConnection connection = new
SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["HUT"]
.ConnectionString))
{
connection.Open();
SqlCommand select = new SqlCommand("SELECT * FROM HUT.dbo.XREF_HIOI_LensStyle_HTL", connection);
SqlDataAdapter adapter = new SqlDataAdapter();
adapter.SelectCommand = select;
data = new DataSet();
adapter.Fill(data, "HUT.dbo.XREF_HIOI_LensStyle_HTL");
table = data.Tables[0]; //is the [0] really correct?
}
return View(/* Right now nothing is returning in any view/ how do i tie the view in? */);
}
}
}

creating XML from SQL TABLE with column patterns

I have a table with columns below,
SALES_ORDERS.ORDER_SLIP.NUMBER|SALES_ORDERS.ORDER_SLIP.DATE|SALES_ORDERS.ORDER_SLIP.ARP_CODE
and the XML output I need to have is like below
<SALES_ORDERS>
<ORDER_SLIP>
<NUMBER>TEST</NUMBER>
<DATE>02.09.2014</DATE>
<ARP_CODE>CARI1</ARP_CODE>
</ORDER_SLIP>
</SALES_ORDERS>
I need to create the xml according to column name which include full path way from the top.
How can I achive such an XML file from such a table? I can use LINQ if it is necessary but I am not sure how to do it?
Too Easy
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient;
namespace ConsoleApplication1
{
class Program
{
const string FILENAME = #"c:\temp\test.xml";
static void Main(string[] args)
{
string SQL = "Enter Your SQL Select string here";
string connStr = "Enter You connection string here";
SqlDataAdapter adapter = new SqlDataAdapter(SQL, connStr);
DataSet ds = new DataSet();
adapter.Fill(ds);
ds.DataSetName = "SALES_ORDERS";
ds.WriteXml(FILENAME, XmlWriteMode.WriteSchema);
}
}
}
​

Using select query in C#.NET for web service application

I am not unable to understand the way in which a select * query is written while we create a web service using C#.NET to connect to an SQL Database.
Basically, I have 4 columns . I am taking a particular input from the user , which is an existing value of 1st column. Now depending on that value I want to select all the records of the remaining 3 columns. I need to write a SELECT * query but I don't in what form will I get those records. I have heard of SqlDataAdapter but then will it return me the records in a row-column format or do have to store the result in some sort of List and then use it for other purposes.
Can someone please help me to understand how such a query can be written?
This code is wrong but it will help understand what I need
I want to get the records of other columns based upon my "where clause" condition
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Xml.Linq;
using System.Data.SqlClient;
namespace statistics
{
/// <summary>
/// Summary description for Service1
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ToolboxItem(false)]
// 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 Service1 : System.Web.Services.WebService
{
[WebMethod]
public int retrieve(String rollno)
{
int rows=0;
SqlConnection myConnection = new SqlConnection(#"Data Source=.\SQLEXPRESS;Initial Catalog=student;User ID=sa;Password=123");
try
{
myConnection.Open();
SqlCommand myCommand = new SqlCommand();
myCommand.Connection = myConnection;
String strsql = "SELECT * FROM checkrecord values WHERE rollno=#rollno";
DataSet dataSet = new DataSet();
SqlDataAdapter dataAdapter = new SqlDataAdapter(strsql, myConnection);
myCommand.Parameters.Add("#rollno", SqlDbType.VarChar).Value = rollno;
rows = myCommand.ExecuteNonQuery();
SqlDataReader myReader = myCommand.ExecuteReader()
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
finally
{
myConnection.Close();
}
return rows;
}
}
}
You need to connect to the database, then use SQLDataAdapter to send the user input SELECT query to the database. Something like,
SELECT col2,col3,col4 FROM yourtable WHERE col1 = ?
There are different ways to use the SQLDataAdapter, and specify the query and parameters. The SQLDataAdapter will return a DataSet that contains a DataTable. You can then use the DataSet or DataTable to populate the control of your choice (ie; DataGrid) with the results. There is a walk-through of this on MSDN: http://msdn.microsoft.com/en-us/library/aa984467%28v=vs.71%29.aspx
Based on your edit, you don't want to use ExecuteNonQuery. To get the rows you use ExecuteReader. Example here:
http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.executereader%28v=VS.71%29.aspx
I think you are talking about the return type of the webservice?
Yes, the database query will return you a list of the record values. With the .net webservices however, you can put these values into a custom class written by you, and the structure of this class will be included in your webservice.
[WebMethod]
public Myclass retrieve(String rollno)
{
return new Myclass("variable1", "variable2");
}
It will be included in the WSDL and thus can be implemented by any other application using your web service.
I recommend looking at the documentation for the class in question, in this case, the SQLDataAdapter
http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldataadapter.aspx
What I think you might want is to fill the results into a dataset.

Categories