System.accessviolationexception in nunit test - c#

I'm using Visual Studio 2012 / C# with nUnit test, and get System.AccessViolationException on simple test...
When I launch the "Execute Test" option, the test returns OK.
When I launch the "Debug Test" option, I get System.AccessViolationException.
Screen Capture of the Exception - Sorry french one !
Adding "break on all exceptions" option, I get this (again, sorry, french) :
L'assembly nommé 'nunit.engine.api' a été chargé à partir de
'file:///C:/USERS/ALAIN/APPDATA/LOCAL/MICROSOFT/VISUALSTUDIO/11.0/EXTENSIONS/CZBUZRPC.SXP/nunit.engine.api.DLL'
à l'aide du contexte LoadFrom. L'utilisation de ce contexte peut provoquer un
comportement inattendu lors des opérations de sérialisation, de conversion et de
résolution de dépendance. Dans la grande majorité des cas, il est recommandé
d'éviter le contexte LoadFrom. Pour ce faire, il suffit d'installer les assemblys
dans le Global Assembly Cache ou dans le répertoire ApplicationBase et d'utiliser
Assembly.Load lors du chargement explicite des assemblys.
I think something in my config is not good. I'm pretty sure the source is good and has no hidden bug.
Any help will help.
Here is the code :
Class1.cs
using System;
namespace ClassLibrary1
{
public class Class1
{
public String test = "1";
public Class1()
{
}
public void Test()
{
test = "2";
}
}
}
UnitTest1.cs
using ClassLibrary1;
using NUnit.Framework;
namespace UnitTestProject1
{
[TestFixture]
public class UnitTest1
{
[Test]
public void TestMethod1()
{
Class1 classe = new Class1();
Assert.AreEqual(classe.test, "1");
classe.Test();
Assert.AreEqual(classe.test, "2");
}
}
}

Related

What could cause a deserialization in a deployed service to fail while it succeeds localy?

