Database logon failed while using mysql azure - mysql

I am trying to print crystal report in PDF format , and on my local machine it’s working fine. But when I publish application to the server, it’s giving me the following error on Print button.
Exception Details: System.Runtime.InteropServices.COMException: Database logon failed.
Below is my code in my controller
public ActionResult Export(int Id)
{
ReportDocument rd = new ReportDocument();
rd.Load(Path.Combine(Server.MapPath("~/Reports/GcReport.rpt")));
var query = rLAService.GetGeneralConsignmentById(Id);
var querylist = new List<GeneralConsignmentDto> { query };
rd.SetDataSource(querylist);
rd.SetParameterValue("Id", Id);
//rd.SetDataSource(rLAService.GetGeneralConsignmentById(Id));
Response.Buffer = false;
Response.ClearContent();
Response.ClearHeaders();
Stream stream = rd.ExportToStream(CrystalDecisions.Shared.ExportFormatType.PortableDocFormat);
stream.Seek(0, SeekOrigin.Begin);
return File(stream, "application/pdf", "GC Report.pdf");
}
Edit
Ok, after digging throuh the problem, i found that error is table name generalconsignment1 does not found. But problem is it is taking automatically instead of generalconsignment.now how to handle this situation?

Related

Getting "Access denied for user..." every 2nd hit

I'm trying to use dapper with mysql in .net core 1.0. I'm using this mysql connector: https://github.com/bgrainger/MySqlConnector
I know the connector is in alpha but I was wondering if anyone had a similar issue when using it together with dapper.
This is my simple model:
public List<GeneralModel> GetAllLists()
{
try
{
using (DbConnection connection = new MySqlConnection("Server=localhost;Database=lists;Uid=Unnamed;Pwd=lol;"))
{
return connection.Query<GeneralModel>("SELECT * FROM lists.general").ToList();
}
}
catch (Exception)
{
throw;
}
}
And this is the controller:
public IActionResult Index()
{
GeneralModel GenRepo = new GeneralModel();
return View(GenRepo.GetAllLists());
}
When I go to the index page for the first time, it works. If I refresh, I get an "Access denied for user...". I have no idea what could be causing the error. I don't think the problem is in my code.
Edit:
I guess the problem is in the connector, since this also returns the error after a refresh:
List<GeneralModel> lists = new List<GeneralModel>();
using (DbConnection connection = new MySqlConnection("Server=localhost;Database=lists;Uid=Unnamed;Pwd=lol;"))
{
using (DbCommand myCommand = connection.CreateCommand())
{
myCommand.CommandText = "SELECT * FROM lists.general";
connection.Open();
using (DbDataReader myReader = myCommand.ExecuteReader())
{
while (myReader.Read())
{
GeneralModel tmpGen = new GeneralModel();
tmpGen.name = myReader["name"].ToString();
tmpGen.description = myReader["description"].ToString();
tmpGen.language = myReader["language "].ToString();
lists.Add(tmpGen);
}
}
connection.Close();
}
}
return lists;
This bug was caused by MySqlConnector not correctly handling the fast path for a COM_CHANGE_USER packet.
MySQL Server (versions 5.6 and 5.7) doesn't appear to immediately accept the user's credentials, but always returns an Authentication Method Switch Request Packet. MariaDB (which you are using) does implement the fast path and immediately returns an OK packet.
The connector has now been updated to handle this response and should stop throwing the spurious "Access Denied" exceptions. The fix is in 0.1.0-alpha09.

Duplicate type name within an assembly

I am working with Effort and Entity Framework 4.1(code first). When I create fake databadse and try to add something
DbConnection connection = Effort.DbConnectionFactory.CreateTransient();
using (var context = new LoveDatabaseContext(connection))
{
context.Banners.Add(new Banners() { Enabled = true, Name = "Test", Priority = 1, Url = "http:\\test.com" });
}
I am getting error:
System.ArgumentException: Duplicate type name within an assembly.
I clean solution rebuilt and it not worked for me
I have found this happens when debugging, put your breakpoint after the call to the database.

Connectng to remote database in Adobe AIR

