Xamarin Forms LibVLC Video is not shown in Release configuration - c#

We are developing an Xamarin.Froms App and we got some problems with the video player the flowing code is working fine in debug or more specifically when shred runtime is enabled.
Package:
<PackageReference Include="LibVLCSharp.Forms" Version="3.4.6" />
<PackageReference Include="Xamarin.Forms" Version="4.7.0.1239" />
<TargetFramework>netstandard2.0</TargetFramework>
Android Package:
<PackageReference Include="Xamarin.Forms" Version="4.7.0.1239" />
<PackageReference Include="Xamarin.Android.Support.Design" Version="28.0.0.3" />
<PackageReference Include="Xamarin.Android.Support.v7.AppCompat" Version="28.0.0.3" />
<PackageReference Include="Xamarin.Android.Support.v4" Version="28.0.0.3" />
<PackageReference Include="Xamarin.Android.Support.v7.CardView" Version="28.0.0.3" />
<PackageReference Include="Xamarin.Android.Support.v7.MediaRouter" Version="28.0.0.3" />
Code behind for page:
using LibVLCSharp.Shared;
using System;
using Xamarin.Forms;
namespace myTrekkaApp.Views
{
public partial class TestPage : ContentPage
{
public TestPage()
{
InitializeComponent();
Core.Initialize();
LibVLC libVlc = new LibVLC();
MediaPlayer mediaPlayer = new MediaPlayer(libVlc)
{
EnableHardwareDecoding = true,
};
mediaPlayer.Media = new Media(libVlc, new Uri("http://commondatastorage.googleapis.com/gtv-videos-bucket/sample/ElephantsDream.mp4"));
MediaPlayerElement.MediaPlayer = mediaPlayer;
MediaPlayerElement.LibVLC = libVlc;
MediaPlayerElement.IsVisible = true;
mediaPlayer.Play();
}
}
}
Page:
<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:vlc="clr-namespace:LibVLCSharp.Forms.Shared;assembly=LibVLCSharp.Forms"
x:Class="myTrekkaApp.Views.TestPage">
<vlc:MediaPlayerElement x:Name="MediaPlayerElement" />
</ContentPage>

Using r8 needs a bit more config.
Create a new file in your Xamarin.Android app root named "r8.cfg".
In this file properties, set the Build Action to "ProguardConfiguration".
In this file, add the following lines:
-keep class org.videolan.** { *; }
-dontwarn org.videolan.**
https://code.videolan.org/videolan/LibVLCSharp/-/blob/3.x/docs/android.md

Related

MissingMethodException in Integration test with sqlite