I added a second method to my WCF service. It essentially does the same job as the other one except that it receives an xml document, deserialise it, and call the other method. It works perfectly locally, my XML is deserialized and the call succeeds. However, now that I have deployed it on my on-premise server, the call returns a 500 error because the deserialization failed.
My XML document has namespaces associated with every node, the root, and sub-root element have the "ns1" et all the others "ns2" prefix. To do the deserialization I (for now at least) hardcoded the namespaces for each node.
The troncated xml document:
<ns1:ValiderEtEnrichirGlobalEchangePartage
xmlns:ns1="API:WebApi"
xmlns:ns0="http://www.ra.fr/API/Transport/"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<ns1:messageGlobal>
<ns0:AuteurEchange>...</ns0:AuteurEchange>
<ns0:Documents>
<ns0:DocumentEchangePartage>...</ns0:DocumentEchangePartage>
</ns0:Documents>
<ns0:ExpediteurEchange>...</ns0:ExpediteurEchange>
</ns1:messageGlobal>
</ns1:ValiderEtEnrichirGlobalEchangePartage>
The deserialising process in the service's method:
public GlobalEchangePartageValide ValiderEtEnrichirGlobalEchangePartageXML(string xmlMessageGlobal)
{
XmlRootAttribute xroot = new XmlRootAttribute();
xroot.ElementName="ValiderEtEnrichirGlobalEchangePartage";
xroot.Namespace="API:WebApi";
XmlSerializer serializer = new XmlSerializer(typeof(ValiderEtEnrichirGlobalEchangePartage),xroot );
StringReader stringReader = new StringReader(xmlMessageGlobal);
ValiderEtEnrichirGlobalEchangePartage messageGlobal = (ValiderEtEnrichirGlobalEchangePartage)serializer.Deserialize(stringReader);
return ValiderEtEnrichirGlobalEchangePartage(messageGlobal.GlobalEchangePartage);
}
The class coresponding to the xml root element:
[XmlRootAttribute("ValiderEtEnrichirGlobalEchangePartage")]
public class ValiderEtEnrichirGlobalEchangePartage
{
[XmlElement(ElementName=("messageGlobal"))]
public GlobalEchangePartage GlobalEchangePartage { get; set; }
}
The class of xml sub root element:
[DataContract(Namespace = NamespacesConstantes.NAMESPACE_TRANSPORT)]
public class GlobalEchangePartage
{
[DataMember]
[XmlElement(ElementName = ("AuteurEchange"), Namespace = "http://www.ra.fr/API/Transport/")]
public Auteur AuteurEchange { get; set; }
[DataMember]
[XmlElement(ElementName = ("ExpediteurEchange"), Namespace = "http://www.ra.fr/API/Transport/")]
public Auteur ExpediteurEchange { get; set; }
[DataMember]
[XmlArray(ElementName="Documents", Namespace = "http://www.ra.fr/API/Transport/")]
[XmlArrayItem("DocumentEchangePartage")]
public List<DocumentEchangePartage> Documents { get; set; }
}
The error I get is in French very ambiguous but can be approximatively translated by :
WCF error : System.ServiceModel.Dispatcher.NetDispatcherFaultException: The formatting module generated an exception when trying to deserialize the
message: an error occurred when trying to deserialize the
API:WebApi:xmlMessageGlobal parameter. The InnerException message was 'An
error occurred when deserializing the System.String object. Ending (TN :
last /final ) element 'xmlMessageGlobal' from the namespace 'API:WebApi'
expected. Found element 'ns1:ValiderEtEnrichirGlobalEchangePartage' from the
namespace "API:WebApi'.
Original :
WCF error : System.ServiceModel.Dispatcher.NetDispatcherFaultException: Le
module de formatage a généré une exception en tentant de désérialiser le
message : Une erreur s'est produite en tentant de désérialiser le paramètre
API:WebApi:xmlMessageGlobal. Le message InnerException était 'Une
erreur s'est produite lors de la désérialisation de l'objet de type
System.String. Élément de fin 'xmlMessageGlobal' provenant de l'espace de
noms 'API:WebApi' attendu. Trouvé élément
'ns1:ValiderEtEnrichirGlobalEchangePartage' provenant de l'espace de noms
'API:WebApi'.'.
Notice how it says that 'xmlMessageGlobal' is expected in the XML document while it is the variable's name ...
Thanks (for reading) a lot !
PS : If the French error message could be put in something that collapses it, I would appreciate, i didn't find a way to do it.
The problem encountered was indeed a deserialization problem. However, it wasn't about the piece of code I had written, it was when the string parameter was beeing received. Because my xml doc was an wrapped in another xml document (the request) there was issues in the processing. By base64 encoding my XML in my Logic App, and decoding it in the service i was able to fix the deserialization issue.
TLDR : be careful when you send xml through a String parameter.

Using DbContext (net core) in Windows Service via external dll

