Retrive DataSet from WCF application - c#

I got the result in WCF Test Client while debugging, not sure how to get dataset value in browser. am working for the first time on wcf project
IService.cs
[ServiceContract]
public interface IService
{
[OperationContract]
DataSet Permit(getPermit name);
}
[DataContract]
public class getPermit{
string name = string.Empty;
[DataMember]
public string Name
{
get { return name; }
set { name = value; }
}
}
Service.SVC
public System.Data.DataSet Permit(getPermit name)
{
DataSet ds = new DataSet();
string connection = ConfigurationManager.ConnectionStrings["xyz"].ConnectionString.ToString();
string cmdText = "sql Query";
SqlConnection con = new SqlConnection(connection);
con.Open();
SqlCommand cmd = new SqlCommand(cmdText, con);
cmd.ExecuteNonQuery();
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
{
da.Fill(ds);
return ds;
}
}
After deploying to IIS, I didn't got any result after passing parameter as query string
i think, i need to mention some bindings in config file to make it work.
Not sure how to configure
Any Suggestions

At first, the problem doesn’t relate to dataset. The failure of connecting the database is the issue. I suggest you check whether the connection string use the integrated security to build the connection. When we deploy the project to IIS, Application pool identity will replace the identity that running VS, thereby the database connection will be invalid.
WCF webservice hosted on IIS returns empty xml response
Second, by default DataSet could be returned properly without specifying the name, this point is different from DataTable type.
Passing an inherited "Data Contract" through WCF call?
At last, the issue has none business with binding configuration except the returned data is too large. As Akshay mentioned, returning a dataset is not a best practice of transmitting data, we had better consider List and custom the user class with DataContract.
https://learn.microsoft.com/en-us/dotnet/framework/wcf/feature-details/using-data-contracts
Feel free to let me know if the problem still exists.

Related

The ConnectionString property has not been initialized. How to fix it?

