Writing Variables via QuickOPC in C# (Visual Studio) - c#

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.

Related

How to connect my Xamarin app with local mySQL server?

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!

C# Executing a query and getting data out of an Access Database (accdb) without using ACE.OLEDB

I'm writing a WPF application.
Trying to use the normal method of getting a connection returns an error similar to: "The 'Microsoft.ACE.OLEDB.12.0' provider is not registered on the local machine."
ACE.OLEDB has never been installed on this machine so this error makes sense.
I'm trying to create this application in a way so that our users won't need to contact IT to have the application installed. Getting IT involved is a no go situation and the project will be abandoned.
Another team has an Access database (accdb) that I want my application to extract information (only read, no insert or update). I talked to the team and they won't convert this database back to an earlier version (mdb).
After my research I assume that installing ACE.OLEDB without using Admin privileges is impossible. Because of this and my application requirement of not requiring admin privileges I need to start looking for "Mutant"/Dirty solutions that don't involve ACE.OLEDB.
I tried using power-shell but I'm getting the same problems as I had with C# (requires IT to install ACE.OLEDB).
I have two potential solutions. One write a VBA script that opens up the database and dumps a query result into a file. My C# application would call this VB script and then parse the created file.
The second option is to create a new Access process using Process.Start(fullFilePath) and somehow pass the command to execute a query and somehow pass the results back to the executing application (either via a method return or first to a file).
How would you get the data out?
Is there a way for C# to duplicate the DB file and convert it from (accdb -> mdb)?
This is the second question I ask that is very similar.
C# Connecting to Access DB with no install
The difference between the two (to prevent this is a duplicate question) is that in the previous question I was looking for ways to install ACE.OLEDB without admin privileges while here I'm just looking for any other work around.
Found a workaround. It uses Microsoft.Office.Interop.Access found in NuGet.
var accApp = new Microsoft.Office.Interop.Access.Application();
accApp.OpenCurrentDatabase(#tests.DatabasePath);
Microsoft.Office.Interop.Access.Dao.Database cdb = accApp.CurrentDb();
Microsoft.Office.Interop.Access.Dao.Recordset rst =
cdb.OpenRecordset(
"SELECT * FROM Users",
Microsoft.Office.Interop.Access.Dao.RecordsetTypeEnum.dbOpenSnapshot);
while (!rst.EOF)
{
Console.WriteLine(rst.Fields["username"].Value);
rst.MoveNext();
}
rst.Close();
accApp.CloseCurrentDatabase();
accApp.Quit();

ErrorMessage while open connection to Denodo via npgsql in c#

sorry, if this is question is (to) easy for stackoverflow community.
I am trying to connect to Denodo (Version 7), via c# code.
I installed npqsql and created a connection string with: {host} {port} {username} {passwd} {database} and the SSL-Mode as required.
(user and pwd combination was checked via Launch Pad)
For trying I use a simple select statement.
If I call Open() on my NpqsqlConnection object I get the error message {"Received unexpected backend message ParseComplete. Please file a bug."}
For beeing sure I tried to ping the host, which works fine. And if I try without SSl, the error message indicates that the SSl is required, therefor I think the correct backend is found.
Could someone give me a hint?
Thanks
Jessi
I checked the Denodo Community, and the given examples: https://community.denodo.com/docs/html/browse/6.0/vdp/developer/access_through_an_ado.net_data_provider/access_through_an_ado.net_data_provider
https://community.denodo.com/answers/question/details?questionId=90670000000XcbkAAC&title=How+to+execute+C%23+program+using+vdp-clients-ADO.NET

C# DCOM event binding Unathorized Execption

For a project I am working on I have to interface with a third-party DCOM library. I started with COM interop and this worked just fine locally, then I switched to DCOM and now I keep getting an unauthorized access exception (0x80070005) when trying to bind an event handler to the exposed event. Below is a summary of what I do in code:
public void connect(string server)
{
object dcomObj = null;
var guidB = Guid.Parse("c8c1f57f-0d7c-40b3-b17c-2eac12512006");
var typ = Type.GetTypeFromCLSID(guidB, server, true);
object[] url = { new UrlAttribute(server) };
dcomObj = Activator.CreateInstance(typ, null, url);
user = (RemoteObjectInterface)dcomObj ;
user.getState(); //works fine locally and remotely
user.stateChange += this.User_StateChange; //only works locally
}
I tried setting every permission I could find on the web but I without success. Does anyone have an Idea as to why only the binding of events fails?
RemoteObjectInterface inherits from both the IRemoteObjectEvents and the IRemoteObject. These interface come from the interop ms generated for me when I imported the original dll.
The server is a windows server 2003 VM in virtual box with a bridged network adapter. On the server Everyone is admin (including guest) and limits are set to full access and defaults are set to full access. I am building and running my code on c# .net 4.5.2 from a Windows 10 machine using visual studio 2015.
The sample application that comes with the SDK also fails when I try to use it remotely, the server registers the user but the sample application never realizes that it logged in successfully, I suspect that this behaviour is related to the failing of event binding.
TL;DR I can get and use a remote object but when I try to add an event handler I get an unauthorized exception (0x80070005), why does this happen on event binding? And how do I fix it?
I had the same problem.
For me the issue was I had a AD running on the same device and had to disable the loopback check in the registry. Other solution could be better I assume, but for me the registry hack will do.

Mathematica .Net/Link in an Asp.Net application

I am using the Mathematica .Net/Link platform to create a web service to format and calculate math problems. However I am unable to get it working.
I create it using this code:
_Log.IpDebug("Starting the Kernel Link");
if (string.IsNullOrEmpty(_MathLinkArguments))
_InternelKernel = MathLinkFactory.CreateKernelLink();
else
_InternelKernel = MathLinkFactory.CreateKernelLink(_MathLinkArguments);
_Log.IpDebug("Kernel Link Started");
_InternelKernel.WaitAndDiscardAnswer();
The value of _MathLinkArguments is -linkmode launch -linkname \"C:\\Program Files\\Wolfram Research\\Mathematica\\7.0\\Math.exe\".
This piece of code is called from the Application_Start method of the global.asax.cs file.
When it gets to the WaitAndDiscardAnswer() call it gives the server error:
Error code: 11. Connected MathLink program has closed the link, but there might still be data underway.
Note: The SampleCode given with the .NET/Link package (both a console app and a WinForms app) works.
Edit:
I copied the console app sample code given with Mathematica into an asp.net page and it gave me the same error the first load and then on subsequent loads it gave me:
Error code: 1. MathLink connection was lost.
Edit2:
I forgot to mention that when I have procmon and task manager open while running my app, I can tell that Math.exe starts but it immediately exits, which makes those error code make complete sense...but doesn't explain why that happened.
To allow the .Net/Link to work in Asp.net (at least in IIS 7.5) you need to enable the property loadUserProfile on the app pool for the web site.
I am not entirely sure why this is the case, but from what I found while trying to debug this, there are some things that are gotten from the user's profile. I know for a fact that the default location of the kernel is, which explains why I couldn't use it with no arguments, and so I can only assume that other things are needed as well and without the profile it couldn't determine that.
But whatever the reason is this is required, it is, or at least it is a fix if you are getting similar problems like this in your own application.
I got the same error in a .Net WinForm application.
mathKernel = new MathKernel();
mathKernel.Compute("<< XYZ`XYZGraphs`");
The error occurred on loading the package straight after instantiating the MathKernel.
To resolve it you can wait a couple of seconds and then instantiating the MathKernel works fine. During this state where there might still be data underway the following conditions are both false:
if (!MathKernel.IsConnected)
{
MathKernel.Connect();
}
if (MathKernel.IsComputing)
{
MathKernel.Abort();
}
Edit:
I've recieved the error again and this time was able to determine the problem.
Using a command line open the MathKernel.exe and view the error message:

Categories