Cosmos DB TransactionalBatch error after update to dotnet 5 - .net-core

I have some methods on my base repository to do some batch operations on Cosmos DB, they are like that:
public async Task AddRangeAsync(List<T> entities)
{
var container = _cosmosDbClientFactory.GetContainer(CollectionName);
var entitiesList = entities.Split(_maxItemsPerBatch).ToList();
foreach (var items in entitiesList)
{
var partitionKey = ResolvePartitionKey(items.FirstOrDefault());
var transactionalBatch = container.CreateTransactionalBatch(partitionKey);
items.ToList().ForEach(item => transactionalBatch.CreateItem(item));
var result = await transactionalBatch.ExecuteAsync();
if (!result.IsSuccessStatusCode)
{
throw new CosmosDbBatchOperationException(result.ErrorMessage);
}
}
}
Today I migrated the dotnet version of my project, from dotnet 3.1 to 5, after that I'm getting this error:
System.MissingMethodException : Method not found: 'System.Threading.Tasks.Task1<Microsoft.Azure.Cosmos.Serialization.HybridRow.Result> Microsoft.Azure.Cosmos.Serialization.HybridRow.RecordIO.RecordIOStream.ReadRecordIOAsync(System.IO.Stream, System.Func2<System.ReadOnlyMemory1<Byte>,Microsoft.Azure.Cosmos.Serialization.HybridRow.Result>, System.Func2<System.ReadOnlyMemory1<Byte>,Microsoft.Azure.Cosmos.Serialization.HybridRow.Result>, Microsoft.Azure.Cosmos.Serialization.HybridRow.MemorySpanResizer1)'.
This occurs in this line:
var result = await transactionalBatch.ExecuteAsync();
Version Info:
Microsoft.Azure.Cosmos on v3.17.0
Dotnet 5.0.201
Somebody knows how to solve this?

I've checked all my projects and they are referecing the same sdk version, so I cleaned my solution and deleted all obj and bin folders and tried again but it didn't work.
Then I tried this solution because I was using Microsoft.Azure.Cosmos 3.17.0 with AspNetCore.HealthChecks.CosmosDb 5.0.3, so I downgraded AspNetCore.HealthChecks.CosmosDb to version 3.1.2 and it worked.

It looks like you might be hitting the same problem as discussed in this SDK issue.
A full binary clean and rebuild is worth trying to clear up dependency conflicts for Microsoft.Azure.Cosmos.Serialization.HybridRow.dll. If that doesn't work you could try adding your details to that issue thread.

Related

LinqToTwitter v5.1.2 AspNetAuthorizer doesn't contains a definition for CredentialStore

In my website .Net Framework 4.8, when I update from LinqToTwitter v5.1.1 to 5.1.2 I get an error message when I try to create a new instance of AspNetAuthorizer saying:
"AspNetAuthorizer doesn't contains a definition for CredentialStore"
and "AuthorizeBase is defined in an assembly is not referenced. You
must add a reference to assembly 'LinqToTwitter.netstandard, Version
=5.1.2.0"
Code Example:
return new AspNetAuthorizer
{
CredentialStore = new SessionStateCredentialStore
{
ConsumerKey = MyKey,
ConsumerSecret = Secret
},
GoToTwitterAuthorization =
twitterUrl => url
};
I tried to add a using and searched for the package "LinqToTwitter.netstandard" in nuget but doesn't exists.
Is this version broken?
This was a bug caused by LINQ to Twitter, which has since been fixed and deployed. Here's the fixed/closed issue on the LINQ to Twitter site:
https://github.com/JoeMayo/LinqToTwitter/issues/200

Publishing web app to Azure Websites Staging deployment slot fails with webjob