2 solutions in visual studio :
1 solution with 2 projects :
library
website ASP.NETCORE (api restful)
1 solution with 1 project :
Windows Services
I've added the dll and Microsoft.AspNetCore + Microsoft.EntityFrameworkCore
In my Windows Service :
var optionsBuilder = new DbContextOptionsBuilder<FidelityContext>();
optionsBuilder.UseSqlServer("Server=XXXXX;Database=XXXXXX;User Id=XXXXX;Password=XXXXX;MultipleActiveResultSets=True");
using (var context = new FidelityContext(optionsBuilder.Options))
{
// do stuff
}
Cause this error :
Log :
$exception {"Impossible de charger le fichier ou l'assembly 'System.Runtime, Version=4.2.0.0,
Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' ou une de ses
dépendances. La définition trouvée du manifeste de l'assembly ne
correspond pas à la référence de l'assembly. (Exception de HRESULT :
0x80131040)":"System.Runtime, Version=4.2.0.0, Culture=neutral,
PublicKeyToken=b03f5f7f11d50a3a"}
System.IO.FileLoadException
=== Informations d'état de liaison préalable ===
JRN : DisplayName = System.Runtime, Version=4.2.0.0, Culture=neutral,
PublicKeyToken=b03f5f7f11d50a3a
(Fully-specified)
JRN : Appbase = file:///C:/Users/Xavier/documents/visual studio
2017/Projects/SocietyServices/SocietyServices/bin/Debug/
JRN : PrivatePath initial = NULL
Assembly appelant : Core, Version=1.0.0.0, Culture=neutral,
PublicKeyToken=null.
===
JRN : cette liaison démarre dans le contexte de chargement de default.
JRN : utilisation du fichier de configuration de l'application :
C:\Users\Xavier\documents\visual studio
2017\Projects\SocietyServices\SocietyServices\bin\Debug\SocietyServices.exe.Config
JRN : utilisation du fichier de configuration d'hôte :
JRN : utilisation du fichier de configuration de l'ordinateur à partir
de
C:\Windows\Microsoft.NET\Framework\v4.0.30319\config\machine.config.
JRN : référence post-stratégie : System.Runtime, Version=4.2.0.0,
Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a
JRN : tentative de téléchargement de la nouvelle URL
file:///C:/Users/Xavier/documents/visual studio
2017/Projects/SocietyServices/SocietyServices/bin/Debug/System.Runtime.DLL.
AVT : la comparaison du nom de l'assembly a entraîné l'incompatibilité
: Version secondaire
ERR : impossible de terminer l'installation de l'assembly (hr =
0x80131040). Détection terminée.
Impossible de charger le fichier ou l'assembly 'System.Runtime,
Version=4.2.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' ou
une de ses dépendances. La définition trouvée du manifeste de
l'assembly ne correspond pas à la référence de l'assembly. (Exception
de HRESULT : 0x80131040)
à System.Signature.GetSignature(Void* pCorSig, Int32 cCorSig,
RuntimeFieldHandleInternal fieldHandle, IRuntimeMethodInfo
methodHandle, RuntimeType declaringType)
à System.Reflection.RuntimeMethodInfo.FetchNonReturnParameters()
à System.Reflection.RuntimeMethodInfo.GetParametersNoCopy()
à System.Reflection.RuntimePropertyInfo.GetIndexParametersNoCopy()
à System.Reflection.RuntimePropertyInfo.GetIndexParameters()
à
Microsoft.EntityFrameworkCore.Internal.DbSetFinder.<>c.b__2_0(PropertyInfo
p)
à System.Linq.Enumerable.WhereArrayIterator`1.MoveNext()
à System.Linq.Buffer1..ctor(IEnumerable1 source)
à System.Linq.OrderedEnumerable`1.d__1.MoveNext()
à System.Linq.Enumerable.WhereSelectEnumerableIterator`2.MoveNext()
à System.Linq.Buffer1..ctor(IEnumerable1 source)
à System.Linq.Enumerable.ToArray[TSource](IEnumerable`1 source)
à Microsoft.EntityFrameworkCore.Internal.DbSetFinder.FindSets(Type
contextType)
à
System.Collections.Concurrent.ConcurrentDictionary2.GetOrAdd(TKey
key, Func2 valueFactory)
à
Microsoft.EntityFrameworkCore.Internal.DbSetFinder.FindSets(DbContext
context)
à
Microsoft.EntityFrameworkCore.Internal.DbSetInitializer.InitializeSets(DbContext
context)
à Microsoft.EntityFrameworkCore.DbContext..ctor(DbContextOptions
options)
à
Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityDbContext`3..ctor(DbContextOptions
options)
à API360Plus.Model.Data.FidelityContext..ctor(DbContextOptions`1
options) dans
C:\Users\Xavier\Source\Workspaces\API3605\Main\Core\Model\Data\FidelityContext.cs:ligne
64
à SocietyServices.Society_GenerationAnniversaire.Traitement() dans
C:\Users\Xavier\documents\visual studio
2017\Projects\SocietyServices\SocietyServices\Society_GenerationAnniversaire.cs:ligne
90
à SocietyServices.Society_GenerationAnniversaire.T1_Elapsed(Object
sender, EventArgs e) dans C:\Users\Xavier\documents\visual studio
2017\Projects\SocietyServices\SocietyServices\Society_GenerationAnniversaire.cs:ligne
152
à System.Timers.Timer.MyTimerCallback(Object state)
I have my answer, it's because my library is in net core and not in net standard.
Now its work perfectly !

NHibernate MappingException