I am using a method(GetConnectionString()) in a class(Utility.cs) as part of another method(fillDT()) in another class(Function.cs).
internal class Utility
{
internal static string GetConnectionString()
{
//Util-2 Assume failure.
string returnValue = null;
//Util-3 Look for the name in the connectionStrings section.
ConnectionStringSettings settings = ConfigurationManager.ConnectionStrings["Assignment_new.Properties.Settings.connString"];
//If found, return the connection string.
if (settings != null)
returnValue = settings.ConnectionString;
return returnValue;
}
}
class Functions
{
public static DataTable fillDT(string sqlstatement) //Fills the datatable with data from sqlstatement
{
string connstr = Assignment_new.Utility.GetConnectionString();
SqlConnection con = new SqlConnection(connstr);
con.Open();
SqlDataAdapter sda = new SqlDataAdapter(sqlstatement, con);
DataTable dt = new DataTable();
sda.Fill(dt);
return dt;
}
Whenever I call Functions.fillDT(#"sql statement"), the error pops out saying connection string is not initialized.
Make sure you use proper config files to save your connection string. I see you are tagging this question as WinForms, so your connection string should be inside App.Config file not in Web.Config. If this a web application then you should do the opposite, keep it in Web.Config file at the top most directory.
Also, if this is a desktop application and you are using App.Config file to save your settings, make sure that file is copied to your output directory, where the executable stays (usually the same name as the executable. i.e <EXNAme>.exe.config). Otherwise when the application runs, it won't find it.
You just checked your connection string to be null. Check string.IsNullOrEmpty() to see if it's not null. Besides, you need to set breakpoint and check if the connection string value you see in your app.config actually retrieved in your code and it is correct.

Controller Refresh after 5 sec - Avoid Constructor Call

I have following code for my Controller Class. I refresh my View from the controller. Every time Refresh takes place, my whole class constructor is called, I wanted to refresh only my Show function and its attached View. How to avoid this constructor getting called every time.
public class DriverController : Controller
{
OdbcConnection DBConnection; //= new OdbcConnection("DSN=pitbuccx");
OdbcConnection DBConnection2; // = new OdbcConnection("DSN=pitbuccx2");
Query q;
string myQuery;
OdbcCommand cmd;
OdbcCommand cmd2;
OdbcDataReader DbReader;
OdbcDataReader DbReader2;
string LoggedInAgents;
string OnCalls;
string AgentsInReadyState;
string AgentsInNotReadyState;
string AgentsInWrapup;
string ReservedAgents;
string CallsOffered;
string CallsAnswered;
string CallsAbandoned;
string CallsInQueue;
string LongestCallInQueue;
string AbandRate;
string ServiceLevelPct;
string ASA;
string AHT;
string LongestTalkDuration;
public DriverController()
{
OdbcConnection DBConnection = new OdbcConnection("DSN=pitbuccx01");
DBConnection.Open();
OdbcConnection DBConnection2 = new OdbcConnection("DSN=pitbuccx02");
DBConnection2.Open();
q = new Query();
myQuery = q.getQuery();
cmd = DBConnection.CreateCommand();
cmd2 = DBConnection2.CreateCommand();
cmd.CommandText = myQuery;
cmd2.CommandText = myQuery;
Console.WriteLine("This is Constructor");
}
public ActionResult Show()
{
DbReader = cmd.ExecuteReader();
DbReader2 = cmd2.ExecuteReader();
DbReader.Read();
DbReader2.Read();
string testData1;
string testData2;
//Checking Connection Data Validity.
testData1 = DbReader["A"].ToString();
testData2 = DbReader2["B"].ToString();
Response.AddHeader("Refresh", "5");
return View();
}
}
~DriverController()
{
DbReader.Close();
cmd.Dispose();
DBConnection.Close();
DbReader2.Close();
cmd2.Dispose();
DBConnection2.Close();
}
You should not be doing this in your controller. By definition a controller is the director of web requests. At the minimum you need a domain type to create and release external resources like DB connections, and do queries against the data source. I can't even see where connections are being closed/disposed.
How to avoid controller instantiation for every request?
You can do that by implementing and registering your own controller factory, which instantiates a given controller only once and then stores it somewhere in the AppDomain so it stays alive for longer than the current request, for example in some static variable.
This question however reeks like an XY problem. You seem to be concerned with the relative cost of opening a database connection for every request.
Well good news, everybody! You're not the first to think about this, and you should not worry, because that has already been fixed long ago by the framework builders: .NET uses connection pooling.
In short, this means that you should not worry about opening database connections, because an earlier opened connection will be saved in the pool and returned to your application when it requests it.

Best method to connect to SQL Server in C# WPF

I'm a beginner.
I already found a way to connect to SQL SERVER using the codes below:
private void getListBtn_Click(object sender, RoutedEventArgs e)
{
SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=myDB;Integrated Security=true;");
SqlDataAdapter sda = new SqlDataAdapter("SELECT ID,Date,Name,City FROM Info;", con);
DataTable dt = new DataTable();
sda.Fill(dt);
dataGridForm.ItemsSource = dt.DefaultView;
I also wanted to get number of rows from a TABLE and set it to a label, But it's not a good idea to copy and paste this code again, I want to have a method for sqlconnection so i won't rewrite this code again and again for every single query.
Sorry i'm an absolute beginner, 3 days since i started learning C# WPF.
Yes some frameworks and/or ADO's solutions are good and maybe the best "professionnal" approch, you say you're a beginner and I was it not so far ;-).
So the simpliest way is to add a new class for the sql connection. In example add a Sqlconnect.cs class.
using System.Data.SqlClient;
public class Sqlconnect
{
public SqlConnection Con { get; set; }//the object
private string conString { get; set; }//the string to store your connection parameters
}
This class will have a method to open the connection and one to close it.
public void conOpen()
{
conString = "Data Source=..."; //the same as you post in your post
Con = new SqlConnection(conString);//
try
{
Con.Open();//try to open the connection
}
catch (Exception ex)
{
//you do stuff if the connection can't open, returning a massagebox with the error, write the error in a log.txt file...
}
}
public void conClose()
{
Con.Close();//close the connection
}
In your other(s) classe(s) where you need a sql query you first instantiate an new object.
private void getListBtn_Click(object sender, RoutedEventArg e)
{
Sqlconnect con = new Sqlconnect();//instantiate a new object 'Con' from the class Sqlconnect.cs
con.conOpen();//method to open the connection.
//you should test if the connection is open or not
if(con!= null && con.State == ConnectionState.Open)//youtest if the object exist and if his state is open
{
//make your query
SqlDataAdapter sda = new SqlDataAdapter("your query", con);
//etc
con.conClose();//close your connection
}
else
{
//the connection failed so do some stuff, messagebox...as you want
return;//close the event
}
}
this example need some ameliorations, it's evident but I wrote it like this to be clearest.
First thing this is not related to WPF, this is general coding even I would not consider this to be related to .net.
For your current problem to show the count, you dont have to make a call again. You can get the count from the datatable row count. But, I would suggest few things:
You should have one or different separate layers like business, data access etc. as per your needs.
You should not give the connection as the way you have provided here.
You can choose to use any ORMs like entity framework, NHibernate etc based on your needs. This just a direction, you can choose to stick with ADO.Net as you have it your choice. But I would definitely suggest to throw in more layers to avoid duplicate codes and more structured approach.
Best choice if you don't need so much performance is ORM like Entity Framework.
Here is something of basics.
Just use it like in MVC app.
If we copy paste your code, then the error is appearing. I have corrected it and maybe others don't need to struggle like me to find this. :)
// Object exists and State is open
if (Conex != null && Conex.Con.State ==
System.Data.ConnectionState.Open)
{
// Create a String to hold the query
string query = "insert into Xray_Table values
(25,'zzz','hij',3,'uuu',6,'2012-06-18
10:34:09.000')";
// Create a SqlCommand object and pass the constructor the connection string and the query string
SqlCommand queryCommand = new SqlCommand(query, Conex.Con);
// Execute the query to update to the database
queryCommand.ExecuteNonQuery();
// method to close the connection.
Conex.conClose();
}

How do I make this web service work?

I am a new developer and trying to develop a web service in C# by following this tutorial. I did everything as explained in that tutorial, however, I did not get any data from the Northwind database and I got the following page when I pressed the Invoke button:
As you will see in the tutorial, I did not add the ConnectionString to the web.config file. Should I do that?
My code:
public class WSGetCustomerCountryWise : System.Web.Services.WebService
{
public WSGetCustomerCountryWise()
{
//Uncomment the following line if using designed components
//InitializeComponent();
}
[WebMethod(Description = "It will generate Customer List, CountryWise")]
public System.Xml.XmlElement
GetCustomerCountryWise(string sCountry)
{
string sConn = ConfigurationManager.ConnectionStrings["connStr"].ToString();
string sSQL = "select CustomerId, CompanyName, ContactTitle, City from Customers where country = '"+sCountry+"'";
SqlConnection connCustomer = new SqlConnection(sConn);
DataSet dsCustomer = new DataSet();
SqlDataAdapter sda = new SqlDataAdapter(sSQL, sConn);
sda.Fill(dsCustomer);
System.Xml.XmlDataDocument xdd = new System.Xml.XmlDataDocument(dsCustomer);
System.Xml.XmlElement docElem = xdd.DocumentElement;
return docElem;
}
}
You are trying to load the connection string with ConfigurationManager.ConnectionStrings["connStr"].ToString(), but you didn't add it to the configuration (=web.config), so yes you should do that.
For starters; yes, you need to add the connectionstring to your web.config. Otherwise it will throw an exception. You cannot ToString() an null object.
To find out where your code breaks: what happens if you put a breakpoint at the line starting with string sConn? You should be able to find the bug with 'debugging'...

access list in sharepoint 2007 using c#

I'm looking to compile data from a few diffrent custome lists in sharepoint 2007
Its a hosted sharepoint site so I don't have access to the machine backend.
Is there any example code to access the sharepoint site using c#?
here is my code thus far (i get the error Cannot connect to the Sharepoint site ''. Try again later.)
DataSet dt = new DataSet();
string query = "SELECT * FROM list";
string site = "http://sp.markonsolutions.com/Lists/Security/";
string list = "35E70EO4-6072-4T55-B741-4B75D5F3E397"; //security db
string myConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;WSS;IMEX=2;RetrieveIds=Yes; DATABASE="+site+";LIST={"+list+"};";
OleDbConnection myConnection = new OleDbConnection();
myConnection.ConnectionString = myConnectionString;
OleDbCommand myAccessCommand = new OleDbCommand(query,myConnection);
OleDbDataAdapter myDataAdapter = new OleDbDataAdapter(myAccessCommand);
myConnection.Open();
myDataAdapter.Fill(dt);
//execute queries, etc
myConnection.Close();
If you can't deploy code on the SharePoint machine, then you pretty much have to use the web services.
The lists web service is what you're after.
It will be located on http://yousharepointsite.com/_vti_bin/Lists.asmx and should be open by default. Note that if your site is configured with FBA, you will have to use the _vti_bin/Authentication.asmx to log in before you query lists.asmx.
Here is an article that gives all the information you need :
http://sharepointmagazine.net/articles/writing-caml-queries-for-retrieving-list-items-from-a-sharepoint-list
For the reasons mentioned above, skip the part on using the object model to query SharePoint lists and go directly to Retrieving list items with CAML using the SharePoint web services.
The article is pretty complete, so I think you should be OK with that.
As per your edit, I don't think that you can create a connection to your remote site like that. You can't query SharePoint with SQL like that, you really need to use CAML...
Once you've added the reference to the web service :
ListService listsClient = new ListService.Lists();
listsClient.Url = #"http://sp.markonsolutions.com/" + #"/_vti_bin/lists.asmx";
listsClient.Credentials = System.Net.CredentialCache.DefaultCredentials;
listsClient.GetListItems(...);
Read more on the GetListItems here
Like I said, you need to use the web services. You are heading towards a dead end if you are trying to create connection like that to query the database directly. It is not recommended.
Not sure if what you try to do is possible unless you use an ado.net connector for SharePoint, have a look at http://www.bendsoft.com/net-sharepoint-connector/
It enables you to talk to SharePoint lists as if they where ordinary sql-tables
In example to insert some data
public void SharePointConnectionExample1()
{
using (SharePointConnection connection = new SharePointConnection(#"
Server=mysharepointserver.com;
Database=mysite/subsite
User=spuser;
Password=******;
Authentication=Ntlm;
TimeOut=10;
StrictMode=True;
RecursiveMode=RecursiveAll;
DefaultLimit=1000;
CacheTimeout=5"))
{
connection.Open();
using (SharePointCommand command = new SharePointCommand("UPDATE `mytable` SET `mycolumn` = 'hello world'", connection))
{
command.ExecuteNonQuery();
}
}
}
Or to select list data to a DataTable
string query = "SELECT * FROM list";
conn = new SharePointConnection(connectionString);
SharePointDataAdapter adapter = new SharePointDataAdapter(query, conn);
DataTable dt = new DataTable();
adapter.Fill(dt);
Or using a helper method to fill a DataGrid
string query = "Select * from mylist.viewname";
DataGrid dataGrid = new DataGrid();
dataGrid.DataSource = Camelot.SharePointConnector.Data.Helper.ExecuteDataTable(query, connectionString);
dataGrid.DataBind();
Controls.Add(dataGrid);

Categories

Resources