using a connection string in web.config for crystal report - asp.net

I`m having problems between two servers, wich use differente odbc dsn.
My apps work great but crystal reports uses the original odbc connection, how can I fix this?
I'm thinking of using the same connection string in the web.config, but I don't know how.
found this but is too confusing for me
thanks,

You can't use a connection string in the same way you can with an ado.net connection. However, you can certainly use values from the web.config to specify the connection info. Create an instance of the ConnectionInfo class and set the ServerName, DatabaseName, UserID, and Password properties. Then attach it to each of the tables in the report:
ConnectionInfo reportConnectionInfo = new ConnectionInfo();
reportConnectionInfo.ServerName = ConfigurationManager.AppSetting["ServerName"];
reportConnectionInfo.DatabaseName = ...;
reportConnectionInfo.UserID = ...;
reportConnectionInfo.Password = ...;
foreach (Table table in reportDocument.Database.Tables) {
table.LogOnInfo.ConnectionInfo = reportConnectionInfo;
}
If you try to use this suggestion, beware of my sloppy typing...

You can use the connection string.
You have to create an instance of the database provider ConnectionStringBuilder passing in the Connection String pulled from a config file. Here is an example in VB.
Dim connString As String = ConfigurationManager.ConnectionStrings["MyDbConn"].ConnectionString
Dim connStringBuilder As SqlConnectionStringBuilder = New SqlConnectionStringBuilder(connString)
Dim myConnectionInfo As ConnectionInfo = New ConnectionInfo()
myConnectionInfo.DatabaseName = connectionStringBuilder.InitialCatalog
myConnectionInfo.UserID = connectionStringBuilder.UserID
myConnectionInfo.Password = connectionStringBuilder.Password
myConnectionInfo.ServerName = connectionStringBuilder.DataSource

Related

Passing datatable to SQL Server stored procedure not working

I have an ASP.NET application that passes a Datatable to a web service, then from the web service to a SQL Server stored procedure. When I publish the web application and web service to the server and run, it fails. When I run the application from the local host pointing to the web service on the server, it works fine. When I run the both the web application and web service from localhost, it works fine.
I did some troubleshooting and see that the following line is the problem but I am not sure how to solve:
cmdCommit.Parameters.AddWithValue(#SourceTable, dtSource);
When I comment the line above, everything works. When I replace the reference to the DataTable (dtSource) in the line above with a string datatype, it works.
Here is the entire web method, I am using this code within a try/catch block:
DataTable dtSource = ObjectToData(sourceTable);
dtSource.TableName = TableTypeObject;
using (SqlConnection cnn = new SqlConnection(_cnnSqlCapss))
{
SqlCommand cmdCommitChange = new SqlCommand("usp_Stored_Procedure", cnn);
cmdCommitChange.CommandType = CommandType.StoredProcedure;
cmdCommitChange.Parameters.AddWithValue("#Parm1", Value1);
cmdCommitChange.Parameters.AddWithValue("#Parm2", Value2);
cmdCommitChange.Parameters.AddWithValue("#Parm3", dtSource);
var returnParameter = cmdCommitChange .Parameters.Add("#ReturnVal", SqlDbType.Int);
returnParameter.Direction = ParameterDirection.ReturnValue;
cnn.Open();
cmdCommitChange .ExecuteNonQuery();
var result = returnParameter.Value;
return (int)result;
}
The confusing part is that when I run the web application from the localhost and reference the web service on the server, it works. I don't understand why it fails when I run the web application from the server.
When I comment the line that reference the DataTable everything works.
I have tried the following and still no success:
SqlParameter tvpParam cmdCommit.Parameters.AddWithValue "#SourceTable", dtSource);
tvpParam.SqlDbType = SqlDbType.Structured;
tvpParam.TypeName = "dbo.SourceTableType";
Also, The web method is not throwing an exception.
Assumed you're already doing these:
Defining table type in User-Defined Table Types in your database (often known as TVP, see reference section below);
Adding parameter to pass DataTable to stored procedure (e.g. #SourceTable).
Then, you can use SqlDbType.Structured to pass DataTable contents as stored procedure parameter like this:
cmdCommitChange.Parameters.Add("#SourceTable", SqlDbType.Structured).Value = dtSource;
Alternative with AddWithValue:
cmdCommitChange.Parameters.AddWithValue("#SourceTable", dtSource).SqlDbType = SqlDbType.Structured;
Example usage in SqlConnection block:
using (SqlConnection cnn = new SqlConnection(_cnnSqlCapss))
{
SqlCommand cmdCommitChange = new SqlCommand("usp_Stored_Procedure", cnn);
cmdCommitChange.CommandType = CommandType.StoredProcedure;
cmdCommitChange.Parameters.AddWithValue("#Parm1", Value1);
cmdCommitChange.Parameters.AddWithValue("#Parm2", Value2);
cmdCommitChange.Parameters.AddWithValue("#Parm3", Value3);
// add this line
cmdCommitChange.Parameters.Add("#SourceTable", SqlDbType.Structured).Value = dtSource;
cmdCommitChange.Parameters.Add("#ReturnVal", SqlDbType.Int).Direction = ParameterDirection.ReturnValue;
cnn.Open();
cmdCommitChange.ExecuteNonQuery();
var result = (int)returnParameter.Value;
return result;
}
Reference:
Table-Valued Parameters (MS Docs)
I found the problem. I am passing a text value that is too large for a column on my datatable.
The web service was indeed throwing an exception but there was some code in my application's routine which was preventing me from seeing it.

How to set database with AdomdConnection

When I execute this code:
AdomdConnection con = new AdomdConnection("Data Source=MyServer;User ID=MyDomain\\MyUserName;Password=MyPassword");
con.Open();
con.ChangeDatabase("Analysis Services Project1");
I get this exception:
Either the user, MyDomain\MyUserName$, does not have access to the
Analysis Services Project1 database, or the database does not exist.
The database name comes from looking at the server using Microsoft SQL Server Management Studio. If I bring up the properties on the server and go to the security section, my account is listed as a Server administrator. While in management studio, I can see data sources, cubes and execute mdx queries fine.
Why can't do I get this exception in code?
whihc line causes the error?
I imagine you have to infor the catalog on your connection string. Try addind
Catalog=Analysis Services Project1
to your con string.
Also, Analysis Services Project1 seems to be the projects name? Are you sure this is the database name as well?
First
added the reference for Microsoft.AnalysisServices.AdomdClient.dll
strCon = "Data Source=DBserverServerName;Integrated Security=SSPI;Initial Catalog=DBName;";
AdomdConnection con = new AdomdConnection("connectionstring"); // connect DB con.Open(); AdomdCommand cmd = new AdomdCommand("MDX query", con); //query
AdomdDataReader reader = cmd.ExecuteReader(); //Execute query
while (reader.Read()) // read
{
Data dt = new Data(); // custom class
dt.Gender = reader[0].ToString();
dt.Eid = reader[1].ToString();
dt.salary = reader[2].ToString();
data.Add(dt);
}

Invalid cast exception on remote server Guid to string

I have this code in my project:
string userId = Membership.GetUser(username).ProviderUserKey.ToString();
SqlConnection conn = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand("UPDATE aspnet_Membership SET IsLockedOut = 0, LastLockoutDate = #LastLockedOutDate WHERE UserId = #Userid", conn);
cmd.Parameters.Add("#LastLockedOutDate", SqlDbType.DateTime).Value = DateTime.Now;
cmd.Parameters.Add("#Userid", SqlDbType.VarChar, 255).Value = userId;
int rowsAffected = 0;
conn.Open();
rowsAffected = cmd.ExecuteNonQuery();
This works fantastic on my local machine. The user gets unlocked no problem. But for some reason when I deploy it to a demo site on the remote server I get this error:
InvalidCastException: Failed to convert parameter value from a Guid to a String
It's failing on the cmd.ExecuteNonQuery line. I tried changing the parameter to a uniqueidentifier and passing the actual guid but that didn't work either.
Anybody know why this would work locally but not on a remote server? Or know of a way I can modify the code to possibly work?
Rather than trying to manually unlock the user could you not use :-
var oUser = Membership.GetUser(username);
oUser.UnlockUser();
Membership.UpdateUser(oUser);
This allows the .NET process to do all the heavy lifting for you.
[Edit to answer the original question]
Guid gUserID = (Guid)Membership.GetUser(username).ProviderUserKey;
if (gUserID != Guid.Empty)
{
using (
var oConn =
new SqlConnection(connectionString)
{
oConn.Open();
using (SqlCommand oCmd = oConn.CreateCommand())
{
oCmd.CommandType = CommandType.Text;
oCmd.CommandText = "UPDATE aspnet_Membership SET IsLockedOut = 0, LastLockoutDate = #LastLockedOutDate WHERE UserId = #gUserID";
oCmd.Parameters.Add(new SqlParameter("#gUserID", gUserID));
oCmd.Parameters.Add(new SqlParameter("#LastLockedOutDate", DateTime.UtcNow));
oCmd.ExecuteNonQuery();
}
}
}
It may also be worth changing your DateTime.Now to DateTime.UtcNow so that if you ever have to move timezones or share with other machines out of your location you are all on a equivilent time.
If you get an error thrown on the ProviderUserKey then chances are either the user doesn't exist or the UserID isn't a GUID after all.
Maybe you can try something like
cmd.Parameters.Add("#Userid", SqlDbType.Guid).Value = new Guid(userId);
Sorry for the lame answering my own question but I resolved this. I stripped the custom membership provider out and just used the default membershipUser.UnlockUser(); and it works great. The custom provider wasn't actually doing anything anyway. I think it was developed for features that aren't being used anymore.

how do i connect to oracle with the info i have?

i have the info below from the oracle DBA and want to connect to oracle from a .net application. i just got done installing the oracle tools/ drivers for windows/ .net and now want to get a console app to connect tot he oracle DB and extract data from oracle into SQL server.
another solution would be to have SQL server pull from oracle all the records in the bugs table. i have no clue what the oracle connection string is and have tried to create a system DSN but failed at that prior to turning to the SO gurus...
ORACLE SQL user name is ‘USER_dev’,
password is ‘welcome’.
Connection string is
‘jdbc:mercury:oracle://qct-ds2-p.apps.com:1139;sid=QCTRP1’
i got lucky and found a simple solution that is all in .net and requires nothing more than this syntax by way of a connection string. all the .ora stuff is presented in the connection string and works well.
static void getData()
{
string connectionString = GetConnectionString();
using (OracleConnection connection = new OracleConnection())
{
connection.ConnectionString = connectionString;
connection.Open();
//Console.WriteLine("State: {0}", connection.State);
//Console.WriteLine("ConnectionString: {0}", connection.ConnectionString);
OracleCommand command = connection.CreateCommand();
string sql = "SELECT * FROM BUG";
//string sql = "SELECT table_name FROM user_tables";
command.CommandText = sql;
OracleDataReader reader = command.ExecuteReader();
while (reader.Read())
{
//string myField = (string)reader["Project"];
string myField = (string)reader[0];
Console.WriteLine(myField);
}
}
}
static private string GetConnectionString()
{
return "User Id=USER_dev;Password=welcome;Data Source=(DESCRIPTION=" +
"(ADDRESS=(PROTOCOL=TCP)(HOST=111.123.479.24)(PORT=1139))" +
"(CONNECT_DATA=(SID=QCTRP1)));";
}
go into your ORACLE_HOME\network\admin directory. Create a file called tnsnames.ora if it is not there already. Add this into it:
QCTRP1.WORLD =
(DESCRIPTION =
(ADDRESS = (PROTOCOL = TCP)(HOST = qct-ds2-p.apps.com)(PORT = 1139))
(CONNECT_DATA =
(SERVER = DEDICATED)
(SERVICE_NAME = QCTRP1)
)
)
I'm making some assumptions here...
does qct-ds2-p.apps.com resolve?
looks like the DBA set it up the listener on port 1139... default is normally 1521 so you'll need to confirm.
You can then set up a connection string as follows:
Connection conn = DriverManager.getConnection
("jdbc:oracle:oci8:#QCTRP1.WORLD", "dev", "welcome");
now that you have the tnsnames created from #erbsock, you will need to get the .net side of
things working. Oracle has several tutorials available to help you in this matter.
When you install the Oracle ODP (in the link you will see samples as well as the downloads) drivers you will get a directory created in the
%oracle_home%\odp.net\samples\4\DataSet\DSPopulate\src
(this appears to be the same example as located # http://www.oracle.com/technology/sample_code/tech/windows/odpnet/DSPopulate/ViewProducts.cs.html)
as an initial test I would recommend just changing around the id/passwrd/sql/etc and trying it out.
it is not that fundamentally different than using System.Data; but there are a few gotchas and remember that each computer will need to have ODP/Oracle client installed to have them work with the ora connection.
if you have any problems post the exact error msg that is displayed as well as a snippet of your .net code that establishes the connection, does the query, and where it is breaking

Adding a database to an ASP.NET Web Service

Okay this question could either be very broad or very specific because I am not sure if I am going about this in a fundamentally wrong way or if I am close to correct.
First an overview: What I am trying to do it create a server application for all of the clients in my organization to connect to. I think the best way to do this is to use a web service. Please correct me if I am wrong!
Anyway, if I use a web service I need the web service(server) to connect to the database. In MS Visual studio when you add a web service project the data menu disappears and you can't add a data source to the project. There may be a workaround for this by hand coding this, but I am not sure how to do it. This is my first time working with a web service and ASP.NET so I am a real noob in this area.
Any help would be greatly appreciated!!!
Add your database connection string to the <connectionStrings/> section of the web service web.config file. Check this web site for a list of the most common database connection strings: Connectionstrings.com
You would use standard ADO.Net commands and SQL statements, rather than using the dataset designer. Example (IN VB)
<WebMethod()> _
Public Function DoesOpenCallExist(ByVal CustID As String, ByVal CallType As String, ByVal SubCallType As String) As Boolean
Dim returnvalue As Boolean = False
' first, entry validation
' snip - code deleted
Dim conn As New System.Data.SqlClient.SqlConnection
conn.ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings("HEATConnectionString").ConnectionString
Dim cmd As New SqlClient.SqlCommand
cmd.Connection = conn
cmd.CommandType = CommandType.StoredProcedure
cmd.CommandText = "sp_GetCallCount"
cmd.Parameters.AddWithValue("#CustID", CustID)
' Etc...
Try
conn.Open()
returnvalue = cmd.ExecuteScalar() > 0
Catch ex As Exception
Throw New Exception(ex.ToString())
Finally
conn.Close()
End Try
Return returnvalue
End Function
*This should be done
web.config file*
here the datsource is the servername,initial catlog is the databasename and the userid ur sql userid and the password is as same.
And then in the class we want to get connect with the database......
****class.cs****
public class connect
{
public static SqlConnection con()
{
String con= ConfigurationManager.AppSettings["connections"].ToString();
SqlConnection cn = new SqlConnection(con);
cn.Open();
return cn;
}
}
here the connection is the keyname......
ok i think its sufficient............

Resources