I'm trying connect to mySQL server with code below: (just part of my whole code)
using MySql.Data.MySqlClient;
//...
public void ConnectToServer()
{
string ConnectionString =
"Server=DESKTOP-91JG566;Database=db_server;Uid=user;Pwd=123456A+;";
MySqlConnection cConn = new MySqlConnection(ConnectionString);
cConn.Open(); // this returns the exception
serverStatus = cConn.Ping() ? serverStatus = "connected" : serverStatus = "disconnected";
}
I'm using MySQL Workbench, there is my server with database https://i.stack.imgur.com/jxn84.jpg
The exception says: System.TypeInitializationException: 'The type initializer for 'MySql.Data.MySqlClient.MySqlConfiguration' threw an exception.'
I have searched about it, and even though I enabled "SQL Server Debugging" in project properties, things are the same.
The problem might be caused because I have bad connection string, I am not sure.
My goal is to communicate with the server, query him, reveive orders etc...
As Jason already mentioned this is a horrible idea to do. Instead, I suggest you build some mini REST API or even use some of the serverless services out there.
When you have that REST API or Azure Function ready then you can communicate with them using your C# code, more precisely using HttpClient from the .NET.
Your mobile app will be the client which will "talk" to REST API, and REST API will proceed with your request and make the request to the DB, grab some data and return you JSON or XML which you can, later on, deserialize into C# objects and show to the user.
The most simple example is located on the MS Docs page here, so you can take a look.
Wishing you lots of luck with coding!
Related
I just started to use MongoDB(4.4) and its C# driver. I set up my MongoDB with the default option, localhost:27017. Then I turned on the authorization, created a superuser with root permission, like this:
db.createUser(
{
user: "superuser",
pwd: "123",
roles: [ "root" ]
}
)
I tested it on both Mongo shell and Compass, it all worked as expected, connected with correct password, and denied with the wrong one.
Then I created a C# windows form app, use NuGet to install all required packages such as MongoDB.Driver for C#(v2.11.0) and its related packages such as MongoDB.Bson, etc
After that, I used the following code to create a MongoClient:
MongoClient client = new MongoClient( "mongodb://superuser:12#localhost:27017" );
So I expected it should throw an exception because I used the wrong password, "12" in this case. But it didn't. Then I tried to list database names with:
client.ListDatabaseNames();
It threw a timeout exception: "A timeout occured after 30000ms selecting a server using CompositeServerSelector"
Even I used the correct password or turned off the authorization, and just go with "mongodb://localhost:27017" or ""mongodb://127.0.0.1:27017", it still threw the same timeout exception.
It feels like something wrong with that client it created which caused the timeout issue later on. But I couldn't figure out what I am missing.
Thank you for your help!
Edit:
The same code works perfectly in a console app, just not a windows form app, which really confuses me.
After trial and error for 2 days, I finally found a work around for this issue, still don't know why this works though.
So basically I have to split the MongoClient creation and its following function calls separately. I can't do anything related to the MongoClient right after its creation. For example, the following throws the time out exception:
MongoClient client = new MongoClient( "mongodb://localhost:27017" ); //I turned off authorization
client.ListDatabaseNames(); //Throw time out exception here!!!
I have to split them separately in 2 functions call, like one in a "Connect" button event, another one in a "ListDatabaseNames" button event.
Once I did that, everything works fine.
mongodb://superuser:12#localhost:27017?authMechanism=SCRAM-SHA-1
because dotNet not support SCRAM-SHA-256 yet
Creating a client does not perform any network operations like connecting to your MongoDB deployment - that is done in background. Hence incorrect credentials won't make client creation fail.
mongo shell works differently and compass probably performs some queries that would fail if credentials aren't correct.
Why you are getting a timeout error - my guess is it's an ipv4/ipv6 difference. Try 127.0.0.1 instead of localhost. If this doesn't help enable debug information in your driver.
I'm new to VersionOne and have limited C#. Need help connecting and testing connection to VersionOne instance using .Net SDK to make sure I'm actually making a connection.
I have some sample code that runs without error, but not sure it is connecting.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using VersionOne.SDK.APIClient;
namespace VersionOneExtract3
{
public class Connection1
{
V1Connector connector = V1Connector
.WithInstanceUrl("https://www14.v1host.com/MyCompanySite")
.WithUserAgentHeader("VersionOneExtract2", "1.0")
.WithWindowsIntegrated("XA\\MyUsername", "MyPassword")
.Build();
}
}
enter code here
No results or errors. Is there a way I can create a variable and have it return some sort of confirmed connection info? Help appreciated!
The code that you posted creates a VersionOne connector which is used to connect to the VersionOne API. I'm assuming that you replaced the username and password with random data for privacy reasons, along with the URL. Make sure that those details are correct.
After you have your connector setup you'll want to use it to query various resources from the api. One example of such is below:
IServices services = new Services(connector);
Oid memberId = services.GetOid("Member:20");
Query query = new Query(memberId);
QueryResult result = services.Retrieve(query);
Asset member = result.Assets[0];
The reason that you're not seeing any feedback from the code you posted it because in reality, it doesn't really do much other than take in some configuration data and then spit out a type of API client.
Be sure to have a good look at the documentation as they do a fairly decent job of explaining how to work with their SDK.
https://community.versionone.com/VersionOne_Connect/Developer_Library/Get_an_SDK/.NET_SDK
Think of your code as code that describes and sets up a VersionOne connection. You are building an object that contains everything needed for a connection. You are not connecting yet.
if your variable connector is null, you know for a fact that you are not connected to VersionOne. On the other hand, your connector might have what looks like valid info in the setting up of the connection so you need to add the next piece of code
IServices services = new Services(connector);
Once you hit this piece of code, this will throw an exception if the connector object is invalid. To get confirmation of this, connect to https://www14.v1host.com/MyCompanySiteWrongURL. If you run your code, connector will reference an object but it will have virtual "junk" in it because it won't connect. As soon as you hit the above new code that I have suggested, it will throw an exception. Conversely, if you enter the correct URL and credentials, you should not throw an exception. You can use #DCCoders chunk of code for querying for member:20. I also recommend using the VersionOne API to do queries in the browser so you can get instant results and get a feel of the VersionOne data model. https://community.versionone.com/VersionOne_Connect/Developer_Library/Learn_the_API/VersionOne_REST_API_Tutorial
I'm developing a WebGL app with Unity 2018.
I need to access a MySQL database hosted on the same server.
My questions is: can I use C# and MySqlConnector (solution i prefer), or I have to use instead web services calls ?
EDIT: it seems it's not either possible to use/consume web service in WebGL build, because System.Web.Services it's not accessible.
Thanks
The general way for doing this (both for security reasons and it's just all round a more standard way from the unity side of things) is that you simply host the server side database interaction pages within php and then make use of either the WWW or UnitWebRequest classes to actually utilize this.
You can fairly easily get back Json formatted data to work with on the client side
A fairly old (though still kinda relevant) tutorial/guide for something along these lines can be found Here
Generally, the idea is though - Game makes a request to PHP using an encrypted key of some kind for validation, PHP does the database work and then fires back some data usually in Json format
You can make a websocket. The server who will host the WebGL app will have a websocket server, who will do the MySQL communication and return the results. And the WebGL app(the unity one) connects to this websocket using a Auth Token(To ensure that is the WebGL connecting, not someone else) and get the results from the queries there
You might already have your answer but i have done it few weeks ago and its pretty easy.
I am posting both php and c# code below, have a look:
C# Code
WWWForm form = new WWWForm();
WWW www = new WWW("url of file location on server goes here", form);
yield return www;
Debug.Log(www.text);// this should return "successful connection"
PHP Code
replace '123' with required fields
<?php
$servername = "123";
$server_username = "123";
$server_password = "123";
$dbName = "123";
//Connection
$conn = new PDO ("mysql:host=$servername;dbname=$dbName", $server_username, $server_password);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
//Check Connection
if(!$conn){
die("Connection failed.");
}else{
echo "Connection Successful";
}
?>
Hope its helps!
my project is about writing an OPC UA Client, to read and write variables on a Siemens PLC OPC UA Server. I'm using Visual Studio 2017 Enterprise and installed the Quick OPC Toolkit from OPClabs to get started and try to connect. To program the client, I'm using Windows Forms and C#.
Connecting with the server and reading variables is working just fine, but writing them gives me a headache:
1.) Before I started programming on my own, I downloaded the OPC UA Sample Client from the OPC Foundation (if someone needs the download-link just ask, the download is hard to find). I connected to the server and could browse through the variables, but the write function was greyed out/not available.
2.) I started programming a very simple client, but also failed to write variables. Reading via Live Binding (http://opclabs.doc-that.com/files/onlinedocs/QuickOpc/2018.2/User%27s%20Guide%20and%20Reference-QuickOPC/webframe.html#Making%20a%20first%20OPC%20UA%20application%20using%20Live%20Binding.html) is working, also reading them by using easyUAClient.Read() works. I tried to write a variable with this code:
namespace ErsteOPCUAVerbindung{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
var easyUAClient = new EasyUAClient();
easyUAClient.WriteValue("opc.tcp://OpcUaClient:password#192.168.216.1:4840/", "nsu=SinumerikVarProvider;ns=2;s=/NC/_N_NC_TEA_ACX/$MN_PLC_CYCLIC_TIMEOUT", 1);
}
}}
but I keep getting an exception:
OpcLabs.EasyOpc.UA.OperationModel.UAException: "An OPC-UA operation failure with error code -2144010240 (0x80350000) occurred, originating from 'OpcLabs.EasyOpcUA'. The inner OPC-UA service exception with service result 'BadAttributeIdInvalid' contains details about the problem."
{"OPC-UA service result - An error specific to OPC-UA service occurred.\r\n---- SERVICE RESULT ----\r\nStatusCode: {BadAttributeIdInvalid} = 0x80350000 (2150957056)\r\n"}
I have no idea what is causing this. I suspected, that maybe some kind of access restriction is the reason, but I can't find any hints about it in the documentations and besides I'm logged in as administrator anyway.
Has anyone an Idea? Thank you.
I have had one more look at your code, and the way you pass in the user name and password (in the URL itself) is definitely not correct. The way it is given now it is essentially ignored. It may or may not be the cause for the problem with the Write, but it definitely needs to be changed. The proper way of specifying the user name and password would be:
var client = new EasyUAClient();
var endpointDescriptor = new UAEndpointDescriptor("opc.tcp://192.168.216.1:4840/");
endpointDescriptor.UserIdentity = UserIdentity.CreateUserNameIdentity("OpcUaClient", "password");
client.WriteValue(endpointDescriptor, "nsu=SinumerikVarProvider;ns=2;s=/NC/_N_NC_TEA_ACX/$MN_PLC_CYCLIC_TIMEOUT", 1);
Update: I found a documentation, which explained, that the administrator does not have write rights by default and how you can change that. You need to call the methode GiveUserAccess and pass two Arguments, the Username and "SinuWriteAll" (the second one is kind of hidden). I'll try it now with C# and post my solution if it works.
I'm currently using the NEST ElasticSearch C# Library for interacting with ElasticSearch. My project is an MVC 4 WebAPI project that basically builds a RESTful webservice for accessing directory assistance information.
We've only just started working with NEST, and have been stumbling over the lack of documentation. What's there is useful, but it's got some very large holes. Currently, everything we need works, however, we're running into an issue with connections sometimes taking up to a full second. What we'd like to do is use some sort of connection pooling, similar to how you'd interact with SQL Server.
Here is the documentation on how to connect using nest: http://mpdreamz.github.com/NEST/concepts/connecting.html
Here is the relevant code snippet from our project:
public class EOCategoryProvider : IProvider
{
public DNList ExecuteQuery(Query query)
{
//Configure the elastic client and it's settings
ConnectionSettings elasticSettings = new ConnectionSettings(Config.server, Config.port).SetDefaultIndex(Config.index);
ElasticClient client = new ElasticClient(elasticSettings);
//Connect to Elastic
ConnectionStatus connectionStatus;
if (client.TryConnect(out connectionStatus))
{
// Elastic Search Code here ...
} // end if
} // end ExecuteQuery
} // end EOCategoryProvider
From looking at the documentation, I can't see any provisions for a connection pool. I've been thinking about implementing my own (having, say 3 or 4 ElasticClient objects stored, and selecting them round-robin style), but I was wondering if anyone had a better solution. If not, does anyone have advice on the best way to implement a connection pool by hand? Any articles to point to?
Thanks for anything you guys come up with.
Update: This seems to have been related to calling TryConnect on every request, and the particular network setup. The problem completely disappeared when using a machine on the same network as the Elastic box; My development machine (which averages 350ms to the Elastic box) seemed to fail to make http connections sometimes, which caused the long times in TryConnect.
You don't have to call TryConnect() each time you do a call to Elasticsearch. It's basically a sanity check call for when your application starts.
NEST is the C# REST client for Elasticsearch and the default IConnection uses WebRequest.Create which already pools TCP connections.
Review the actual implementation: https://github.com/elastic/elasticsearch-net/blob/master/src/Elasticsearch.Net/Connection/HttpConnection.cs
Reusing ElasticClient won't offer any performance gains since each call already gets its own HttpWebRequest. The whole client is built stateless on purpose.
I am however very interested in why calls are taking 1 second for you. Could you post the actual NEST code, how you are are measuring the calls and describe your data.
Disclaimer: I'm the author of NEST.