Failed To Create Assembly in MS SQL SERVER - c#

I am trying to implement routing funcationality in MS SQL Server 2012 using the prospatial tutorial, I created a C# class and successfully build DLL file.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SqlServer.Server;
using Microsoft.SqlServer.Types;
namespace ProSQLSpatial.Ch14
{
public partial class UserDefinedFunctions
{
[Microsoft.SqlServer.Server.SqlFunction]
public static SqlGeometry GeometryTSP(SqlGeometry PlacesToVisit)
{
// Convert the supplied MultiPoint instance into a List<> of SqlGeometry points
List<SqlGeometry> RemainingCities = new List<SqlGeometry>();
// Loop and add each point to the list
for (int i = 1; i <= PlacesToVisit.STNumGeometries(); i++)
{
RemainingCities.Add(PlacesToVisit.STGeometryN(i));
}
// Start the tour from the first city
SqlGeometry CurrentCity = RemainingCities[0];
// Begin the geometry
SqlGeometryBuilder Builder = new SqlGeometryBuilder();
Builder.SetSrid((int)PlacesToVisit.STSrid);
Builder.BeginGeometry(OpenGisGeometryType.LineString);
// Begin the LineString with the first point
Builder.BeginFigure((double)CurrentCity.STX, (double)CurrentCity.STY);
// We don't need to visit this city again
RemainingCities.Remove(CurrentCity);
// While there are still unvisited cities
while (RemainingCities.Count > 0)
{
RemainingCities.Sort(delegate(SqlGeometry p1, SqlGeometry p2)
{ return p1.STDistance(CurrentCity).CompareTo(p2.STDistance(CurrentCity)); });
// Move to the closest destination
CurrentCity = RemainingCities[0];
// Add this city to the tour route
Builder.AddLine((double)CurrentCity.STX, (double)CurrentCity.STY);
// Update the list of remaining cities
RemainingCities.Remove(CurrentCity);
}
// End the geometry
Builder.EndFigure();
Builder.EndGeometry();
// Return the constructed geometry
return Builder.ConstructedGeometry;
}
};
}
I also enabled CLR and when I try to create a assembly using the above created DLL:
CREATE ASSEMBLY GeometryTSP
FROM 'D:\Routing\my example\GeometryTSP\GeometryTSP\bin\Debug\GeometryTSP.dll'
WITH PERMISSION_SET = EXTERNAL_ACCESS;
GO
I'm getting "Failed to create AppDomain" error like this:
Msg 6517, Level 16, State 1, Line 2
Failed to create AppDomain "master.dbo[ddl].12".
Exception has been thrown by the target of an invocation.
What should be the reason?

try remove the neamespace section
namespace ProSQLSpatial.Ch14
{
}
sql server use default namespace

After Some research i found the solution,
its the problem with a system restart after .NET framework installation

Related

