C# Error while trying to connect to MySql using MySql.Data - c#

ISSUE
While trying to connect to maria db using mysql.data i get this error:
System.IndexOutOfRangeException: Index was outside the bounds of the array.
at System.Diagnostics.TraceInternal.get_AppName () [0x0000e] in <e804fc8285a9419784599893ed028695>:0
at System.Diagnostics.TraceInternal.TraceEvent (System.Diagnostics.TraceEventType eventType, System.Int32 id, System.String format, System.Object[] args) [0x0003d] in <e804fc8285a9419784599893ed028695>:0
at System.Diagnostics.Trace.TraceError (System.String message) [0x00000] in <e804fc8285a9419784599893ed028695>:0
at MySql.Data.MySqlClient.MySqlTrace.LogError (System.Int32 id, System.String msg) [0x00026] in <89b4d3936e0b4e49b8d299ddbfe7933d>:0
at MySql.Data.MySqlClient.MySqlPool.TryToGetDriver () [0x0002e] in <89b4d3936e0b4e49b8d299ddbfe7933d>:0
at MySql.Data.MySqlClient.MySqlPool.GetConnection () [0x0001c] in <89b4d3936e0b4e49b8d299ddbfe7933d>:0
at MySql.Data.MySqlClient.MySqlConnection.Open () [0x00245] in <89b4d3936e0b4e49b8d299ddbfe7933d>:0
at MyResource.Server.ServerMain..ctor () [0x00026] in C:\Users\Maurice\CFX\MyResource\Server\ServerMain.cs:23
Done.
The .dll file was compiled with dotnet build under debian 10 without warnings or errors
TRIED:
I want to connect to sql Database (MariaDB) via C# and MySql.Data from Oracle.
First I created a folder with the C# script and the .dll's of the MySql.Data package.
After that i added the reference to the .proj:
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<DebugType>portable</DebugType>
<TargetName>ServerMain.net</TargetName>
<DefineConstants>SERVER</DefineConstants>
<AssemblyName>TEST.Server.net</AssemblyName>
</PropertyGroup>
<ItemGroup>
<Reference Include="MySql.Data">
<HintPath>MySql.Data.DLL</HintPath>
</Reference>
</ItemGroup>
</Project>
To build the project i used the Visual Studio Code SSH Connection to run in vsc Terminal: dotnet build.
RESULT:
Succesfully started Script with test output but after SQL Connection Open() the Error as seen above was thrown.
MY CODE:
using System;
using System.Threading.Tasks;
using MySql.Data.MySqlClient;
namespace TEST.Server
{
public class ServerMain : BaseScript
{
public static void DBTEST()
{
var connString = "server=localhost;user=NAME;database=NAME;port=3306;password=*****";
MySqlConnection conn = new MySqlConnection(connString);
try
{
Console.WriteLine("Connecting to MySQL...");
conn.Open();
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
public ServerMain()
{
DBTEST();
}
}
}

Related

Uploading to Azure File Share from a Razor Page

I am trying to find an example of uploading a file to an Azure file share or blob storage from a razor page. I use this code from the tutorial
but this copy files only to the local filesystem.
Now I found the article here on stackoverflow, but it won't work. I got the error in line
var storageAccount = CloudStorageAccount.Parse(< your creds here>);
the name "CloudStorageAccount does not exist in the current context"
I am using Visual Studio 2022, .Net Core 2.2. Any help would be much appreciated.
Initially even I got the error.
The NuGet package required for CloudStorageAccount is WindowsAzure.Storage.
But in Package Manager you can see WindowsAzure.Storage is deprecated.
You can also see the alternate package Azure.Storage.Blobs is mentioned.
Install the latest Azure.Storage.Blobs NuGet package.
When I tried to Install Azure.Storage.Blobs package, got the below error.
"System.IO.Hashing doesn't support $(TargetFramework). Consider >updating the TargetFramework to netcoreapp3.1 or later." />
The error clearly says to update and use the .NET Core latest version.
I am able to clear the issue in .Net Core 2.1 by installing the below NuGet Package.
Microsoft.Azure.Storage.DataMovement
Add the using namespace using Microsoft.Azure.Storage
My .csproj file
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>netcoreapp2.1</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.App" />
<PackageReference Include="Microsoft.AspNetCore.Razor.Design" Version="2.1.2" PrivateAssets="All" />
<PackageReference Include="Microsoft.Azure.Storage.DataMovement" Version="2.0.4" />
</ItemGroup>
</Project>
My Conroller.cs
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.Storage;
using Microsoft.Azure.Storage.File;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using WebAppMVC.Models;
namespace WebAppMVC.Controllers
{
public class HomeController : Controller
{
public IActionResult Index()
{
return View();
}
[HttpPost]
public async Task<IActionResult> Upload(IFormFile file)
{
if (file != null)
{
using (var stream = new MemoryStream())
{
try
{
await file.CopyToAsync(stream);
stream.Seek(0, SeekOrigin.Begin);
var filename = file.FileName;
var storageAccount = CloudStorageAccount.Parse("YOUR CREDS HERE");
var client = storageAccount.CreateCloudFileClient();
var shareref = client.GetShareReference("YOUR FILES SHARE");
var rootdir = shareref.GetRootDirectoryReference();
var fileref = rootdir.GetFileReference(filename);
await fileref.DeleteIfExistsAsync();
await fileref.UploadFromStreamAsync(stream);
return Ok(new { fileuploaded = true });
}
catch (Exception ex)
{
return BadRequest(ex);
}
}
}
else
{
return BadRequest(new { error = "there was no uploaded file" });
}
}
}
}

C#: Unhandled exception. System.TypeLoadException: Could not load type 'System.Drawing.Color'

ANSWER for this question thanks to Jeremy C.:
There is no KeePass nuget package for the Net5.0 yet. Thats why there is that error message. Thanks Jeremy C. for the help and answers.
QUESTION:
Im getting this error after starting my solution.
Unhandled exception. System.TypeLoadException: Could not load type 'System.Drawing.Color' from assembly 'Splat, Version=3.0.0.0, Culture=neutral, PublicKeyToken=null'.
Already used google and tried to find a fix for it and also red all articles about similiar errors like "System.Drawing.Font" or "System.Drawing.Image". But theres nothing really helpful and nothing really informative about 'System.Drawing.Color'.
Ive got the code example and package from here:
github.com/wismna/ModernKeePassLib
This is my code:
.csproj
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net5.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="ModernKeePassLib" Version="2.45.1" />
<PackageReference Include="System.Drawing.Common" Version="5.0.2" />
</ItemGroup>
</Project>
And:
using ModernKeePassLib;
using ModernKeePassLib.Interfaces;
using ModernKeePassLib.Keys;
using ModernKeePassLib.Serialization;
using System;
using System.Linq;
using System.Text;
namespace KeePasso
{
class Program
{
static void Main()
{
var dbpath = #"C:\Users\prusinma\Desktop\KeePassDatabase\Database.kdbx";
var keypath = #"C:\Users\prusinma\Desktop\KeePassDatabase\Database.key";
var masterpw = "1234abcd";
Console.WriteLine("init done");
byte[] DBPathBytes = Encoding.ASCII.GetBytes(dbpath);
byte[] KeyPathBytes = Encoding.ASCII.GetBytes(keypath);
var ioConnection = IOConnectionInfo.FromByteArray(DBPathBytes);
var compositeKey = new CompositeKey();
compositeKey.AddUserKey(new KcpPassword(masterpw)); // Password
compositeKey.AddUserKey(new KcpKeyFile(IOConnectionInfo.FromByteArray(KeyPathBytes))); // Keyfile
var db = new PwDatabase();
db.Open(ioConnection, compositeKey, new NullStatusLogger());
var kpdata = from entry in db.RootGroup.GetEntries(true)
select new
{
Group = entry.ParentGroup.Name,
Title = entry.Strings.ReadSafe("Title"),
Username = entry.Strings.ReadSafe("UserName"),
Password = entry.Strings.ReadSafe("Password"),
URL = entry.Strings.ReadSafe("URL"),
Notes = entry.Strings.ReadSafe("Notes")
};
db.Save(new NullStatusLogger());
var contents = db.IOConnectionInfo.Bytes;
string bitString = BitConverter.ToString(contents);
Console.WriteLine(bitString);
Console.WriteLine(kpdata.ToString());
}
}
}
Those classes were moved into their own nuget package. Add it to your project and you should be good to go: https://www.nuget.org/packages/System.Drawing.Common/
From the project directory at the command line:
dotnet add package System.Drawing.Common
Closer inspection reveals ModernKeepPass targets.netstandard1.2 and will not work with 5's System.Drawing nuget package without being upgraded to target the new framework.
https://github.com/wismna/ModernKeePassLib/blob/master/ModernKeePassLib/ModernKeePassLib.csproj
<PropertyGroup>
<TargetFramework>netstandard1.2</TargetFramework>

SSIS script task not executing outside SSDT

I created a SSIS script task which reads data from excel sheets and saves it into different tables in SQL Server DB. When I execute the SSIS package inside Visual Studio SSDT it works fine.
When I am trying to execute my SSIS package from C# .NET code I get the following error.
Error in Microsoft.SqlServer.Dts.Runtime.TaskHost/Script Task : There was an exception while loading Script
Task from XML: System.Exception: The Script Task "ST_71d9425916264171ab93a0d340aad54d" uses version 14.0 script
that is not supported in this release of Integration Services. To run the package, use the Script task to create
a new VSTA script. In most cases, scripts are converted automatically to use a supported version,when you open a
SQL Server Integration Services packages in %SQL_Product_Short_Name% Integrtion Services.
I tried to change the deployment version by changing the TargetServerVersion to SQL server 2016 but I still get the same error.
Here is my code to execute the package.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using System.Data.SqlClient;
using Microsoft.SqlServer.Dts.Runtime;
namespace Execute_DriverImpact
{
class MyEventListener : DefaultEvents
{
public override bool OnError(DtsObject source, int errorCode, string subComponent,
string description, string helpFile, int helpContext, string idofInterfaceWithError)
{
// Add application-specific diagnostics here.
Console.WriteLine("Error in {0}/{1} : {2}", source, subComponent, description);
return false;
}
}
class Program
{
static void Main(string[] args)
{
// The code provided will print ‘Hello World’ to the console.
// Press Ctrl+F5 (or go to Debug > Start Without Debugging) to run your app.
//Console.WriteLine("Hello World!");
//Console.ReadKey();
//ExecuteSSIS exec = new ExecuteSSIS();
//exec.ExePackage();
//ExecuteSSIS2 exec = new ExecuteSSIS2();
//exec.ExePackage2();
string pkgLocation;
Package pkg;
Application app;
DTSExecResult pkgResults;
MyEventListener eventListener = new MyEventListener();
pkgLocation =
#"D:\Driver_Impact\Driver_Impact\Package.dtsx";
app = new Application();
pkg = app.LoadPackage(pkgLocation, eventListener);
pkgResults = pkg.Execute(null, null, eventListener, null, null);
Console.WriteLine(pkgResults.ToString());
Console.ReadKey();
}
}
}
Tech Stack
Visual Studio 2017 with SSDT
SQL server 2016

Edit and Continue doesn't work with Roslyn compiled class library

Background
I'm trying to get Edit and Continue to work with a class library I'm compiling at runtime using Roslyn. This is for adding modding support to a game I'm developing.
Breakdown of problem
I have one class library project (A) with source files (.cs)
I have another console application project (B) in another solution that does the following:
Compiles all of project A's source files
Emits a dll and pdb
Loads the emitted dll and pdb via an assembly context
Calls a static method defined within project B
My desire is to be able to attach a debugger to a running process of project B in an instance of VS with project A loaded and be able to break, edit project A's code, and continue with my changes being executed
Currently, I am only able to break and continue
Any edits lead to the following notification:
This source file has changed. It no longer matches the version of the file used to build the application being debugged.
Source
Project A: DebuggableClassLibrary.csproj
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net5.0</TargetFramework>
</PropertyGroup>
</Project>
Project A: Test.cs
using System;
namespace DebuggableClassLibrary
{
public class Test
{
public static int Ct = 0;
public static void SayHello()
{
Ct++;
Console.WriteLine("Hello World");
}
}
}
Project B: DynamicLoading.csproj
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>net5.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.CodeAnalysis.CSharp" Version="3.8.0" />
</ItemGroup>
</Project>
Project B: Program.cs
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.Emit;
using System;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.Loader;
using System.Text;
namespace DynamicLoading
{
class Program
{
static void Main(string[] args)
{
var references = new MetadataReference[]
{
MetadataReference.CreateFromFile(Assembly.Load("System.Runtime").Location),
MetadataReference.CreateFromFile(typeof(object).Assembly.Location),
MetadataReference.CreateFromFile(typeof(Console).Assembly.Location)
};
var files = Directory.GetFiles(#"C:\Users\mrbri\source\repos\DebuggableClassLibrary\DebuggableClassLibrary", "*.cs");
var assemblyName = "DebuggableClassLibrary.dll";
var debug = true;
var allowUnsafe = false;
var outputDirectory = #"C:\Users\mrbri\Documents\Test";
var preprocessorSymbols = debug ? new string[] { "DEBUG" } : new string[] { };
var parseOptions = new CSharpParseOptions(LanguageVersion.Latest, preprocessorSymbols: preprocessorSymbols);
var compilation = CSharpCompilation.Create(
assemblyName: assemblyName,
syntaxTrees: files.Select(f => SyntaxFactory.ParseSyntaxTree(File.ReadAllText(f), parseOptions, f, Encoding.UTF8)),
references: references,
options: new CSharpCompilationOptions(
OutputKind.DynamicallyLinkedLibrary,
assemblyIdentityComparer: DesktopAssemblyIdentityComparer.Default,
optimizationLevel: debug ? OptimizationLevel.Debug : OptimizationLevel.Release,
allowUnsafe: allowUnsafe
));
var pePath = Path.Combine(outputDirectory, assemblyName);
var pdbPath = Path.Combine(outputDirectory, Path.ChangeExtension(assemblyName, ".pdb"));
using (var peStream = new FileStream(pePath, FileMode.Create))
using (var pdbStream = new FileStream(pdbPath, FileMode.Create))
{
var results = compilation.Emit(
peStream: peStream,
pdbStream: pdbStream,
options: new EmitOptions(debugInformationFormat: DebugInformationFormat.PortablePdb)
);
}
var assemblyLoadContext = new SimpleUnloadableAssemblyLoadContext();
var assembly = assemblyLoadContext.LoadFromStream(File.OpenRead(pePath), File.OpenRead(pdbPath));
var type = assembly.GetTypes().First();
var method = type.GetMethod("SayHello");
while (true)
{
method.Invoke(null, null);
}
}
}
internal class SimpleUnloadableAssemblyLoadContext : AssemblyLoadContext
{
public SimpleUnloadableAssemblyLoadContext(): base(true) { }
protected override Assembly Load(AssemblyName assemblyName) => null;
}
}
Attempts at solutions and observations
Compiling project A manually through VS and loading the generated pdb and dll exactly as I do for the Roslyn compiled one does allow for Edit and Continue
Comparing project A's dlls generated via Roslyn and VS in JetBrains dotPeek did yield some interesting differences that stem from the compilation time generated .NETCoreApp,Version=v5.0.AssemblyAttributes.cs and DebuggableClassLibrary.AssemblyInfo.cs that I do not include when I compile in project B
Going through the trouble of compiling project A via a MSBuildWorkspace Project did not allow Edit and Continue, although did include .NETCoreApp,Version=v5.0.AssemblyAttributes.cs and DebuggableClassLibrary.AssemblyInfo.cs
Alternatives
I am open to Roslyn alternatives/wrappers that do have Edit and Continue support.
Edit and Continue does not support this scenario. The project for the library being edited needs to be loaded in VS (in the current solution) and the program needs to be launched with the debugger attached.

System.MissingMethodException after upgrading from EF 6.0 Beta to RC

what does this mean?
System.MissingMethodException was unhandled by user code
HResult=-2146233069 Message=Method not found:
'System.Data.Entity.ModelConfiguration.Configuration.PrimitivePropertyConfiguration
System.Data.Entity.ModelConfiguration.Configuration.StructuralTypeConfiguration1.Property(System.Linq.Expressions.Expression12<!0,!!0>>)'.
Source=Att.Uds.DataLayerMappings StackTrace:
at Att.Uds.DataLayerMappings.ItemTypeItemConfiguration..ctor()
at Att.Uds.DataLayerMappings.UdsContext.OnModelCreating(DbModelBuilder
modelBuilder) in
c:\TFS\ATS-MSDev\UDS\Dev\Code\Att.Uds.DataLayerMappings\UdsContext.cs:line
163
at System.Data.Entity.DbContext.CallOnModelCreating(DbModelBuilder
modelBuilder)
at System.Data.Entity.Internal.LazyInternalContext.CreateModelBuilder()
at System.Data.Entity.Internal.LazyInternalContext.CreateModel(LazyInternalContext
internalContext)
at System.Data.Entity.Internal.RetryLazy2.GetValue(TInput input) InnerException:
Error happens on this class:
namespace Contoso.Fabrikam.DataLayerMappings
{
public abstract class NamedEntityConfiguration<TEntity> : EntityBaseConfiguration<TEntity> where TEntity : NamedEntity
{
public ConfigurationColumn NameColumn;
protected new int LastOrdinalPosition
{
get
{
return (NameColumn.Ordinal);
}
}
public NamedEntityConfiguration() <=== EXCEPTION HERE
{
NameColumn = new ConfigurationColumn() { Ordinal = base.LastOrdinalPosition+1, Name = "Name", IsRequired = true, Length = 128 };
this.Property(t => t.Name)
.HasColumnName(NameColumn.Name)
.HasColumnOrder(NameColumn.Ordinal)
.HasMaxLength(NameColumn.Length);
if(NameColumn.IsRequired)
{
this.Property(t => t.Name).IsRequired();
}
}
}
}
Thank you
The reason why #Saber his answer works is because when you upgrade your project to a higher .NET Version, the project file is not upgraded automatically. For example, if you upgrade from .NET 4.0 to .NET 4.5 and edit the project file, you might see the following:
<Reference Include="EntityFramework">
<HintPath>..\packages\EntityFramework.6.1.3\lib\net40\EntityFramework.dll</HintPath>
</Reference>
<Reference Include="EntityFramework.SqlServer">
<HintPath>..\packages\EntityFramework.6.1.3\lib\net40\EntityFramework.SqlServer.dll</HintPath>
</Reference>
You will have to change the reference to net45 instead of net40. When removing the packages, this will produce the same behaviour.
I've encountered same error.
It worked for me:
Uninstall-Package EntityFramework in Package Manager Console
Delete EntityFramework folder from 'packages' folder
Install-Package EntityFramework in Package Manager Console
In my case I had to remove the EntityFramework.dll from this folder:
C:\Windows\Microsoft.NET\assembly\GAC_MSIL\EntityFramework

Categories