I just created a new deployment slot for my app, imported the publishing profile to Visual Studio, but after deployment I get this error message:
Error 8: An error occurred while creating the WebJob schedule: No website could be found which matches the WebSiteName [myapp__staging] and WebSiteUrl [http://myapp-staging.azurewebsites.net] supplied.
I have 2 webjobs, a continuous and a scheduled webjob.
I already signed in to the correct Azure account, as stated by this answer.
Will I need to set something else up in order to deploy my app to a staging Deployment Slot with webjobs?
My app is using ASP.NET, if it makes a difference?
There are a few quirks when using the Azure Scheduler. The recommendation is to use the new CRON support instead. You can learn more about it here and here.
Jeff,
As David suggested, you can/should migrate to the new CRON support. Here's an example. The WebJob will be deployed as a continuous WebJob.
Keep in mind that in order to use this you need to install the WebJobs package and extensions that are currently a prerelease. You can get them on Nuget.
Install-Package Microsoft.Azure.WebJobs -Pre
Install-Package Microsoft.Azure.WebJobs.Extensions -Pre
Also, as David suggested if you're not using the WebJobs SDK, you can also run this using a settings.job file. He provided an example here.
Program.cs
static void Main()
{
//Set up DI (In case you're using an IOC container)
var module = new CustomModule();
var kernel = new StandardKernel(module);
//Configure JobHost
var storageConnectionString = "your_connection_string";
var config = new JobHostConfiguration(storageConnectionString) { JobActivator = new JobActivator(kernel) };
config.UseTimers(); //Use this to use the CRON expression.
//Pass configuration to JobJost
var host = new JobHost(config);
// The following code ensures that the WebJob will be running continuously
host.RunAndBlock();
}
Function.cs
public class Functions
{
public void YourMethodName([TimerTrigger("00:05:00")] TimerInfo timerInfo, TextWriter log)
{
//This Job runs every 5 minutes.
//Do work here.
}
}
You can change the schedule in the TimerTrigger attribute.
UPDATE Added the webjob-publish-settings.json file
Here's an example of the webjob-publiss-settings.json
{
"$schema": "http://schemastore.org/schemas/json/webjob-publish-settings.json",
"webJobName": "YourWebJobName",
"startTime": null,
"endTime": null,
"jobRecurrenceFrequency": null,
"interval": null,
"runMode": "Continuous"
}

ASP.NET 5, EF 7 and SQLite - SQLite Error 1: 'no such table: Blog'

I followed the Getting Started on ASP.NET 5 guide about Entity Framework 7 and I replaced MicrosoftSqlServer with Sqlite, the only difference in the code is in Startup.cs:
services.AddEntityFramework()
.AddSqlite()
.AddDbContext<BloggingContext>(options => options.UseSqlite("Filename=db.db"));
When I run the website and navigate to /Blogs, I get an error:
Microsoft.Data.Sqlite.SqliteException was unhandled by user code
ErrorCode=-2147467259 HResult=-2147467259 Message=SQLite Error 1:
'no such table: Blog' Source=Microsoft.Data.Sqlite
SqliteErrorCode=1 StackTrace:
at Microsoft.Data.Sqlite.Interop.MarshalEx.ThrowExceptionForRC(Int32 rc,
Sqlite3Handle db)
at Microsoft.Data.Sqlite.SqliteCommand.ExecuteReader(CommandBehavior
behavior)
at Microsoft.Data.Sqlite.SqliteCommand.ExecuteDbDataReader(CommandBehavior
behavior)
at System.Data.Common.DbCommand.ExecuteReader()
at Microsoft.Data.Entity.Query.Internal.QueryingEnumerable.Enumerator.MoveNext()
at System.Linq.Enumerable.WhereSelectEnumerableIterator`2.MoveNext()
at System.Linq.Enumerable.d__1`2.MoveNext()
at System.Linq.Enumerable.WhereSelectEnumerableIterator`2.MoveNext()
at Microsoft.Data.Entity.Query.LinqOperatorProvider.ExceptionInterceptor`1.EnumeratorExceptionInterceptor.MoveNext()
at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
at EFGetStarted.AspNet5.Controllers.BlogsController.Index() in d:\arthur\documents\visual studio
2015\Projects\EFGetStarted.AspNet5\src\EFGetStarted.AspNet5\Controllers\BlogsController.cs:regel
18 InnerException:
I understand this as if there is no table called 'Blog', but when I open the .db file in DB Browser for SQLite, there actually is a table called 'Blog':
Does SQLite require other changes in the code, or is this an error in the SQLite connector for Entity Framework?
It is very likely the database actually being opened by EF is not the file you are opening in DB Browser. SQLite use the process current working directory, which if launched in IIS or other servers, can be a different folder than your source code directory. (See issues https://github.com/aspnet/Microsoft.Data.Sqlite/issues/132 and https://github.com/aspnet/Microsoft.Data.Sqlite/issues/55).
To ensure your db file is in the right place, use an absolute path. Example:
public class Startup
{
private IApplicationEnvironment _appEnv;
public Startup(IApplicationEnvironment appEnv)
{
_appEnv = appEnv;
}
public void ConfigureServices(IServiceCollection services)
{
services.AddEntityFramework()
.AddSqlite()
.AddDbContext<MyContext>(
options => { options.UseSqlite($"Data Source={_appEnv.ApplicationBasePath}/data.db"); });
}
}
I did this and was still having trouble loading the database. I added the following code in the constructor for the database context:
Database.EnsureCreated();
Now my context file looks like this:
It created a new database on my new Azure hosting site, so if you have a lot of existing data to migrate, this won't work. It worked for me so figured I'd share.
Taken from EF Core documentation...
Run from Visual Studio
To run this sample from Visual Studio, you must set the working
directory manually to be the root of the project. Ifyou don't set the
working directory, the following Microsoft.Data.Sqlite.SqliteException
is thrown: SQLite Error 1: 'no such table: Blogs'.
To set the working directory:
In Solution Explorer, right click the project and then select Properties.
Select the Debug tab in the left pane.
Set Working directory to the project directory.
Save the changes.
I had this issue on netcoreapp2.0. There's a related issue that may be at fault, but I didn't want to solve it by going to a nightly build.
The solution for me was to create and pass an SqliteConnection instead of using the builder string.
So for this setup:
string id = string.Format("{0}.db", Guid.NewGuid().ToString());
var builder = new SqliteConnectionStringBuilder()
{
DataSource = id,
Mode = SqliteOpenMode.Memory,
Cache = SqliteCacheMode.Shared
};
Compose for the DI like so:
var connection = new SqliteConnection(builder.ConnectionString);
connection.Open();
connection.EnableExtensions(true);
services.AddDbContext<SomeDbContext>(options => options.UseSqlite(connection));
The error I had was using this style of init:
services.AddDbContext<SomeDbContext>(options => options.UseSqlite(builder.ConnectionString));
My scaffolding also has a one-time call to:
var dbContext = serviceScope.ServiceProvider.GetService<SomeDbContext>();
dbContext.Database.OpenConnection();
dbContext.Database.EnsureCreated();
Using this approach all my DI-instantiated copies of SomeDbContext would all point at a valid SQLite db, and that db would have auto-created schema as per my entities.
Looks like things have changed because IApplicationEnvironment has been replaced with IHostingEnvironment.
Removing IApplicationEnvironment \ IRuntimeEnvironment
public class Startup
{
private IHostingEnvironment _appHost;
public Startup(IHostingEnvironment appHost)
{
_appHost = appHost;
}
public void ConfigureServices(IServiceCollection services)
{
services.AddEntityFrameworkSqlite()
.AddDbContext<MyContext>(
options => { options.UseSqlite($"Data Source={_appHost.ContentRootPath}/data.db"); });
}
}
I Had the same problem and I found the answer in this link:
https://www.youtube.com/watch?v=yRmMYrSROPs
Just update your database via command:
dotnet ef update database
you can set up the configuration adding;
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
optionsBuilder.UseSqlite("Data Source = path//DatabaseName.db");
}
the example uses SQLite, but you can choose your own DB.
If you have multiple DataContexts, the EnsureCreated method will only work on the first call. See its documentation:
If the database exists and has any tables, then no action is taken
To create tables of additional DataContexts, use
RelationalDatabaseCreator databaseCreator =
(RelationalDatabaseCreator) secondDbContext.Database.GetService<IDatabaseCreator>();
databaseCreator.CreateTables();

Meteor crashes constantly even after reinstalling

I am trying to run my project on the localhost but whenever I try it crashes. I even tried deploying it directly to the meteor website but nothing happens. It happened all of a suddenly. Everything was working fine till I added packages "tap:i18n" and "accounts-facebook".
/Users/haraldur/.meteor/packages/meteor-tool/.1.1.9.1sd3e7j++os.osx.x86_64+web.browser+web.cordova/mt-os.osx.x86_64/dev_bundle/server-lib/node_modules/fibers/future.js:245
throw(ex);
^ReferenceError: ServiceConfiguration is not defined
at lib/app.js:29:1
at /Users/haraldur/myapp/.meteor/local/build/programs/server/app/lib/app.js:47:4
at /Users/haraldur/myapp/.meteor/local/build/programs/server/boot.js:242:10
at Array.forEach (native)
at Function._.each._.forEach (/Users/haraldur/.meteor/packages/meteor-tool/.1.1.9.1sd3e7j++os.osx.x86_64+web.browser+web.cordova/mt-os.osx.x86_64/dev_bundle/server-lib/node_modules/underscore/underscore.js:79:11)
at /Users/haraldur/myapp/.meteor/local/build/programs/server/boot.js:137:5
Exited with code: 8
Your application is crashing. Waiting for file change.
This is my app.js file. I don't even have line 47. I am quite confused.
Timeouts = {};
// Initialize my collections
Rooms = new Meteor.Collection("rooms");
Videos = new Meteor.Collection("videos");
Messages = new Meteor.Collection("messages");
Votes = new Meteor.Collection("votes");
Favorites = new Meteor.Collection("favorites");
Skips = new Meteor.Collection("skips");
Cache = {};
Cache.Spotify = new Meteor.Collection("cache_spotify");
Cache.YouTube = new Meteor.Collection("cache_youtube");
Cache.Echonest = new Meteor.Collection("cache_echonest");
Cache.Freebase = new Meteor.Collection("cache_freebase");
// Dependencies for YouTube player
youtubeApiReady = false;
youtubePlayerReady = false;
youtubeApiDependency = new Deps.Dependency;
youtubePlayerDependency = new Deps.Dependency;
onYouTubeIframeAPIReady = function(){
youtubeApiReady = true;
youtubeApiDependency.changed();
}
ServiceConfiguration.configurations.remove({
service: "twitter"
});
ServiceConfiguration.configurations.insert({
service: "twitter",
consumerKey: APIKeys.twitter.consumerKey,
secret: APIKeys.twitter.secret
});
Looks like the package accounts-facebook need specific configuration for it
try add service-configuration to your application
meteor add service-configuration
Reference https://atmospherejs.com/meteor/service-configuration
Since adding those two packages seem to be the culprit, try removing them one at a time. I would first:
meteor remove tap:i18n
And try to run it. If it still fails, try:
meteor remove accounts-facebook
...and try it again.
Alternatively or first, you might want to see what's at these two locations:
lib/app.js:29:1
lib/app.js:47:4
IOW, what's at line 29, char 1, and line 47 char 4 of your app.js file. Perhaps there is something problematic there, though if it worked prior to adding those two packages, likely not.

Field not found: 'RabbitMQ.Client.ConnectionFactory.VirtualHost'

I'm trying to use RabbitMQ messaging using SignalR.RabbitMQ (https://github.com/mdevilliers/SignalR.RabbitMq) from a queue consumer in c# with the code below:
RabbitMQ.Client.ConnectionFactory factory = new RabbitMQ.Client.ConnectionFactory();
factory.UserName= "username";
factory.Password="password";
factory.HostName="host.name.com";
factory.VirtualHost = "VirtualHost";
factory.Port = 5672;
var exchangeName = "SignalR.Messages";
var configuration = new RabbitMqScaleoutConfiguration(factory, exchangeName);
GlobalHost.DependencyResolver.UseRabbitMq(configuration);
var hubContext = GlobalHost.ConnectionManager.GetHubContext<Chat>();
But unfortunately, fails on:
var configuration = new RabbitMqScaleoutConfiguration(factory, exchangeName);
with the error:
"Field not found: 'RabbitMQ.Client.ConnectionFactory.VirtualHost'."
Same connection works fine on a console app. If I remove the VirtualHost still gives the same error.
No idea what's wrong. Found same error here: https://github.com/MassTransit/MassTransit/issues/204 but doesn't help for me. I use EasyNetQ last version (0.40.3.353) and last version of RabbitMQ Client (3.4.3)
The solution that worked for me invoked using an older version of rabbitmq.client
install-package RabbitMQ.Client -version 3.1.5
Hopefully this helps someone

Resources