Trying to connect neo4j with c# and run a query - c#

Im expirementing with databases and most recently specifically with the graph-database Neo4J. Im trying to connect Neo4j with C#, just as what I did with postgreSQL (see code)
class Sql_connection : DatabaseConnection
{
public string Server, Port, User_Id, Password, Database, Connstring;
public NpgsqlConnection SQLconnection;
public Sql_connection(string Server, string Port, string User_Id, string Password, string Database)
{
this.Server = Server;
this.Port = Port;
this.User_Id = User_Id;
this.Password = Password;
this.Database = Database;
this.Connstring = "Server="+this.Server+";Port="+this.Port+";User Id="+this.User_Id+";Password="+this.Password+";Database="+this.Database /* +";" */;
this.SQLconnection = new NpgsqlConnection(this.Connstring);
this.SQLconnection.Open();
}
public string InsertQuery(string INSERT_INTO, string VALUES)
{
NpgsqlCommand InsertCommand = new NpgsqlCommand();
InsertCommand.Connection = this.SQLconnection;
InsertCommand.CommandText = "insert into "+INSERT_INTO+" values "+VALUES;
InsertCommand.ExecuteNonQuery();
return "succes";
}
I already typed "Install-Package Neo4j.Driver-1.0.2" in the NuGetPackagemanager.
Besides that, I of course did some research myself, but I found multiple websites and github-repositories all saying something different, and I dont know what to believe/do anymore.
My two concrete questions are:
1: "How do you make a Neo4J-C# connection?"
2: "How do you run a query with this library/API"
I am aware of how graph-databases work and the syntax of Neo4j, so I understand the insertquery will not have insert into and values as key words.
Thanks in advance to everyone trying to help :D

Neo4j has good official documentation. Out of all sources the developers should be the most trustworthy. This is straight from their website and seems to work fine.
using Neo4j.Driver.V1;
using (var driver = GraphDatabase.Driver("bolt://localhost", AuthTokens.Basic("Username", "Password")))
using (var session = driver.Session()) {
sesion.Run("CREATE (a:Person {name:'Arthur', title:'King'})");
var result = session.Run("MATCH (a:Person) WHERE a.name = 'Arthur' RETURN a.name AS name, a.title AS title");
foreach (var record in result)
Console.WriteLine($"{record["title"].As<string>()} {record["name"].As<string>()}");
}
Taken from here : https://neo4j.com/developer/dotnet/
Simply replace the localhost with your server ip (or localhost if you run it locally) and the username and password with your own username and password.
The developers have given multiple links to examples both documentation and Github source code. Hope this helps.

Related

How to connect to Oracle with C# using a LDAP/OID connection string

I have two questions regarding connecting to an Oracle database using C#.NET.
My program references Oracle.DataAccess.dll (version 2.122.19.1) in my Oracle 19c client 64-bit folder.
I have a using statement:
using Oracle.DataAccess.Client;
and this code to connect:
string connectionString = "Data Source=(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=myserver.sys.mycompany.com)(PORT=1521)))(CONNECT_DATA=(SERVER=DEDICATED)(SERVICE_NAME=mydb.mycompany.com)));User Id=MyLanId;Password=MyPasswors;Validate Connection=True;"
using (OracleConnection connection = new OracleConnection(connectionString))
{
connection.Open();
}
Question #1:
How do I create an OID connection string that does not specify the DB name but instead queries the LDAP for the detail server/port info that is hardcoded in my TNS-less connection string above?
For example, in a Java program, we connect like this.
base.oracle.db.url=jdbc:oracle:thin:#ldap://oid.gtm.internal.mycompany.com:3060/dbname,cn=OracleContext,dc=mycompany,dc=com
What would the .NET equivalent be?
Question Number #2:
When I compile my C# program I selected "Any CPU" yet my program only works when I reference the 64-bit Oracle.DataAccess.dll. Is this because my PATh variable mentions my 64-bit oracle client folder before my 32-bit folder (I have both)? Right now, my PATH variable is way over the max length of 2048 and I cannot change it without making it shorter and I'm not sure what to delete.
I found this SO post,
How do I query LDAP from C# to resolve Oracle TNS hostname while using managed ODP.NET?
Instead of just passing in a connection string that points to an LDAP server, I can do an LDAP query to get the db descriptor to build the connection string.
It's a 2 step process, so I probably want to cache the connection string once I build it. I normally count on connection pooling and "close" connections when I am done with them but this two step process seems like I have to manually add some caching of the connection string to avoid the overhead of hitting LDAP multiple times.
Is there a better way?
string directoryServer = "oid.gtm.internal.mycompany.com:3060";
string defaultAdminContext = "cn=OracleContext,dc=mycompany,dc=com";
string serviceName = "mydb";
string userId = "mylanid";
string password = "mypwd";
using (IDbConnection connection = GetConnection(directoryServer, defaultAdminContext, serviceName, userId, password))
{
connection.Open();
connection.Close();
}
private static IDbConnection GetConnection(string directoryServer, string defaultAdminContext,
string serviceName, string userId, string password)
{
string descriptor = ConnectionDescriptor(directoryServer, defaultAdminContext, serviceName);
// Connect to Oracle
string connectionString = $"user id={userId};password={password};data source={descriptor}";
OracleConnection con = new OracleConnection(connectionString);
return con;
}
private static string ConnectionDescriptor(string directoryServer, string defaultAdminContext,
string serviceName)
{
string ldapAdress = $"LDAP://{directoryServer}/{defaultAdminContext}";
string query = $"(&(objectclass=orclNetService)(cn={serviceName}))";
string orclnetdescstring = "orclnetdescstring";
DirectoryEntry directoryEntry = new DirectoryEntry(ldapAdress, null, null, AuthenticationTypes.Anonymous);
DirectorySearcher directorySearcher = new DirectorySearcher(directoryEntry, query, new[] { orclnetdescstring },
SearchScope.Subtree);
SearchResult searchResult = directorySearcher.FindOne();
byte[] value = searchResult.Properties[orclnetdescstring][0] as byte[];
if (value != null)
{
string descriptor = Encoding.Default.GetString(value);
return descriptor;
}
throw new Exception("Error querying LDAP");
}

c# odbc update query doesnt work properly

Hi I'm having a lot of truble doing a program in c#
i have to connect to SQLANYWHERE 11 and do an update to a table
could u tell me where I'm wrong?
program go well until i reach the:
int number = wCommand.ExecuteNonQuery(); line
the program doesnt crash but tables get not updated
string dns = "Dsn=dattest;Uid=******;Pwd=******;";
OdbcDataReader reader;
OdbcCommand wCommand;
ODBCClass dst1 = new ODBCClass(dns);
queryins = "UPDATE dba.Sala_export_dati_macchina_produzione SET stato='p'";
// +"WHERE id_prd_lav_ord_lav='"+ id_prd_lav_ord_lav + "'";
wCommand = dst1.GetCommand(queryins);
int number = wCommand.ExecuteNonQuery();
Console.WriteLine("executed "+ number);
this is the odbc class that i'm using
public class ODBCClass
{
OdbcConnection oConnection;
OdbcCommand oCommand;
public ODBCClass(string DataSourceName)
{
oConnection = new OdbcConnection(DataSourceName);
try
{
oConnection.Open();
System.Diagnostics.Trace.WriteLine("Connessione stabilita con il database " + DataSourceName);
}
catch (OdbcException caught)
{
System.Diagnostics.Trace.WriteLine(caught.Message);
}
}
public void CloseConnection()
{
oConnection.Close();
}
public OdbcCommand GetCommand(string Query)
{
oCommand = new OdbcCommand
{
Connection = oConnection,
CommandText = Query
};
return oCommand;
}
public void Dispose()
{
oConnection.Close();
}
}
EDIT
just in case i've tried to change connection string with this pattern:
#"Driver={SQL Anywhere 11};DatabaseName=my_db_name;EngineName=my_server_name;uid=username;pwd=password;LINKs=tcpip(host=host_ip_address)"
and always the system gave me no error on connection in both cases
Ok guys that was kinda strange.
Let me explain the whole thing. I was doing that program for a customer that asked a software which could link my mysql db and a sybase db of another company.
The problem was that the DBMS of that company when is opened on the server block all kind of external editing to the db with which is connected.
So select query worked regularly but update and insert were blocked by that client...
I've passed 4 day with a perfect working program but that company didn't told me this "little" thing.
So be aware of DBMS they are cruel.

Unable to query Oracle database via C# API

Good morning.
I am attempting to connect to an Oracle database I have set up. before I go into detail, here's the code:
//string was slightly altered.
string connectionString = "Data Source=(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=127.0.0.1)(PORT=1521))(CONNECT_DATA=(SERVICE_NAME=name)));User Id = system; Password = mypass; ";
string toReturn = "D.BUG-";
using (OracleConnection oracleConnection = new OracleConnection(connectionString))
{
oracleConnection.Open();
using (OracleCommand oracleCommand = new OracleCommand())
{
oracleCommand.Connection = oracleConnection;
oracleCommand.CommandText = "SELECT lixo FROM lixeira WHERE lixo IS NOT NULL";
oracleCommand.CommandType = CommandType.Text;
using (OracleDataReader oracleDataReader = oracleCommand.ExecuteReader())
{
//This point IS reached!
while (oracleDataReader.Read())
//This point is never reached...
toReturn += oracleDataReader.GetString(0);
}
}
}
return toReturn;
Now, I know for a fact that connecting works, and I know for a fact that the table "lixeira" can be found; I have tested this by changing that name to another name, and getting the corresponding "i can't find that table" exception.
'ORA-00942: tabela ou visualização não existe'. (Table or View does not exist)
The issue is that this code is unable to read. The same query ran through SQL Developer works:
SQL Developer screenshot of the same query
So, I'm kinda at a loss as to why oracleDataReader.Read() just never works. Am I doing something wrong?
Make sure your user/password in the connection string is the correct one.
If a table doesn't exist but exists... it probably doesn't exist for your current user (= that user has not the necessary permissions)
Previous answer is correct, I am just adding another bit.
can you replace your query as following :
SELECT lixo FROM <table owner>.lixeira WHERE lixo IS NOT NULL
This will give more appropriate error of what you are missing.
Its probably a permission (grant select) issue.
Abhi

"The multi-part identifier could not be bound" sql, visual studio

I am just learning c# and sql server. This question has been asked a couple of times but the solutions posted don't seem to help me.
I have a table called "LoginInfo" that has a user's "email" and "pass".
In visual studio i have this method that checks a users login information
private boolean dbQueryLogin(string email, string password)
{
string com = "SELECT pass FROM LoginInfo WHERE email = XXXXX#yahoo.com";
SqlCommand command = new SqlCommand(com, conn);
SqlDataReader reader = command.ExecuteReader();
return reader.GetString(0).Equals(password);
}
This keeps on throwing the error "Additional information: The multi-part identifier "XXXX.edu" could not be bound."
The syntax looks right to me, is there anything i'm missing??
The clue is in the error message:
The multi-part identifier "XXXX.edu" could not be bound.
That strongly suggests that the problem isn't with identifying your table - it's with the bit that ends with "edu", which seems like to be an email address.
The immediate problem is that you've forgotten to quote a value. The deeper problem is that you should be using parameterized SQL anyway, to avoid SQL injection attacks, conversion problems and unreadable code. Given that the value you've given in the same code isn't the same as what's in the error message, I suspect you really have code like:
string sql = "SELECT pass FROM LoginInfo WHERE email = " + email;
Don't do that. Use parameterized SQL instead:
private boolean dbQueryLogin(string email, string password)
{
string sql = "SELECT pass FROM LoginInfo WHERE email = #email";
using (var connection = new SqlConnection(connectionString))
{
using (var command = new SqlCommand(sql))
{
command.Parameters.Add("#email", SqlDbType.NVarChar).Value = email;
using (var reader = command.ExecuteReader())
{
// FIXME: What do you want to do if
// there are no matches?
reader.Read();
return reader.GetString(0) == password;
}
}
}
}
This still isn't good code though:
Don't store plain-text passwords in a database
Handle the case where there are no results
Don't build your own authentication system at all; use an existing one written by people with more experience in securing data

Querying remote MySql server

I think I have a straight forward question. I'm writing a system that allows users from company A to single sign on to the system and for this I go back to the central database of users at company A and validate the user credentials passed to me.
Currently my implementation involves building up my query using a stringbuilder and then passing the string as command text. My question is; is there a nicer way of doing this. below is my code;
public User LoginSSO(string UserName, Int32 sectorCode)
{
using (OdbcConnection con = new OdbcConnection(ConfigurationManager.ConnectionStrings["ComapnyA"].ConnectionString))
{
con.Open();
StringBuilder sb = new StringBuilder();
sb.AppendLine("Select mx.Id, mx.UserName, mx.firstname,mx.surname,mx.sectorCode,");
sb.AppendLine("mx.deleteFlag, dn.sectorGroupCode, dn.region, dn.district");
sb.AppendLine("from users mx");
sb.AppendLine("Inner Join sector dn on dn.sectorCode = mx.sectorCode");
sb.AppendLine("Where (mx.UserName = '{0}')");
string commandText = string.Format(sb.ToString(), UserName, sectorCode);
using (OdbcCommand comm = new OdbcCommand(commandText, con))
{
using (OdbcDataReader reader = comm.ExecuteReader())
{
if (reader.Read())
{
User user = new User();
user.Id = Convert.ToInt32(reader["Id"]);
user.Username = Convert.ToString(reader["UserName"]);
user.Firstname = Convert.ToString(reader["firstname"]);
user.Surname = Convert.ToString(reader["surname"]);
_dealerGroupCode = Convert.ToString(reader["sectorGroupCode"]);
_region = Convert.ToInt32(reader["region"]);
_district = Convert.ToInt32(reader["district"]);
_dealerCode = dealerCode;
_accessLevel = AccessLevel.Sector;
return user;
}
}
}
}
return null;
}
I don't like the fact that I am building up my sql which is ultimately a static script. Please note that I can't manipulate the remote server in any way or add any stored procedures to it. For the rest of the app I have been using LINQ but I'm assuming that isn't an option.
This is the most low-level way of querying a database with ADO.NET. Open connection, send command, read out results. You should however use parametrized queries instead of String.Format, since that will open up your program to SQL injection. Just consider what would happen if UserName has a ' character in it. The following would be much better:
string sql = #"Select mx.Id, mx.UserName, mx.firstname, mx.surname,
mx.sectorCode, mx.deleteFlag, dn.sectorGroupCode,
dn.region, dn.district
From users mx
Inner Join sector dn on dn.sectorCode = mx.sectorCode
Where (mx.UserName = ?)";
var command = new OleDbCommand(sql);
command.Parameters.AddWithValue(0, UserName);
If you want a higher level interface, look into DataSets/DataAdapters. They aren't as fancy as LINQ, but they'll give you an easy fill/update, and work with any database adapter. If you're using Visual Studio, you even get a visual designer that can generate Typed Datasets in drag-and-drop fashion that'll give you strong-typed accessors for all your data.
You might also want to look into the native MySql connector classes, instead of using ODBC.
You can use ‘sp_addlinkedserver’ system store procedure to link to the remote server server and then fire a query. following is the sample command.:
EXEC sp_addlinkedserver
#server = ‘SourceServer’
, #Srvproduct = ”
, #Provider = ‘SQLNCLI’
, #datasrc = ‘Remote SQL Server instance name’
I suggest you to please refer following link to know about how to run sql query on remote server http://ashishkhandelwal.arkutil.com/sql-server/sql-query-to-the-remote-sql-server/

Categories

Resources