I have the following exception:
I was using .NET 6 (I still had the error) and thought that it could be some conflict with the nugets I am using in my solution. It turns out that even after updating to .NET 7 the error persists when I run the test. For testing I'm using MSTest Framework and using an inmemory database (sqlite) to make integration tests. The error is happening when executing the line await context.Database.EnsureCreatedAsync();. The test classes are the following:
public class SQLiteDatabaseContextFactory : IDisposable
{
private DbConnection _connection;
private DbContextOptions<DataContext> CreateOptions()
{
return new DbContextOptionsBuilder<DataContext>()
.UseSqlite(_connection).Options;
}
public DataContext CreateContext()
{
if (_connection == null)
{
_connection = new SqliteConnection("DataSource=:memory:");
_connection.Open();
var options = CreateOptions();
using var context = new DataContext(options);
context.Database.EnsureCreated();
}
return new DataContext(CreateOptions());
}
public void Dispose()
{
if (_connection != null)
{
_connection.Dispose();
_connection = null;
}
}
}
And:
[TestClass]
public class SQLiteIntegrationTests
{
[TestMethod]
public async Task TestMethod_UsingSqliteInMemoryProvider_Success()
{
using var connection = new SqliteConnection("DataSource=:memory:");
connection.Open();
var options = new DbContextOptionsBuilder<DataContext>()
.UseSqlite(connection) // Set the connection explicitly, so it won't be closed automatically by EF
.Options;
// Create the dabase schema
// You can use MigrateAsync if you use Migrations
using (var context = new DataContext(options))
{
//await context.Database.MigrateAsync();
await context.Database.EnsureCreatedAsync();
} // The connection is not closed, so the database still exists
using (var context = new DataContext(options))
{
var user = new ManualClassifier()
{
FirstName = "First",
LastName = "Last",
Email = "example#gmail.com",
Username = "firstlast123",
PasswordHash = "5994471abb01112afcc18159f6cc74b4f511b99806da59b3caf",
PasswordSalt = "5994471abb01112afcc18159f6cc74b4f511b99806da59b3caf"
};
context.ManualClassifiers.Add(user);
await context.SaveChangesAsync();
}
using (var context = new DataContext(options))
{
var count = await context.ManualClassifiers.CountAsync();
Assert.AreEqual(1, count);
var u = await context.ManualClassifiers.FirstOrDefaultAsync(user => user.Email == "example#gmail.com");
Assert.IsNotNull(u);
}
}
}
EDIT: The full error is the following:
The .csproj of the project where I'm running the tests:
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net7.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.EntityFrameworkCore.Sqlite" Version="6.0.13" />
<PackageReference Include="MSTest.TestFramework" Version="3.0.2" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\VSC.Repo\VSC.Repo.csproj" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.7.1" />
<PackageReference Include="MSTest.TestAdapter" Version="2.1.1" />
<PackageReference Include="MSTest.TestFramework" Version="2.1.1" />
<PackageReference Include="coverlet.collector" Version="1.3.0" />
</ItemGroup>
</Project>
Dbcontext class library .csproj:
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net7.0</TargetFramework>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
</PropertyGroup>
<ItemGroup>
<FrameworkReference Include="Microsoft.AspNetCore.App" />
</ItemGroup>
<ItemGroup>
<Folder Include="Services\" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="7.0.2" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="7.0.2">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="7.0.2" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="7.0.2">
<PrivateAssets>all</PrivateAssets>
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
</PackageReference>
<PackageReference Include="System.Configuration.ConfigurationManager" Version="7.0.0" />
</ItemGroup>
</Project>
Any help figuring what is happening would be much appreciated. I honestly have no clue what is causing this.
Looks a lot like package version mismatch (in my practice it is the most common source of such errors). Update Microsoft.EntityFrameworkCore.Sqlite to the latest 7th version (my guess is that EF project uses that version) to match major version of EF Core packages in the tested solution.

Incremental Source Generator generated code passed compilation with syntax error