I am developing an AIR mobile application. I am using Sqlite as my local database. Now I have to maintain some datas in a centralised database which has located in remote server ie., i have to push some data to remote database from my mobile application as well as retreieve.
My questions are
Can I use sqlite as centralised database?
How can I connect to the database located in server.
Thanks in Advance.
I'll try to sum up the answer for this question. SQLite is not designed to be a service and therefore can not be used as a remote database, unless you only need to read from it.
If you only need it for reading data you can download it from the server, save as a file and then use it as a local database. This method is better explained here: Link
But if you want to use it for writing as well as reading you'll have a lot of problems with concurrency and data usage, so using a SQLite database is not an option here. Better explained here: Link
The correct way of doing this is having a backend (server script or server program), which listens to your requests and acts according to them.
For example if you want to authenticate user you can send something like this to the server:
username: "Gio"
password: "123"
action: "login"
In Actionscript 3 call would look like this:
import flash.net.URLVariables;
import flash.net.URLRequest;
import flash.net.URLLoader;
import flash.events.IOErrorEvent;
import flash.events.Event;
import flash.net.URLRequestMethod;
// create a URLLoader to POST data to the server
var loader:URLLoader = new URLLoader();
// server address where your script is listening
var request:URLRequest = new URLRequest("http://example.com");
// create and set the variables passed to the server script
var params:URLVariables = new URLVariables();
params.username = "Gio";
params.password = "123";
params.action = "login";
request.data = params;
// set the request type to POST as it's more secure and can hold more data
request.method = URLRequestMethod.POST;
loader.addEventListener(Event.COMPLETE, onPostComplete);
loader.addEventListener(IOErrorEvent.IO_ERROR, onPostFailed);
loader.load(request);
function onPostFailed(e:Event):void
{
// happens if the server is unreachable
trace("I/O Error when sending a POST request");
}
function onPostComplete(e:Event):void
{
// loader.data will hold the response received from the server
trace(e.target.data);
}
On the server side I'd recommend using PHP as it's easier to learn, simple and works great with MySQL.
In PHP you'd have something like this to handle the request:
<?php
$host="localhost"; // Host name
$username=""; // Mysql username
$password=""; // Mysql password
$db_name="test"; // Database name
$tbl_name="members"; // Table name
// Connect to server and select databse.
mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");
// username and password sent from form
if($_POST['action'] == "login")
{
$receivedUsername=$_POST['username'];
$receivedPassword=$_POST['password'];
$sql="SELECT * FROM $tbl_name WHERE username='$receivedUsername' and password='$receivedPassword'";
$result=mysql_query($sql);
// Mysql_num_row is counting table row
$count=mysql_num_rows($result);
// If result matched $receivedUsername and $receivedPassword, table row must be 1 row
if($count==1){
echo "Authentication success";
}
else {
echo "Wrong Username or Password";
}
}
?>
This will seem a little complicated at first, but it's not of a big deal actually. You'll have to read more on PHP and how to setup it as I can't fit all the details in this post.
I using AMFPHP in serverside.
In Flash You call service on server:
_net_connection = new NetConnection();
_net_connection.addEventListener(NetStatusEvent.NET_STATUS, connectionStatusHandler);
_net_connection.connect(_server_url);
_responder = new Responder(loginResult, null);
_net_connection.call("userSerivce2/login", _responder, _user_login, _user_passwword);
private function loginResult(result_object:Object):void {
save_log('loginResult (' + result_object.status + ")");
//rest of code
}
responder - is function in AS3 you will execute after call
userSerivce2/login - class userSerivce2, method login
you add responder (_responder) and additional arguments like _user_login, _user_passwword, in this case.
server PHP:
public function login($user_name, $user_password) {
//SELECT blablabla
try {
if ($logged) {
$this->call_result['status'] = 0;
throw new mysqli_sql_exception("Pomyślnie zalogowano.");
} else {
$this->call_result['status'] = 3;
throw new mysqli_sql_exception("Błąd logowania. Wprowadź poprawny login, oraz hasło.");
}
} catch(Exception $e) {
$this->call_result['error_message'] = $e->getMessage();
return $this->call_result;
}
return $this->call_result; //method will return object
}

Stored procedure with referenced linkedserver

