I cannot set IIS authentication programatically using c# - c#

I'm trying to turn of Anonymous authentication on a site using c#
This code throws exception written at bottom i searched everywhere i cant find answer how to solve it:
using (ServerManager serverManager = new ServerManager())
{
Configuration configapp = serverManager.GetApplicationHostConfiguration();
ConfigurationSection anonymousAuthenticationSection = configapp.GetSection("system.webServer/security/authentication/anonymousAuthentication", Site1);
anonymousAuthenticationSection["enabled"] = false;
serverManager.CommitChanges();
}
The exception:
System.IO.FileNotFoundException: Filename: \\?\C:\Windows\system32\inetsrv\config\applicationHost.config
Error: Unrecognized configuration path 'MACHINE/WEBROOT/APPHOST/Site1'
at Microsoft.Web.Administration.Interop.AppHostWritableAdminManager.GetAdminSection(String bstrSectionName, String bstrSectionPath)
at Microsoft.Web.Administration.Configuration.GetSectionInternal(ConfigurationSection section, String sectionPath, String locationPath)
at Microsoft.Web.Administration.Configuration.GetSection(String sectionPath, String locationPath)
at FlowSuiteWebConfigurator.label.button1_Click(Object sender, EventArgs e) in C:\Users\Administrator\documents\visual studio 2010\Projects\Projectname\Projectname\Form1.cs:line 264
Can someone guide me how to fix this?

A bit late maybe (1 year and a half after...), but the problem seems to be in your location definition (2nd parameter of configapp.GetSection): the exception said Error: Unrecognized configuration path 'MACHINE/WEBROOT/APPHOST/Site1'
Tested locally on my machine, I have no exception with a valid location name like Default Web Site/MyCustomPortal.
Note: the reference added is Microsoft.Web.Administration.dll under C:\Windows\System32\inetsrv\ , and those lines of code look into the file applicationHost.config located in C:\Windows\System32\inetsrv\config

Related

MagickBlobErrorException: no such file or directory

