SSIS: Exception has been thrown by the target of an invocation - sql

I have a SSIS package to perform incremental processing of the cube. In the sequence container in this package, we have a script task to count the number of rows.
and the code in script task is as follows :
public void Main()
{
string connectionString = "Data Source=localhost;PROVIDER=MSOLAP;Impersonation Level=Impersonate;Catalog=EcovaPlatform";
connectionString = connectionString.Replace("localhost", Dts.Variables["User::CubeServer1"].Value.ToString()).Replace("EcovaPlatform", Dts.Variables["User::CubeName1"].Value.ToString());
string queryString = "evaluate row(\"count\", countrows(BillDetail))";
AdomdConnection connection = new AdomdConnection(connectionString);
connection.Open();
AdomdCommand cmd = new AdomdCommand(queryString);
cmd.Connection = connection;
using (var reader = cmd.ExecuteReader())
{
while (reader.Read())
{
Dts.Variables["CubeBillDetailRowCount1"].Value = Convert.ToInt64(reader[0]);
}
}
Dts.TaskResult = (int)ScriptResults.Success;
But every once in a while, this script task(here I am assuming its the script task) fails. It throws out the following error:
Source Name: Cube Table RowCount
Error Code: 1
Error Description: Exception has been thrown by the target of an invocation.
Now I dont know how to fix this issue. So I am turning to you good folks, to guide me in the right direction.
If somebody wants to look at the XMLA script, I can post that as well.
Thanks.

Related

LogIn form, SQL exception

I'm trying to make a simple program that has a log-in part, with a local database just for testing.And i keep getting an error when I try to open the connection to the SQL database.
private void logInButton_Click(object sender, EventArgs e)
{
MainMenu openMainMenu = new MainMenu();
SqlConnection sqlcon = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C: \Users\Nea Florin\Desktop\PlatformaTestare\PlatformaTestare\Server.mdf;Integrated Security=True;Connect Timeout=30");
sqlcon.Open();
SqlCommand cmd = new SqlCommand("Select * from Table Where username ='" + usernameTextBox.Text + "' and password = '" + passwrodTextBox.Text + "'");
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dtbl = new DataTable();
sda.Fill(dtbl);
if (dtbl.Rows.Count > 0)
{
openMainMenu.Show();
this.Hide();
}
else
MessageBox.Show("Wrong username or password!");
}
I get the error at sqlcon.Open();, and it is: "An unhandled exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll
Additional information: An attempt to attach an auto-named database for file C: \Users\Nea Florin\Desktop\PlatformaTestare\PlatformaTestare\Server.mdf failed. A database with the same name exists, or specified file cannot be opened, or it is located on UNC share."
Well, the best advice I can give you is to google the error message. Keep in mind that if there is an error message it means that the problem is well known an as such it's a safe bet that someone have encountered it before you and managed to solve it. The first 4 results of this search are on stackoverflow and at least two of them have accepted answers, so I believe a little reasearch would have saved you a long time.
This is the best advice because it streaches far beyond your current problem. I firmly believe that good searching skills is the most important and most powerfull tools of a sotfware developer. I can assure you, no matter how much time you are developing software, almost every exception you get, someone else have already solved and posted the solution somewhere, you only need to find it.
Now, as for the code it self - You have some major problems other then the exception you are asking about:
Concatenating strings into sql statements instead of using parameters expose your code to SQL injection attacks. This is a very serious threat that is extremely easy to fix.
Using insntances of classes that implements the IDisposable interface without properly disposing them may lead to memory leak. Read about the using statement and make it a habit to use it every time it's possible.
Exception handling. Currently, if your database can't be reached, you get an exception and your program crash. You should use a try...catch block anywhere you can't control in code to let your program end gracefuly instead. (Don't ever use try...catch for things you can do in code such as validate user input or checking division by zero - only for things that are beyon your control such as database availability.)
Having said all that, your code should look something like this:
private void logInButton_Click(object sender, EventArgs e)
{
using (var sqlcon = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|C:\Users\Nea Florin\Desktop\PlatformaTestare\PlatformaTestare\Server.mdf;Integrated Security=True;Connect Timeout=30"))
{
sqlcon.Open();
using (var cmd = new SqlCommand("Select 1 from Table Where username = #userName and password = #password"))
{
cmd.Parameters.Add("#userName", SqlDbType.NVarChar).Value = usernameTextBox.Text;
cmd.Parameters.Add("#password", SqlDbType.NVarChar).Value = passwrodTextBox.Text;
using (var dtbl = new DataTable())
{
using (var sda = new SqlDataAdapter(cmd))
{
sda.Fill(dtbl);
}
if (dtbl.Rows.Count > 0)
{
var openMainMenu = new MainMenu();
openMainMenu.Show();
this.Hide();
}
}
else
{
MessageBox.Show("Wrong username or password!");
}
}
}

C# Elastic search connection pool implementation facing issue

Error: "Invalid NEST response built from a unsuccesful low level call on HEAD:Audit exception in step 2 PingFailure:\r\nElasticsearch.Net.PipelineException: An error occurred trying to establish a connection with the specified node.\r\n "
private static ElasticClient GetESClient(Uri[] nodes, string username, string password)
{
var connectionPool = new SniffingConnectionPool(nodes);
var setting = new ConnectionSettings(connectionPool)
.SniffOnConnectionFault(false)
.SniffOnStartup(false)
.SniffLifeSpan(TimeSpan.FromMinutes(1)).DisableDirectStreaming()
.BasicAuthentication(username, password)
.MaximumRetries(5);
setting.DefaultIndex(ConfigurationManager.AppSettings["ElasticSearch_val"].ToString());
var esClient = new ElasticClient(setting);
return esClient;
}

Cannot access existing table from WCF Code

try
{
string strSQLConnString = GetConnectionString();
using (SqlConnection myConnection = new SqlConnection(strSQLConnString))
{
SqlCommand myCommand = new SqlCommand("spFortesting", myConnection);
myCommand.CommandType = CommandType.StoredProcedure;
myCommand.Parameters.AddWithValue("#Param1", varParam1);
myCommand.Parameters.AddWithValue("#Param2", varParam2);
myCommand.Parameters.AddWithValue("#Param3", varParam3);
myCommand.Parameters.AddWithValue("#Param4", varParam4);
myConnection.Open();
using (SqlDataReader myReader = myCommand.ExecuteReader())
{
dt = new DataTable();
if (myReader.HasRows)
{
dt.Load(myReader);
}
myReader.Close();
}
myConnection.Close();
}
}
catch (Exception ex)
{
throw ex;
}
I am getting exception like
"The exception message is 'Could not find stored procedure 'spFortesting'."
All other existing Stored Procs are accessed correctly.
Connection string is common for all other SQL calls in the application.
'spFortesting' is newly created StoredProc.
owner is 'dbo' I tried with dbo.spname as well
While I can access the Stored Proc and Tables which are newly created using SQL Mgmt Studio and the same credentials as in web.config, but not thru the code.
What could have been wrong.
Thanks in Advance,
Amit
My mistake! when i watched it very closely I found that connection strings are not matching, the connectionstring was being picked up from the other similar sounding virtual directory. System.Configuration.Configuration rootWebConfig =
System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration(#"\AppName");
and my appname on the deployed server was AppNameNew for some unkown reasons, since ages. With the name AppName there was another virtual folder and its web.config was pointing towards different database.
Sorry for the inconvenience caused if any.
Cheers!!!
and a Happy new year

how does one programmatically create a localdb .mdf?

how does one programmatically create a localdb .mdf?
acceptable solutions exclude visual studio, ssms, aspnet_regsql.
a naive stab at a solution might look like this:
static void Main(string[] args)
{
using (var con = new SqlConnection(#"Integrated Security=SSPI;Data Source=(LocalDb)\v11.0;AttachDbFilename=test.mdf"))
{
con.Open();
using (var cmd = new SqlCommand("CREATE DATABASE test", con))
{
cmd.CommandType = CommandType.Text;
cmd.ExecuteNonQuery();
}
}
}
but of course, this fails in SqlConnection.Open with the error
An attempt to attach an auto-named database for file test.mdf failed. A database with the same name exists, or specified file cannot be opened, or it is located on UNC share.
You cannot connect to a database if the specified .mdf doesn't exist.
So... how do you create one?
Had to piece together several answers from Stackoverflow and the great Getting Started with SQL Server 2012 Express LocalDB article from #AaronBertrand
Code assumes Dapper.NET is installed:
PM> Install-Package Dapper
Programmatic creation:
var dbServerName = "SERVER_NAME";
var dbName = "DATABASE_NAME";
var infoResult = SqlLocalDbCommand($"info {dbServerName}");
var needsCreated = infoResult?.Trim().EndsWith($"\"{dbServerName}\" doesn't exist!");
if (needsCreated.GetValueOrDefault(false))
{
var createResult = SqlLocalDbCommand($"create {dbServerName} -s");
var success = createResult?.Trim().EndsWith($"\"{dbServerName}\" started.");
if (false == success)
{
var msg = $"Failed to create database:{Environment.NewLine}{createResult}"
throw new ApplicationException(msg);
}
var master = $#"Server=(localdb)\{dbServerName};Integrated Security=True;"
using (var conn = new SqlConnection(master))
{
var result = conn.Execute($"CREATE DATABASE {dbName}");
}
var #new = $#"Server=(localdb)\{dbServerName};Integrated Security=True;Database={dbName}"
using (var conn = new SqlConnection(#new))
{
//verify i can access my new database
var tables = conn.Query($"SELECT * FROM {dbName}.INFORMATION_SCHEMA.Tables");
}
}
Helper (thanks T30):
/// <summary>
/// Executes a command against SqlLocalDB
/// </summary>
/// <remarks></remarks>
/// <param name="arguments">The arguments to pass to SqlLocalDB.exe</param>
/// <returns></returns>
/// <exception cref="System.ApplicationException">Error returned from process</exception>
private static string SqlLocalDbCommand(string arguments)
{
var process = new Process
{
StartInfo =
{
FileName = "SqlLocalDB",
Arguments = arguments,
UseShellExecute = false,
RedirectStandardOutput = true,
RedirectStandardError = true
}
};
process.Start();
//* Read the output (or the error)
var output = process.StandardOutput.ReadToEnd();
Console.WriteLine(output);
var err = process.StandardError.ReadToEnd();
Console.WriteLine(err);
process.WaitForExit();
if (err.Exists()) throw new ApplicationException(err); //Is LocalDB installed?
return output;
}
Note that with this solution you won't see the mdf files, i'm sure they exist in some user folder but the key take away is that you'll connect by the connection string
(localdb)\SERVER_NAME;Integrated Security=True;Database=DATABASE_NAME
So I take it what you actually want to do is create a database called test in your LocalDB instance, but you don't have an MDF file already created for this database?
If that's the case, the code you have will fail at the connection phase since you've asked it to attach your test.mdf file.
What you would normally do in this situation is make a connection to the master database initially, and then run the create database statement which will create the test database with it's associated MDF file, maybe try changing your connection string so it looks more like this and then running again:
Integrated Security=SSPI;Data Source=(localdb)\V11.0;Initial Catalog=master

storing pdf files using filestream on file system

I am first time trying to use filestream to store pdf files on file system using varbinary(MAX) column type of DB.
I have followed following steps.
enabled filestream feature on SQL server 2008 R2.
Create a filegroup for BLOB storage
created table with blob column of type varbinary(max)
Now, I want to use file upload control to select file and when click on upload button it should save the pdf file. Also, how to retrieve the file?
I have tried following code
protected void btnFSupload_Click(object sender, EventArgs e)
{
SqlConnection cn = null;
SqlTransaction tx = null;
SqlCommand cmd = null;
SqlCommand cmd2 = null;
bool bCommit = false;
try
{
// read in the file to be saved as a blob in the database
FileStream input = new FileStream(#"D:\swami.pdf", FileMode.Open, FileAccess.Read);
byte[] buffer = new byte[(int)input.Length];
input.Read(buffer, 0, buffer.Length);
cn = new SqlConnection("server=at-hetal01\\sqlexpress;Initial Catalog=practice;Integrated Security=true;");
cn.Open();
tx = cn.BeginTransaction();
cmd = new SqlCommand("dbo.stp_AddBLOB", cn, tx);
cmd.CommandType = System.Data.CommandType.StoredProcedure;
SqlDataReader r = cmd.ExecuteReader(System.Data.CommandBehavior.SingleRow);
r.Read();
string id = r[0].ToString();
string path = r[1].ToString();
r.Close();
// get the transaction context
cmd2 = new SqlCommand("SELECT GET_FILESTREAM_TRANSACTION_CONTEXT()", cn, tx);
Object obj = cmd2.ExecuteScalar();
byte[] txCtx = (byte[])obj;
// open the filestream to the blob
SafeFileHandle handle = OpenSqlFilestream(path,DESIRED_ACCESS_WRITE,SQL_FILESTREAM_OPEN_NO_FLAGS,txCtx,(UInt32)txCtx.Length,0);
// open a Filestream to write the blob
FileStream output = new FileStream(handle,FileAccess.Write,buffer.Length,false);
output.Write(buffer,0,buffer.Length);
output.Close();
if (handle != null && !handle.IsClosed)
handle.Close();
bCommit = true;
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
finally
{
if (cn != null)
{
switch (bCommit)
{
case true:
tx.Commit();
break;
case false:
tx.Rollback();
break;
}
cn.Close();
}
}
}
Above code shows error as below
The operating system returned the error '0xc000003a({Path Not Found} The path %hs does not exist.)' while attempting 'NtCreateFile' on 'D:\DB\FS\d11132f8-c2a8-452d-ae0c-208164a550d7\beb8e1f1-8116-440b-870b-7cef4281a15d\0000001c-000000e4-010d'. The statement has been terminated.
So, any clue on this?
If you have altered your table using SSMS table designer, the FILESTEAM column attribute will be lost producing the path not found. Make sure the FILESTREAM attribute is set for the file field by running the follwoing statement in your database:
select SERVERPROPERTY('FilestreamShareName') as ShareName,
SERVERPROPERTY('FilestreamConfiguredLevel') as ConfiguredLevel,
SERVERPROPERTY('FilestreamEffectiveLevel') as EffectiveLevel
You'll need to alter the table via a script and NOT SSMS to tie your varchar(max)/filestream field to the FileGroup you should have already created.
When I ran into this issue, I found the answer on StackOverflow, but can't seem to find it again for the reference.
I know this is old, but for future reference:
We checked the SERVERPROPERTY values that #BMP suggested. They were configured correctly, so that didn't help.
However, we went ahead and turned OFF the windows file share part of the file streaming access. Once this was done, the error went away.
In our case it was a web app running on the exact same machine as the sql server which exhibited the problem. I'm not sure if the web app's app pool user didn't have access to the file share created by windows or not.
The details were:
Windows 2003 Server (x86)
IIS 6
SQL Server 2008 R2 Express
UPDATE: Apparently this worked for a few days. It's not working any more.