Do I need to install the same reference/dependencies across multiple namespaces to solve this FileNotFound exception? (C#)

I'm following along with a Tim Corey tutorial on making a Tournament Tracker WinForm app (this one at this point, in case it helps - https://preview.tinyurl.com/yxmyz8h6)
I've gotten to the point where we are starting to hook up the class library to SQL using some NuGet packages - namely Dapper, System.Data.SqlClient & System.Configuration.ConfigurationManager.
So far the project is split across two namespaces, the class library that holds all the models and data access classes (TrackerLibrary) & the form UI (TrackerUI). I was under the impression from the tutorial that these references only need to exist in the class library and not in the UI (as TrackerLibrary is where Tim directed us to add them)
But without them referenced in the TrackerUI - a FileNotFoundException shows up for all three when you run the code. However, that doesn't happen to him in the tutorial.
The SQL connection string is set up in the App.Config file of the TrackerUI and looks like this...
<connectionStrings>
<add name="Tournaments"
connectionString="Server=localhost;Database=TournamentTracker;Trusted_Connection=True;"
providerName="System.Data.SqlClient"/>
</connectionStrings>
There is a class in TrackerUI called CreatePrizeForm that has a button click method to validate the form a user completes and then turn that data into a model and pass that model into SQL...
using System;
using System.Windows.Forms;
using TrackerLibrary;
using TrackerLibrary.Models;
namespace TrackerUI
{
public partial class CreatePrizeForm : Form
{
public CreatePrizeForm()
{
InitializeComponent();
}
private void createPrizeButton_Click(object sender, EventArgs e)
{
if (ValidateForm())
{
PrizeModel model = new PrizeModel(
placeNameValue.Text,
placeNumberValue.Text,
prizeAmountValue.Text,
prizePercentageValue.Text);
GlobalConfig.Connection.CreatePrize(model);
placeNameValue.Text = "";
placeNumberValue.Text = "";
prizeAmountValue.Text = "0";
prizePercentageValue.Text = "0";
}
GlobalConfig class handles deciphering whether we are saving to SQL or saving to a Text File as per the imaginary client requirements for the tutorial and grabs the connection string, which looks like this...
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Text;
using TrackerLibrary.DataAccess;
using System.Data.SqlClient;
using Dapper;
public static class GlobalConfig
{
public static IDataConnection Connection { get; private set; }
public static void InitializeConnections(DatabaseType db)
{
if (db == DatabaseType.Sql)
{
SqlConnector sql = new SqlConnector();
Connection = sql;
}
else if (db == DatabaseType.TextFile)
{
TextConnector text = new TextConnector();
Connection = text;
}
}
public static string CnnString(string name)
{
return ConfigurationManager.ConnectionStrings[name].ConnectionString;
}
}
The IDataConnection interface looks like this...
using System;
using System.Collections.Generic;
using System.Text;
using TrackerLibrary.Models;
namespace TrackerLibrary.DataAccess
{
public interface IDataConnection
{
PrizeModel CreatePrize(PrizeModel model);
}
}
And the CreatePrize method looks like this...
using Dapper;
using System;
using System.Collections.Generic;
using System.Data;
using System.Text;
using TrackerLibrary.Models;
public class SqlConnector : IDataConnection
{
public PrizeModel CreatePrize(PrizeModel model)
{
using (IDbConnection connection = new
System.Data.SqlClient.SqlConnection(GlobalConfig.CnnString("Tournaments")))
{
var p = new DynamicParameters(); // Dapper object
p.Add("#PlaceNumber", model.PlaceNumber);
p.Add("#PlaceName", model.PlaceName);
p.Add("#PrizeAmount", model.PrizeAmount);
p.Add("#PrizePercentage", model.PrizePercentage);
p.Add("#id", 0, dbType: DbType.Int32, direction: ParameterDirection.Output);
connection.Execute("dbo.spPrizes_Insert", p, commandType: CommandType.StoredProcedure);
model.Id = p.Get<int>("#id");
return model;
}
The error occurs when the code reaches here...
GlobalConfig.Connection.CreatePrize(model);
With the following exception...
System.IO.FileNotFoundException: 'Could not load file or assembly 'System.Data.SqlClient, Version=4.6.1.2, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. The system cannot find the file specified.'
When I installed the System.Data.SqlClient NuGet package into the TrackerUI's references - it errors at the same point as before but this time it talks about Dapper...
System.IO.FileNotFoundException: 'Could not load file or assembly 'Dapper, Version=2.0.0.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. The system cannot find the file specified.'
Then if you then install Dapper into TrackerUI references, it gets past the GlobalConfig.Connection.CreatePrize call into SqlConnector.cs and errors on the using (IDbConnection connection = new System.Data.SqlClient.SqlConnection... line below...
using Dapper;
using System;
using System.Collections.Generic;
using System.Data;
using System.Text;
using TrackerLibrary.Models;
namespace TrackerLibrary.DataAccess
{
public class SqlConnector : IDataConnection
{
public PrizeModel CreatePrize(PrizeModel model)
{
using (IDbConnection connection = new System.Data.SqlClient.SqlConnection(GlobalConfig.CnnString("Tournaments")))
{
var p = new DynamicParameters(); // Dapper object
p.Add("#PlaceNumber", model.PlaceNumber);
p.Add("#PlaceName", model.PlaceName);
p.Add("#PrizeAmount", model.PrizeAmount);
p.Add("#PrizePercentage", model.PrizePercentage);
p.Add("#id", 0, dbType: DbType.Int32, direction: ParameterDirection.Output);
connection.Execute("dbo.spPrizes_Insert", p, commandType: CommandType.StoredProcedure);
model.Id = p.Get<int>("#id"); //Pulls ID from the p variable that represents the id of the record in the database
return model;
}
With another FileNotFoundException...
System.IO.FileNotFoundException: 'Could not load file or assembly 'System.Configuration.ConfigurationManager, Version=4.0.3.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51' or one of its dependencies. The system cannot find the file specified.'
Adding references within the TrackerUI namespace to Dapper, System.Data.SqlClient and System.Configuration.ConfigurationManager resolves the exceptions and enables the program to write to SQL no problem. I just wanted to clear up whether that was what I needed to do by default or whether I've missed something earlier and the TrackerUI namespace shouldn't feature references to them. Just don't want to get into bad habits.
Sorry if I've missed any important detail - kinda new to this and have tried to be as thorough as possible but let me know if there is anything else I need to provide.
Thank you for your clarification and help in advance!

Linq and localhost, entity namespace is different than program namespace but still get error

I have tried to search for this but every example I find has a problem like them actually having the same namespace as their class or something.
I am simply trying to start using Linq. When I add new item Host is localhost. I have my database in Visualstudio and my project name is different than the DataContext name but I can't get it initialized. I get error:
'LinkedContext' is a namespace but is used like a type'
here is code...
namespace TryAgain
{
class Program
{
static void Main(string[] args)
{
LinkedContext db = new LinkedContext();
}
}
}
LinkedContext doesn't work? In settings of the Database Diagram it says the Entity Namespace is 'LinkedContext' So what am I missing. I thought I saw you could run that one line of code to connect your database that is already in VisualStudio due to adding a new item and then start playing with it? I just want to be able to practice with a database! Do stuff like:
var example = from x in example.Table
orderby x.field
select x;
you need using LinkedContext at the top of your file. the error you’re getting is telling you LinkedContext is a namespace but you’re treating like a type, ie a class. once you define it at the top you can then use the type that you need within that namespace.
added "using LinkedContext" to the top of code then also had to use LinkedDataContext not just LinkedContext:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using LinkedContext;
namespace TryAgain
{
class Program
{
static void Main(string[] args)
{
LinkedDataContext db = new LinkedDataContext();
var example = from x in db.employees
orderby x.employee_id
select x;
foreach (var whatever in example)
{
Console.WriteLine(whatever.name);
}

fakeXrmEasy for crm testing initialization issues

I'm trying to follow the basic tutorial for FakeXrmEasy, but I'm not sure why I'm getting errors. I installed everything that needs to be installed to mock Dynamics 365, but I'm still getting errors. I can't figure out what I'm missing, I really want to be able to use this tool.
CS1950 The best overloaded Add method 'List.Add(Entity)' for the collection initializer has some invalid arguments unitTest c:\Users\acapell\documents\visual studio 2015\Projects\unitTest\unitTest\Program.cs 48 Active
CS0246 The type or namespace name 'Account' could not be found (are you missing a using directive or an assembly reference?) unitTest c:\Users\acapell\documents\visual studio 2015\Projects\unitTest\unitTest\Program.cs 45 Active
Didn't know if I was suppose to create an account class, I also tried that but that didn't work either. I got
CS1503 Argument 1: cannot convert from 'unitTest.Account' to 'Microsoft.Xrm.Sdk.Entity' unitTest c:\Users\acapell\documents\visual studio 2015\Projects\unitTest\unitTest\Program.cs 48 Active
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xunit;
using FakeItEasy;
using FakeXrmEasy;
using Microsoft.Xrm.Sdk;
namespace unitTest
{
class Program
{
static void Main(string[] args)
{
}
}
class unitTest
{
public object ProxyTypesAssembly { get; private set; }
public void MyFirstTest()
{//test method body
var context = new XrmFakedContext();
//You can think of a context like an Organisation database which stores entities In Memory.
//We can also use TypedEntities but we need to tell the context where to look for them,
//this could be done, easily, like this:
context.ProxyTypesAssembly = Assembly.GetAssembly(typeof(Account));
//We have to define our initial state now,
//by calling the Initialize method, which expects a list of entities.
var account = new Account() { Id = Guid.NewGuid(), Name = "My First Faked Account yeah!" };
context.Initialize(new List<Entity>() {
account
});
}
}
}
Do you use early binding in your CRM project and got the references right? If you do not use early binding, you can try late binding, e.g.
//context.ProxyTypesAssembly = Assembly.GetAssembly(typeof(Account));
var account = new Entity();
account.LogicalName = "account";
account.Attributes["name"] = "your account name";

C# Windows Service - this keyword error

I have the following code which works fine when I use it within a Windows Forms application, however the application I'm writing needs to run as a Windows service, and when I moved my code into the Windows Service template in Visual Studio 2015 Community Edition, I get the following error.
Cannot implicitly convert type "MyWindowsService.Main" to "System.ComponentModel.ISynchronizeVoke". An explicit conversion exists (are you missing a cast?)
Could anyone shed some light on why I am getting this error, and what I need to do to resolve it?
The code which throws the error is the line below, and it is located within the OnStart method of my main class (named Main.cs). The code is used to create an instance of the DataSubscriber class (AdvancedHMI library).
dataSubscribers[dataSubscriberIndex].SynchronizingObject = this;
It has to have something to do with the fact that the code is in a Windows service template, because using this works perfectly in my forms application running the same code.
UPDATE
Correction, I've attempted to cast this to the required type, and now get the following error on run.
Additional information: Unable to cast object of type 'MyWindowsService.Main' to type 'System.ComponentModel.ISynchronizeInvoke'.
Code:
dataSubscribers[dataSubscriberIndex].SynchronizingObject = (System.ComponentModel.ISynchronizeInvoke)this;
UPDATE
I've included the entire contents of the Main.cs file from my Windows Service application.
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;
using MySql.Data.MySqlClient;
using AdvancedHMIDrivers;
using AdvancedHMIControls;
using MfgControl.AdvancedHMI.Drivers;
using MfgControl.AdvancedHMI.Controls;
using System.Collections.ObjectModel;
namespace PLCHistoricDataHarvester {
public partial class Main : ServiceBase {
private EthernetIPforCLXCom commObject = new EthernetIPforCLXCom();
private globals globals = new globals();
private Dictionary<String, String> operationLines = new Dictionary<String, String>();
private Dictionary<String, String> tags = new Dictionary<String, String>();
private Collection<DataSubscriber> dataSubscribers = new Collection<DataSubscriber>();
private int harvesterQueueCount = 0;
private string harvesterInsertValues = String.Empty;
public Main() {
InitializeComponent();
}
protected override void OnStart(string[] args) {
// Initialize our harvester program
initializeHarvester();
Console.WriteLine("The program has started");
}
protected override void OnStop() {
// Call code when the service is stopped
Console.WriteLine("Program has stopped");
Console.ReadLine();
}
public void initializeHarvester() {
// First, we connect to the database using our global connection object
globals.dbConn.DatabaseName = "operations";
if (!globals.dbConn.IsConnect()) {
// TODO: Unable to connect to database. What do we do?
}
// Second, we connect to the database and pull data from the settings table
globals.initializeSettingsMain();
// Set IP address of PLC
commObject.IPAddress = globals.getSettingsMain("Processor_IP");
// Pull distinct count of our parent tags (Machines ex: Line 1, etc)
operationLines = globals.getOperationLines();
// If we have at least 1 operation line defined...we continue
if (operationLines.Keys.Count > 0) {
//Now we loop over the operation lines, and pull back the data points
int dataSubscriberIndex = 0;
foreach (KeyValuePair<String, String> lines in operationLines) {
int line_id = int.Parse(lines.Key);
string name = lines.Value;
tags = globals.getTags(line_id);
// If we have at least 1 tag for this operation line, we continue...
if (tags.Keys.Count > 0 && tags["tags"].ToString().IndexOf(",") != -1) {
// Create our dataSubscriber object
dataSubscribers.Add(new DataSubscriber());
dataSubscribers[dataSubscriberIndex].SynchronizingObject = (ISynchronizeInvoke)this;
dataSubscribers[dataSubscriberIndex].CommComponent = commObject;
dataSubscribers[dataSubscriberIndex].PollRate = 1000;
dataSubscribers[dataSubscriberIndex].PLCAddressValue = tags["tags"];
dataSubscribers[dataSubscriberIndex].DataChanged += new EventHandler<MfgControl.AdvancedHMI.Drivers.Common.PlcComEventArgs>(subscribeCallback);
// Increment our dataSubscriberIndex
dataSubscriberIndex++;
}
}
}
}
private void subscribeCallback(object sender, MfgControl.AdvancedHMI.Drivers.Common.PlcComEventArgs e) {
// code removed as it is irrelevant
}
}
}
The error message says this:
An explicit conversion exists (are you missing a cast?)
So add a cast like this:
dataSubscribers[dataSubscriberIndex].SynchronizingObject = (ISynchronizeInvoke)this;
^^^^^^^^^^^^^^^^^^^^
//Add this
If you've got a console app, the easiest way to convert it to a windows service is by using Topshelf, a nuget package which lets you run in either console mode or nt service mode.
Here's the quickstart guide.
We use it to write services all the time and it helps you avoid this kind of fragile shenanigans.

Why can't I read a db4o file created by a Java app in a C# app?

I have a db4o database that was generate by a Java app and I'm trying to read it using a C# app.
However, when running the following line of code:
IObjectContainer db = Db4oEmbedded.OpenFile(#"..\..\..\Databases\people.db4o");
I get the following error:
Unable to cast object of type
'Db4objects.Db4o.Reflect.Generic.GenericObject' to type
'Db4objects.Db4o.Ext.Db4oDatabase'.
Any ideas? I know there are person objects that contain personId fields (along with others) in the DB. I'm using db4o version 8. I'm not sure what version was used to generate the database.
The entire program is:
using System;
using System.Collections.Generic;
using System.Linq;
using Db4objects.Db4o;
using Db4objects.Db4o.Config;
using MyCompany.Domain;
namespace MyCompany.Anonymizer
{
internal class Program
{
// Private methods.
private static IEmbeddedConfiguration ConfigureAlias()
{
IEmbeddedConfiguration configuration = Db4oEmbedded.NewConfiguration();
configuration.Common.AddAlias(new TypeAlias("com.theircompany.Person", "MyCompany.Domain.Person, MyCompany.Domain"));
configuration.Common.Add(new JavaSupport());
return configuration;
}
private static void Main(string[] args)
{
IObjectContainer db = Db4oEmbedded.OpenFile(#"..\..\..\Databases\people.db4o");
try
{
IList<Person> result = db.Query<Person>();
for (int i = 0; i < result.Count; i++)
{
Person person = result[i];
Console.WriteLine(string.Format("Person ID: {0}", person.personId));
}
}
finally
{
db.Close();
}
}
}
}
The most common scenario in which this exception is thrown is when db4o fails to resolve the type of a stored object.
In your case, db4o is failing to read one of its internal objects which makes me believe you have not passed the configuration to the OpenFile() method (surely, the code you have posted is not calling ConfigureAlias() method);
Keep in mind that as of version 8.0 no further improvement will be done regarding cross platform support (you can read more details here).

Categories

Resources