When i run the testcase c# application from windows(local machine) it works fine. But when run from azure pipeline getting below exception. Anyone faced like this error? Please help me on this.
i used code:
MagickImage sourceImage = new MagickImage("../../../Images/OutputImages/output-SlightSkew.jpg");
Got error:
Error Message:
ImageMagick.MagickBlobErrorException : UnableToOpenBlob '../../../Images/OutputImages/output-SlightSkew.jpg': No such file or directory # error/blob.c/OpenBlob/3537
Stack Trace:
at ImageMagick.NativeInstance.CheckException(IntPtr exception, IntPtr result)
at ImageMagick.MagickImage.NativeMagickImage.ReadFile(IMagickSettings1 settings) at ImageMagick.MagickImage.Read(String fileName, IMagickReadSettings1 readSettings, Boolean ping)
at ImageMagick.MagickImage.Read(String fileName, IMagickReadSettings`1 readSettings)
at ImageMagick.MagickImage.Read(String fileName)
at ImageMagick.MagickImage..ctor(String fileName)
According to your error message, the error is most likely due to the wrong file path.
In Azure DevOps pipeline, your source code files are in $(System.DefaultWorkingDirectory).
You can check if there is a output-SlightSkew.jpg file in ../../../Images/OutputImages/ in your repository.
If the answer is no, change your path to the correct path.
If the answer is yes, try to replace your path to a specific path, for example {folder A}/{folder B}/Images/OutputImages/output-SlightSkew.jpg.

Where are situated all SharePoint server error codes descriptions?

During execution the code belowe Microsoft.SharePoint.Client.ServerException with ServerErrorCode = -2147024894 has been thrown. But I don't know any information about this code. May be you know where I can find the correspondence between SP ServerErrorCodes and their descriptions ?
private SP.Folder GetFolderByRelativeUrl(string folderRelativePath)
{
var folder = _spClientContext.SpContext.Web.GetFolderByServerRelativeUrl(folderRelativePath);
_spClientContext.SpContext.Load(folder);
_spClientContext.SpContext.ExecuteQuery(); // here exception is thrown
return folder;
}
MSDN has no information about codes' descriptions.
UPDATED:
Full description
Microsoft.SharePoint.Client.ServerException: File Not Found.
at Microsoft.SharePoint.Client.ClientRequest.ProcessResponseStream(Stream responseStream)
at Microsoft.SharePoint.Client.ClientRequest.ProcessResponse()
...
Finally, by chance I've found.
SharePoint server erros codes
Many common error codes are included in the ClientErrorCodes class:
CSOM: Microsoft.SharePoint.Client.ClientErrorCodes
JSOM: SP.ClientErrorCodes

Missing manifest error when trying to retrieve resource via resource manager

I'm having a few troubles with getting resources dynamically as I get "Missing manifest" errors. I looked up a few possible causes and did what was written there but so far nothing worked.
Currently I have this situation:
The resx file I'm trying to access is: "Resources/Messages.resx" (thus in a nonstandard folder.
The code I'm using is this:
ResourceManager resourceManager = new ResourceManager("Resources.Messages", this.GetType().Assembly);
resourceManager.GetString("ResourceText" + MessageType + "Subject")
with messageType being a string. On the second line I get the error message.
The status of the resource file is this:
Build Aciton: Embedded Resource
Custom Tool: PublicResXFileCodeGenerator
Access Modifier Public
The resfile has 2 variants: Messages.res and Messages.de.resx with the same names for each row and also the same general properties (the "GetString" also definitively tries to access the correct name).
So my question is what I'm doing wrong there and what can I do to correct this problem?
Found the problem. For new ResourceManager not only the namespace of the resourcesfiles has to be given but also the default namespace. Thus if the application has a default namespace of: MyApplication.MyServerApp then instead of "Resources.Messages" one must put in: "MyApplication.MyServerApp.Resources.Messages" leading to the following functioning sourcecode:
ResourceManager resourceManager = new ResourceManager("MyApplication.MyServerApp.Resources.Messages", this.GetType().Assembly);
resourceManager.GetString("ResourceText" + MessageType + "Subject")

"The invocation of the constructor on type 'TestWPF.MainWindow' that matches the specified binding constraints threw an exception."- how to fix this?

I'm working with WPF. When I'm trying to declare SQLiteConnection in the code, the problem arises-
The invocation of the constructor on type 'TestWPF.MainWindow' that matches the specified binding constraints threw an exception.
InnerException: Make sure that the file is a valid .NET Framework assembly.
can anyone tell me, how to fix it?
If you click on View Detail... from the exception window you can look at the InnerException. Expand that node and you will see exactly what went wrong.
In my specific case, I was getting this because I had a few of my referencing assemblies mismatched between x64 and x86. Apparently I was binding to something that needed to be loaded by the runtime.
I mention this here as a reminder to check your build configurations if you've looked everywhere else!
I fixed the problem by adding the below content in app.config,
<configuration> <startup useLegacyV2RuntimeActivationPolicy="true" /> </configuration>
I found this via a community addition by user FCAA below the article "
Troubleshooting Exceptions: System.IO.FileLoadException" on MSDN.
I got the same error and, after wasting about 2 hours with it, found that it is my SQL Server service that's not running. Not sure if this can ever help someone, but it did solve my problem to just start the service.
The mentioned exeption is quite generic and you can receive it, for instance, when code fails in the constructor. I had a case of an IO exception that showed up with a similar text. Stepping into the code may provide hints to fix this that may not be obvious otherwise.
I got it in when I specified the FrameworkPropertyMetadata of a DependencyProperty with a default value
the defaultValue was
new AdressRecord { Name = "<new>", Adress = "?" }
i replaced with
default(AddressRecord)
and vs2015 ate it
public static readonly DependencyProperty AdressRecordsProperty =
DependencyProperty.Register("AdressRecords",
typeof(ObservableCollection<AdressRecord>),
typeof(PageViewModel),
new FrameworkPropertyMetadata(
default(AdressRecord),//This noes not work: new AdressRecord { Name = "<new>", Adress = "?" },
OnAdressRecordsChanged));
I ran into this issue and it was caused because my startup application was built as any CPU but I was referencing a project that was built as x64. Setting the startup to build x64 resolved the issue.
In VS2015 I was able to see the specific code causing this problem once I turned on 'Enable Just My Code' in the Debugging Options under Tools -> Options.
I had this error in another part of code which has to do with my application resources.
This was fixed after explicitly setting the ResourcePath folder in my App.config file
I had the same problem. i could make it work by renaming the name of App1.config to App.config. I tried all other methods but the solution for me was to change the default name (for me it was App1.config) of the config file to App.config. I shared this because someone may get help by this small modification.
My problem was about the interface. I fixed it by deleting the Betternet folder that is located at C:\ProgramData.
Hidden Items/Folders must be shown in order to be able to view the folder.
With Visual Studio it will sometimes not show anything in the exception details or even have them, running the diagnostic tool however can easily pinpoint what is wrong.
Try Adding "Integreted Security = True" in Connection String.
It worked for me.
In my case it happened in a code-first WPF project. The cause was model changes after restoring a backup, and the error was not being handled appropriately. "The model backing the 'MyDataContext' context has changed since the database was created." Update-Database sorted it out.
I had to change the target .Net framework from 4.5.2 to 4.
my issue was regular System.IndexOutOfRangeException error in my own code,
but received this weird error because my code was called inside:
public MainWindow()
{
InitializeComponent();
// my code with error
}
same issue, if call it inside:
private void Window_Initialized(object sender, EventArgs e)
{
// my code with error
}
Fixed, if I call my code inside:
private void Window_Loaded(object sender, RoutedEventArgs e)
{
// my code with error
}
Then i get correct error message for IndexOutOfRangeException in my code.

C# Class Library: StreamWriter writing to system32 folder

I have a class library which is deployed on an ISP server to be consumed by an ASP.NET web service. I'd like to keep track of any errors and in this case the windows event log is inaccessible to me. So I thought I'd write to a txt file using the StreamWriter class. Problem is if I don't give an absolute path and just a file name it tries to write to C:\Windows\System32, and that's no good to me.
How can I tell it to use maybe the data directory or the application root? Any thoughts?
Use Server.MapPath to get a path relative to the web application.
using (FileStream fs = new FileStream(Server.MapPath("~/logs/logfile.txt"),
FileMode.Append)) {
//do logging here.
}
While some of the previous posters have suggested using reflection to get the executing assembly, I'm not sure whether or not that will net you the web application or the w3wp process. If it's the latter, you're still going to end up trying to write to the System32 folder.
Here is what I used to use, it's a little clunky but it gets the job done:
using System;
using System.Collections.Generic;
using System.Web.UI;
public static class Logger
{
private static readonly Page Pge = new Page();
private static readonly string Path = Pge.Server.MapPath("~/yourLogPath/Log.txt");
private const string LineBreaker = "\r\n\r======================================================================================= \r\n\r";
public static void LogError(string myMessage, Exception e)
{
const LogSeverity severity = LogSeverity.Error;
string messageToWrite = string.Format("{0} {1}: {2} \r\n\r {3}\r\n\r {4}{5}", DateTime.Now, severity, myMessage, e.Message, e.StackTrace, LineBreaker);
System.IO.File.AppendAllText(Path, messageToWrite);
}
}
I had this class in it's own project, separate from the website itself, and I used it in all of my other non website projects...
Edit:
Btw LogSeverity is just an enum I made up...
In my web product, in the web.config I specify an appSettings block like this:
<configuration>
<appSettings>
<add key="MyLogPath" value="LogPath" />
</appSettings>
</configuration>
which you can use from the code like
ConfigurationManager.AppSettings["MyLogPath"]
then you can have the installer configure it to wherever you want. you probably don't want the log files in your application directory.
Try checking out:
Application.StartupPath;
Here's a link to the docs
Gets the path for the executable file
that started the application, not
including the executable name.
string path = Application.StartupPath;
Note: you'll still need to add a file name.
You can find out the path of your executable by doing this:
string path = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);

Categories