Set .NET CLR Version to No Managed Code - iis

Im trying to build an installer for my asp.net core service, but im having problems setting the .NET CLR Version on IIS app pool. Is there any way to set it to No Managed Code?
Setting <iis:WebAppPool ManagedRuntimeVersion="No Managed Code"> results in error The worker process failed to pre-load .Net Runtime version No Managed Code.

Solution is to use "" instead of "No Managed Code" when setting managedRuntimeVersion.

The iis:WebAppPool/#ManagedRuntimeVersion attribute's value cannot be an empty string.

Use the below sample method to create Application pool with No Managed Code
public void CreateApplicationPoolDotNetCore(string appPoolName)
{
using (ServerManager serverManager = new ServerManager())
{
ApplicationPool newPool = serverManager.ApplicationPools.Add(appPoolName);
newPool.ManagedRuntimeVersion = "";
newPool.Enable32BitAppOnWin64 = true;
newPool.ManagedPipelineMode = ManagedPipelineMode.Integrated;
serverManager.CommitChanges();
}
}

Related

Excel to DataSet using OLEDB working differently between .NET Core and .NET Framework

I have a worker service that references a .NET Framework class library. The class library contains a method to convert Excel to a dataset.
While debugging on Visual Studio, everything works as expected, but after publishing I get the error message:
The 'Microsoft.ACE.OLEDB.12.0' provider is not registered on the local machine.
To debug, I built the below two console apps with exactly the same codeā€”one in .NET Core, the other .NET Framework. I then run the projects on two computers.
Computer A: Microsoft Office Tools installed, but no AccessDatabaseEngine.exe
Computer B: No Microsoft Office Tools, AccessDatabaseEngine installed
using System;
using System.Data;
using System.Data.OleDb;
using System.Text;
namespace ToDataSheetCore
{
class Program
{
static void Main(string[] args)
{
DataSet dt2 = ExcelToDataSetCommon("C:\\pathToExcel\\excelFile - AUGUST 04 2021.xlsx");
StringBuilder sb2 = new StringBuilder();
foreach (DataTable table in dt2.Tables)
{
foreach (DataRow row in table.Rows)
{
sb2.Append(string.Join(" ", row.ItemArray));
sb2.AppendLine();
}
}
Console.WriteLine(sb2);
Console.ReadLine();
}
public static DataSet ExcelToDataSetCommon(string SourceFilename)
{
DataSet ds = new DataSet();
try
{
string connStr = string.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=\"Excel 12.0;HDR=YES;\"", SourceFilename);
OleDbConnection conn = new OleDbConnection(connStr);
conn.Open();
DataTable schemaDT = conn.GetSchema("Tables", new string[] { null, null, null, "TABLE" });
conn.Close();
string tableName = schemaDT.Rows[0]["TABLE_NAME"].ToString();
OleDbCommand cmd = new OleDbCommand(string.Format("SELECT * FROM [{0}]", tableName), conn);
OleDbDataAdapter adapter = new OleDbDataAdapter(cmd);
adapter.Fill(ds);
}
catch (Exception ex)
{
Console.Error.WriteLine(ex.Message);
}
return ds;
}
}
}
Result
Computer A
.NET Core
Debug mode
Prints excel content to console
Publish mode - self-contained(win64, anypc)
The 'Microsoft.ACE.OLEDB.12.0' provider is not registered on the local machine.
.NET Framework
Debug mode
The 'Microsoft.ACE.OLEDB.12.0' provider is not registered on the local machine.
Publish mode - self-contained
The 'Microsoft.ACE.OLEDB.12.0' provider is not registered on the local machine.
Computer B
.NET Core
Debug mode
The 'Microsoft.ACE.OLEDB.12.0' provider is not registered on the local machine.
Publish mode - self-contained(win64, anypc)
The 'Microsoft.ACE.OLEDB.12.0' provider is not registered on the local machine.
.NET Framework
Debug mode
Prints excel content to console (Fails on uninstalling AccessDatabaseEngine)
Publish mode - self-contained
Prints excel content to console (Fails on uninstalling AccessDatabaseEngine)
I understand installing AccessDatabaseEngine provider has an effect, but I don't understand the different results from .NET Framework and .NET Core.
Though I have resorted to using ExcelDataReader since I want to avoid external dependencies.
I am confused by the difference in the results using OleDB API between .NET Core and .NET Framework. Is there a way the AccessDatabaseEngine provider can be published together with a .NET project?

