I'm a fairly new C# Programmer, and I've run into an error beyond my ability to fix.
Currently I'm working on coding a discord bot, and upon trying to instantiate and Program object, it returns an "Access is denied error".
The issue is that the error is referring to a folder, not a file and I've tried a bunch of stuff to fix it.
Running Visual Studio as administrator
Ensuring my account has permissions to access the files and folder
Changing the location of the project files
Restarting visual Studio
Recoding the project off a clean sheet
Ensuring the folder and files are not "Read Only"
The error is thrown at this line: => new Program().MainAsync().GetAwaiter().GetResult();
I'm basically out of ideas at this point. The full details of the exception message are as follows:
System.UnauthorizedAccessException
HResult=0x80070005
Message=Access to the path 'C:\Users\XXX\source\repos\discordBot\discordBot\bin\Debug' is denied.
Source=mscorlib
StackTrace:
at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy, Boolean useLongPath, Boolean checkHost)
at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access)
at train_bot.Program.d__3.MoveNext() in C:\Users\XXX\source\repos\discordBot\discordBot\Program.cs:line 46
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.GetResult()
at train_bot.Program.Main(String[] args) in C:\Users\XXX\source\repos\discordBot\discordBot\Program.cs:line 21
The less detailed version
System.UnauthorizedAccessException: 'Access to the path 'C:\Users\SettingAdmin\source\repos\discordBot\discordBot\bin\Debug' is denied.'
using System;
using System.IO;
using System.Reflection;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Discord;
using Discord.Commands;
using Discord.WebSocket;
namespace train_bot
{
class Program
{
private DiscordSocketClient Client;
private CommandService Commands;
static void Main(string[] args)
=> new Program().MainAsync().GetAwaiter().GetResult();
private async Task MainAsync()
{
//configuring client
Client = new DiscordSocketClient(new DiscordSocketConfig
{
LogLevel = LogSeverity.Debug //changes detail in log
});
Commands = new CommandService(new CommandServiceConfig
{
CaseSensitiveCommands = true,
DefaultRunMode = RunMode.Async,
LogLevel = LogSeverity.Debug
});
Client.MessageReceived += Client_MessageReceived;
await Commands.AddModulesAsync(Assembly.GetEntryAssembly());
Client.Ready += Client_Ready;
Client.Log += Client_Log;
string Token = "";
using (var Steam = new FileStream(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location).Replace(#"bin\Debug\netcoreapp2.0", #"Token.txt"), FileMode.Open, FileAccess.Read))using (var ReadToken = new StreamReader(Steam))
{
Token = ReadToken.ReadToEnd();
}
await Client.LoginAsync(TokenType.Bot, Token);
await Client.StartAsync();
await Task.Delay(-1);
}
private async Task Client_Log(LogMessage Message)
{
Console.WriteLine($"{DateTime.Now} at {Message.Source}] {Message.Message}");
}
private async Task Client_Ready()
{
await Client.SetGameAsync("Hentai King 2018", "", StreamType.NotStreaming);
}
private async Task Client_MessageReceived(SocketMessage arg)
{
//Configure the commands
}
}
}
The problem may be that you try to open a directory as file. The path you construct is:
Path.GetDirectoryName(Assembly.GetEntryAssembly().Location).Replace(#"bin\Debug\netcoreapp2.0", #"Token.txt")
This would only work if Assembly.GetEntryAssembly().Location indeed contains the string #"bin\Debug\netcoreapp2.0".
You probably intended something like
Path.Combine(Path.GetDirectoryName(Assembly.GetEntryAssembly().Location), #"Token.txt")
Like the error said, you don't have access to that folder. If you are running it on debug mode make sure you run visual studio as administrator so you get to ignore all that on dev environment. If its deployed, make sure the the account running your program has appropriate rights to the folder.
Related
Below are the Stacktrace;
System.NotSupportedException
HResult=0x80131515
Message=The given path's format is not supported.
Source=mscorlib
StackTrace:
at System.Security.Permissions.FileIOPermission.EmulateFileIOPermissionChecks(String fullPath)
at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy, Boolean useLongPath, Boolean checkHost)
at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access)
at EntryLog.Handlers.StreamEntryLogs.StreamWritter(String log, String foldername) in C:\Users\JNyingi\source\repos\EntryLog\EntryLog\Handlers\StreamEntryLogs.cs:line 31
at EntryLog.EntryLog.LogWarning(String Warning) in C:\Users\JNyingi\source\repos\EntryLog\EntryLog\EntryLog.cs:line 55
at EntryLogConsoleTest.Program.Main(String[] args) in C:\Users\JNyingi\source\repos\EntryLogConsoleTest\EntryLogConsoleTest\Program.cs:line 21
This exception was originally thrown at this call stack:
System.Security.Permissions.FileIOPermission.EmulateFileIOPermissionChecks(string)
System.IO.FileStream.Init(string, System.IO.FileMode, System.IO.FileAccess, int, bool, System.IO.FileShare, int, System.IO.FileOptions, Microsoft.Win32.Win32Native.SECURITY_ATTRIBUTES, string, bool, bool, bool)
System.IO.FileStream.FileStream(string, System.IO.FileMode, System.IO.FileAccess)
EntryLog.Handlers.StreamEntryLogs.StreamWritter(string, string) in StreamEntryLogs.cs
EntryLog.EntryLog.LogWarning(string) in EntryLog.cs
EntryLogConsoleTest.Program.Main(string[]) in Program.cs
The exception is coming about from the following lines;
string filePath = System.IO.Path.Combine(EntryLog.LogPath.AbsolutePath, currentTimeFilename + " - " + $"{foldername}.log");
var fileStreamer = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.Write);
var streamWriter = new StreamWriter(fileStreamer);
The LogPath is obtained by this method;
LogPath = new Uri(Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location));
I have tried all manner of debugging but it always throws the above exception at StreamWriter. Kindly assist me in resolving this. I'm using 4.5.2 .net Framework
FILE PATH
The file path in question is this;
C:\Users\JNyingi\source\repos\EntryLogConsoleTest\EntryLogConsoleTest\bin\Debug
CURRENT TIME AND FOLDER NAME
string currentTimeFilename = DateTime.Now.ToString("yyyy-MM-dd HH:mm");
string foldername = "Log"
the problem is the : in your filename
string currentTimeFilename = DateTime.Now.ToString("yyyy-MM-dd HH:mm");
^
Change it to - or _ or even a . for example and the error disappears
string currentTimeFilename = DateTime.Now.ToString("yyyy-MM-dd HH_mm");
Using ILSpy you can find that the code of the method EmulateFileIOPermissionChecks (which raises the NotSupportedException) is:
internal static void EmulateFileIOPermissionChecks(string fullPath)
{
if (AppContextSwitches.UseLegacyPathHandling || !PathInternal.IsDevice(fullPath))
{
if (PathInternal.HasWildCardCharacters(fullPath))
{
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidPathChars"));
}
if (PathInternal.HasInvalidVolumeSeparator(fullPath))
{
throw new NotSupportedException(Environment.GetResourceString("Argument_PathFormatNotSupported"));
}
}
}
So your path contains invalid chars.
EDIT
If in your settings hours - minutes separator is a colon (see your datetime formatted string), please consider that ':' cannot be used in a path, but after driver letter.
I'm trying to learn how to write a Discord bot and I need to read form a JSON file.
Here is my Utilities class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using System.IO;
namespace mah_discord_bot
{
class Utilities
{
private static Dictionary<string, string> alerts;
static Utilities()
{
string json = File.ReadAllText("SystemLang\alerts.json");
var data = JsonConvert.DeserializeObject<dynamic>(json);
alerts = data.ConvertToObject<Dictionary<string, string>>();
}
public static string GetAlert(string key)
{
if (alerts.ContainsKey(key))
{
return alerts[key];
}
else
{
return "";
}
}
}
}
And here is my Main class where I call the Utilities class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace mah_discord_bot
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine(Utilities.GetAlert("test"));
}
}
}
My JSON file goes as follows
{
"test": "Hello"
}
and my folder structure looks like this, I'm not really sure if it's because it can't read the JSON file I created, when debugging this line
string json = File.ReadAllText("SystemLang\alerts.json");
It returns null so I'm not sure where I'm messing up.
Also the complete error log
Unhandled Exception: System.TypeInitializationException: The type initializer for 'mah_discord_bot.Utilities' threw an exception. ---> System.ArgumentException: Illegal characters in path.
at System.IO.Path.CheckInvalidPathChars(String path, Boolean checkAdditional)
at System.IO.Path.GetFileName(String path)
at System.IO.StreamReader..ctor(String path, Encoding encoding, Boolean detectEncodingFromByteOrderMarks, Int32 bufferSize, Boolean checkHost)
at System.IO.File.InternalReadAllText(String path, Encoding encoding, Boolean checkHost)
at System.IO.File.ReadAllText(String path)
at mah_discord_bot.Utilities..cctor() in K:\visual sutdio proj\mah-discord-bot\mah-discord-bot\Utilities.cs:line 18
--- End of inner exception stack trace ---
at mah_discord_bot.Utilities.GetAlert(String key)
at mah_discord_bot.Program.Main(String[] args) in K:\visual sutdio proj\mah-discord-bot\mah-discord-bot\Program.cs:line 13
Press any key to continue . . .
System.ArgumentException: Illegal characters in path.
\ is used as escape character in C# and \a is not a valid path character.
"SystemLang\alerts.json"
Use #"SystemLang\alerts.json" or "SystemLang\\alerts.json" instead.
Today i run Visual Studio and open my project, that i not opened about 5 months.
And running test (it was be OK) invoke IOException with additional information: "Bad descriptor".
It was in this line:
var defaultConsoleEncoding = Console.InputEncoding;
Console.InputEncoding = TryGetEncoding("UTF-8"); // <--- There is error
...
public static Encoding TryGetEncoding(string encoding)
{
try
{
return Encoding.GetEncoding(encoding);
}
catch (ArgumentException)
{
Logger.WarnAndPrint($"Can't using {encoding} encoding. Fallback to utf-8");
return Encoding.UTF8;
}
}
All my tests were OK, but now all fails with that error. I never chage code in project. And i try many encodings - nothing work.
What's the problem?
P.S. This is stack trace
System.IO.IOException was unhandled by user code
HResult=-2147024890
Message=Неверный дескриптор.
Source=mscorlib
StackTrace:
в System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
в System.Console.set_InputEncoding(Encoding value)
в PasswordListGenerator.Substitutions.Substitution.Process() в C:\GITHUB\passwordlistgenerator\PasswordListGenerator\PasswordListGenerator\Substitutions\Substitution.cs:строка 89
в PasswordListGeneratorTest.SubstitutionTests.SkipManySymbols_ShouldReturnSubstitutions() в C:\GITHUB\passwordlistgenerator\PasswordListGenerator\PasswordListGeneratorTest\SubstitutionTests.cs:строка 588
InnerException:
I have a dotnet script which is for encryption and decryption. I have to pass the parameters for the setvalues function in installshield. How can I achieve this? Dotnet code is as follows. I have the assembly (.dll) file.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
using System.Security;
using System.Xml;
using System.Collections.Specialized;
namespace EncryptionDecryption
{
public class EncrptionHelper
{
#region Member variables
static byte[] entropy = { 0, 8, 2, 3, 5 };
#endregion
#region Public Methods
public static void SetValue(string configFilePathName, string appSettingKey, string appSettingValue)
{
appSettingValue = EncryptString(ToSecureString(appSettingValue));
SetSetting(appSettingKey, appSettingValue, configFilePathName);
}
public static string GetValue(string configFilePathName, string appSettingKey)
{
string value = GetSetting(appSettingKey, configFilePathName);
value = ToInsecureString( DecryptString(value));
return value;
}
#endregion
#region Private Methods
private static bool SetSetting(string Key, string Value, string configFilePath)
{
bool result = false;
try
{
// System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(configFilePath);
// config.AppSettings.File = configFilePath;
// config.AppSettings.Settings[Key].Value = Value;
// config.Save(ConfigurationSaveMode.Modified);
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.Load(configFilePath);
xmlDoc.SelectSingleNode("//appSettings/add[#key='" + Key +"']").Attributes["value"].Value = Value;
xmlDoc.Save(configFilePath);
ConfigurationManager.RefreshSection("appSettings");
result = true;
}
finally
{ }
return result;
}
private static string GetSetting(string Key, string configFilePath)
{
string result = null;
try
{
XmlDocument appSettingsDoc = new XmlDocument();
appSettingsDoc.Load(configFilePath);
XmlNode node = appSettingsDoc.SelectSingleNode("//appSettings");
XmlElement value = (XmlElement)node.SelectSingleNode(string.Format("//add[#key='" + Key + "']"));
result = (value.GetAttribute("value").ToString());
}
finally
{ }
return result;
}
private static SecureString ToSecureString(string input)
{
SecureString secure = new SecureString();
foreach (char c in input)
{
secure.AppendChar(c);
}
secure.MakeReadOnly();
return secure;
}
private static string ToInsecureString(SecureString input)
{
string returnValue = string.Empty;
IntPtr ptr = System.Runtime.InteropServices.Marshal.SecureStringToBSTR(input);
try
{
returnValue = System.Runtime.InteropServices.Marshal.PtrToStringBSTR(ptr);
}
finally
{
System.Runtime.InteropServices.Marshal.ZeroFreeBSTR(ptr);
}
return returnValue;
}
private static string EncryptString(System.Security.SecureString input)
{
byte[] encryptedData = System.Security.Cryptography.ProtectedData.Protect(
System.Text.Encoding.Unicode.GetBytes(ToInsecureString(input)), entropy, System.Security.Cryptography.DataProtectionScope.CurrentUser);
return Convert.ToBase64String(encryptedData);
}
private static SecureString DecryptString(string encryptedData)
{
try
{
byte[] decryptedData = System.Security.Cryptography.ProtectedData.Unprotect(
Convert.FromBase64String(encryptedData),
entropy,
System.Security.Cryptography.DataProtectionScope.CurrentUser);
return ToSecureString(System.Text.Encoding.Unicode.GetString(decryptedData));
}
catch
{
return new SecureString();
}
}
#endregion
}
}
Update: Action start 14:31:36: Encryption.
MSI (c) (84:40) [14:31:36:525]: Invoking remote custom action. DLL: C:\Users\<username>\AppData\Local\Temp\MSIE259.tmp, Entrypoint: m1
InstallShield: Attempting to load through CLR 4 APIs...
InstallShield: Getting meta host...
InstallShield: Enumerating available runtimes...
InstallShield: Highest available runtime: v4.0.30319
InstallShield: Trying to use highest runtime...
InstallShield: Using highest version runtime...
InstallShield: Loading assembly Security.Encryption from resource 4097
InstallShield: Calling method with parameters [(System.String)C:\Program Files (x86)\<Installdir>\<configfilename>.config, (System.String)VWFPassword, (System.String)]
InstallShield: Exception: System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.IO.DirectoryNotFoundException: Could not find a part of the path 'C:\Program Files (x86)\<Installdir>\<configfilename>.config'.
at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy, Boolean useLongPath)
at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize)
at System.Xml.XmlDownloadManager.GetStream(Uri uri, ICredentials credentials, IWebProxy proxy, RequestCachePolicy cachePolicy)
at System.Xml.XmlUrlResolver.GetEntity(Uri absoluteUri, String role, Type ofObjectToReturn)
at System.Xml.XmlTextReaderImpl.OpenUrlDelegate(Object xmlResolver)
at System.Threading.CompressedStack.runTryCode(Object userData)
at
System.Runtime.CompilerServices.RuntimeHelpers.ExecuteCodeWithGuaranteedCleanup(TryCode code, CleanupCode backoutCode, Object userData)
at System.Threading.CompressedStack.Run(CompressedStack compressedStack, ContextCallback callback, Object state)
at System.Xml.XmlTextReaderImpl.OpenUrl()
at System.Xml.XmlTextReaderImpl.Read()
at System.Xml.XmlLoader.Load(XmlDocument doc, XmlReader reader, Boolean preserveWhitespace)
at System.Xml.XmlDocument.Load(XmlReader reader)
at System.Xml.XmlDocument.Load(String filename)
at Security.Encryption.EncrptionHelper.SetSetting(String appSettingKey, String appsettingValue, String configFilePathName)
at Security.Encryption.EncrptionHelper.SetValue(String configFilePathName, String appSettingKey, String appSettingValue)
--- End of inner exception stack trace ---
at System.RuntimeMethodHandle._InvokeMethodFast(IRuntimeMethodInfo method, Object target, Object[] arguments, SignatureStruct& sig, MethodAttributes methodAttributes, RuntimeType typeOwner)
at System.RuntimeMethodHandle.InvokeMethodFast(IRuntimeMethodInfo method, Object target, Object[] arguments, Signature sig, MethodAttributes methodAttributes, RuntimeType typeOwner)
at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture, Boolean skipVisibilityChecks)
at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
at InstallShield.ClrHelper.CustomActionHelper.CallMethod(EntryPointInfo info)
at InstallShield.ClrHelper.CustomActionHelper.RunAction(UInt32 installHandle, Int32 entryNumber, Int64 instanceHandle)
InstallShield: Managed code threw an unhandled exception.
This is the error I receive after doing all that is mentioned in the screenshots below and doing some R&D. The directory mentioned "C:\Program Files (x86)\\.config" exists when the encryption custiom action is being called but it throws an exception.
Yes, it can be done with following steps:
1- write your required functionality in c# installer class (make sure your are using installer class)
2- Compile and add your dll into installshield (recomended create a separate component for this dll)
3- Select component view -> select above component and go to .Net settings section, set the ".Net Installer class" to true. Set the ".net installer class parameters"
Parameters are passed as key/value pair e.g
/targetDirectory="[INSTALLDIR]\"
All steps are same, just added screenshots.
Create a dll with an installer class and your encrypt/decrypt class.
Add dll and config file to component(above mentioned), if config file is already added to some other component then its fine. no need to add again.
I have added and retrieved INSTALLDIR variable as argument which is predefined. if you want to receive some input from user (from some custom textboxes) then you will need to define your own variables to store and pass values as arguments.
Creating dll with installer class and your requred logic for other task
Creating component and adding files
Mark the dll as installer class and pass arguments
Here goes installer class:
using System;
using System.Text;
using System.IO;
using System.Diagnostics;
using System.ComponentModel;
using System.Configuration.Install;
using System.Collections.Generic;
namespace EncryptionDecryption
{
[RunInstaller(true)]
public class InstallerClassDemo : Installer
{
private string installationDirectory=string.Empty;
private string testString=string.Empty ;
public override void Install(System.Collections.IDictionary stateSaver)
{
base.Install(stateSaver);
try
{
//For testing purpose only.. work only in debug mode when pdb files are deployed as well.
//Debugger.Break();
installationDirectory = Context.Parameters["INSTALLDIR"];
//I believe, the config file must be located in the installation directory if so, then use the following way to compute path
string configFilePath = Path.Combine(installationDirectory, "myConfigFile.config");
EncrptionHelper.SetValue(configFilePath, "testKey", "testValue");
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex.Message);
}
}
protected override void OnCommitted(System.Collections.IDictionary savedState)
{
base.OnCommitted(savedState);
}
public override void Uninstall(System.Collections.IDictionary savedState)
{
base.Uninstall(savedState);
}
}
}
I think installshield cannot (or need extra work) for read your assemblies, but you can run simple console application which consume your assemblies from installscript and passing parameter from installshield.
Create simple console application
Include console application on Support Files
Copy to installation folder or assemblies location, so console application can access your assemblies
Launch from installscript using launchappandwait
If consoleapp.exe not use anymore, just delete it.
I am trying to run a simple application that uses drool.net. Whenever I execute, the application crashed at builder.AddPackageFromDrl("DroolsApp.Rules.drl", stream); The Error stated that NullReferenceException was unhandled and Object reference not set an instance of an object. I tried to change drl file but the error was still present. Am I missing anything? Also is there any site that provides a detailed tutorial for using drools.net and do I need any specific program to create and edit drl files as I am using a simple notepad.
Thanks in Advance
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using org.drools.dotnet.compiler;
using org.drools.dotnet.rule;
using org.drools.dotnet;
using System.IO;
using System.Reflection;
namespace DroolsApp
{
class Program
{
static void Main(string[] args)
{
PackageBuilder builder = new PackageBuilder();
Stream stream = Assembly.GetExecutingAssembly()
.GetManifestResourceStream("DroolsApp.Rules.drl");
builder.AddPackageFromDrl("DroolsApp.Rules.drl", stream);
Package pkg = builder.GetPackage();
RuleBase ruleBase = RuleBaseFactory.NewRuleBase();
ruleBase.AddPackage(pkg);
executeRules(ruleBase, 5);
executeRules(ruleBase, 6);
executeRules(ruleBase, 7);
}
public static void executeRules(RuleBase ruleBase, int amount)
{
WorkingMemory workingMemory = ruleBase.NewWorkingMemory();
Quest quest = new Quest();
quest.Value = amount;
workingMemory.assertObject(quest);
workingMemory.fireAllRules();
}
}
}
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace DroolsApp
{
class Quest
{
public int Value { set; get; }
}
}
DRL File:
package DroolsApp
rule "NumberFive"
when
quest : Quest( Value == 5 )
then
Console.WriteLine("FIVE");
end
rule "NumberSix"
when
quest : Quest( Value == 6 )
then
Console.WriteLine("SIX");
end
Stack Trace:
System.NullReferenceException was unhandled
Message=Object reference not set to an instance of an object.
Source=drools.dotnet
StackTrace:
at org.drools.dotnet.semantics.DotnetClassTypeResolver.resolveType(String className)
at org.drools.semantics.java.RuleBuilder.build(ColumnDescr columnDescr)
at org.drools.semantics.java.RuleBuilder.build(RuleDescr ruleDescr)
at org.drools.semantics.java.RuleBuilder.build(Package pkg, RuleDescr ruleDescr)
at org.drools.compiler.PackageBuilder.addRule(RuleDescr ruleDescr)
at org.drools.compiler.PackageBuilder.addPackage(PackageDescr packageDescr)
at org.drools.compiler.PackageBuilder.addPackageFromDrl(String fileName, Reader reader)
at org.drools.dotnet.compiler.PackageBuilder.AddPackageFromDrl(String fileName, Stream drlStream)
at MinimalDroolsForm.Program.Main(String[] args) in C:\Users\Carl\Desktop\DroolsApp\Program.cs:line 19
at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
InnerException:
It's for sure an error in drl file. Try to remove all rules and imports, compile them, and then add single line and repeat (it must validate though). Drools.net reacts for compilation errors with NullReferenceException or an error with loading CompiledRules0.dll (because it wasn't generated). It is also a good thing to add a Pre-build Build Event deleting the previously generated CompiledRules0.dll (when Drools.net fails to generate the file it uses the previous one). Here's the code:
cd $(TargetDir)
del CompiledRules0.*
Two hints:
1) when calling GetManifestResourceStream method, be sure to pass namespace and filename as parameter.
2) In visual studio (if you are using it), rule file properites, set build action to embedded resource.