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'...
Related
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.
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();
}
I have a desktop application, which verifies the finger and prompt the result
I am calling that app in wpf, then this all is showing in asp.net
On asp.net user put the finger, results comes to him how is that done?
On asp.net I created a static class & a web service having a two static members which gets 'query' & connection string, these both member set by asp.net i.e
button1_click() {
string query = "select * from employee where userid='123'";
string connString = "Data Source=mypc;Initial Catalog=abc;Persist Security Info=True;User ID=re;Password=12345";
StaticClass.Query = query;
StaticClass.ConnStr = connString;
}
Value setting in web service
[WebMethod]
public string Query()
{
string SelectDataQuery = StaticClass.Query;
return SelectDataQuery;
}
Desktop application subscribed the web-service which gets and give data. All is well, NOW then I hosted the application on IIS, multiple users are using the application now, on the same time, user1 set the query while user2 gets it.
I want to make it multi user, so whats the suggestion, should i create static strings dynamically as much as users create requests which uniqueness or any thing else?
You could try to create an instance object holding the query and connection and then pass it along to the query method. this way each user will have their own instance.
something like this
[WebMethod]
public string Query(StaticClass query)
{
string SelectDataQuery = query.Query;
return SelectDataQuery ;
}
Just use String.Format to place in the current user id.
button1_click() {
string query = "select * from employee where userid='{0}'";
string connString = "Data Source=mypc;Initial Catalog=abc;Persist Security Info=True;User ID=re;Password=12345";
StaticClass.Query = String.Format(query, currentUserId);
StaticClass.ConnStr = connString;
}
This is my simple Code which stores parameters value in variables and use it on query
but it's give me ERROR message "INVALID Object name "DTA010.DFDR00" because I guess i'm not connected with the AS/400
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
//string strQuery;
string order_no = Request.QueryString["order"];
if (order_no != null)
{
Response.Write("\n");
Response.Write("Order No is ");
Response.Write(order_no);
}
else
{
Response.Write("You Order number is not correct");
}
Response.Write("Your Order Status is");
Response.Write(niceMethod1());
Response.Write("\n");
}
public string niceMethod1()
{
string tDate = "";
string nOrder = (Request.QueryString["order"] ?? "0").ToString();
using (SqlConnection connection = new SqlConnection("Data Source=*****;User ID=web;Password=****;Initial Catalog=WEBSTATUS;Integrated Security=False;"))
{
string commandtext = "SELECT A.STAT01 FROM DTA010.DFDR00 AS A WHERE A.ORDE01 = #nOrder"; //#nOrder Is a parameter
SqlCommand command = new SqlCommand(commandtext, connection);
//command.Parameters.AddWithValue("#nPhone", nPhone); //Adds the ID we got before to the SQL command
command.Parameters.AddWithValue("#nOrder", nOrder);
connection.Open();
tDate = (string)command.ExecuteScalar();
} //Connection will automaticly get Closed becuase of "using";
return tDate;
}
}
The drivers needed to connect from a .NET application to a AS/400 are properly installed.
If the names of the schema (aka library) and table (aka file) are spelled correctly, try replacing the period with a slash /. This would be used for "system" naming syntax, rather than "standard" naming syntax.
You are definitely connected. I think the issue may be in the error you received. Make sure that the object exists that you are connecting to. WRKOBJ OBJ(BTGDTA010/DF01HDR00) will see if it exists. Check that everything is spelled right. It might be a typo.
Here is the simplest way I Found may be useful for someone..!!
First need to add Assembly IBM library and
using IBM.Data.DB2.iSeries;
then
iDB2Connection connDB2 = new iDB2Connection(
"DataSource=158.7.1.78;" +
"userid=*****;password=*****;DefaultCollection=MYTEST;");
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);