Keyword not supported: 'authentication' error for azure integrated connection

Getting Keyword not supported: 'authentication' error while trying to connect an azure DB through 'Active Directory Integrated' option in .NET core 2.1 project.
Note: I am using EF core to connect the Data source.
TL;DR
As called out by #Aamir Mulla in the comments, this has officially been added since Version 2.0.0
UPDATE - 16/08/2019
Active Directory Password Authentication has now been added for .NET Core in Microsoft.Data.SqlClient 1.0.19221.1-Preview
Unfortunately, the authentication keyword is not yet fully supported in .NET Core. Here is an issue which discusses this.
But .NET Core 2.2 has added some support for this use case as mentioned in this comment. The basic idea is to get the access token by any means (ADAL, REST, etc.) and set SqlConnection.AccessToken to it.
As for using this with EF Core, there's a good discussion about this in this github issue and in particular the comment by mgolois provides a simple implementation to the solution that cbriaball mentions in the thread.
Here is the same for reference
Note that this sample is using the Microsoft.Azure.Services.AppAuthentication library
// DB Context Class
public class SampleDbContext : DbContext
{
public SampleDbContext(DbContextOptions<TeamsDbContext> options) : base(options)
{
var conn = (System.Data.SqlClient.SqlConnection)this.Database.GetDbConnection();
conn.AccessToken = (new AzureServiceTokenProvider()).GetAccessTokenAsync("https://database.windows.net/").Result;
}
}
// Startup.cs
services.AddDbContext<SampleDbContext>(options =>
{
options.UseSqlServer(<Connection String>);
});
The connection string would be something like this
Server=tcp:<server_name>.database.windows.net,1433;Database=<db_name>;
If you're still having the issue, make sure you have
Microsoft.Data.SqlClient package installed, not System.Data.SqlClient. They both contain SqlConnection class, switching the package for the first one fixed the issue for me.
As of today 7/18/2022 , I am still getting the issue from Azure when trying to use it through ManagedIdentity.
The microsoft doc at https://learn.microsoft.com/en-us/azure/app-service/tutorial-connect-msi-sql-database?tabs=windowsclient%2Cefcore%2Cdotnetcore
to use managed identity we need to use the connection string in this format!
"Server=tcp:.database.windows.net;Authentication=Active Directory Default; Database=;"
But looks like Azure is not liking it!
However, adding the access token helped!
var connectionString =
"Server=tcp:yourazuresqlservername.database.windows.net; Database=yourazuresqldbname;";
var con = new SqlConnection(connectionString);
//And then
con.AccessToken = (new AzureServiceTokenProvider()).GetAccessTokenAsync("https://database.windows.net/").Result;
con.Open();
//Do sql tasks
con.Close();

Windows Azure project errors The CctSharedPackage did not load correctly