I made a Incremental Source Generator:
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<IsRoslynComponent>true</IsRoslynComponent>
<LangVersion>latest</LangVersion>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.CodeAnalysis" Version="4.2.0" />
<PackageReference Include="System.Text.Json" Version="6.0.0" />
</ItemGroup>
</Project>
It generates code that has an obvious syntax error
[Generator]
public class SourceGenerator : IIncrementalGenerator {
public void Initialize(IncrementalGeneratorInitializationContext context) {
context.RegisterSourceOutput(context.AdditionalTextsProvider, static (context, name) => {
string sourceCode = $#"
public class {"AAA"}{{
{{
}}
";
context.AddSource("AAA" + ".g.cs", sourceCode);
});
}
After building the solution for the first time and errors were expected. I restarted Visual Studio. I can see following code was generated:
public class AAA{
{
}
When viewing this AAA.g.cs, the text editor didn't highlight the fault of less closing braket.
Then I build the solution for the second time. It was succeeded. How can this be possible?

How to avoid using namespace prefixes in Xaml

I've started migrating company owned application from UWP 10 to WinUI (on NET5) using upgrade-assistant tool. Give or take, the most conflicts are gone, but the the nasty one remains in .xaml files. The underlying code can't be source-generated due to missing namespace prefixes:
<ResourceDictionary
xmlns:xaml="clr-namespace:Windows.UI.Xaml;assembly=Windows"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:Ifs.Uma.UI.Controls">
<Style TargetType="local:Dialog">
<Setter Property="Background" Value="#FFEDEDED" />
</Style>
</ResourceDictionary>
I'm not sure if I'm missing some package references. Or if it's possible to just define them somewhere (XmlnsDefinitionAttribute is not available)? Is it even possible without going through hundreds of .xaml files and fixing all them manually or via find-replace?
For example, one of .csproj files with referenced packages below:
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<OutputType>Library</OutputType>
<RootNamespace>SomeUI</RootNamespace>
<DefaultLanguage>en</DefaultLanguage>
<CodeAnalysisRuleSet>..\FrameworkRules.ruleset</CodeAnalysisRuleSet>
<AppxBundlePlatforms>x86|x64</AppxBundlePlatforms>
<GenerateAssemblyInfo>false</GenerateAssemblyInfo>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
<DefineConstants>DEBUG;TRACE;NETFX_CORE;WINDOWS_UWP</DefineConstants>
<WarningLevel>4</WarningLevel>
</PropertyGroup>
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DefineConstants>TRACE;NETFX_CORE;WINDOWS_UWP</DefineConstants>
<WarningLevel>4</WarningLevel>
<CodeAnalysisRuleSet>..\FrameworkRules.Release.ruleset</CodeAnalysisRuleSet>
<TreatWarningsAsErrors>true</TreatWarningsAsErrors>
</PropertyGroup>
<PropertyGroup>
<NetStandardImplicitPackageVersion>2.0.3</NetStandardImplicitPackageVersion>
</PropertyGroup>
</ItemGroup>
<ItemGroup>
<Compile Update="Properties\AssemblyInfo.cs">
<CopyToOutputDirectory>Always</CopyToOutputDirectory>
</Compile>
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.DotNet.UpgradeAssistant.Extensions.Default.Analyzers" Version="0.3.330701">
<PrivateAssets>all</PrivateAssets>
</PackageReference>
</ItemGroup>
<!-- I had to add those manually to get the code working -->
<ItemGroup>
<PackageReference Include="System.Runtime.InteropServices.WindowsRuntime" Version="4.3.0" />
<PackageReference Include="System.Runtime.WindowsRuntime" Version="4.7.0" />
<PackageReference Include="System.Runtime.WindowsRuntime.UI.Xaml" Version="4.7.0" />
<Reference Include="Windows">
<HintPath Condition="Exists('C:\Program Files (x86)\Windows Kits\10\UnionMetadata\Facade\Windows.winMD')">C:\Program Files (x86)\Windows Kits\10\UnionMetadata\Facade\Windows.winMD</HintPath>
</Reference>
<Reference Include="Windows.Foundation.FoundationContract">
<HintPath Condition="Exists('C:\Program Files (x86)\Windows Kits\10\References\10.0.19041.0\Windows.Foundation.FoundationContract\4.0.0.0\Windows.Foundation.FoundationContract.winmd')">C:\Program Files (x86)\Windows Kits\10\References\10.0.19041.0\Windows.Foundation.FoundationContract\4.0.0.0\Windows.Foundation.FoundationContract.winmd</HintPath>
</Reference>
<Reference Include="Windows.Foundation.UniversalApiContract">
<HintPath Condition="Exists('C:\Program Files (x86)\Windows Kits\10\References\10.0.19041.0\Windows.Foundation.UniversalApiContract\10.0.0.0\Windows.Foundation.UniversalApiContract.winmd')">C:\Program Files (x86)\Windows Kits\10\References\10.0.19041.0\Windows.Foundation.UniversalApiContract\10.0.0.0\Windows.Foundation.UniversalApiContract.winmd</HintPath>
</Reference>
</ItemGroup>
</Project>
I've just went an obvious way, made a simple UWP program to add prefixes and namespaces to those tags (just in case someone's interested):
public sealed partial class MainPage : Page
{
public MainPage()
{
this.InitializeComponent();
this.Loaded += MainPage_Loaded;
}
private async void MainPage_Loaded(object sender, RoutedEventArgs e)
{
// 1. run the following command to make your .xaml files accessible to UWP:
// XCOPY <your_solution_dir>/*.xaml C:\Users\<you>\Pictures\XAML /E
// 2. Delete \bin and \obj directories from there (optional)
// 3. Add Pictures capability to your manifest (imho the easiest one to use)
// <Capabilities>
// <uap:Capability Name = "picturesLibrary" />
// </Capabilities>
var assembly = typeof(ResourceDictionary).Assembly;
var regulars = assembly
.GetExportedTypes()
.Where(type => typeof(DependencyObject).IsAssignableFrom(type) && type.IsClass)
.Select(type => new { Namespace = type.Namespace, TypeName = type.Name, Prefix = type.Namespace.Split('.').Last().ToLowerInvariant() })
.GroupBy(x => x.Prefix)
.Select(x => new {
Regex = new Regex($"(</?)(?={string.Join("|", x.Select(n => n.TypeName))})"),
Replacements = x.Select(y => new Replacement(y.Namespace, y.Prefix)).First() })
.ToDictionary(x => x.Regex, x => x.Replacements);
var namespaceAttributes = new Regex("<(?<=[\b\\w\\d\\D]).*(xmlns)[^>]+", RegexOptions.Singleline);
var picturesDirectory = KnownFolders.PicturesLibrary;
var sourceDirectory = await picturesDirectory.GetFolderAsync("XAML");
var xamlFiles = await GetXamlFilesAsync(sourceDirectory);
var fixedFiles = 0;
foreach (var xamlFile in xamlFiles)
{
var markup = await FileIO.ReadTextAsync(xamlFile);
var matchedReplacements = new List<Replacement>();
foreach (var replacer in regulars)
{
if (replacer.Key.IsMatch(markup))
{
matchedReplacements.Add(replacer.Value);
markup = replacer.Key.Replace(markup, $"$&{replacer.Value.Prefix}:");
}
}
if (matchedReplacements.Count == 0) continue;
var nsAttributes = namespaceAttributes.Match(markup);
if (nsAttributes.Success && markup.Length > nsAttributes.Length)
{
markup = nsAttributes.Result("$&" + Environment.NewLine +
string.Join(Environment.NewLine,
matchedReplacements.Where(replacement => !markup.Contains($"xmlns:{replacement.Prefix}")).Select(replacement =>
$"xmlns:{replacement.Prefix}=\"clr-namespace:{replacement.Namespace};assembly=Windows.Foundation.UniversalApiContract\"")))
+ markup.Substring(nsAttributes.Length);
}
await FileIO.WriteTextAsync(xamlFile, markup);
fixedFiles++;
}
await new Windows.UI.Popups.MessageDialog($"{fixedFiles} of {xamlFiles.Count} xaml files were fixed").ShowAsync();
}
async Task<IList<StorageFile>> GetXamlFilesAsync(StorageFolder topFolder)
{
var xamlFiles = new List<StorageFile>();
var folders = await topFolder.GetFoldersAsync();
foreach (var folder in folders)
{
xamlFiles.AddRange((await folder.GetFilesAsync()).Where(f => StringComparer.OrdinalIgnoreCase.Equals(f.FileType, ".xaml")));
xamlFiles.AddRange(await GetXamlFilesAsync(folder));
}
return xamlFiles;
}
private readonly struct Replacement
{
public Replacement(string #namespace, string prefix)
{
Namespace = #namespace; Prefix = prefix;
}
public readonly string Namespace;
public readonly string Prefix;
}
}
<xaml:ResourceDictionary
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="using:Ifs.Uma.UI.Controls"
xmlns:nav="using:Ifs.Uma.UI.Navigation"
xmlns:xaml="clr-namespace:Windows.UI.Xaml;assembly=Windows.Foundation.UniversalApiContract"
xmlns:controls="clr-namespace:Windows.UI.Xaml.Controls;assembly=Windows.Foundation.UniversalApiContract"
xmlns:shapes="clr-namespace:Windows.UI.Xaml.Shapes;assembly=Windows.Foundation.UniversalApiContract">
<xaml:Style TargetType="local:PageHeader">
<xaml:Setter Property="Height" Value="48" />
<xaml:Setter Property="Background" Value="{ThemeResource IfsAppBackgroundBrush}" />
<xaml:Setter Property="Template">
<xaml:Setter.Value>
<controls:ControlTemplate TargetType="local:PageHeader">
<controls:Grid Background="{TemplateBinding Background}"
BorderBrush="{TemplateBinding BorderBrush}"
BorderThickness="{TemplateBinding BorderThickness}">
<!-- Grid and other controls -->
</controls:Grid>
</controls:ControlTemplate>
</xaml:Setter.Value>
</xaml:Setter>
</xaml:Style>
</xaml:ResourceDictionary>
It all went fine, but resulted in a message that type <controls:ControlTemplate /> does not support direct content. This type is pretty much within every .xaml file. TemplateBinding and other binding types also not found. Perhaps, it's not the way to fix the issue, there might be an SDK missing or something.

NET 5 error when adding migration on Entity Framework Core

I'm setting up a new project with Entity Framework Core 5 and Postgres. All my project and my context are in the same project.
When adding a migration, I'm getting this error:
/src/Api.csproj : error MSB4057: The target "GetEFProjectMetadata" does not exist in the project. Unable to retrieve project metadata. Ensure it's an MSBuild-based .NET Core project. If you're using custom BaseIntermediateOutputPath or MSBuildProjectExtensionsPath values, Use the --msbuildprojectextensionspath option.
EF Core version: 5.0.1
Target framework: net5.0
These are all the commands I tried:
dotnet ef migrations add NewMigration
dotnet ef migrations add NewMigration --msbuildprojectextensionspath
dotnet ef migrations add NewMigration -p ".\src\Api.csproj"
dotnet ef migrations add NewMigration -p ".\src\Api.csproj" --msbuildprojectextensionspath*
I have tried a lot of options I found on the internet, but none worked.
if i add -v , the last lines are:
Using project '/media/pablo/l/Projetos/Web/backend/boilerplate/dotnet_csharp/src/Api.csproj'.
Using startup project '/media/pablo/l/Projetos/Web/backend/boilerplate/dotnet_csharp/src/Api.csproj'.
Writing '/media/pablo/l/Projetos/Web/backend/boilerplate/dotnet_csharp/src/obj/Api.csproj.EntityFrameworkCore.targets'...
dotnet msbuild /target:GetEFProjectMetadata /property:EFProjectMetadataFile=/tmp/tmpbscOwZ.tmp /verbosity:quiet /nologo /media/pablo/l/Projetos/Web/backend/boilerplate/dotnet_csharp/src/Api.csproj
/media/pablo/l/Projetos/Web/backend/boilerplate/dotnet_csharp/src/Api.csproj : error MSB4057: O destino "GetEFProjectMetadata" não existe no projeto.
Microsoft.EntityFrameworkCore.Tools.CommandException: Unable to retrieve project metadata. Ensure it's an SDK-style project. If you're using a custom BaseIntermediateOutputPath or MSBuildProjectExtensionsPath values, Use the --msbuildprojectextensionspath option.
at Microsoft.EntityFrameworkCore.Tools.Project.FromFile(String file, String buildExtensionsDir, String framework, String configuration, String runtime)
at Microsoft.EntityFrameworkCore.Tools.RootCommand.Execute(String[] _)
at Microsoft.EntityFrameworkCore.Tools.Commands.CommandBase.<>c__DisplayClass0_0.<Configure>b__0(String[] args)
at Microsoft.DotNet.Cli.CommandLine.CommandLineApplication.Execute(String[] args)
at Microsoft.EntityFrameworkCore.Tools.Program.Main(String[] args)
Unable to retrieve project metadata. Ensure it's an SDK-style project. If you're using a custom BaseIntermediateOutputPath or MSBuildProjectExtensionsPath values, Use the --msbuildprojectextensionspath option.
Api.csproj:
<Project Sdk="Microsoft.NET.Sdk.Web">
<PropertyGroup>
<TargetFramework>net5.0</TargetFramework>
<DocumentationFile>bin\Debug\net5.0\comments.xml</DocumentationFile>
<GenerateRuntimeConfigurationFiles>true</GenerateRuntimeConfigurationFiles>
<noWarn>1591;1572;1573</noWarn>
<PublishWithAspNetCoreTargetManifest>false</PublishWithAspNetCoreTargetManifest>
<CodeAnalysisRuleSet>../roslynator.ruleset</CodeAnalysisRuleSet>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="FluentValidation" Version="9.4.0" />
<PackageReference Include="FluentValidation.AspNetCore" Version="9.4.0" />
<PackageReference Include="Mapster" Version="7.0.1" />
<PackageReference Include="Swashbuckle.AspNetCore" Version="5.5.1" />
<PackageReference Include="Scrutor" Version="3.3.0" />
<PackageReference Include="Microsoft.EntityFrameworkCore" Version="5.0.1" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Relational" Version="5.0.1" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="5.0.1" />
<PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="5.0.1" />
<PackageReference Include="Npgsql.EntityFrameworkCore.PostgreSQL" Version="5.0.1" />
<PackageReference Include="jaeger" Version="0.4.2" />
<PackageReference Include="OpenTracing.Contrib.NetCore" Version="0.7.1" />
<PackageReference Include="RestSharp" Version="106.2.1" />
<PackageReference Include="Microsoft.AspNetCore.Authentication.JwtBearer" Version="5.0.1" />
<PackageReference Include="Microsoft.EntityFrameworkCore.InMemory" Version="5.0.1" />
<PackageReference Include="Microsoft.AspNet.WebApi.Client" Version="5.2.7" />
<PackageReference Include="Microsoft.AspNetCore.Mvc.NewtonsoftJson" Version="5.0.1" />
<PackageReference Include="Microsoft.Extensions.Hosting" Version="5.0.0" />
<PackageReference Include="Microsoft.OpenApi" Version="1.2.3" />
<PackageReference Include="Swashbuckle.AspNetCore.Newtonsoft" Version="5.6.3" />
</ItemGroup>
<ItemGroup>
<None Include="*.json" CopyToPublishDirectory="Always" CopyToOutputDirectory="Always" />
<None Include="Locales\**\*.json" CopyToPublishDirectory="Always" CopyToOutputDirectory="Always" />
</ItemGroup>
</Project>
Program.cs:
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
namespace Linear.Service_Name.Api
{
public static class Program
{
public static void Main(string[] args)
{
CreateWebHostBuilder(args).Build().Run();
}
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args).UseStartup<Startup>();
}
}
Startup.cs:
using Linear.Service_Name.DataBase.Entities;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using System.Reflection;
[assembly: Microsoft.AspNetCore.Mvc.ApiController]
namespace Linear.Service_Name.Api
{
public class Startup
{
private IWebHostEnvironment _environment { get; }
public Startup(IConfiguration _, IWebHostEnvironment environment)
{
_environment = environment;
}
public void ConfigureServices(IServiceCollection services)
{
services.AddDbContext<Context>(opt => opt
.UseNpgsql(EnvVariables.LINEAR_API_DOMAIN_NAME_DB_CONNECTION_STRING)
);
services.AddCommonsServices<Context>(new CommonServices
{
Env = _environment,
ConnectionString = EnvVariables.LINEAR_API_DOMAIN_NAME_DB_CONNECTION_STRING,
Assembly = Assembly.GetExecutingAssembly(),
Swagger = new CommonServices.SwaggerSettings{
Version = "v1",
Title = "Service_Name",
Description = "API REST do Módulo de " + ("Service_Name").ToUpper()
+ " da solução SG Web."
}
});
}
public void Configure(IApplicationBuilder app)
{
app.UserCommonsMiddlewares(new CommonMiddlewares
{
Env = _environment,
PathBase = EnvVariables.LINEAR_API_SERVICE_NAME_BASE_PATH,
Swagger = new CommonMiddlewares.SwaggerSettings
{
Version = "v1",
Title = "Service_Name"
}
});
}
}
}
Context.cs:
using Linear.Infrastructure.Data.Audit;
using Linear.Infrastructure.Data.MultiTenancy;
using Microsoft.EntityFrameworkCore;
namespace Linear.Service_Name.DataBase.Entities
{
public class Context : DbContext
{
public virtual DbSet<Sample_NamesEntity> Sample_Names { get; set; }
private readonly IAuditEntity _auditEntity;
private readonly IMultiTenancy _multiTenancy;
public Context(DbContextOptions<Context> options, IAuditEntity auditEntity,
IMultiTenancy multiTenancy)
: base(options)
{
_auditEntity = auditEntity;
_multiTenancy = multiTenancy;
}
#region Métodos Protegidos
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
}
protected override void OnModelCreating(ModelBuilder modelBuilder)
=> modelBuilder.ApplyConfigurationsFromAssembly(typeof(Context).Assembly);
#endregion
#region Métodos Públicos
public override int SaveChanges()
{
_multiTenancy.OnSaveChanges(this);
_auditEntity.OnSaveChanges(this);
return base.SaveChanges();
}
public int SaveChangesWithoutMultiTenancy()
{
_auditEntity.OnSaveChanges(this);
return base.SaveChanges();
}
public int SaveChangesWithoutMultiTenancyAndAudit() => base.SaveChanges();
#endregion
}
}
Project link to download:
https://drive.google.com/file/d/1YWlm_teyGMjJe193AwrFqe3VAeVVKWLq/view?usp=sharing
I've been stuck with this problem for over 3 hours, tried a lot of suggestions on internet and still no sucess, i appreciate if i have some help.
After doing some research, it seems that there is a problem with projects with docker integration and the EF Core tooling.
I have downloaded your code and this is the content of your Directory.Build.props
<Project>
<PropertyGroup>
<DefaultItemExcludes>$(DefaultItemExcludes);$(MSBuildProjectDirectory)/obj/**/*</DefaultItemExcludes>
<DefaultItemExcludes>$(DefaultItemExcludes);$(MSBuildProjectDirectory)/bin/**/*</DefaultItemExcludes>
</PropertyGroup>
<PropertyGroup Condition="'$(DOTNET_RUNNING_IN_CONTAINER)' == 'true'">
<BaseIntermediateOutputPath>$(MSBuildProjectDirectory)/obj/container/</BaseIntermediateOutputPath>
<BaseOutputPath>$(MSBuildProjectDirectory)/bin/container/</BaseOutputPath>
</PropertyGroup>
<PropertyGroup Condition="'$(DOTNET_RUNNING_IN_CONTAINER)' != 'true'">
<BaseIntermediateOutputPath>$(MSBuildProjectDirectory)/obj/local/</BaseIntermediateOutputPath>
<BaseOutputPath>$(MSBuildProjectDirectory)/bin/local/</BaseOutputPath>
</PropertyGroup>
</Project>
According to #bricelam in this issue the root of the problem lies here:
Changing BaseIntermediateOutputPath from its default when not running inside a
container breaks the EF Core tooling experience (*)
Since your BaseIntermediateOutputPath was changed from its default to obj/local when running outside the docker container, what you need to do is let the EF Core CLI know where to find that folder. You can accomplish that by using the --msbuildprojectextensionspath parameter. In your case, it would like like this (as suggested here):
dotnet ef migrations add NewMigration --msbuildprojectextensionspath obj/local
If you are still unable to make it work, you could follow the discussion in this other issue. In there, it was suggested that another possible fix is to change a bit your Directory.Build.props and *.csproj files so that the latter looks like the following:
<Project> <!-- Note: No Sdk="" here. -->
<PropertyGroup>
<!-- Don't use $(Configuration) since it isn't set yet. -->
<MSBuildProjectExtensionsPath>$(MSBuildProjectDirectory)\_intermediate_\</MSBuildProjectExtensionsPath>
</PropertyGroup>
<!-- MSBuildProjectExtensionsPath must be set before this gets imported. Directory.Build.props is too late. -->
<Import Project="Sdk.props" Sdk="Microsoft.NET.Sdk" />
<!-- (Project content goes here) -->
<Import Project="Sdk.targets" Sdk="Microsoft.NET.Sdk" />
</Project>

Azure Data Lake store create folder via C# script

I am trying to create new folder inside my datalake store, there is no error in code however nothing is being reflected in datalake store.
Code:
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Threading;
using Microsoft.Azure.Management.DataLake.Store;
using Microsoft.Azure.Management.DataLake.Store.Models;
using Microsoft.Rest.Azure.Authentication;
namespace test_dlstore
{
class Program
{
private static DataLakeStoreAccountManagementClient _adlsClient;
private static DataLakeStoreFileSystemManagementClient _adlsFileSystemClient;
private static string _adlsAccountName;
private static string _subId;
private static void Main(string[] args)
{
_adlsAccountName = "mycreds#mysite.com";
_subId = "2342342-97ce-a54b2-ba6e-234234234234234";
string localFolderPath = #"C:\myfolder\"; // TODO: Make sure this exists and can be overwritten.
string localFilePath = Path.Combine(localFolderPath, "try.txt");
string remoteFolderPath = "adl://mystore.azuredatalakestore.net/myfolder";
string remoteFilePath = Path.Combine(remoteFolderPath, "try.txt");
SynchronizationContext.SetSynchronizationContext(new SynchronizationContext());
var tenant_id = "my-tenant-id";
var nativeClientApp_clientId = "1950a258-227b-4e31-a9cf-717495945fc2";
var activeDirectoryClientSettings = ActiveDirectoryClientSettings.UsePromptOnly(nativeClientApp_clientId, new Uri("urn:ietf:wg:oauth:2.0:oob"));
var creds = UserTokenProvider.LoginWithPromptAsync(tenant_id, activeDirectoryClientSettings).Result;
_adlsClient = new DataLakeStoreAccountManagementClient(creds) { SubscriptionId = _subId };
_adlsFileSystemClient = new DataLakeStoreFileSystemManagementClient(creds);
Console.WriteLine(ListAdlStoreAccounts());
Console.WriteLine(AppendToFile("adl://mystore.azuredatalakestore.net/myfolder/stage/testfile.txt", "abcdefghijklmnopqrstuvwxyz"));
CreateDirectory("adl://mystore.azuredatalakestore.net/myfolder/newdir");
Console.ReadLine();
}
// Append to file
public static string AppendToFile(string path, string content)
{
using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(content)))
{
Console.WriteLine(_adlsAccountName, path, content);
Console.WriteLine(path);
Console.WriteLine(content);
_adlsFileSystemClient.FileSystem.AppendAsync(_adlsAccountName, path, stream);
return "Tried";
}
}
public static string CreateDirectory(string path)
{
_adlsFileSystemClient.FileSystem.MkdirsAsync(_adlsAccountName, path);
return "Tried Creating directory.";
}
}
}
After execution of above code, program exits with no error. The connection is being made.
Also it is displaying datalake stores that are present but not able to do anything at all over the data lake stores.
I am new to azure please help me out.
I do a demo test on my side,it works correctly on side. The following is my detail steps:
Preparation:
Registry an AD application and assign role to applcation, more details please
refer to Azure official tutorials. After that we can get tenantId, appId, secretKey from the Azure Portal.
Steps:
1.Create an C# console project
2.Referece the Microsoft.Azure.Management.DataLake.Store SDK, more details please refer to packages.config file section.
3.Add the follow code
var applicationId = "appid";
var secretKey = "secretkey";
var tenantId = "tenantid";
var adlsAccountName = "adlsAccount Name";
var creds = ApplicationTokenProvider.LoginSilentAsync(tenantId, applicationId, secretKey).Result;
var adlsFileSystemClient = new DataLakeStoreFileSystemManagementClient(creds,clientTimeoutInMinutes:60);
adlsFileSystemClient.FileSystem.Mkdirs(adlsAccountName, "/tomtest/newfolder");
4.Run the test code
5.Check from the azure portal.
Packages.config
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="Microsoft.Azure.Management.DataLake.Store" version="2.2.0" targetFramework="net452" />
<package id="Microsoft.IdentityModel.Clients.ActiveDirectory" version="3.13.8" targetFramework="net452" />
<package id="Microsoft.Rest.ClientRuntime" version="2.3.8" targetFramework="net452" />
<package id="Microsoft.Rest.ClientRuntime.Azure" version="3.3.7" targetFramework="net452" />
<package id="Microsoft.Rest.ClientRuntime.Azure.Authentication" version="2.2.0-preview" targetFramework="net452" />
<package id="Newtonsoft.Json" version="9.0.2-beta1" targetFramework="net452" />
</packages>

Categories