I am fighting with stored procedure with referenced linkedserver. Linked server is accesible over internet via port forwarding - so no VPN, LAN.
Servers are on both sides MS SQL SERVER 2008 EE v. 10.0.5512
Configurations Linked server, DTC:
cannot insert images yet:(
enable promotion of distributed transaction = false
RPC = false
RPC out = false
Network DTC Access checked
Allow inbound true
Allow outbound true
No authentication Required
Stored procedure looks like
CREATE PROCEDURE [dbo].[spSynchronizeArticles]
-- Add the parameters for the stored procedure here
(
#pDebug bit,
#siteId bigint
)
AS
BEGIN
SELECT *
FROM [LinkedServer].[MyDatabase].dbo.Storages
WHERE Storage.siteId = #siteId
RETURN 0
END
As you can see no transaction here. If I am correct the MS DTC is creating transaction every time when the linked server is called.
I am calling this procedure from c# like this
SqlCommand sqlCmd = new SqlCommand("spSynchronizeArticles");
sqlCmd.CommandType = CommandType.StoredProcedure;
sqlCmd.Parameters.AddWithValue("#pDebug", false);
sqlCmd.Parameters.AddWithValue("#siteId", siteId);
SqlParameter returnValue = new SqlParameter("returnVal", SqlDbType.Int);
returnValue.Direction = ParameterDirection.ReturnValue;
sqlCmd.Parameters.Add(returnValue);
using (SqlConnection conn = new SqlConnection(Context.LocalData.ConnectionString))
{
try
{
try
{
conn.Open();
sqlCmd.Connection = conn;
sqlCmd.ExecuteScalar();
return Convert.ToInt32(returnValue.Value);
}
catch (Exception ex)
{
//log exception to file
return -1;
}
}
finally
{
conn.Close();
}
}
}
This c# code is called in infinite while to synchronize data. In same Thread and while there is also another method called which is getting data from file (if any exist) and saving them to local DB.
The SynchronizeArticles method is invoking more often and everything is working, but once the method for getting data from file is called, the SynchronizeArticles always throw this exception
System.Data.SqlClient.SqlException (0x80131904): MSDTC on server
'LocalServer\SQLEXPRESS2008' is unavailable.
The method is using Transaction and looks like
public void FillDataFromViewWithTrans(DataTable dt, string wherePhrase)
{
dt.Rows.Clear();
SqlCommand sql = new SqlCommand(String.Format(#"SELECT *
FROM SomeView
{0}", String.IsNullOrEmpty(wherePhrase) ? String.Empty : "WHERE " + wherePhrase));
using (SqlConnection conn = new SqlConnection(Context.LocalData.ConnectionString))
{
SqlTransaction trans = null;
try
{
try
{
conn.Open();
trans = conn.BeginTransaction(IsolationLevel.RepeatableRead);
sql.Transaction = trans;
sql.Connection = conn;
SqlDataAdapter dA = new SqlDataAdapter(sql);
dA.Fill(dt);
trans.Commit();
}
catch (Exception ex)
{
trans.Rollback();
//log exception to file
return;
}
}
finally
{
conn.Close();
}
}
}
This is just illustration samples :)
Tell me what I am missing.
Additionally I have big troubles with the MS DTC with various errors
From C# code when some users calls the procedure manually they sometimes got exception:
The operation could not be performed because the OLE DB provider
'SQLOLEDB' was unable to begin a distributed transaction.
When I put the begin distributed transaction inside the stored procedure I got:
Warning: Fatal error 8510 occurred at Apr 10 2013 9:07AM. Note the
error and time, and contact your system administrator.
What only helps is the restart of the windows service or the UI application. From the MS SQL management studio the procedure works all the time without problems.
Now I must say I am desperate, what am I missing?
Edit:
int i = 0;
while (true)
{
i++;
if ((i % 9) == 0)
{
//local select with transaction Works all the time
CallLocalSelectWithTransaction();
}
// CallProcedure works 8 times, after first calling of CallLocalSelectWithTransaction
// the callProcedure works no more.
CallProcedure(); // procedure with linked server
}

JavaMail SMTPSendFailedException

I am writing a bulk email program using the JavaMail api. I have a Microsoft Exhange server which I am trying to send the emails in to. When I run my program I get the following error:
**com.sun.mail.smtp.SMTPTransport.issueSendCommand(SMTPTransport.java:2057)
at com.sun.mail.smtp.SMTPTransport.finishData(SMTPTransport.java:1862)
at com.sun.mail.smtp.SMTPTransport.sendMessage(SMTPTransport.java:1100)
at javax.mail.Transport.send0(Transport.java:195)
at javax.mail.Transport.send(Transport.java:124)
at SendEmail.postMail(SendEmail.java:100)
at EmailGenerator.main(EmailGenerator.java:52)**
The part of my code trying to send the message is as follows:
Properties props = new Properties();
props.put("mail.smtp.host", email_server);
props.put("mail.transport.protocol", "smtp");
props.put("mail.smtp.auth", true);
class EmailAuthenticator extends Authenticator {
String user;
String pw;
EmailAuthenticator (String FROM, String PASSWORD)
{
super();
this.user = FROM;
this.pw = PASSWORD;
}
public PasswordAuthentication getPasswordAuthentication()
{
return new PasswordAuthentication(user, pw);
}
}
Session session = Session.getInstance(props, new EmailAuthenticator(USER, PASSWORD));
session.setDebug(debug);
System.out.println("Session created");
.. CREATED MESSAGE HERE...
Transport transport = session.getTransport("smtp");
transport.connect(exchange_server,user,password);
transport.send(msg);
transport.close();
I wonder am I missing some configuration on the Exchange server side, or is an issue with my code?
OK I figured out where I was going wrong here and am posting up the answer incase anybody else can get some value out of it. I had the following line of code:
props.put("mail.smtp.auth", true);
This was telling my application that it needed to authenticate to the SMTP server, when in fact it didnt. This was causing my application from logging into the SMTP server and sending the email and thus producing the error message. Setting this property to false or not having this line of code fixed the issue for me. This line of code is only necessary for SMTP servers that require you to login, which my Exchange server didnt.