I opened a solution file that was working fine and got this mysterious error
The 'CctSharedPackage' did not load correctly
This project was a Windows Azure 2.1 project that had no issues working last week, however between then and a reboot it would not successfully load in Visual Studio 2012 any longer. This occurred on a machine that does have Windows Azure SDK 2.1 installed (the project did work fine last week)
The error stated to check the c:\Users\{user}\AppData\Roaming\Microsoft\VisualStudio\11.0\ActivityLog.xml file for more information.
In this file it stated "Could not find assembly Microsoft.Azure.Diagnostics ver 2.1".
Seeing as Windows Azure SDK 2.1 was already installed, i redownloaded the installer and went to run it to ask it to reinstall or repair the installation. Seeing as the install is the Web Platform Installer, it provided none of those options. At this point I decided that I must uninstall the SDK to be able to reinstall it from Add/Remove Programs.
When I went to Add/Remove Programs I saw that there were installations there for Windows Azure Libraries for .NET - v1.8 and Windows Azure Authoring Tools - v1.8. I removed both of these installations and then the project was able to load successfully.
this seems to be a problem with the installer. Re-installing is an option, but you can fix it with a simple command line by registering your assemblies in the GAC.
C:\Program Files (x86)\Windows Azure Tools\Visual Studio 11.0>gacutil /i .\Microsoft.VisualStudio.WindowsAzure.Diagnostics.dll
I don't have the 1.8 SDK installed. I believe it was a windows update relating to .Net 3.5 which might have broken my installation. To Fix all I did was open up Explorer in Windows 8 and select the 'Uninstall or Change a program' option from the ribbon.
Search for Azure and when there was an option to 'repair' I repaired the program. FIXED
I ran into similar problem (The 'CctSharedPackage' did not load correctly). In my case starting Visual Studio with Run as administrator solved the issue.
I also encountered this prolem today, but for me luckily it was solved just by restarting Visual Studio 2012. Just try it at least once to be sure :-) !
I was having this same problem. Reinstalling SDKs didn't seem to be helping and reinstalling Visual Studio sounded too painful so I decided to figure out what was causing the error.
I used another instance of Visual Studio and attached it to debug the offending Visual Studio instance. I couldn't see where the exact error was happening, but I was able to see what library the exception occured in and could see the source code using .NET Reflector to get an idea of what it does.
On startup the Microsoft.Cct.CctSharedPackage library iterates through all the Azure SDKs to figure out which ones are installed on your computer.
I ended up writing a console application to emulate what the startup does and see if I could find what was wrong. All the classes are internal so I had to use reflection to access them.
On my computer it turned out to be the Azure SDK 1.6 that was messed up. The SDK was installed, but the TargetAzureLibraries property was coming back as null. I uninstalled that SDK and it corrected the problem.
Console app below:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Console.WindowWidth = 240;
// The Microsft.Cct.AssemblyResolver does this:
/*
private IEnumerable<IAzureToolsVersionInfo> GetInstalledSDKsByProductVersionDesc(IServiceProvider serviceProvider) =>
(from knownProduct in AzureToolsVersionInfoUtilities.GetAllProducts()
where knownProduct.TargetAzureSDK.IsSDKInstalled() && knownProduct.TargetAzureLibraries.IsLibrariesInstalled()
orderby knownProduct.ProductVersion descending
select knownProduct)
*/
// Duplicate this logic using reflection to find the SDK install that is broken.
var asm = System.Reflection.Assembly.LoadFile("C:\\Program Files (x86)\\Microsoft Visual Studio 14.0\\Common7\\IDE\\Extensions\\Microsoft\\Windows Azure Tools\\Microsoft.VisualStudio.WindowsAzure.Common.2.8.dll");
var typ = asm.GetType("Microsoft.Cct.ProductVersionInfo.AzureToolsVersionInfoConstants");
//Console.WriteLine(typ.ToString());
var allMethods = typ.GetFields(BindingFlags.Static | BindingFlags.Public).Select(it => it.Name).ToArray();
allMethods = allMethods.Where(it => it.StartsWith("WAT") && it.Length == 5).OrderBy(it => it).ToArray();
foreach (string version in allMethods)
{
var fld = typ.GetField(version, System.Reflection.BindingFlags.Static | System.Reflection.BindingFlags.Public);
dynamic val = fld.GetValue(null);
var azTypeInfo = asm.GetType("Microsoft.Cct.ProductVersionInfo.AzureToolsVersionInfo");
bool isSdkInstalled = false;
bool isLibrariesInstalled = false;
Dictionary<string, string> sdkProperties = new Dictionary<string, string>();
Dictionary<string, string> libProperties = new Dictionary<string, string>();
// Get the SDK reference
var targetAzureSDK = azTypeInfo.GetProperty("TargetAzureSDK").GetValue(val);
Type targetAzureSDKProp = targetAzureSDK.GetType();
var methodNames = targetAzureSDKProp.GetMethods().Select(it => it.Name).ToArray();
var sdkIsInstalledMethod = targetAzureSDKProp.GetMethods().FirstOrDefault(it => it.Name == "IsSDKInstalled");
isSdkInstalled = (bool)sdkIsInstalledMethod.Invoke(targetAzureSDK, null);
var sdkProps = targetAzureSDKProp.GetProperties().ToArray();
foreach (var prop in sdkProps)
{
try
{
sdkProperties[prop.Name] = string.Concat(prop.GetValue(targetAzureSDK));
}
catch (Exception ex)
{
sdkProperties[prop.Name] = "Error:" + ex.Message;
}
}
if (isSdkInstalled)
{
// Get the Azure libraries reference
var targetAzureLibraries = azTypeInfo.GetProperty("TargetAzureLibraries").GetValue(val);
Type targetAzureLibrariesProp = targetAzureLibraries.GetType();
var isInstalledMethod = targetAzureLibrariesProp.GetMethods().FirstOrDefault(it => it.Name == "IsLibrariesInstalled");
isLibrariesInstalled = (bool)isInstalledMethod.Invoke(targetAzureLibraries, null);
var props = targetAzureLibrariesProp.GetProperties().ToArray();
foreach (var prop in props)
{
try
{
libProperties[prop.Name] = string.Concat(prop.GetValue(targetAzureLibraries));
}
catch (Exception ex)
{
libProperties[prop.Name] = "Error:" + ex.Message;
}
}
}
// Output details of this SDK
Console.WriteLine("{0}, {1}, {2}", version, isSdkInstalled, isLibrariesInstalled);
Console.WriteLine("\tSDK");
foreach (var kp in sdkProperties)
{
Console.WriteLine("\t{0} {1}", kp.Key, kp.Value);
}
Console.WriteLine("\tLib");
foreach (var kp in libProperties)
{
Console.WriteLine("\t{0} {1}", kp.Key, kp.Value);
}
}
}
}
}
Uninstalled all Windows Azure entries ending with October 2012 via control panel. After reopening my solution I got a dialog to convert the project target (screenshot).
I second the turn it off then on again option. Got this error on loading a project after a week away. Rebooted and it went away. So try that at least once.

