How do I use databases within ASP.Net - mysql

I've developed web applications in PHP for a few years and would like to learn about ASP.Net. I've installed VS2013 and have created an ASP.Net Web Application. I tried playing around with something that I found on wait for it W3Schools just because I knew it would be as simple as simple could be but it caused me some errors. I was trying to "connect" to an Access file in the wwwroot directory by using System.Data.OleDb but I had some problems.
My question is: Is there a simplistic way like in PHP where you have PHPMyAdmin to manage the database and then connect via something simple like $conn = new mysqli('localhost', 'user', 'password', 'db'); but for ASP.Net?
I'm struggling to find beginner level support for this on the web and would like to figure it out asap!

David, isnt's going to be "simple" as PHP, remember that VS2013 it's a server side language, more strong and complex.
I recommend to you the next:
Work with objects.
Here is some code may help you.
C#:
public System.Data.DataSet GetQuery(string _QueryComm){
System.Data.DataSet objResult = new System.Data.DataSet();
OleDbDataAdapter objAdapter;
strProvider = "Provider=SQLOLEDB.1;Data Source=YourServer;Initial Catalog=Database;User Id=databaseuser;Password=pass;";
objCon = new OleDbConnection(strProvider);
objCon.Open();
try
{
objAdapter = new OleDbDataAdapter(_QueryComm, objCon);
objAdapter.Fill(objResult);
objAdapter.Dispose();
objCon.Close();
}
catch (Exception e)
{
// Some exception handler
}
return objResult;}
Usage:
DataSet datainfo = GetQuery("select * from table");
VB:
Public Function GetQuery(strCommandQuery as String) As System.Data.DataSet
Dim objResult As System.Data.DataSet = New System.Data.DataSet
Dim objAdapter As OleDbDataAdapter
strProvider = "Provider=SQLOLEDB.1;Data Source=YourServer;Initial Catalog=Database;User Id=databaseuser;Password=pass;"
objCon = New OleDbConnection(strProvider)
objCon.Open()
Try
objAdapter = New OleDbDataAdapter(strCommandQuery, objCon)
objAdapter.Fill(objResult)
objAdapter.Dispose()
objCon.Close()
Catch ex As System.Exception
' Some exception handler
End Try
Return objResult End Function
Usage:
Dim datainfo as DataSet = GetQuery("select * From table")
Let me know if it's work for you.

Related

aws mysql connection issue for azure site

