iis console application directoryentry searchresult - c#

Running a Console Application as a CGI in IIS on Windows 2012 R2.
On connection to Active Directory (AD), using DirectoryEntry, ref:
lccDEDirectoryEntry = new DirectoryEntry(lccSDomainConnectionString, lccSUserId, lccSUserPassword, lccATAuthTypes);
Then using DirectorySearcher, ref:
lccDSSearcher = new DirectorySearcher(lccDEDirectoryEntry);
Then finding all matching objects, ref:
lccSRCResults = lccDSSearcher.FindAll();
Then finally accessing the search results, ref:
foreach (SearchResult lccSRResultLoop in lccSRCResults)
All works fine, until I try to access the Search Results, it throws an "Illegal Characters In Path".
I can run the same Console Application directly on the server hosting the IIS in a command window and it works fine, including accessing/displaying the SearchResults. Also works fine on Windows 7 workstation/etc.
I hit this same type issue a year ago with a call to HttpUtility, and it ended up being a bug in IIS where it is looking for a configuration setting that is null. Microsoft supplied a fix to use this line:
AppDomain.CurrentDomain.SetData("APP_CONFIG_FILE", Environment.CurrentDirectory + "\" + System.AppDomain.CurrentDomain.FriendlyName + ".config");
Per this blog page:
http://www.dreamincode.net/forums/topic/300197-webrequest-in-a-cgi
And that solved the null configuration setting a year ago, as when you run HttpUtility, IIS looks for an "APP_CONFIG_FILE" setting that is not set when running as a Console Application and isn't used.
Well, my debugging/etc. has shown that the same issue being hit, i.e. a setting is null and so the function "CheckIllegalCharacters" isn't crashing as it can't parse a null value.
Unfortunately, I cannot locate the setting it is looking for. I even enumerated through all AppSetting keys, ref:
https://msdn.microsoft.com/en-us/library/system.appdomain.getdata%28v=vs.110%29.aspx?f=255&MSPPError=-2147217396
And have my code filling each one in with a dummy value, but, no go.
Any clue on how to find the missing setting key name? Or other solution?
Here is the Stack Trace. At the bottom is my function 'lccLDAP', which initiates the rest by calling the SearchResults loop.
STACK TRACE
at System.Security.Permissions.FileIOPermission.CheckIllegalCharacters(String[] str, Boolean onlyCheckExtras)
at System.Security.Permissions.FileIOPermission.AddPathList(FileIOPermissionAccess access, AccessControlActions control, String[] pathListOrig, Boolean checkForDuplicates, Boolean needFullPath, Boolean copyPathList)
at System.Security.Permissions.FileIOPermission..ctor(FileIOPermissionAccess access, String path)
at System.Reflection.RuntimeModule.get_FullyQualifiedName()
at System.Configuration.ClientConfigPaths.SetNamesAndVersion(String applicationFilename, Assembly exeAssembly, Boolean isHttp)
at System.Configuration.ClientConfigPaths..ctor(String exePath, Boolean includeUserConfig)
at System.Configuration.ClientConfigPaths.GetPaths(String exePath, Boolean includeUserConfig)
at System.Configuration.ClientConfigurationHost.RequireCompleteInit(IInternalConfigRecord record)
at System.Configuration.BaseConfigurationRecord.GetSectionRecursive(String configKey, Boolean getLkg, Boolean checkPermission, Boolean getRuntimeObject, Boolean requestIsHere, Object& result, Object& resultRuntimeObject)
at System.Configuration.BaseConfigurationRecord.GetSection(String configKey)
at System.Configuration.ConfigurationManager.GetSection(String sectionName)
at System.Configuration.PrivilegedConfigurationManager.GetSection(String sectionName)
at System.DirectoryServices.SearchResultCollection.ResultsEnumerator..ctor(SearchResultCollection results, String parentUserName, String parentPassword, AuthenticationTypes parentAuthenticationType)
at System.DirectoryServices.SearchResultCollection.get_InnerList()
at System.DirectoryServices.SearchResultCollection.get_Item(Int32 index)
at lccCoreFunctionsClass.lccLDAP(lccSettingsClass lccParamSCSettings, Int32 lccLDAPId, Int32 lccIFlag, String lccSParam)

Adding what I finally did. Since my console app runs fine on the IIS server, just not through IIS for Directory.SearchResults, I split the program to run in front-end and back-end modes. The front-end servers IIS web pages, and passes requests to the back-end for LDAP tasks. The back-end then serves responses to the front-end. Good tier-3 security anyway. Just in case others look for a possible solution.

Related

specflow+ example test on mac os (x64)

I am running specflow+ example test from here on mac catalina( x64) using Visual Studio for mac but I get this error
ExecutionThreadApartmentState option not supported for framework: .NETCoreApp,Version=v3.1.
Since apartmentState property is not supported on mac as mentioned here
I tried by removing apartmentState from <execution> element and also tried removing the whole <execution> element from Default.srprofile but still get same error in test results output. (test just keeps on running. Upon cancelling shows error in test output)
Tried x64 in platform settings in build but I get below when try to run test
Test run will use DLL(s) built for framework .NETCoreApp,Version=v3.1 and platform X86. Following DLL(s) do not match framework/platform settings.
TestApplication.UiTests.dll is built for Framework .NETCoreApp,Version=v3.1 and Platform X64.
Is it that the example tests mentioned above can not be run on mac os (x64) ? or am I missing some other thing?
EDIT
I installed and targeted .net core 3.0 and the still get
ExecutionThreadApartmentState option not supported for framework: .NETCoreApp,Version=v3.0.
EDIT2
The error I see in the logs is below. I think the above error about ExecutionThreadApartmentState may be just a warning because I still see it in test output
2020-04-29T13:55:54.5764790-04:00:Executing test executor at '/usr/bin/dotnet' 'exec "/Users/../Desktop/../projects/specflow/SpecFlow.Plus.Examples-master/SeleniumWebTest/TestApplication.UiTests/bin/Debug/netcoreapp3.0/SpecFlowPlusRunner/netcoreapp3.0/TechTalk.SpecRun.Framework.Executor.anycpu.netcoreapp3_0.dll" --remoteRunnerPid 37116 --uniqueId "2020-04-29T135554" --outputFolder "/Users/../Desktop/../projects/specflow/SpecFlow.Plus.Examples-master/SeleniumWebTest/TestApplication.UiTests/obj/TestResults" --callbackPort 32770 --loggerPort 32771' in '/Users/../Desktop/../projects/specflow/SpecFlow.Plus.Examples-master/SeleniumWebTest/TestApplication.UiTests/bin/Debug/netcoreapp3.0'
2020-04-29T13:55:54.6057600-04:00:System.ComponentModel.Win32Exception (2): No such file or directory
at System.Diagnostics.Process.ForkAndExecProcess(String filename, String[] argv, String[] envp, String cwd, Boolean redirectStdin, Boolean redirectStdout, Boolean redirectStderr, Boolean setCredentials, UInt32 userId, UInt32 groupId, UInt32[] groups, Int32& stdinFd, Int32& stdoutFd, Int32& stderrFd, Boolean usesTerminal, Boolean throwOnNoExec)
at System.Diagnostics.Process.StartCore(ProcessStartInfo startInfo)
at System.Diagnostics.Process.Start()
at TechTalk.SpecRun.Framework.Execution.OutOfProc.OutProcExecutorManager.StartProcess(ExecutorProcessInfo executorProcessInfo)
at TechTalk.SpecRun.VisualStudio.TestAdapter.VsOutProcExecutorManager.StartProcess(ExecutorProcessInfo executorProcessInfo)
at TechTalk.SpecRun.Framework.Execution.OutOfProc.StreamJsonRPC.OutOfProcessTestAssemblyExecutorHost.Initialize(Int32 threadId, ITestExecutionManager executionManager, IAssemblyReference testAssembly, ITestLogger currentLogger, String testAssemblyFullPath, String testAssemblyConfigFilePath, TestExecutionConfiguration testExecutionConfiguration, String target)
I'm no expert, not yet;) but I got this error too. and I found that it happened because a Class variable I declared in the Test - in its constructor there was a call to a method of an object stored in a field of the class with I/O from the Console.
when I removed the call from the constructor the tests (unit test) could run ok again.

Unable to load shared library 'python37' or one of its dependencies

I am quite new to dotnet and Keras.NET, and I was trying to set it up on a goorm.io container. After installing the prerequisites (adding $HOME/.keras/keras.json for Tensorflow backend and pip install numpy), and then adding Keras.NET, I tried to run the XOR sample code, but ran into an error.
Unhandled exception. System.DllNotFoundException: Unable to load shared library 'python37' or one of its dependencies. In order to help diagnose loading problems, consider setting the LD_DEBUG environment variable: libpython37: cannot open shared object file: No such file or directory
at Python.Runtime.Runtime.Py_IsInitialized()
at Python.Runtime.Runtime.Initialize(Boolean initSigs)
at Python.Runtime.PythonEngine.Initialize(IEnumerable1 args, Boolean setSysArgv, Boolean initSigs) at Python.Runtime.PythonEngine.Initialize(Boolean setSysArgv, Boolean initSigs) at Python.Runtime.PythonEngine.Initialize() at Numpy.np.InstallAndImport(Boolean force) at Numpy.np.<>c.<.cctor>b__599_0() at System.Lazy1.ViaFactory(LazyThreadSafetyMode mode)
at System.Lazy1.ExecutionAndPublication(LazyHelper executionAndPublication, Boolean useDefaultConstructor) at System.Lazy1.CreateValue()
at System.Lazy1.get_Value() at Numpy.np.get_self() at Numpy.np.get_float32() at Numpy.DtypeExtensions.GetDtype(Object obj) at Numpy.np.array[T](T[,] object, Dtype dtype, Nullable1 copy, String order, Nullable1 subok, Nullable1 ndmin)
at Proj.Program.Main(String[] args) in /workspace/XOR/Proj/Program.cs:line 14
I do not know how to share with the python37 directory. If someone could direct me in the right direction, it would be much appreciated. By the way, I am using Linux if that helps.
Thanks

NReco FFPMegConverter: The path is not of a legal form

I'm using the NReco FFMPegConverter, and when I try to get a thumbnail, I get the error:
System.ArgumentException: The path is not of a legal form.
at System.IO.Path.LegacyNormalizePath(String path, Boolean fullCheck, Int32 maxPathLength, Boolean expandShortPaths)
at System.IO.Path.NormalizePath(String path, Boolean fullCheck, Int32 maxPathLength, Boolean expandShortPaths)
at System.IO.Path.GetFullPathInternal(String path)
at System.IO.File.InternalGetLastWriteTimeUtc(String path, Boolean checkHost)
at NReco.VideoConverter.FFMpegConverter.EnsureFFMpegLibs()
at NReco.VideoConverter.FFMpegConverter.ExtractFFmpeg()
Here is the line of code where I'm getting my error.
var filep = domainVideoFile.AbsolutePath;
_fFMpegConverter.GetVideoThumbnail(filep, tempfileName);
In the above example, filep = "C:\Users\me_000\Downloads\GRoma\G.mp4"
and tempFileName = "C:\Users\me_000\Desktop\f480b6c0.jpeg"when copied directly from the Locals view in Debug mode.
There is another thread citing this issue on SO and the stated solution is to set the FFMPegToolPath property.
fFMpegConverter.FFMpegToolPath = _thumbPathManager.GetFFMPegPath;
I've tried that and various versions of it and I still get the error. I'm using the version of 1.1.2.0 if that helps.
The error pops up no matter what I do with respect to calling FFMpegToolPath, ExtractFFmpeg and what not.
Any help is greatly appreciated.
The problem was very insidious but I figured out what was happening.
I'm using Fody.Costura to merge my DLL resources. This works for all the other DLLS, but the NReco DLLs don't take kindly to being merged. I guess somewhere along the way this is causing file pathing issues since the DLL doesn't exist as a standalone file.

Semantic Logging Exception: Keywords values larger than 0x0000100000000000 are reserved for system use

I am using the Semantic Logging for my ASP.NET MVC app. https://github.com/mspnp/semantic-logging (SQL database) installed via nuget
Install-Package EnterpriseLibrary.SemanticLogging.Database
Here is the code that throws the exception.
var blockEventListener = new ObservableEventListener();
blockEventListener.EnableEvents(SemanticLoggingEventSource.Log, EventLevel.LogAlways, Keywords.All);
In my development platform using IIS Express, I don't have any exception but when I uploaded it to IIS 8.0 I got the following exception.
[ArgumentException: Keywords values larger than 0x0000100000000000 are reserved for system use]
System.Diagnostics.Tracing.EventSource.CreateManifestAndDescriptors(Type eventSourceType, String eventSourceDllName, EventSource source) +14523758
System.Diagnostics.Tracing.EventSource.EnsureInitialized() +103
System.Diagnostics.Tracing.EventSource.SendCommand(EventListener listener, Int32 perEventSourceSessionId, Int32 etwSessionId, EventCommand command, Boolean enable, EventLevel level, EventKeywords matchAnyKeyword, IDictionary`2 commandArguments) +6352938
System.Diagnostics.Tracing.EventListener.EnableEvents(EventSource eventSource, EventLevel level, EventKeywords matchAnyKeyword) +71

Windows 10 cannot access the specified device, path, or file when using full path to executable, running as Administrator

Note : I've replace the directory with a and the exe with b.exe and I've repeat every test I have made to make sure it's not a typing syntax.
I have a very simple piece code of which works perfectly from Windows XP to Windows 7.
var processPath = #"c:\a\b.exe" ; // this exe exists on my computer
Process.Start(processPath);
and also
Directory.Exists(#"c:\a\") returns false on Windows 10.
Since Windows 10 (I have not test yet 8 and 8.1) the first code will throws System.ComponentModel.Win32Exception ("Specified file not found") and second will return false. .
I've noticed also that it's the same behaviour when I run "c:\a\b.exe" with the windows run window (Windows Key + R).
Is there any workarounds to solve this issue? In preference, a solution which implies no recompilation.
NB :
I'm running windows as Administrator
The user has access to the file (security attribute enable for everyone in the computer).
c:\b.exe works !!
I'm not looking for a solution like change your application working directory and run Process.Start("b.exe").
Thank you all,
EDIT :
The specified path is not WRONG and the file is not missing.
Every user of the computer as Total control level acceess over the folder and the file (a directory and b.exe)
Works when I put the exe on the root directory : "c:\b.exe"
Same behaviour with .bat file with only "echo Hello inside"
Console.WriteLine(String.Join("\r\n", Directory.GetDirectories(#"c:\"))) display the directory c:\a
UPDATE :
Results of icalcs c:\a\ :
c:\a\ Tout le monde:(OI)(CI)(F)
BUILTIN\Administrateurs:(I)(OI)(CI)(F)
AUTORITE NT\SystŠme:(I)(OI)(CI)(F)
BUILTIN\Utilisateurs:(I)(OI)(CI)(RX)
AUTORITE NT\Utilisateurs authentifi‚s:(I)(M)
AUTORITE NT\Utilisateurs authentifi‚s:(I)(OI)(CI)(IO)(M)
Results of icalcs c:\a\b.exe :
c:\a\b.exe Tout le monde:(I)(F)
BUILTIN\Administrateurs:(I)(F)
AUTORITE NT\SystŠme:(I)(F)
BUILTIN\Utilisateurs:(I)(RX)
AUTORITE NT\Utilisateurs authentifi‚s:(I)(M)
"Tout le monde" means Everyone.
UPDATE :
On the last news, I'm able to do :
File.WriteAllBytes(#"c:\a\b.exe", somebinaries) ;
But I'm not able to do
FileInfo fileInfo = new FileInfo(#"c:\a\b.exe") ;
Throwing 'System.NotSupportedException'. StackTrace is as follows:
à System.Security.Permissions.FileIOPermission.QuickDemand(FileIOPermissionAccess access, String fullPath, Boolean checkForDuplicates, Boolean needFullPath)
à System.IO.FileInfo.Init(String fileName, Boolean checkHost)
à System.IO.FileInfo..ctor(String fileName)
à ConsoleApplication1.Program.Main(String[] args) dans F:\MAPW10\Development\Sources\Tools\ConsoleApplication1\Program.cs:ligne 22
à System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
à System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
à Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
à System.Threading.ThreadHelper.ThreadStart_Context(Object state)
à System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
à System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
à System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
à System.Threading.ThreadHelper.ThreadStart()
I found it !!
It's some extra non-printable bytes added in file path when Copying / Pasting from some labels in Windows 10 explorer.
Consider this piece of code :
Console.WriteLine(new DirectoryInfo(#"c:\a\"));
Console.WriteLine(new DirectoryInfo(#"‪c:\a\"));
These line looks the same and should not raise any exception (even if directory c:\a doesn't exist) but actually if you copy/paste the code above in an application, the second line will raise NotSupportedException with words : "The given path's format is not supported".
I've ended up checking .NET source code and I found method StringExpressionSet.Canonicalize which raised NotSupportedException :
...
if (path.IndexOf( ':', 2 ) != -1)
throw new NotSupportedException( Environment.GetResourceString( "Argument_PathFormatNotSupported" ) );
...
And actually :
Console.WriteLine(#"c:\a\".IndexOf( ':', 2 )); // results -1
Console.WriteLine(#"‪c:\a\".IndexOf( ':', 2 )); // result 2
// Copy/Paste to test
Where did I caught it ?
In order to not making any typing mistake, I'm used to copy directory path from Right Click to a file -> Properties -> Security
You are warned now !
...SystŠme
...authentifi‚s
Obfuscating the directory and file name makes it very hard to help you. But there's one obvious rock to look under, getting the accented characters mangled so badly like this should never happen. The machine speaks French but the encoding that appears to be used is 1250, only used in Eastern Europe. A very bizarre mismatch, especially so for a console mode app.
If the real a directory likewise contains characters with diacritics then whatever root cause behind the mangled icalcs.exe program output could affect the file system name encoding as well. Rough conclusion is that this machine is pretty sick and needs help from the geek squad to get better.

Categories

Resources