Subsonic 3 Class Library & Winforms App Null IDataProvider BUG

I have got a class library project and a winforms app.
Everything is getting geerated fine and my Winforms app references the class library but as soon as I run it and try to retreive data it comes up with dataprovider is null.
The one thing to note is that I do not have a app.config in my Winforms app only in the class library. Do I need one in the Winforms app and if so what do I put in it?
Thanks
UPDATE: I think I have found a bug in Query\Select.cs
public Select(IDataProvider provider, params string[] columns)
{
//_provider is null
//provider is populated correctly
this.sqlFragment = new SqlFragment(_provider);
_provider = provider;
SelectColumnList = columns;
SQLCommand = this.sqlFragment.SELECT;
}
Yes, you need an App.config in your Winforms app and you put your connection string there. It's worth noting that an App.config is pointless in a class library EXCEPT when you're using SubSonic :), which will pull one from the project.
Class libraries don't have their own configuration - they pull their config from the execution environment.

How to Create a Managed Path through SharePoint Object Model

This is a question for a WSS/SharePoint guru.
Consider this scenario: I have an ASP.Net web service which links our corporate CRM system and WSS-based intranet together. What I am trying to do is provision a new WSS site collection whenever a new client is added to the CRM system. In order to make this work, I need to programmatically add the managed path to the new site collection. I know that this is possible via the Object Model, but when I try it in my own web service, it fails. Sample code extract below:
Dim _ClientSiteUrl As String = "http://myintranet/clients/sampleclient"
Using _RootWeb As SPSite = New SPSite("http://myintranet")
Dim _ManagedPaths As SPPrefixCollection = _RootWeb.WebApplication.Prefixes
If Not (_ManagedPaths.Contains(_ClientSiteUrl)) Then
_ManagedPaths.Add(_ClientSiteUrl, SPPrefixType.ExplicitInclusion)
End If
End Using
This code fails with a NullReferenceException on SPUtility.ValidateFormDigest(). Research suggested that this may be due to insufficient privileges, I tried running the code within an elevated privileges block using SPSecurity.RunWithElevatedPrivileges(AddressOf AddManagedPath), where AddManagedPath is a Sub procedure containing the above code sample.
This then fails with an InvalidOperationException, "Operation is not valid due to the current state of the object."
Where am I going wrong?
One workaround I have managed to do is to call out to STSADM.EXE via Process.Start(), supplying the requisite parameters, and this works.
Update: whilst developing the web service, I am running it using the built-in Visual Studio 2005 web server - what security context will this be running under? Can I change the security context by putting entries in web.config?
Update: I think the problem is definitely to do with not running the web service within the correct SharePoint security context. I decided to go with the workaround I suggested and shell out to STSADM, although to do this, the application pool identity that the web service runs under must be a member of the SharePoint administrators.
Update
I think you have proved that the issue is not with the code.
SPSecurity.RunWithElevatedPrivileges: Normally the code in the SharePoint web application executes with the privileges of the user taking the action. The RunWithElevatedPrivileges runs the code in the context of the SharePoint web application pools account (i think)
The description on MSDN could go into the details a tiny bit more.
The issue with the call may be that the web service is not actually running the code within a SharePoint process, so explaining why it cannot elevate (wild guess alert).
Have a crack at changing the user of your web services application pool and see if that gives any joy.
It is likely to be a permissions issue.
Maybe try:
Dim clientSiteUrl As String = "http://myintranet/clients/sampleclient"
Using SPSite = new SPSite(clientSiteUrl)
webApp As SPWebApplication = SPWebApplication.Lookup(new Uri(clientSiteUrl));
If Not (webApp.Prefixes.Contains(clientSiteUrl)) Then
webApp.Prefixes.Add(clientSiteUrl, SPPrefixType.ExplicitInclusion)
End If
End Using
This is not exact code.
Since the above code is not the exact code, here is the exact working code for a Web Application scopped feature in the Feature Activated event:
On feature activation at the Mange web application features page, activate feature will create a new Explicit managed path in the specified web application (I want to replace the hard coding, maybe with Properties.Feature.Parent, or something similar.)
using (SPSite site = new SPSite("http://dev-moss07-eric/PathHere")) {
SPWebApplication webApp = SPWebApplication.Lookup(new Uri("http://dev-moss07-eric"));
if (webApp.Prefixes.Contains("PathHere"))
{
//
}
else
{
webApp.Prefixes.Add("PathHere", SPPrefixType.ExplicitInclusion);
}
}
Code can probably be improved, but its my attempt at converting the above code.
If you want to create a managed path (explicit) and a site collection at that path, do the following:
using (SPSite site = new SPSite("http://dev-moss07-eric")) {
SPWebApplication webApp = SPWebApplication.Lookup(new Uri("http://dev-moss07-eric"));
if (webApp.Prefixes.Contains("ManagedPathHere"))
{
//
}
else
{
webApp.Prefixes.Add("ManagedPathHere", SPPrefixType.ExplicitInclusion);
}
using (SPWeb web = site.OpenWeb())
{
SPWebApplication webApplication = web.Site.WebApplication;
try
{
webApplication.Sites.Add("ManagedPathHere","Site Title Here","This site is used for hosting styling assets.", 1033, "STS#1", "6scdev\\eric.schrader", "Eric Schrader", "eric.schrader#6sc.com");
}
catch (Exception ex)
{
//ex.ToString;
}
}
}

Resources