I need to work with HTMLAgilityPack and Newtonsoft.Json on my Azure function, and it has become a serious headache for me. Even after installing and referencing all the required packages via Nuget, multiple times over the course of many days, nothing seems to be working in my favor.
Below is a piece of my code for reference:
#r "HtmlAgilityPack"
using HtmlAgilityPack;
public static SiteMeta GetSiteMeta(string URL)
{
SiteMeta siteMeta = new SiteMeta();
string retImg = "", retDesc = "", retTitle = "", retKeywords = "";
var getHtmlDoc = new HtmlWeb(); // Need to use this function from HTMLAgility pack
var document = getHtmlDoc.Load(URL);
var metaTags = document.DocumentNode.SelectNodes("//meta");
if (metaTags != null)
{
foreach (var sitetag in metaTags)
{
if (sitetag.Attributes["property"] != null && sitetag.Attributes["content"] != null && sitetag.Attributes["property"].Value.ToLower() == "og:description")
{
retDesc = sitetag.Attributes["content"].Value;
}
}
}
}
I've tried https://stackoverflow.com/a/63048380/1584140 a couple of times and many other answers over Stackoverflow as well as other websites, but the only errors I see everywhere are:
run.csx(5,1): error CS0006: Metadata file 'HtmlAgilityPack' could not be found
run.csx(17,7): error CS0246: The type or namespace name 'HtmlAgilityPack' could not be found (are you missing a using directive or an assembly reference?)
run.csx(108,30): error CS0246: The type or namespace name 'HtmlWeb' could not be found (are you missing a using directive or an assembly reference?)
Similar thing happens with Newtonsoft.Json as well.
This is how my VS project looks like:
Edit July 10 2022: Adding content on .csproj
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net461</TargetFramework>
</PropertyGroup>
<ItemGroup>
<None Remove="TimerTrigger1\run.csxc" />
</ItemGroup>
<ItemGroup>
<None Include="TimerTrigger1\function.proj" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="HtmlAgilityPack" Version="1.11.43" />
<PackageReference Include="Microsoft.NET.Sdk.Functions" Version="4.1.1" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.1" />
<PackageReference Include="System.Text.Json" Version="6.0.5" />
</ItemGroup>
<ItemGroup>
<Reference Include="Microsoft.CSharp" />
</ItemGroup>
<ItemGroup>
<None Update="host.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
<None Update="TimerTrigger1/function.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
<None Update="TimerTrigger1/readme.md">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
<None Update="TimerTrigger1\run.csx">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
<None Update="local.settings.json">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
</ItemGroup>
</Project>
Related
I recently tried decrypting and verifying PKCS#7 message in C# .NET Core 3.1 Web Application. Here is how I did it.
I used System.Security.Cryptography.Pkcs in Web app project. But after implementing same package and trying to decrypt and verify in Azure function, it returns exception
{"Could not load file or assembly 'System.Security.Cryptography.Pkcs, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'. The system cannot find the file specified.":"System.Security.Cryptography.Pkcs, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"}.
I tried several stack overflow answers but couldn't sort it.
System.Security.Cryptography.X509Certificates is working fine in Azure function, but Pkcs seems to have issue.
Anyway I can sort it out?
Here is my .csproj:
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netcoreapp3.1</TargetFramework>
<AzureFunctionsVersion>v3</AzureFunctionsVersion>
<UserSecretsId>695a883e-9b1a-4d55-98a9-0b47b683bbb2</UserSecretsId>
<Nullable>annotations</Nullable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Autofac" Version="6.1.0" />
<PackageReference Include="Dapper" Version="2.0.78" />
<PackageReference Include="Microsoft.ApplicationInsights.WorkerService" Version="2.15.0" />
<PackageReference Include="Microsoft.Azure.Functions.Extensions" Version="1.1.0" />
<PackageReference Include="Microsoft.Azure.WebJobs.Extensions.DurableTask" Version="2.4.2" />
<PackageReference Include="Microsoft.NET.Sdk.Functions" Version="3.0.11" />
<PackageReference Include="System.Collections" Version="4.3.0" />
<PackageReference Include="System.Data.SqlClient" Version="4.8.2" />
<PackageReference Include="System.Security.Cryptography.Pkcs" Version="6.0.0" />
</ItemGroup>
<ItemGroup>
<None Update="host.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
<None Update="local.settings.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
<CopyToPublishDirectory>Never</CopyToPublishDirectory>
</None>
</ItemGroup>
</Project>
Mishra](https://stackoverflow.com/users/13378259/rocky-mishra) Glad that your issue got resolved and posting your suggestion as answer to help the other community members who face similar kind of issue.
Below example code with helping in resolving the issue.
public class FunctionsAssemblyResolver
{
public static void RedirectAssembly()
{
var list = AppDomain.CurrentDomain.GetAssemblies().OrderByDescending(a => a.FullName).Select(a => a.FullName).ToList();
AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve;
}
private static Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs args)
{
var requestedAssembly = new AssemblyName(args.Name);
Assembly assembly = null;
AppDomain.CurrentDomain.AssemblyResolve -= CurrentDomain_AssemblyResolve;
try
{
assembly = Assembly.Load(requestedAssembly.Name);
}
catch (Exception ex)
{
}
AppDomain.CurrentDomain.AssemblyResolve += CurrentDomain_AssemblyResolve;
return assembly;
}
}
For further information check this SO.
I would like to ask you about parsing of XML, I try it by many ways but never get result what I "want/expect".
I would like to get ALL elements of specific name ("packageReference") and his attributes/children(elements). After that I will make collection and parse the result to get value of "include" attribute and value of element/atribute with name "version"
example of xml (my elements which I am interest is on bottom):
<?xml version="1.0" encoding="utf-8"?>
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<PropertyGroup>
<AutoGenerateBindingRedirects>true</AutoGenerateBindingRedirects>
<IsWebBootstrapper>false</IsWebBootstrapper>
<PublishUrl>publish\</PublishUrl>
<Install>true</Install>
<UpdateIntervalUnits>Days</UpdateIntervalUnits>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|iPhoneSimulator' ">
<DebugSymbols>true</DebugSymbols>
<DebugType>full</DebugType>
<Optimize>false</Optimize>
</PropertyGroup>
<ItemGroup>
<Compile Include="Launch.cs" />
<Compile Include="Launch.designer.cs">
<DependentUpon>Launch.cs</DependentUpon>
</Compile>
<Compile Include="Main.cs" />
<None Include="Info.plist">
<SubType>Designer</SubType>
</None>
</ItemGroup>
<ItemGroup>
<Reference Include="System" />
<Reference Include="System.Core" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\Model\Project.Model.csproj">
<Project>{0511395F-513C-4F56-BF87-718CA49BB13B}</Project>
<Name>Project.Model</Name>
</ProjectReference>
</ItemGroup>
<ItemGroup>
<PackageReference Include="AutoMapper">
<Version>7.0.1</Version>
</PackageReference>
<PackageReference Include="GMImagePicker.Xamarin">
<Version>2.5.0</Version>
</PackageReference>
<PackageReference Include="IdentityModel">
<Version>4.1.0</Version>
</PackageReference>
<PackageReference Include="Microsoft.AppCenter">
<Version>4.3.0</Version>
</PackageReference>
<PackageReference Include="Microsoft.AppCenter.Analytics">
<Version>4.3.0</Version>
</PackageReference>
<PackageReference Include="Microsoft.AppCenter.Crashes">
<Version>4.3.0</Version>
</PackageReference>
<PackageReference Include="Package.Test" Version="1.1.21" />
</ItemGroup>
<ItemGroup />
</Project>
The result should be:
AutoMapper;7.0.1
GMImagePicker.Xamarin;2.5.0
...
...
Package.Test;1.1.21
My code:
var text = System.IO.File.ReadAllText(#"C:\MyGit\TestXML3.csproj");
var root = XElement.Parse(text);
var packageReferencesElements = root.Descendants("PackageReference");
var packageReferencesElementsAndSelf = root.DescendantsAndSelf("PackageReference");
var packageReferencesElementsOffElement = root.Elements().DescendantsAndSelf("PackageReference");
I tried many ways and few of them you can see in code.
I dont want to "go" into every element which have child and checking in loop if there is something what I can be interest. There must be better way. And point there is that I am not sure if my elements which I am looking for is in 2 layer or even deeper.
Update: this code is working to get my information, when I know how deep they are... But when I dont know how deep it should be?
var root = XElement.Parse(fileString);
var itemGroupsELements = root.Elements().Where(x => x.Name.LocalName == "ItemGroup");
var packageReferenceElements = itemGroupsELements.Elements().Where(x => x.Name.LocalName == "PackageReference");
foreach (var packageReference in packageReferenceElements)
{
string packageName = packageReference.Attribute("Include").Value;
string version = (packageReference.Attribute("Version") != null)
? packageReference.Attribute("Version").Value
: packageReference.Value;
_packageList.Add(new Package(){App = app, PackageName = packageName, PackageVersion = version, Project = projectName});
}
Any idea what I am doing wrong?
Thank you!
PackageReference (like all the other elements in the file) is in the XML namespace "http://schemas.microsoft.com/developer/msbuild/2003". You have to specify the namespace in your call to Descendants:
XNamespace build = "http://schemas.microsoft.com/developer/msbuild/2003";
var packageReferencesElements = root.Descendants(build + "PackageReference");
When I send an HTTP request to the function, It shows this error on console output, and returns HTTP 500 status code without hitting the the break point of function's first line.
Executed 'Validate' (Failed, Id=548b4612-42f8-4e49-886a-da6888045c32,
Duration=343ms) System.Net.Primitives: Value cannot be null.
(Parameter 'host') An unhandled host error has occurred.
System.Net.Primitives: Value cannot be null. (Parameter 'host').
Function
[FunctionName("Validate")]
public async Task Run(
[HttpTrigger(AuthorizationLevel.Function, "post", Route = null)] string req,
[SignalR(HubName = "PubSub")] IAsyncCollector<SignalRMessage> signalRMessageQueue)
{
...
}
host.json
{
"version": "2.0",
"logging": {
"applicationInsights": {
"samplingExcludedTypes": "Request",
"samplingSettings": {
"isEnabled": true
}
}
}
.csproj
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netcoreapp3.1</TargetFramework>
<AzureFunctionsVersion>v3</AzureFunctionsVersion>
<RootNamespace>ZulaMobile.Lobby.StoreValidation</RootNamespace>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Azure.Functions.Extensions" Version="1.1.0" />
<PackageReference Include="Microsoft.Azure.WebJobs" Version="3.0.30" />
<PackageReference Include="Microsoft.Azure.WebJobs.Extensions.SignalRService" Version="1.6.0" />
<PackageReference Include="Microsoft.Extensions.Logging.Abstractions" Version="3.1.21" />
<PackageReference Include="Microsoft.NET.Sdk.Functions" Version="3.0.11" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\zulamobile-azure-lobby-common\zulamobile-azure-lobby-common.csproj" />
</ItemGroup>
<ItemGroup>
<None Update="host.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
<None Update="local.settings.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
<CopyToPublishDirectory>Never</CopyToPublishDirectory>
</None>
</ItemGroup>
<ItemGroup>
<Folder Include="Functions\CafeBazaar\" />
<Folder Include="Huawei\" />
</ItemGroup>
</Project>
I tried to reproduce the same issue but it worked fine at my end.
Followed by this MS DOC & demo GitHub project ,
Created a Signal IR in Azure portal .
Open the download folder from my VS Code-
And added the following packages into my local here is my .csproj file
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netcoreapp3.1</TargetFramework>
<AzureFunctionsVersion>v3</AzureFunctionsVersion>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Azure.WebJobs.Extensions.SignalRService" Version="1.6.0" />
<PackageReference Include="Microsoft.NET.Sdk.Functions" Version="3.0.11" />
</ItemGroup>
<ItemGroup>
<None Update="content\index.html">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</None>
<None Update="host.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
<None Update="local.settings.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
<CopyToPublishDirectory>Never</CopyToPublishDirectory>
</None>
</ItemGroup>
</Project>
And make sure that you have added your connection string in your local settings.json which have to copy from portal from Azure signalIR > Keys>Connection string.
Here are some screenshot for reference output:
Note: If still facing the same issue you can try to Un install the Azure function V3 and install it again .
For more information please refer this SO THREAD .
I'm trying to load a ViewComponent from a different assembly but in the main project I'm getting the error below
InvalidOperationException: A view component named 'Pro.ItemViewComponent' could not be found. A view component must be a public non-abstract class, not contain any generic parameters, and either be decorated with 'ViewComponentAttribute' or have a class name ending with the 'ViewComponent' suffix. A view component must not be decorated with 'NonViewComponentAttribute'.
Library.csproj
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netcoreapp2.1</TargetFramework>
</PropertyGroup>
<ItemGroup>
<None
Remove="Views\Shared\Components\ContainerViewComponent\Default.cshtml"/>
<None Remove="Views\Shared\Components\ItemViewComponent\Default.cshtml" />
<None Remove="Views\Shared\_ViewImports.cshtml" />
</ItemGroup>
<ItemGroup>
<Content
Include="Views\Shared\Components\ContainerViewComponent\Default.cshtml">
<CopyToPublishDirectory>PreserveNewest</CopyToPublishDirectory>
<Pack>$(IncludeRazorContentInPack)</Pack>
</Content>
<Content Include="Views\Shared\Components\ItemViewComponent\Default.cshtml">
<CopyToPublishDirectory>PreserveNewest</CopyToPublishDirectory>
<Pack>$(IncludeRazorContentInPack)</Pack>
</Content>
<Content Include="Views\Shared\_ViewImports.cshtml">
<CopyToPublishDirectory>PreserveNewest</CopyToPublishDirectory>
<Pack>$(IncludeRazorContentInPack)</Pack>
</Content>
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="Views/**/*.cshtml" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.App" Version="2.1.1" />
</ItemGroup>
Startup.cs in main project.
var assembly = typeof(Pro.ItemViewComponent).Assembly;
var embeddedFileProvider = new EmbeddedFileProvider(
assembly,
"Pro"
);
services.Configure<RazorViewEngineOptions>(options =>
{
options.FileProviders.Add(embeddedFileProvider);
});
I have followed many articles and some questions and answer in StackOverflow but I didn't find any solution, What should I do to share the ViewComponent from a different assembly?
The problem was really simple in the configuration in Startup.cs, I had to add services.AddMvc().AddApplicationPart(myAssembly); the full configuration is below.
var myAssembly = typeof(MyViewComponent).Assembly;
services.AddMvc().AddApplicationPart(myAssembly);
services.Configure<RazorViewEngineOptions>(options =>
{
options.FileProviders.Add(new EmbeddedFileProvider(myAssembly, "ComponentLib"));
});
I'm compiling a projet both for net462 and dotnetcore2.0.
I have set the net462;dotnetcore2.0
It seems to work but I need to load an embedded resource like this:
using (var stream = assembly.GetManifestResourceStream("Alcuin.Admin.Api.Beans.TypeTraduction.json"))
using (var reader = new StreamReader(stream))
result = reader.ReadToEnd();
It gives me back a null stream.
Here is my csproj file:
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFrameworks>netcoreapp2.0;net462</TargetFrameworks>
<GenerateAssemblyInfo>false</GenerateAssemblyInfo>
</PropertyGroup>
<ItemGroup>
<None Remove="Beans\TypeTraduction.json" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="Beans\TypeTraduction.json" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Newtonsoft.Json" Version="10.0.3" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\..\..\..\Common\Alcuin.Common.Basics\Alcuin.Common.Basics.csproj" />
<ProjectReference Include="..\..\..\..\Common\Alcuin.Common.Graph\Alcuin.Common.Graph.csproj" />
</ItemGroup>
</Project>
Does someone know how to make it work properly?
Thanks.
Nevermind... I just had to remove this section :
<ItemGroup>
<None Remove="Beans\TypeTraduction.json" />
</ItemGroup>
Problem solved.