I cant seem to find an answer to my issue.
I made a quick little website with .net and published it on azure.
when I test it I can query my aws mysql db just fine however after publishing I am getting.
System.InvalidOperationException: Connection must be valid and open. at
MySql.Data.MySqlClient.Interceptors.ExceptionInterceptor.Throw(Exception
exception) at MySql.Data.MySqlClient.MySqlConnection.Throw(Exception ex) at
MySql.Data.MySqlClient.MySqlCommand.Throw(Exception ex) at
MySql.Data.MySqlClient.MySqlCommand.CheckState() at
MySql.Data.MySqlClient.MySqlCommand.ExecuteReader(CommandBehavior behavior)
at MySql.Data.MySqlClient.MySqlCommand.ExecuteReader() at
TaskiiLink._Default.Page_Load(Object sender, EventArgs e) in
C:\............\Default.aspx.cs:line 39
line 39: MySqlDataReader reader = command.ExecuteReader();
my connection string is :
<add name="dbconn" connectionString="user id=NAME;Password=PASS;persistsecurityinfo=true;server=AWSENDPOINT;Port=3306;database=DB;" providerName="MySql.Data.MySqlClient"/>
page load code
if(Request["type"] == "1")
{
string sql = "checkDB";
conn.Open();
using (MySqlCommand command = new MySqlCommand(sql))
{
command.Connection = conn;
try
{
MySqlDataReader reader = command.ExecuteReader();
if (!reader.Read())
{
Response.Write("false");
} else
{
Response.Write("true");
}
You need to pass the connection object.
MySql.Data.MySqlClient.MySqlCommand myCommand = new MySql.Data.MySqlClient.MySqlCommand(insertQuery, connection);
Figured it out myself,
AWS security group was only allowing my local host ip as an inbound.
found my web apps outbound ip in the property settings in azure portal.
helpful links if anyone has the same issue.
AWS issue
https://forums.aws.amazon.com/thread.jspa?threadID=176030
azure info
https://social.msdn.microsoft.com/forums/azure/en-US/fd53afb7-14b8-41ca-bfcb-305bdeea413e/maintenance-notice-upcoming-changes-to-increase-capacity-for-outbound-network-calls
issue I had when adding the ip solution.
https://forums.aws.amazon.com/thread.jspa?threadID=158994

Database logon failed while using mysql azure

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?

Getting the cannot callsendredirect() after the response has been committed

Again my question related with the same project which i am doing for the report tracking system getting the below error in the tomcat logs after accessing the login page which is redirect towards "userloginmid.jsp".The code as shown below in the same window.
Please provide the solution for the same if possible.
<%# page import="java.sql.*,java.util.*,java.text.*,java.text.SimpleDateFormat" %>
<%
String userName = request.getParameter("userName");
String password = request.getParameter("password");
System.out.println("MySQL Connect Example.");
Connection conn = null;
String url = "jdbc:mysql://localhost:3306/";
String dbName = "report_tracking";
String driver = "com.mysql.jdbc.Driver";
String username = "root";
String userPassword = "root";
java.util.Date now = new java.util.Date();
String DATE_FORMAT = "yyyy-MM-dd hh:mm:ss";
SimpleDateFormat sdf = new SimpleDateFormat(DATE_FORMAT);
String strDateNew = sdf.format(now) ;
try {
Class.forName(driver).newInstance();
conn = DriverManager.getConnection(url+dbName,username,userPassword);
Statement st = conn.createStatement();
String strQuery = "select * from userregister where username='"+userName+"' and password='"+password+"'";
out.println(strQuery);
ResultSet rs = st.executeQuery(strQuery);
if(rs.next())
{
int userid=rs.getInt(1);
String user=rs.getString(2);
session.setAttribute("userid",userid);
session.setAttribute("username",user);
session.setAttribute("intime",strDateNew);
String queryString = "INSERT INTO admin set userid="+userid+",intime='"+strDateNew+"'";
int i = st.executeUpdate(queryString);
if(i>0)
{
response.sendRedirect("welcome.jsp");
}
}
response.sendRedirect("login.jsp");
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
%>
As all said there are lot of loopholes in your code.
But the answer to your quesion is
sendRedirect requires a return statement
So change your lines of code to
response.sendRedirect( "welcome.jsp"); return; and
response.sendRedirect("login.jsp"); return;
Also read this .
There are a lot of problems with your code.
First, the explanation of your stated problem, redirecting after committing a response:
When the HTTP headers are already sent to the client (read about the HTTP protocol if you don't know it yet), they are out and cannot be pulled back. You're coding your sample in a jsp, which is the VIEW part of your architecture - and at least between the "page import" and the code part there's a newline which might trigger the server to flush its buffers to the client. Once that's done, the HTTP headers are gone and you cannot redirect any more.
Workaround: Don't implement this routine in a jsp, but in a servlet (or use a decent framework that handles this problem for you. Any of the current will suffice).
Now about some of the problems that your code has:
Please read about SQL injection. Think of someone posting
usernames like someone'; someone' OR '0' = '0 or similar (just
making them up as I go)
Once you get your connection and run in to any error, you won't clean
up the connection (e.g. you will leak connections on any exception)
You seem to be storing clear text passwords. Definitely a no-go as
soon as someone else than you will have an account

SSIS Script Component connection

I've been searching for a solution for days now and I still cant seem to find one. I have a problem acquiring a connection in my Script component. I need to query my database to retrieve an Id to be used before I insert it in the
public override void AcquireConnections(object Transaction)
{
connMgr = base.Connections.Connection;
conn = (SqlConnection)connMgr.AcquireConnection(null);
}
I get an exception here.
System.InvalidCastException: Unable to cast COM object of type 'System.__ComObject' to class type 'System.Data.SqlClient.SqlConnection'. Instances of types that represent COM components cannot be cast to types that do not represent COM components; however they can be cast to interfaces as long as the underlying COM component supports QueryInterface calls for the IID of the interface.
Any solutions?
For those that want to be able to do this in a Script Component:
Double Click the Script component to open the "Script Transformation Editor"
Click the "Connection Managers" list item.
Add a new Connection Manager. Select an existing ADO.NET connection manager.
Click on the "Script" list item and then the "Edit Script..." button.
You can do something like this inside your script:
using (SqlConnection connection = this.Connections.Connection.AcquireConnection(null) as SqlConnection)
{
using (SqlCommand command = connection.CreateCommand())
{
command.CommandText = "SELECT [Value] FROM dbo.MyTable";
command.CommandType = CommandType.Text;
using (SqlDataReader reader = command.ExecuteReader())
{
while (reader.Read())
{
ProfanityWords.Add(reader.GetValue(0).ToString());
}
}
}
this.Connections.Connection.ReleaseConnection(connection);
}
ADO.NET connection manger should be created and refer into the code to type cast to the SqlConnection. If you dont have the ADO.NET connection in your SSIS pakcage you will get the TypeCast exception. Following steps should be used if you want to use the SqlConnection.
Create the ADO.NET connection.
Use the following line in your code.
var connObj = Dts.Connections["ADO.NETConnectionName"].AcquireConnection(null);
var sqlConn = (SqlConnection)connObj;
Once you done with your SQL connection. Use the following code to Close/ Release your connection.
Dts.Connections["ADO.NETConnectionName"].ReleaseConnection(connObj);
Hope this helps.

Access2007 OleDbConnection over network share persists although share is deletedH

I've encountered a quite strange behavior of ADO.NET / Access 2007.
I run my C# 2008 program (target framework .NET 2.0) on PC1.
PC1 has a network share on PC2 (\PC2\Temp mapped as X:)
On PC2 in Temp there is the access database file xy.mdb
The program opens a OleDbConnection to X:\xy.mdb. Works fine.
Then while the program is still running I drop the share on PC2.
(Windows Explorer on PC1 tells me the share X: is lost)
I renamed the database file on PC2, so no new connection should be possible.
But the program can still query the database !
(via OleDbCommand.ExecuteReader() or ExecuteNonQuery())
Has anyone an explanation for me ?
Is the whole database latched ?
And can I prevent this so that I get an OleDbException when the share is dropped and I try to query the no longer available database ?
Thanks for any help,
Ralf
I tried to reproduce the issue with the following code and a sample access db...not matter how I tried (sahre or mapped drive) i always got the exception:
Unhandled Exception:
System.Data.OleDb.OleDbException: The
Microsoft Jet database engine cannot
find the input table or query
'somejunk'. Make sure it exists and
that its name is spelled correctly.
which is expected. You should re-examine you environment to be 100%.
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.OleDb;
using System.Linq;
using System.Text;
namespace AccessOverShare
{
class Program
{
static void Main(string[] args)
{
int ct = 0;
using(OleDbConnection oleDbConnection = new OleDbConnection())
{
//oleDbConnection.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=\\\\127.0.0.1\\share\\test.mdb.";
oleDbConnection.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=w:\\test.mdb.";
oleDbConnection.Open();
using(OleDbCommand oleDbCommand = oleDbConnection.CreateCommand())
{
oleDbCommand.CommandType = CommandType.Text;
oleDbCommand.CommandText = "select junkid, junktext from somejunk";
using (OleDbDataReader oleDbDataReader = oleDbCommand.ExecuteReader(CommandBehavior.Default))
{
ct = 0;
while(oleDbDataReader.Read())
{
ct++;
Console.WriteLine("{0:0000}", oleDbDataReader["junkid"]);
}
}
Console.WriteLine();
Console.WriteLine(ct);
}
Console.WriteLine();
Console.WriteLine();
Console.Write("kill the share then press enter to continue");
Console.ReadLine();
using (OleDbCommand oleDbCommand = oleDbConnection.CreateCommand())
{
oleDbCommand.CommandType = CommandType.Text;
oleDbCommand.CommandText = "select junkid, junktext from somejunk";
using (OleDbDataReader oleDbDataReader = oleDbCommand.ExecuteReader(CommandBehavior.Default))
{
ct = 0;
while (oleDbDataReader.Read())
{
ct++;
Console.WriteLine("{0:0000}", oleDbDataReader["junkid"]);
}
}
Console.WriteLine();
Console.WriteLine(ct);
}
}
}
}
}