I have been interested in learning NHibernate, so i search a course, and i found one in Pluralsight, but when i go to follow the examples i get this exception and i don't know why i get this exception... and it's kind of annoying because where i search i can't find more info about the exception or an up-to-date guide of NHibernate. So my question is:
a) for the exception itself, why it occurs
b) if you can recommend me a site or a course or anything up to date to learn NHibernate.
Thanks in advance.
I leave the code here:
Customer.cs:
namespace NHibernateDemo
{
public class Customer
{
public virtual int Id { get; set; }
public virtual string FirstName { get; set; }
public virtual string LastName { get; set; }
}
}
Customer.hbm.xml:
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:hibernate-mapping-2.2"
assembly="NHibernateDemo"
namespace="NHibernateDemo">
<class name="Customer">
<id name="Id">
<generator class="native"/>
</id>
<property name="FirstName"/>
<property name="LastName"/>
</class>
</hibernate-mapping>
Program.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using NHibernate.Cfg;
using NHibernate.Dialect;
using NHibernate.Driver;
namespace NHibernateDemo
{
class Program
{
static void Main(string[] args)
{
var cfg = new Configuration();
cfg.DataBaseIntegration(x =>
{
x.ConnectionString = "Server=localhost;Database=NHibernateDemo;Integrated Security=SSPI;";
x.Driver<SqlClientDriver>();
x.Dialect<MsSql2008Dialect>();
});
// Here is where i get the MappingException. It says that it can't compile the Customer.hbm.xml file.
cfg.AddAssembly(Assembly.GetExecutingAssembly());
var sessionFactory = cfg.BuildSessionFactory();
using (var session = sessionFactory.OpenSession())
{
using (var tx = session.BeginTransaction())
{
var customers = session.CreateCriteria<Customer>()
.List<Customer>();
foreach (var customer in customers)
{
Console.WriteLine("{0} {1}", customer.FirstName, customer.LastName);
}
tx.Commit();
}
Console.WriteLine("Press <ENTER> to exit...");
Console.ReadLine();
}
}
}
}
Message of the exception:
"Could not compile the mapping document: NHibernateDemo.Customer.hbm.xml"
StackTrace:
NHibernate.MappingException: Could not compile the mapping document: NHibernateDemo.Customer.hbm.xml ---> System.InvalidOperationException: Error en el documento XML (1, 2). ---> System.InvalidOperationException: No se esperaba <hibernate-mapping xmlns='urn:hibernate-mapping-2.2'>.
en Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationReaderHbmMapping.Read109_hibernatemapping()
--- Fin del seguimiento de la pila de la excepción interna ---
en System.Xml.Serialization.XmlSerializer.Deserialize(XmlReader xmlReader, String encodingStyle, XmlDeserializationEvents events)
en System.Xml.Serialization.XmlSerializer.Deserialize(TextReader textReader)
en NHibernate.Cfg.NamedXmlDocument..ctor(String name, XmlDocument document, XmlSerializer serializer)
en NHibernate.Cfg.NamedXmlDocument..ctor(String name, XmlDocument document)
en NHibernate.Cfg.Configuration.LoadMappingDocument(XmlReader hbmReader, String name)
--- Fin del seguimiento de la pila de la excepción interna ---
en NHibernate.Cfg.Configuration.LogAndThrow(Exception exception)
en NHibernate.Cfg.Configuration.LoadMappingDocument(XmlReader hbmReader, String name)
en NHibernate.Cfg.Configuration.AddInputStream(Stream xmlInputStream, String name)
en NHibernate.Cfg.Configuration.AddResource(String path, Assembly assembly)
en NHibernate.Cfg.Configuration.AddAssembly(Assembly assembly)
en NHibernateDemo.Program.Main(String[] args) en d:\Sistema\Documents\Visual Studio 2015\Projects\NHibernateDemo\NHibernateDemo\Program.cs:línea 28
the problem is that it can't find the file to compile it, so :
try manually copying the file into your bin directory ( Debug or Release or .. )
make sure your NHibernateDemo.Customer.hbm.xml properties are Build Action : Embedded resource and Copy to Output Directory : Copy Always
if you still have the problem, try adding : cfg.AddFile("NHibernateDemo.Customer.hbm.xml") ( or the path to your hbm.xml file )
if you still have the problem, then try :
cfg.addFile(AssemblyLocation() + "NHibernateDemo.Customer.hbm.xml"); ( or the path to your hbm.xml file, where AssemblyLocation() is :
private string AssemblyLocation()
{
var codebase = new Uri(Assembly.GetExecutingAssembly().CodeBase);
return Path.GetDirectoryName(codebase.LocalPath);
}
cfg.AddAssembly isn't necessary so you might consider removing it if none of the above works :P
I found (thanks to Fréderic) that the problem was a line in the hbm.xml file. This line was the one that have make the problem occur: <hibernate-mapping xmlns="urn:hibernate-mapping-2.2". I forgot a 'n' in front of the 'hibernate' word and because of that it can't parse the file.
Thanks to Taki and Fréderic for the time.

Error CS0246 when launching C# web API

I am developing a WEB API 2 project and I am trying to set up a basic authentication system on my REST server.
I'm having issues with an error when I launch my application and I don't find the origin of this error.
Class code :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http;
namespace CalypsoWebApplication.App_Code
{
public class ResultWithChallenge : IHttpActionResult
{
private readonly System.Web.Http.IHttpActionResult next;
public ResultWithChallenge(IHttpActionResult next)
{
this.next = next;
}
public async Task<HttpResponseMessage> ExecuteAsync(
CancellationToken cancellationToken)
{
var res = await next.ExecuteAsync(cancellationToken);
if (res.StatusCode == HttpStatusCode.Unauthorized)
{
res.Headers.WwwAuthenticate.Add(
new AuthenticationHeaderValue("Basic", null));
}
return res;
}
}
}
Erreur au lancement :
Message d'erreur du compilateur: CS0246: Le type ou le nom d'espace de noms 'HttpResponseMessage' est introuvable (une directive using ou une référence d'assembly est-elle manquante ?)
English translation : type or namespace 'HttpResponseMessage' cannot be found, is a using directive or an assembly reference missing ?
Erreur source:
Ligne 22 : }
Ligne 23 :
Ligne 24 : public async Task ExecuteAsync(
Ligne 25 : CancellationToken cancellationToken)
Ligne 26 : {
Fichier source: e:\Users\mehin\Documents\Visual Studio 2013\Projects\Calypso\CalypsoWebApplication\App_Code\ResultWithChallenge.cs Ligne: 24
Whe looking on https://msdn.microsoft.com/fr-fr/library/w7xf6dxs.aspx the possibles sources of this error, I still don't understand why it happens.
Target Framework .NET 4.5
In my project references, I have "System.Net.Http" which targets System.NetNHttp.dll, version 4.0.0.0
When trying to prefix HttpResponseMessage with System.Net.http, the error still occurs.
When cleaning and building my solution in Visual Studio 2013, I don't get any error. I only get it when i launch the application.
I don't know what else I could add, don't hesitate to ask for more details.

Winsock instance exception

I'm trying to use MSWinSock in C# 2008, but it doen't work.
I keep on getting this Exception:
System.Runtime.InteropServices.COMException (0x80040112): Het maken van een exemplaar van het COM-onderdeel met CLSID {248DD896-BB45-11CF-9ABC-0080C7E7B78D} uit de IClassFactory is mislukt door de volgende fout: 80040112.
I use this as my code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using MSWinsockLib;
using Info.Kernel.Logging;
namespace InfoEmu.Kernel.OldSock
{
public class WinSockListener
{
private WinsockClass Winsock;
private WinsockClass[] Clients = new WinsockClass[1000];
public WinSockListener(int port)
{
try
{
Winsock = new WinsockClass();
Winsock.LocalPort = port;
Winsock.Listen();
}
catch (Exception e)
{
Cout.WriteLine("[ERROR!] {0} {1}", Environment.NewLine, e);
}
}
}
}
I've looked for a long time without good solution. Please help.
0x80040112 CLASS_E_NOTLICENSED "Class is not licensed for use". The error suggests that COM class requires a design-time license. See details here: Licensing ActiveX Controls - Design-Time Licensing. That is you need either a license for this control, or an alternate (and perhaps a better) solution to implement sockets.

Categories

Resources