text:
.paperTrader is working fine not .trader

Hello (Ubuntu 16.04 LTS 64 bits) =) ,
Probably a noob mistake here, but I have trouble getting started with live trading. When .paperTrader is enabled it seems to work fine when I set it to false and .trader to true
I have
`Gekko encountered an error and can't continue
Error:
Do you understand what Gekko will do with your money? Read this first:
https://github.com/askmike/gekko/issues/201
Meta debug info:
Gekko version: v0.4.10
Nodejs version: v8.1.3
`
Here is my config.js
`// Everything is explained here:
// @link https://github.com/askmike/gekko/blob/stable/docs/advanced_usage/plugins.md
var config = {};
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//                          GENERAL SETTINGS
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
config.debug = true; // for additional logging / debugging
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//                         WATCHING A MARKET
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
config.watch = {
// see https://github.com/askmike/gekko#supported-exchanges
exchange: 'poloniex',
currency: 'BTC',
asset: 'ETH',
// You can set your own tickrate (refresh rate).
// If you don't set it, the defaults are 2 sec for
// okcoin and 20 sec for all other exchanges.
// tickrate: 20
}
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//                       CONFIGURING TRADING ADVICE
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
config.tradingAdvisor = {
enabled: true,
method: 'CCI',
candleSize: 30,
historySize: 1,
adapter: 'sqlite',
talib: {
enabled: false,
version: '1.0.2'
}
}
// Exponential Moving Averages settings:
config.DEMA = {
// EMA weight (α)
// the higher the weight, the more smooth (and delayed) the line
short: 10,
long: 21,
// amount of candles to remember and base initial EMAs on
// the difference between the EMAs (to act as triggers)
thresholds: {
down: -0.025,
up: 0.025
}
};
// MACD settings:
config.MACD = {
// EMA weight (α)
// the higher the weight, the more smooth (and delayed) the line
short: 10,
long: 21,
signal: 9,
// the difference between the EMAs (to act as triggers)
thresholds: {
down: -0.025,
up: 0.025,
// How many candle intervals should a trend persist
// before we consider it real?
persistence: 1
}
};
// PPO settings:
config.PPO = {
// EMA weight (α)
// the higher the weight, the more smooth (and delayed) the line
short: 12,
long: 26,
signal: 9,
// the difference between the EMAs (to act as triggers)
thresholds: {
down: -0.025,
up: 0.025,
// How many candle intervals should a trend persist
// before we consider it real?
persistence: 2
}
};
// Uses one of the momentum indicators but adjusts the thresholds when PPO is bullish or bearish
// Uses settings from the ppo and momentum indicator config block
config.varPPO = {
momentum: 'TSI', // RSI, TSI or UO
thresholds: {
// new threshold is default threshold + PPOhist * PPOweight
weightLow: 120,
weightHigh: -120,
// How many candle intervals should a trend persist
// before we consider it real?
persistence: 0
}
};
// RSI settings:
config.RSI = {
interval: 14,
thresholds: {
low: 30,
high: 70,
// How many candle intervals should a trend persist
// before we consider it real?
persistence: 1
}
};
// TSI settings:
config.TSI = {
short: 13,
long: 25,
thresholds: {
low: -25,
high: 25,
// How many candle intervals should a trend persist
// before we consider it real?
persistence: 1
}
};
// Ultimate Oscillator Settings
config.UO = {
first: {weight: 4, period: 7},
second: {weight: 2, period: 14},
third: {weight: 1, period: 28},
thresholds: {
low: 30,
high: 70,
// How many candle intervals should a trend persist
// before we consider it real?
persistence: 1
}
};
// CCI Settings
config.CCI = {
constant: 0.015, // constant multiplier. 0.015 gets to around 70% fit
history: 90, // history size, make same or smaller than history
thresholds: {
up: 150, // fixed values for overbuy upward trajectory
down: -30, // fixed value for downward trajectory
persistence: 0 // filter spikes by adding extra filters candles
}
};
// StochRSI settings
config.StochRSI = {
interval: 3,
thresholds: {
low: 20,
high: 80,
// How many candle intervals should a trend persist
// before we consider it real?
persistence: 3
}
};
// custom settings:
config.custom = {
my_custom_setting: 10,
}
config['talib-macd'] = {
parameters: {
optInFastPeriod: 10,
optInSlowPeriod: 21,
optInSignalPeriod: 9
},
thresholds: {
down: -0.025,
up: 0.025,
}
}
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//                       CONFIGURING PLUGINS
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// do you want Gekko to simulate the profit of the strategy's own advice?
config.paperTrader = {
enabled: false,
// report the profit in the currency or the asset?
reportInCurrency: true,
// start balance, on what the current balance is compared with
simulationBalance: {
// these are in the unit types configured in the watcher.
asset: 1,
currency: 100,
},
// how much fee in % does each trade cost?
fee: 0.25,
// how much slippage/spread should Gekko assume per trade?
slippage: 0.05,
// what is the risk free return in % (to calculate sharpe ratio)
riskFreeReturn: 5
}
// Want Gekko to perform real trades on buy or sell advice?
// Enabling this will activate trades for the market being
// watched by config.watch.
config.trader = {
enabled: true,
key: 'MYAPIKEY',
secret: 'MYSECRETKEYHERE',
username: '' // your username, only required for specific exchanges.
}
config.adviceLogger = {
enabled: false,
muteSoft: true // disable advice printout if it's soft
}
config.pushover = {
enabled: false,
sendPushoverOnStart: false,
muteSoft: true, // disable advice printout if it's soft
tag: '[GEKKO]',
key: '',
user: ''
}
// want Gekko to send a mail on buy or sell advice?
config.mailer = {
enabled: false,       // Send Emails if true, false to turn off
sendMailOnStart: true,    // Send 'Gekko starting' message if true, not if false
email: '',    // Your Gmail address
muteSoft: true, // disable advice printout if it's soft
// You don't have to set your password here, if you leave it blank we will ask it
// when Gekko's starts.
//
// NOTE: Gekko is an open source project < https://github.com/askmike/gekko >,
// make sure you looked at the code or trust the maintainer of this bot when you
// fill in your email and password.
//
// WARNING: If you have NOT downloaded Gekko from the github page above we CANNOT
// guarantuee that your email address & password are safe!
password: '',       // Your Gmail Password - if not supplied Gekko will prompt on startup.
tag: '[GEKKO] ',      // Prefix all email subject lines with this
        //       ADVANCED MAIL SETTINGS
        // you can leave those as is if you
        // just want to use Gmail

server: 'smtp.gmail.com',   // The name of YOUR outbound (SMTP) mail server.
smtpauth: true,     // Does SMTP server require authentication (true for Gmail)
// The following 3 values default to the Email (above) if left blank
user: '',       // Your Email server user name - usually your full Email address 'me@mydomain.com'
from: '',       // 'me@mydomain.com'
to: '',       // 'me@somedomain.com, me@someotherdomain.com'
ssl: true,        // Use SSL (true for Gmail)
port: '',       // Set if you don't want to use the default port
}
config.pushbullet = {
// sends pushbullets if true
enabled: false,
// Send 'Gekko starting' message if true
sendMessageOnStart: true,
// disable advice printout if it's soft
muteSoft: true,
// your pushbullet API key
key: 'xxx',
// your email, change it unless you are Azor Ahai
email: 'jon_snow@westeros.org',
// will make Gekko messages start mit [GEKKO]
tag: '[GEKKO]'
};
config.ircbot = {
enabled: false,
emitUpdates: false,
muteSoft: true,
channel: '#your-channel',
server: 'irc.freenode.net',
botName: 'gekkobot'
}
config.telegrambot = {
enabled: false,
emitUpdates: false,
token: 'YOUR_TELEGRAM_BOT_TOKEN',
botName: 'gekkobot'
}
config.xmppbot = {
enabled: false,
emitUpdates: false,
client_id: 'jabber_id',
client_pwd: 'jabber_pw',
client_host: 'jabber_server',
client_port: 5222,
status_msg: 'I'm online',
receiver: 'jabber_id_for_updates'
}
config.campfire = {
enabled: false,
emitUpdates: false,
nickname: 'Gordon',
roomId: null,
apiKey: '',
account: ''
}
config.redisBeacon = {
enabled: false,
port: 6379, // redis default
host: '127.0.0.1', // localhost
// On default Gekko broadcasts
// events in the channel with
// the name of the event, set
// an optional prefix to the
// channel name.
channelPrefix: '',
broadcast: [
'candle'
]
}
config.candleWriter = {
enabled: false
}
config.adviceWriter = {
enabled: false,
muteSoft: true,
}
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//                       CONFIGURING ADAPTER
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
config.adapter = 'sqlite';
config.sqlite = {
path: 'plugins/sqlite',
dataDirectory: 'history',
version: 0.1,
dependencies: [{
module: 'sqlite3',
version: '3.1.4'
}]
}
// Postgres adapter example config (please note: requires postgres >= 9.5):
config.postgresql = {
path: 'plugins/postgresql',
version: 0.1,
connectionString: 'postgres://user:pass@localhost:5432', // if default port
database: null, // if set, we'll put all tables into a single database.
schema: 'public',
dependencies: [{
module: 'pg',
version: '6.1.0'
}]
}
// Mongodb adapter, requires mongodb >= 3.3 (no version earlier tested)
config.mongodb = {
path: 'plugins/mongodb',
version: 0.1,
connectionString: 'mongodb://mongodb/gekko', // connection to mongodb server
dependencies: [{
module: 'mongojs',
version: '2.4.0'
}]
}
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//                       CONFIGURING BACKTESTING
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// Note that these settings are only used in backtesting mode, see here:
// @link: https://github.com/askmike/gekko/blob/stable/docs/Backtesting.md
config.backtest = {
daterange: 'scan',
batchSize: 50
}
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
//                       CONFIGURING IMPORTING
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
config.importer = {
daterange: {
// NOTE: these dates are in UTC
from: "2016-01-01 00:00:00"
}
}
// set this to true if you understand that Gekko will
// invest according to how you configured the indicators.
// None of the advice in the output is Gekko telling you
// to take a certain position. Instead it is the result
// of running the indicators you configured automatically.
//
// In other words: Gekko automates your trading strategies,
// it doesn't advice on itself, only set to true if you truly
// understand this.
//
// Not sure? Read this first: https://github.com/askmike/gekko/issues/201
config['I understand that Gekko only automates MY OWN trading strategies'] = false;
module.exports = config;`

For live trading you should disable the paper trader and enable the trader. The error you got was:

Do you understand what Gekko will do with your money? Read this first:
#201

The idea is that you click that link (so click this: #201) and read it - and change what is described there :)

authors: DPoSign askmike


text:
[request] Add cryptopia.co.nz Exchange

cryptopia.co.nz is one of the Exchanges which trades a lot of unpopular coins;
This may be very interesting for some traders here
Public API Docs:
https://www.cryptopia.co.nz/Forum/Thread/255
Private API Docs:
https://www.cryptopia.co.nz/Forum/Thread/256
API Examples:
https://www.cryptopia.co.nz/Forum/Thread/262

I will be to busy to add more exchanges in the coming time. The good thing is that anyone can add an exchange to gekko and submit a pull request to have it added. The required documentation can be found here: https://gekko.wizb.it/docs/extending/add_an_exchange.html

I am closing this as I don't see this as an existing issue. I am very open to a PR and if you have questions let me know!

source: gharchive/issue

authors: JohannesFerner askmike

repo: askmike/gekko

license: MIT

license_type: permissive

license_source: github-api


text:
cssPath struggles with special characters

cssPath is also struggling with special characters like < and {. I am using those for templating in Django, and later using a replace for local development, but it doesn't work as the output is garbled.
For example, in my task I have:
cssPath: '{{ STATIC_URL }}img/'
which outputs as:
background-image: url('%7B%7B%20STATIC_URL%20%7D%7Dimg/sprite.png');

The problem should be fixed in sprity v1.0.0

authors: aslansky hisnameisjimmy

repo: aslansky/css-sprite

license: mit

license_source: bigquery


text:
🛑 Nextcloud is down

In 448682b, Nextcloud (https://nextcloud.asm0dey.ru) was down:

HTTP code: 0
Response time: 0 ms

Resolved: Nextcloud is back up in eae537d.


text:
how do i compile

thanks for this project
How do i compile to .exe?
:)

You hit "build".
Good luck.


text:
Disappearing menu when hovering over

When opening up the settings menu in an automation, the menu auto hides if you hover over the words. The menu stays open if you hover over the icons.
Maybe personal preference, but it would be nice to have menu stay open regardless of hovering over the word or the icon.

Take a look at the new release v0.6.1

My guy! Sweet! Still maybe easier on the eyes with less transition stuff and just having static text and icon ;)
Thank you none the less. It's a thankless task most of the time, but you are doing something for nothing in return for what I feel is an awesome community.
I'll be spreading shortumation love to all my HA buds!
Peace! <3

authors: asosnovsky neekul

repo: asosnovsky/Shortumation


text:
perf: persist None instead of empty depsets in JsInfo

This way when we collect transitive depsets of these it will be a significantly smaller tree in some cases. Smaller, but only because empty depsets are not there. Do empty depsets make any difference?
Alternative to https://github.com/aspect-build/rules_js/pull/1786

Changes are visible to end-users: no
Test plan

Covered by existing test cases

Closed in favor of https://github.com/aspect-build/rules_js/pull/1786

source: gharchive/pull-request


text:
Remove .NET Framework build for source-build.

This allows source-build to get rid of the prebuilt .NET FX reference assemblies.
cc @JunTaoLuo

This is no longer required due to Aditya's reference package work, closing.  Sorry for the trouble.

repo: aspnet/AspNetCore-Tooling


text:
Webpack: allow dynamic timeout

I require a higher timeout than the default 100 seconds. I propose to make the timeout configurable. This would become an property on WebpackDevMiddlewareOptions.
Please let me know if you are open for this, and like a pull request.

Thanks for contacting us. We're closing this issue as this doesn't align with our long-term plans in this area. You can read more details about our vision for this area at https://github.com/aspnet/AspNetCore/issues/12890.

authors: Sebazzz mkArtakMSFT

repo: aspnet/AspNetCore


text:
[2.1] Update dependency version of Extensions.Binder to avoid downgrading sharedfx versions from 2.1.10

Fixes https://github.com/aspnet/AspNetCore-Internal/issues/2212
Test error caught what would have been another version-downgrade from 2.1.10 to 2.1.11. This updates the dependency version of Extensions.Binder

@natemcmaster this looks ready to merge…

authors: dougbu natemcmaster


text:
No explanation for how multiple parameters are inferred

Prior to the new ApiController, the follow code worked fine:
[HttpPost("Name/{name}/Status")]
public Task<ActionResult<bool>> Status(string name, [FromBody]string status)
Our presumption was that the following would be equivalent after the 2.1 changes (the only difference being that [FromBody] was removed):
[HttpPost("Name/{name}/Status")]
public Task<ActionResult<bool>> Status(string name, string status)
I don't see anything in this document that explains how the two signatures are treated differently.
For the record, we now get a model binding error (400 bad request) saying that "name is required". I'm unable to determine if it's referring to the name parameter in the Status method, or if it's somehow picking a different action on the controller and complaining about that.
Further, POSTing to the API like this does work: /name/whatever/status?status=anything. But since we need to post status in the body, this solution does not work.
Do we need to go back to [FromBody] or is there something else we're missing?

Document Details
⚠ Do not edit this section. It is required for docs.microsoft.com ➟ GitHub issue linking.

ID: b391017f-25e1-d5e1-c4f7-020408ade7b5
Version Independent ID: 263a7b64-2e42-bbfc-c1d3-61680438e1e4
Content: Build web APIs with ASP.NET Core
Content Source: aspnetcore/web-api/index.md
Product: aspnet-core
GitHub Login: @scottaddie
Microsoft Alias: scaddie

Well, I may have figured it out. Went hunting through the source code (I'm always amazed when I'm able to do this quickly and easily), and found this:
https://github.com/aspnet/Mvc/blob/504da3c565a9a159365b4564dba5f2cd7d059e7f/src/Microsoft.AspNetCore.Mvc.Core/Internal/ApiBehaviorApplicationModelProvider.cs#L229
So I came back to the doc find found this: "[FromBody] is inferred for complex type parameters.".
Why such a limitation? Feel free to close if necessary. Or I can create an issue to request an explanation for why simple types aren't supported.

@alexdresko You can open an issue in the aspnet/Mvc to ask engineering about the limitation.

Done. https://github.com/aspnet/Mvc/issues/8267

authors: alexdresko scottaddie

repo: aspnet/Docs


text:
[SignalR] Malformatted code in JavaScript client doc

Issue visible here

thanks mates!


text:
UWP.Sqlite canot pass Windows App Cerification Kits

I refer to UWP - New Database to added Sqlite into my UWP apps.
My UWP works well on my PC. But it cannot pass Windows Apps Ceritification Kits when I want to publish it into Windows Store.
The issue is caused by sqlite3.dll, it cannot pass checking.
I checked,
the installed programs
  Visual Studio Community 2015 14.0.25431.01 Update 3
  Win10 SDK 10.0.10586.212            (size: 2.34 GB)
  Win10 SDK 10.0.14393.33             (size: 1.95 GB)
  Win10 SDK 10.0.26624                (size: 1.43 GB)

App
  Microsoft.EntityFrameworkCore.Sqlite        v1.1.0
  Microsoft.EntityFrameworkCore.Tools         v1.1.0-preview4-final
  Microsoft.NETCore.UniversalWindowsPlatform  v5.3.0-beta2

  Target version       Windows 10 (10.0 Build 10586)
  Min version          Windows 10 (10.0 Build 10586)

I pasted the AppCertKit/ValidationResult.htm
应用版本:
1.1.0.0
应用体系结构:
x64
工具包版本:
10.0.14393.33
操作系统版本:
Microsoft Windows 10 专业版 (10.0.14393.0)
OS 体系结构:
x64
报告时间:
2016/12/25 16:33:46
Windows 安全功能测试

失败
二进制分析器
发现错误: 二进制分析器测试检测到以下错误:
文件 c:\program files\windowsapps\51900a0dfdc68.27948d8d6e661_1.1.0.0_x64__9w70a5dfr1b10\sqlite3.dll 未通过 AppContainerCheck 检查。
文件 c:\program files\windowsapps\51900a0dfdc68.27948d8d6e661_1.1.0.0_x64__9w70a5dfr1b10\sqlite3.dll 未通过 DBCheck 检查。
未修复时会产生影响: 如果应用未使用可用的 Windows 保护，则它可能会增加客户计算机遭遇恶意软件的漏洞。
如何修复: 在链接应用时应用所需链接器选项 - SAFESEH、DYNAMICBASE、NXCOMPAT 和 APPCONTAINER。有关详细信息，请参阅下面的链接:
正在修复二进制分析器错误

支持的 API 测试
失败
支持的 API
发现错误: 支持的 API 测试检测到以下错误:
此应用程序类型不支持 kernel32.dll 中的 API AreFileApisANSI。sqlite3.dll 调用此 API。
此应用程序类型不支持 kernel32.dll 中的 API CompareStringA。sqlite3.dll 调用此 API。
此应用程序类型不支持 kernel32.dll 中的 API CompareStringW。sqlite3.dll 调用此 API。
此应用程序类型不支持 kernel32.dll 中的 API CreateFileA。sqlite3.dll 调用此 API。
此应用程序类型不支持 kernel32.dll 中的 API CreateFileMappingA。sqlite3.dll 调用此 API。
此应用程序类型不支持 kernel32.dll 中的 API CreateFileMappingW。sqlite3.dll 调用此 API。
此应用程序类型不支持 kernel32.dll 中的 API CreateFileW。sqlite3.dll 调用此 API。
此应用程序类型不支持 kernel32.dll 中的 API EnumSystemLocalesA。sqlite3.dll 调用此 API。
此应用程序类型不支持 kernel32.dll 中的 API ExitProcess。sqlite3.dll 调用此 API。
此应用程序类型不支持 kernel32.dll 中的 API FatalAppExitA。sqlite3.dll 调用此 API。
此应用程序类型不支持 kernel32.dll 中的 API FreeEnvironmentStringsA。sqlite3.dll 调用此 API。
此应用程序类型不支持 kernel32.dll 中的 API FreeEnvironmentStringsW。sqlite3.dll 调用此 API。
此应用程序类型不支持 kernel32.dll 中的 API GetACP。sqlite3.dll 调用此 API。
此应用程序类型不支持 kernel32.dll 中的 API GetDateFormatA。sqlite3.dll 调用此 API。
此应用程序类型不支持 kernel32.dll 中的 API GetEnvironmentStrings。sqlite3.dll 调用此 API。
此应用程序类型不支持 kernel32.dll 中的 API GetEnvironmentStringsW。sqlite3.dll 调用此 API。
此应用程序类型不支持 kernel32.dll 中的 API GetFileSize。sqlite3.dll 调用此 API。
此应用程序类型不支持 kernel32.dll 中的 API GetFullPathNameA。sqlite3.dll 调用此 API。
此应用程序类型不支持 kernel32.dll 中的 API GetLocaleInfoA。sqlite3.dll 调用此 API。
此应用程序类型不支持 kernel32.dll 中的 API GetLocaleInfoW。sqlite3.dll 调用此 API。
此应用程序类型不支持 kernel32.dll 中的 API GetModuleHandleW。sqlite3.dll 调用此 API。
此应用程序类型不支持 kernel32.dll 中的 API GetOEMCP。sqlite3.dll 调用此 API。
此应用程序类型不支持 kernel32.dll 中的 API GetStartupInfoA。sqlite3.dll 调用此 API。
此应用程序类型不支持 kernel32.dll 中的 API GetStdHandle。sqlite3.dll 调用此 API。
此应用程序类型不支持 kernel32.dll 中的 API GetStringTypeA。sqlite3.dll 调用此 API。
此应用程序类型不支持 kernel32.dll 中的 API GetTempPathA。sqlite3.dll 调用此 API。
此应用程序类型不支持 kernel32.dll 中的 API GetTickCount。sqlite3.dll 调用此 API。
此应用程序类型不支持 kernel32.dll 中的 API GetTimeFormatA。sqlite3.dll 调用此 API。
此应用程序类型不支持 kernel32.dll 中的 API GetUserDefaultLCID。sqlite3.dll 调用此 API。
此应用程序类型不支持 kernel32.dll 中的 API GetVersionExA。sqlite3.dll 调用此 API。
此应用程序类型不支持 kernel32.dll 中的 API GetVersionExW。sqlite3.dll 调用此 API。
此应用程序类型不支持 kernel32.dll 中的 API HeapValidate。sqlite3.dll 调用此 API。
此应用程序类型不支持 kernel32.dll 中的 API IsValidLocale。sqlite3.dll 调用此 API。
此应用程序类型不支持 kernel32.dll 中的 API LCMapStringA。sqlite3.dll 调用此 API。
此应用程序类型不支持 kernel32.dll 中的 API LCMapStringW。sqlite3.dll 调用此 API。
此应用程序类型不支持 kernel32.dll 中的 API LoadLibraryA。sqlite3.dll 调用此 API。
此应用程序类型不支持 kernel32.dll 中的 API LoadLibraryW。sqlite3.dll 调用此 API。
此应用程序类型不支持 kernel32.dll 中的 API LockFile。sqlite3.dll 调用此 API。
此应用程序类型不支持 kernel32.dll 中的 API MapViewOfFile。sqlite3.dll 调用此 API。
此应用程序类型不支持 kernel32.dll 中的 API RtlCaptureContext。sqlite3.dll 调用此 API。
此应用程序类型不支持 kernel32.dll 中的 API RtlVirtualUnwind。sqlite3.dll 调用此 API。
此应用程序类型不支持 kernel32.dll 中的 API SetConsoleCtrlHandler。sqlite3.dll 调用此 API。
此应用程序类型不支持 kernel32.dll 中的 API SetEnvironmentVariableA。sqlite3.dll 调用此 API。
此应用程序类型不支持 kernel32.dll 中的 API SetHandleCount。sqlite3.dll 调用此 API。
此应用程序类型不支持 kernel32.dll 中的 API UnhandledExceptionFilter。sqlite3.dll 调用此 API。
此应用程序类型不支持 kernel32.dll 中的 API UnlockFile。sqlite3.dll 调用此 API。
未修复时会产生影响: 使用不在用于 Windows 应用商店应用的 Windows SDK 中的 API 与 Windows 应用商店认证要求冲突。
如何修复: 查看错误消息以确定不属于适用于 Windows 应用商店应用的 Windows SDK 的 API。请注意，在调试配置中生成的应用或未根据需要启用 .NET Native 的应用可能无法通过此测试，因为这些环境可能拉入不支持的 API。请使用发布配置重新测试你的应用，并根据需要启用 .NET Native。 有关详细信息，请参阅下面的链接:
Windows 应用商店应用中 Windows API 的替代选择。

@flychensc this was already reported in https://github.com/aspnet/EntityFramework/issues/7040. Please downgrade the "SQLite" package to the 3.12 version as a workaround.

OK, I'll try it, thank you

authors: divega flychensc


text:
Navigation properties in DbQuery

In model-first DbSets the database structure is generated to fit the navigation properties defined on the entity models.
On the other hand, according to documentation, a DbView model has to match a view that already exists and is not generated by EF.
What I couldn't find in the documentation is how to create navigation properties in a DbView model, along with an example on how to support that navigation when creating the view in the database.
Thanks

Duplicate of #809

authors: ajcvickers drinkbird


text:
IDbCommandTreeInterceptor: NavigationProperties not present

Hi!
I modified jbogards EntityFramework.Filters which adds the support for "global filters" to an EF DbContext. (see https://github.com/jbogard/EntityFramework.Filters)
As I am trying to get this to work with a simple join expression, I stumbled over a problem.
I my scenario, I have an "AccessPredicate" table which contains an id of an IResource (Document or Chapter) and the id of a User.
Now what I am trying to achieve is to filter the Documents and Chapters a User is not allowed to see like so
    modelBuilder.Conventions.Add(FilterConvention.Create<IResource, long>("UserId",
                (e, userId) => e.AccessPredicates.Any(@as => @as.UserId == userId)));

What I had to change in EntityFramework.Filters in order to support this was the ParameterReplacer.VisitLamda method, as it tries to always return a lamda expression of type Func<TEntity, bool>, but as I have a sub-lamda (as.UserId == 2l) I have to add a type-check:
           protected override Expression VisitLambda<T>(Expression<T> node)
            {
                var arg1 = typeof (T).GetGenericArguments().FirstOrDefault();
                if(arg1 != null && !arg1.IsAssignableFrom(typeof(TEntity)))
                    return base.VisitLambda<T>(node);

                var body = Visit(node.Body);
                return Expression.Lambda<Func<TEntity, bool>>(body, node.Parameters[0]);
            }

so now it blows up in the second last line of FilterQueryVisitor.Visit(...)
var output = result.Predicate.Accept(normalizer);

with the error: A first chance exception of type 'System.ArgumentOutOfRangeException' occurred in EntityFramework.dll
Additional information: No property with the name 'AccessPredicates' is declared by the type 'CodeFirstDatabaseSchema.Document'.
AccessPredicates is a navigationproperty on Document, however the EdmType (I debugged entity framework where the error is thrown: System.Data.Entity.Core.Common.CommandTrees.ExpressionBuilder.Internal.ArgumentValidation.ValidateProperty)
only has two items in its "Member" collection: "Id" and "Title"
However, if I do not use the filter, and write the query manually like so:
var x = ctx.Documents
                .Where(@d => @d.AccessPredicates.Any(@a => @a.UserId == userId))
                .Take(1).FirstOrDefault();

then the "Member" collection contains "Id", "Title", "AccessPredicates" and "Chapter" as I'd expect.
Do you have any idea how that can be?
It seems to me that EntityFramework constructs the StructuralTypes (which inherit EdmType)
for every query it parses and when I add my filter, I misses something... :/
For ease of debugging, I added a test project: http://1drv.ms/1BbrBAL
Just run "update-database" in package-manager and then hit F5.
I do not know if this is a really EF issue, but I do not know any other place where people could help me with that amount of insight into EF internals that you have. I really hope you can help me on this one :/

This issue was moved to aspnet/EntityFramework6#101

authors: divega gentledepp

repo: aspnet/EntityFramework


text:
The default HistoryRepository implementation does not respect a provider implementation of ISqlGenerationHelper

Meaning that for example the StatementTerminator is hardcoded with semicolon in the default HistoryRepository implementation...

@ErikEJ you should be able to override the HistoryRepository for RTM. We agree this should be fixed though, but we're going to have to deal with it post-1.0.0. We would of course take a PR if you wanted to go down that route 😄 .

Sure, I will consider a PR when I am able to build again...

authors: ErikEJ rowanmiller


text:
Slow Performance on Entity Framework

Hi,
I am not sure where to post this issue. I have concern on the slow performance of Entity Framework. I have a web application project related to stock trading and the traffic is very busy and very fast all the time. At first I was trying to use EF 6 as the ORM framework, but after half year usage of the app and more and more user uses it, the app becomes slower and eventually crash. After conduct some investigation, I found out that Database usage is still light and actually EF operation is the bottleneck. I try to optimize the app by converting some complex LINQ/Lambda query to pure SQL query. Some issue are relieved by the optimization, but user still complains that it is still slow. After doing research on other library, I found out that Dapper is suitable for high-traffic web site, then I have no choice but to combine between EF and Dapper for ORM framework.
During my research, I try to simulate simple query and observe the speed of pure SQL query, but it turns out that query using EF is much slower than that using Dapper.

I like the design of Entity Framework and plan to use it for high-traffic web application, but could you please to optimize the speed performance for the release of EF Core?
Thank you.

Your test isn't accurate for multiple reasons.
A. You should ignore the first query as there are many bootstrapping going in then.
B. First query inserts the data into the RAM, so the following one will be much faster.
C. There's the garbage collection issue too that you need to isolate.

To add more to above list, you are creating context after starting timer, first time context creation will create the model from scratch and many other services are initialized which are not related to query.

If EF 6 was indeed the bottleneck, don't use EF core, currently it's much worse, but even when things will stable, it won't be much faster.
You are much better using Dapper.
(Representing only myself, I'm not a Microsoft employee)
But I'm not sure that even Dapper or raw ADO.NET will save you, you probably need to add a Redis caching layer (I worked in stock trading in the past)

There isn't really anything actionable in this issue, so we are closing it out. If you have specific code listings that you think are executing poorly on EF Core, then please open an issue with the runnable code listing and the times you are seeing.

authors: darius-iko gdoron rowanmiller smitpatel


text:
Include/ThenInclude includes OrderBy

Steps to reproduce
build a linq query with multiple Include/ThenInclude that also has an OrderBy
The issue
It's rather late, so I don't really have to time to pull out exact code.  This problem is fairly easy to reproduce though.  The issue is that when you do a query that has multiple Include/ThenInclude, and also has an OrderBy, you get the following:
SqlException: The multi-part identifier "*" could not be bound.
After tracing the SQL output, it seems the issue is that when EF produces the second query for the Include, the OrderBy output is present as well containing references to fields from the root model's table, which are not included in the second query for the child entities.
Exception message:  SqlException: The multi-part identifier "*" could not be bound.
Stack trace: Stack trace is useless, the error comes from the SQL Server because of invalid SQL.

Further technical details
EF Core version: 1.0.0
Operating system: Windows 7
Visual Studio version: VS 2015
You shouldn't need any special setup to reproduce this issue.  Issue is bad SQL generated when Include/OrderBy are combined and EF determines a second query is necessary to eager load children.
Again, I apologize for the brevity but it is rather late here (4 AM!).  If need be, I should be able to provide more details if asked.

Again since it's early, and I've been struggling with this for many hours, I may actually be on the wrong track.  I'm going to close this for now.


text:
RequiresBufferingExpressionVisitor is too agressive

RequiresBufferingExpressionVisitor marks queries as requiring buffering even if the EF.Property calls are not referring to shadow properties or the shadow properties from referenced entity types are not used in materialization.

or the shadow properties from referenced entity types are not used in materialization.

The shadow properties may be accessed from anywhere during a query and such accesses are unrelated to materialization - The whole query may be in terms of ValueBuffers.
The first point is fair, though; should be trivial to fix.

We do entity equality rewrite which would convert entityType != null to EF.Property(entityType, PK) != null). Here PK can be shadow/non-shadow either. When we bind this through via query buffer we guard against entityType being null. If we stop using QueryBuffer then we have to make this a member access which is not null safe and we have no easy way to make it null safe.
Removing from milestone if this provides us enough value to go through making bigger changes in binding.

We removed QueryBuffer.

authors: AndriySvyryd anpete smitpatel


text:
Create a read-only implementation of IModel

This IModel will be built after Validate and will not have the ConfigurationSource or other data only used during model building.
The builder service will be replaceable so providers can have a derived implementation with provider-specific caches.
Also rename Model.Validate()
To access the cached values interfaces are to be used, see https://github.com/aspnet/EntityFramework/issues/5074

The relational implementation will also include a read-only database model, which could be reused in Scaffolding and Migrations.
@bricelam, @smitpatel

Plan for 3.0 is to make the API changes anyway. That is, the underlying model may not yet actually be different than it is now.

authors: AndriySvyryd ajcvickers


text:
Implement EntityEntry.Reload

Issue #1203
A little bit more permissive than in EF6 where the we were constrained by the exceptions thrown by the original stack.

:shipit:

authors: ajcvickers bricelam


text:
Includes are unpredictably ignored

@halosghost and I have been working on a project together and have found it increasingly difficult to guarantee some of the navigational properties in our queries. When I first read the documentation on ignoring includes (https://docs.microsoft.com/en-us/ef/core/querying/related-data#ignored-includes), I thought that only it was applicable when lazy loading was being used. I was quite surprised to learn that it wasn't.
It's unreasonable to say that .include() can be ignored just because it isn't referenced before it is ToListed.
I searched past issues but couldn't find the reasoning behind why .include()s can be ignored. Can you either shed some light on this or make a way to explicitly force the includes to be used? Without being sure that a navigational property is eagerly loaded, it is very hard to keep our project running correctly.
Steps to reproduce
Exception / Warning message:
> The Include operation for navigation '[x].Distributor.LevelTypeLookup' is unnecessary and was ignored because the navigation is not reachable in the final query results. See https://go.microsoft.com/fwlink/?linkid=850303 for more information.

By running the code below, the exception/warning above is logged during runtime, and the LevelTypeLookup navigational property on the Distributor is null.
var tree = _services.GetService<AdHocService>().GetTreeNodes("123456")
    .Select(x => x.Distributor)
    .ToList();

var level = tree.FirstOrDefault()?.LevelTypeLookup?.Name;

Here's the resulting query:
SELECT [x.Distributor].[Id], [x.Distributor].[CompanyName], [x.Distributor].[ContractTypeLookupId], [x.Distributor].[CreatedBy], [x.Distributor].[CreatedOn], [x.Distributor].[Cycle], [x.Distributor].[EnrollmentTypeLookupId], [x.Distributor].[FamilyTypeLookupId], [x.Distributor].[IsBusiness], [x.Distributor].[LevelTypeLookupId], [x.Distributor].[ModifiedBy], [x.Distributor].[ModifiedOn], [x.Distributor].[SponsorId], [x.Distributor].[SpousalAgreement], [x.Distributor].[StartDate], [x.Distributor].[StatusTypeLookupId]
FROM (
    select * from dbo.GetTreeNodes(@p0, @p1)
) AS [x]
LEFT JOIN [Distributor] AS [x.Distributor] ON [x].[DistributorId] = [x.Distributor].[Id]

I was surprised to find that when the .ToList() is moved before the .Select(), then the LevelTypeLookup property is retrieved and accessible.
 var tree = _services.GetService<AdHocService>().GetTreeNodes("123456")
+     .ToList()
+     .Select(x => x.Distributor);
-     .Select(x => x.Distributor)
-     .ToList();

Method in my repository:
public IQueryable<TreeNode> GetTreeNodes(string distributorId, DateTime? asOf = null) =>
    _repo.TreeNodes
        .Include(x => x.Distributor)
        .ThenInclude(x => x.LevelTypeLookup)
        .FromSql("select * from dbo.GetTreeNodes({0}, {1})", distributorId, asOf ?? DateTime.Now);

The models:
    public class TreeNode
    {
        public string DistributorId { get; set; }
        public string ParentId { get; set; }
        public int NumberOfChildren { get; set; }

        public virtual Distributor Distributor { get; set; }
    }

    public class Distributor
    {
        public string Id { get; set; }
        public int LevelTypeLookupId { get; set; }
        public string CompanyName { get; set; }

        [ForeignKey("LevelTypeLookupId")]
        public virtual LevelTypeLookup LevelTypeLookup { get; set; }
    }

    public class LevelTypeLookup
    {
        public int Id { get; set; }
        public string Abbreviation { get; set; }
        public string Name { get; set; }
    }

within the DbContext:
        ...
        public virtual DbQuery<TreeNode> TreeNodes { get; set; }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            base.OnModelCreating(modelBuilder);
            new TreeNodeConfig(modelBuilder);
        }

TreeNodeConfig.cs:
    public class TreeNodeConfig
    {
        public TreeNodeConfig(ModelBuilder modelBuilder)
        {
            modelBuilder.Query<TreeNode>()
                .Property(e => e.DistributorId)
                .HasColumnName("DistributorId");

            modelBuilder.Query<TreeNode>()
                .Property(e => e.ParentId)
                .HasColumnName("ManagerId");

            modelBuilder.Query<TreeNode>()
                .Property(e => e.NumberOfChildren)
                .HasColumnName("NumberOfChildren");
        }
    }

Further technical details
EF Core version: 2.1.0
Database Provider: Microsoft.EntityFrameworkCore.SqlServer
Operating system: Windows 10
IDE: Visual Studio 2017 15.7.4

You applied Include on TreeNode entity type and you are not projecting out TreeNode in your final projection. You are selecting Distribution. Hence include got ignored. (When you do ToList without any Select it implies .Select(e => e) which is equivalent of projecting out TreeNode)

Why is this intended behavior?

You specify include on entity type you want. To include navigation on distribution above, do Select before Include and it will load nav prop.

If that is the case, why allow chained ThenIncludes? Unless projecting to the deepest property, all of those would be thrown away regardless, no?
I guess what we're balking at is that eliding a side-effect (especially one as fundamental as "fetch this data”) is hugely surprising.

@HalosGhost The semantics of Include are, "when Include is used on an IQueryable<T>, then when returning entities of type T, also bring back related entities as specified in the Include calls."
If the query does not return entities of type T, then Include does not apply.

Isn't this a huge pitfall for developers (with many devs who probably have used Entity Framework in the past and are now moving to EFCore)? I thought Entity Framework always respected Includes (but I could be wrong).

@slimeygecko EF6 and all previous versions work in basically the same way.

I would also be interested in knowing why this is the case.
It does not, for example, always avoid fetching extra data (for example, if you use a Where clause before the Select which operates on a given navigational property, that property will still need to be fetched for the evaluation of that clause, it will just have its data thrown away after the Selection).
What's the rationale behind this behavior?

@HalosGhost Depends what you mean by "fetched". If you project out the navigation, then the data will be returned. If the navigation is used in the projection as part of the query, then it may not result in the data for that navigation being returned. They are really two different things.

I think we may have misunderstood one another there; but I'm not worried about how it works anymore. I'm interested in why it was designed to work this way rather than just actually loading the requested data.
Can you shed some light on why it was designed to work this way?

@vsopko I'm not able to fully understand what you are asking. I don't see any real connection between the many-to-many implementation and ignored Includes. Making a navigation private has no bearing on whether or not an Include will be ignored.
@HalosGhost I'm not sure on the reasoning for why it works this way. I will follow up on that.

@HalosGhost and others. I'm going to try to explain this based on our discussion. Consider this model:
public class Blog
{
    [DatabaseGenerated(DatabaseGeneratedOption.None)]
    public int Id { get; set; }

    public virtual ICollection<Post> OldPosts { get; set; }
    public virtual ICollection<Post> FeaturedPosts { get; set; }
}

public class Post
{
    [DatabaseGenerated(DatabaseGeneratedOption.None)]
    public int Id { get; set; }

    public Author Author { get; set; }
}

public class Author
{
    [DatabaseGenerated(DatabaseGeneratedOption.None)]
    public int Id { get; set; }
}

Notice that there are two ways to get from a blog to a post--the OldPosts relationship and the FeaturedPosts relationship. Let's populate this with model with some data:
using (var context = new BloggingContext())
{
    context.Database.EnsureDeleted();
    context.Database.EnsureCreated();

    var post1 = new Post { Id = 1, Author = new Author { Id = 1 } };
    var post2 = new Post { Id = 2, Author = new Author { Id = 2 } };
    var post3 = new Post { Id = 3, Author = new Author { Id = 3 } };
    var post4 = new Post { Id = 4, Author = new Author { Id = 4 } };

    context.Add(
        new Blog
        {
            Id = 1,
            OldPosts = new List<Post> { post1, post2 },
            FeaturedPosts = new List<Post> { post3, post4 }
        });

    context.SaveChanges();
}

Notice that some posts are related to blogs through one relationship, some through the other. Now lets do a simple query with Include:
using (var context = new BloggingContext())
{
    var blog = context.Blogs
        .Include(e => e.FeaturedPosts).ThenInclude(e => e.Author)
        .Include(e => e.OldPosts)
        .First();

    foreach (var post in blog.OldPosts)
    {
        Console.WriteLine($"Old post: {post.Id} Author: {post.Author?.Id}");
    }

    foreach (var post in blog.FeaturedPosts)
    {
        Console.WriteLine($"Featured post: {post.Id} Author: {post.Author?.Id}");
    }
}

The output from this on my machine is:
Old post: 1 Author:
Old post: 2 Author:
Featured post: 3 Author: 3
Featured post: 4 Author: 4

Notice that both posts accessed through the FeaturedPosts relationship have the author included. This is because the Include for FeaturedPosts also has a ThenInclude for Author: .Include(e => e.FeaturedPosts).ThenInclude(e => e.Author)
However, neither post accessed only through the OldPosts relationship have the author included, since the Include for this relationship does not have an associated ThenInclude for Author: .Include(e => e.OldPosts)
Hopefully all that is quite clear. 😄
So what happens if we change the shape of the query with a projection? Consider for example:
using (var context = new BloggingContext())
{
    var oldPosts = context.Blogs
        .Include(e => e.FeaturedPosts).ThenInclude(e => e.Author)
        .Include(e => e.OldPosts)
        .SelectMany(e => e.OldPosts)
        .ToList();

    var featuredPosts = context.Blogs
        .Include(e => e.FeaturedPosts).ThenInclude(e => e.Author)
        .Include(e => e.OldPosts)
        .SelectMany(e => e.FeaturedPosts)
        .ToList();

    foreach (var post in oldPosts)
    {
        Console.WriteLine($"Post: {post.Id} Author: {post.Author?.Id}");
    }

    foreach (var post in featuredPosts)
    {
        Console.WriteLine($"Featured post: {post.Id} Author: {post.Author?.Id}");
    }
}

As described above, the Include is dropped, so the output on my machine is:
Old post: 1 Author:
Old post: 2 Author:
Featured post: 3 Author:
Featured post: 4 Author:

That is, no authors have been loaded because the Include was ignored.
Now, a simplistic suggestion for not ignoring Include is to say something like, "If an entity type in the final projection is also contained in some Include path, then use the remainder of that Include path." Doing so in this case would mean that since Post is in the final projection, and Post is in one of the Include paths, then Author should be included in the results because it exists as a ThenInclude on Post.
However, there are two issues with this. First, if the type is used in multiple Include paths, then which one should be used? Ignoring that for the moment, and looking at the output if we did this:
Old post: 1 Author: 1
Old post: 2 Author: 2
Featured post: 3 Author: 3
Featured post: 4 Author: 4

Why, in this case, are authors being Included for old posts? This is wrong--there was never a ThenInclude for the OldPosts relationship, so they should not have Author included. This is the second and more significant issue.
But what if we use information about the projection to drive this? For example, looking again at this:
var oldPosts = context.Blogs
    .Include(e => e.FeaturedPosts).ThenInclude(e => e.Author)
    .Include(e => e.OldPosts)
    .SelectMany(e => e.OldPosts)
    .ToList();

we are selecting OldPosts, in the projection, so we could use this to determine which Include path to use--in this case, the one that does not also include Author. Likewise, for this query:
var featuredPosts = context.Blogs
    .Include(e => e.FeaturedPosts).ThenInclude(e => e.Author)
    .Include(e => e.OldPosts)
    .SelectMany(e => e.FeaturedPosts)
    .ToList();

we would use the other Include path, which would include Author.
This would likely work for all cases except for entirely uncorrelated types in the projection. However, the implementation is very complicated, and as the length of this post shows, the mental model for figuring out what is going on is also complicated.
This is why, rather than attempting to implement something like this, we believe a better approach is as described in #2953. That is, if a relationship should always be included when an entity of a given type is loaded, regardless of where it came from, then that should be specified in a different API that allows such rules to be expressed independently of the shape of the query.

@ajcvickers, thank you for the long and detailed reasoning and explanation. This is yet another point of significant disappointment I've run into with Entity Framework, but I recognize that this (along with many other pieces) is not necessarily a simple problem.

@ajcvickers, thank you for the long and detailed reasoning and explanation. This is yet another point of significant disappointment I've run into with Entity Framework, but I recognize that this (along with many other pieces) is not necessarily a simple problem.
Consider this my vote to close.

Can anyone explain why a simple .Include of a one to many entity would not get included in this projection?
var allNotDeletedJobs = await context.ModelJobs.Include(mj => mj.Model).Where(mj => !mj.IsDeleted).ToListAsync();
Pretty simple looking. A ModelJob has a Model. Yet every single Model is null.

@ntimmerman - Please file a new issue with a repro code which demonstrate the issue you are seeing.

@ntimmerman - Please file a new issue with a repro code which demonstrate the issue you are seeing.

The problem was with my data. I had some unexpected junk data causing my problem. Sorry for the trouble.

Please help, I really can't figure this out.
 var query = _db.Orders
                .Include(o => o.Items)
                .OrderBy(o => o.OrderDate)
                .ToArray();

In this, Items is an empty collection for each order.
var tt = _db.Orders
                .Select(x => new {x.Member, x.Items.Count})
                .ToArray();

This shows the counts correctly.
Please tell me what is wrong with the first code.

@Thorocaine Please open a new issue and include a small, runnable project/solution or complete code listing and we will investigate.

authors: HalosGhost Thorocaine ajcvickers ntimmerman slimeygecko smitpatel

repo: aspnet/EntityFrameworkCore


text:
.NET Core Tracking bug

Welcome !
I have 2 tables: Document, Customer. The document is referencing to the customer via CustomerId field.
When I want to update a document, I loaded it from the DB via the the following LINQ command:
_var documents = await this.documentService
	.Query(d => string.Equals(d.Barcode, doc.Barcode, StringComparison.InvariantCultureIgnoreCase))
	.Include(d => d.Customer)
	.Take(2)
	.ToArrayAsync().ConfigureAwait(false);_

Here are the "this.documentService.Query(...)" implementation:
        _public virtual IQueryable<TEntity> Query(Expression<Func<TEntity, bool>> predicate = null)
        {
            var result = this.Repository.Entities.AsNoTracking();
            if (predicate != null)
            {
                result = result.Where(predicate);
            }
            return result;
        }_

and the "this.Repository.Entities":  ... = this.dbSet.AsQueryable();
When I got back only 1 document, I do the required checks and modifications, and executes the dbContext.Documents.Update command.
In this case, I get the following exception:
(The instance of entity type 'Document' cannot be tracked because another instance with the key value '{Id: 17203}' is already being tracked. When attaching existing entities, ensure that only one entity instance with a given key value is attached.)
After spending couple of hours to investigate this, I got the following conclusion:
the .Include(d => d.Customer) cause the exception, but I don't know why.

the exception doesn't mention to this property, entity, ...
why does it cause error when updating an entity which has a filled navigation property via EFCore?, I checked it, the program didn't do anything with this (now, I removed the .Include(), currently isn't necessary).
In the other case, when I executes the DbSet.Add command, the EFCore wanna insert the Customer too, not just use the existing one's Id value.

Exception message:
The instance of entity type 'Document' cannot be tracked because another instance with the key value '{Id: 17208}' is already being tracked. When attaching existing entities, ensure that only one entity instance with a given key value is attached.
Stack trace:
at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.IdentityMap1.ThrowIdentityConflict(InternalEntityEntry entry) at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.IdentityMap1.Add(TKey key, InternalEntityEntry entry, Boolean updateDuplicate)
at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.IdentityMap1.Add(TKey key, InternalEntityEntry entry) at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.NullableKeyIdentityMap1.Add(InternalEntityEntry entry)
at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.StateManager.StartTracking(InternalEntityEntry entry)
at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.InternalEntityEntry.SetEntityState(EntityState oldState, EntityState newState, Boolean acceptChanges)
at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.EntityGraphAttacher.PaintAction(EntityEntryGraphNode node, Boolean force)
at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.EntityEntryGraphIterator.TraverseGraph[TState](EntityEntryGraphNode node, TState state, Func3 handleNode) at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.EntityEntryGraphIterator.TraverseGraph[TState](EntityEntryGraphNode node, TState state, Func3 handleNode)
at Microsoft.EntityFrameworkCore.ChangeTracking.Internal.EntityEntryGraphIterator.TraverseGraph[TState](EntityEntryGraphNode node, TState state, Func3 handleNode) at Microsoft.EntityFrameworkCore.DbContext.SetEntityState[TEntity](TEntity entity, EntityState entityState) at ....RepositoryBase1.Update(TEntity entity) in ...
at ....LogicServiceBase1.<UpdateAsync>d__27.MoveNext() in ... at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Runtime.CompilerServices.ConfiguredTaskAwaitable1.ConfiguredTaskAwaiter.GetResult()
at DocuDepo.BusinessLogic.Services.Document.DocumentService.d__2.MoveNext() in ...
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.ConfiguredTaskAwaitable1.ConfiguredTaskAwaiter.GetResult() at DocuDepo.BusinessLogic.Services.Transaction.EntryDemand.EntryDemandService.<GetDocumentAsync>d__17.MoveNext() in ... at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Runtime.CompilerServices.ConfiguredTaskAwaitable1.ConfiguredTaskAwaiter.GetResult()
at DocuDepo.BusinessLogic.Services.Transaction.EntryDemand.EntryDemandService.d__14.MoveNext() in ...
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.ConfiguredTaskAwaitable1.ConfiguredTaskAwaiter.GetResult() at DocuDepo.BusinessLogic.Services.Transaction.EntryDemand.EntryDemandService.<AddOrUpdateNewAsync>d__13.MoveNext() in ... at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw() at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Runtime.CompilerServices.ConfiguredTaskAwaitable1.ConfiguredTaskAwaiter.GetResult()
at DocuDepo.BusinessLogic.Services.Transaction.EntryDemand.EntryDemandService.d__10.MoveNext() in ...
Steps to reproduce
Created a demo application, which is available from GDrive: https://drive.google.com/open?id=1EotkvU7zsQXYVVHxTgwiYGN-ZOgxPySk
The program is working perfectly, if I comment the DemoExecuter.cs's 57th line.

### Further technical details
EF Core version: 2.2.4
Database Provider: .SqlServer 2.2.4
Operating system: Microsoft Windows [Version 10.0.18362.266]
IDE: Visual Studio 2019 Preview 16.3.0 Preview 1.0

@cj748s16 The exception is being thrown because the graph being attached to the context has two different Document instances with the same ID:


text:
Recursive Insert TEnitiy design time error

I have an entitiy STUDENT and it has a property GRADE. I want to insert firstly sub entities.
If I try recursive insert because GRADE can contains another sub entitiy too.
My insert function want TEntity, if I cast GRADE as TEntity, code try to assign GRADE as a STUDENT
how can I resolve this problem?
public int Insert(TEntity entity)
        {
var xx = entity.GetType().GetProperties().Where(x => x.PropertyType.FullName == item.SubPropName).FirstOrDefault();
                Type entityType = xx.PropertyType;
                    var insertableEntity = Activator.CreateInstance(entityType);
                    insertableEntity = cc;

                   var id = Insert((TEntity)insertableEntity);
                }

@aburcuburcu There isn't enough information here for us to be able to effectively investigate. Please post a small, runnable project/solution or complete code listing that demonstrates what you are trying to do and where it is not working.

EF Team Triage: Closing this issue as the requested additional details have not been provided and we have been unable to reproduce it.
BTW this is a canned response and may have info or details that do not directly apply to this particular issue. While we'd like to spend the time to uniquely address every incoming issue, we get a lot traffic on the EF projects and that is not practical. To ensure we maximize the time we have to work on fixing bugs, implementing new features, etc. we use canned responses for common triage decisions.

authors: aburcuburcu ajcvickers


text:
Add RelationalCommandCaching based on parameter value nullability

Resolves #15892
I attempted to add to cosmos also but ran into #18033
Currently this takes naïve approach that if SelectExpression was modified during parameter based EV then we cannot cache it. If we work on #16375 then that would be quite accurate logic without us having to pass back the information. I filed #18034 to track.

Implementation follows what we had in previous versions.

Tests?

Do you have any ideas in mind, how to test this? A way to catch regression would be our perf tests.

You can add unit tests with a mock QuerySqlGenerator and assert how many times a command was created.

We should also consider extracting some nested classes out of the partial classes. The fact that they are partial is a smell and it's ok to have a separate type even if it's only used in one place.

They are implementation detail of this visitor hence stayed inside. Is partial is the issue or nesting?

@smitpatel The partial means that the class is too big and should be split. And in practice you don't gain much by keeping the class nested.

@AndriySvyryd - Since this is also cache, do we need to do anything specific for cache eviction?

@smitpatel Yes, use MemoryCache and set size for the entries

Filed https://github.com/aspnet/EntityFrameworkCore/issues/18493 for tests

authors: AndriySvyryd smitpatel


text:
Httpclient bug

Describe the bug
Httpclient accesses part of the domain name in the dotnet core and throws an exception. Normally in freamwork 4.7
To Reproduce
https://github.com/lun3322/httpclient-bug
Expected behavior
A clear and concise description of what you expected to happen.
System.AggregateException: One or more errors occurred.

You may want to move this to https://github.com/dotnet/corefx if it's an HttpClient bug.

repo: aspnet/Extensions


text:
Roadmap: Apache/NGINX InProc hosting

Hi,
What is the road map to have a better hosting experience on a *NIX OS?
Currently the only solution is to start the application at bootup and setup a reverse proxy to the Kestral server. If you are going to host multiple .NET Core sites this model is rather inflexible and requires port binding for every .NET app you want to run.
Is there are roadmap for how hosting is going to work under Apache/NGINX moving forward?
The quickest fix is can a hosting provider change the default port at runtime? ie: dotnet xxx.dll -port 23678.
The hosting provider may not have the ability to modify the source code so binding would have to be modified at run time without recompiling the application.

We've discussed better out of process integration (UseNginxIntegration), but nothing for in process.
The caller can set the binding url at runtime (dotnet xxx.dll -url http://localhost:23678), but you have to be careful that the app doesn't override it. It will work fine if the process hasn't tried to configure any bindings explicitly in code.

We won't be doing this.

authors: Tratcher Wayne-Mather muratg

repo: aspnet/Hosting


text:
Access denied exception in UrlGroup.RegisterPrefix

I have a very odd problem with UrlPrefixes in development. Sample attached, don't use IISExpress when testing. (This comes from a larger Api hosted as a WinService)
Consider this configuration:
options.UrlPrefixes.Add("http://localhost:19800/");
options.UrlPrefixes.Add("http://" + Environment.MachineName + ":19800/");

If I run this as a regular user (from VS or command line), the first prefix works fine (as expected I believe, a port above 10000 on localhost/127.0.0.1 is ok for any user (TLS needs more though)).
The second prefix fails (with error from subject), also as expected since I as a regular user has no access to do that.
Fixing the use of the second prefix should be done using (as a local admin)
netsh http add urlacl url=http://+:19800/ user=<user> (or Everyone or similar to be even more permissive)
What really happens when that is done is that the second prefix still fails with same error, but now the first prefix also fails with the same error ?!. Highly confusing and I don't understand why....
I do have selfhosted WCF services where usage of urlacl:s works as expected, but I can't easily find the code to see what is different there compared to HttpSysServer. I don't think there is anything strange in the UrlGroup code.
TestAppHttpSys.zip

Note the netsh reservation url must match exactly what you pass to UrlPrefixes. Also, + reserves all hosts, it doesn't stack like * does.

Ah, that is exactly what the documentation says. But not until this morning did I realise that I had made incorrect assumptions based on the word "match" when there were wildcards in the vicinity. I had assumed that match meant match a registration against the wildcard reservations, but it meant match the registration against the list of reservations. The wildcards are only used in http.sys routing, nothing else (right?).
And realising that I could also find ConnectionOrientedTransportDefaults.HostNameComparisonMode where it becomes obvious that WCF with default settings uses a strong wildcard (+) registration no matter what actual hostname I request it to listen on.

Correct.

Additional notes from some additional testing for someone that comes across this issue:
A prefix with host 127.0.0.1 only listens on the loopback interface.
A prefix with host localhost listens on all interfaces but host header spoofing is blocked in HTTP.SYS and only traffic from localhost to localhost is allowed, but that is a software only thing it seems.

authors: Tratcher cadwal

repo: aspnet/HttpSysServer


text:
Remove cancellationToken parameter in UserManager::RemovePasswordAsync

Inline with the other methods in UserManager, the cancellationToken parameter in the RemovePasswordAsync method should be removed and if required, the CancellationToken property should be used instead.

7fbc36c56684769d3535cf1dfd1cddf88fb26343

authors: HaoK dealdiane

repo: aspnet/Identity


text:
React/Redux template: How to disable server-side rendering?

I'm having some issues related to code that tries to run on the server while it shouldn't. I really don't have the expertise to deal with universal code so I'd like to just remove server-side rendering since I don't really need it.
I tried removing the asp-prerender-module tag in the div#react-app but that ended up in an empty div. I guess because the webpack.config.js never gets executed, and so boot-client.tsx never runs.
Is there an easy way to disable server-side rendering? I still want to use JavaScript services for its webpack integration.

You should add dist/main.js into your script, so it will start to render.

Great, it's working. Thanks

authors: emzero laskoviymishka

repo: aspnet/JavaScriptServices


text:
Package Microsoft.Extensions.Logging.Abstractions requires netstandard 2.0

Would this package not be more useful if it targeted a lower version of netstandard (it's still compatible with 1.3) thus allowing it to be used in a broader range of scenarios. Per Microsoft's own guidance:
In general, we recommend you to target the lowest version of .NET Standard possible.
Unless my understanding is wrong by targeting netstandard 2.0 doesn't this force any other package that relies upon it to also make the leap to 2.0? When MS started splitting out these foundational components into abstractions and implementation packages I thought it was great to see some reference interfaces being defined in this space while at the same time allowing for theoretically many implementations - we've arguably lost something if they are going to needlessly push on to the latest broadest netstandard implementation.
Admittedly there is currently only a 2.0 implementation of the abstractions and so reality it's going to be running inside a runtime that supports netstandard 2.0 but surely this "platform raising" is better left as far up towards runtime selection as possible to maximise flexibility lower down the dependency graph.
As an example if I had a set of packages that I wanted to support, say, UWP it would be fairly trivial to implement a simple logger on top of the abstractions. But by forcing all packages that reference this to netstandard 2.0 I've got a much tougher job.

@JamesRandall What can't you target the 1.x abstractions?

I can work round it by directly referencing 2.0.0 of the abstractions in the 1 of 5 packages I have that requires this (it has a dependency on Entity Framework Core which has a >= 2.0.0 dependency on Microsoft.Extensions.Logging).
In that world I can leave the other 4 packages targeting netstandard 1.3 and logging abstractions 1.x and have the package that depends on Entity Framework Core target netstandard 2.0 and logging abstractions 2.x.
However then, within a related set of packages, I have a mix of major version changes of dependencies that ostensibly follow a semver model  - by definition that's dangerous (a major version bump being used to indicate the making of incompatible API changes) and my packages, or their consumers, are eventually going to run fowl of this.
Whereas if the logging abstractions follow the recommended best practice (that makes an awful lot of sense to me) and target the lowest compatible netstandard version then, I would argue, everything is playing nicely with both the semver model and the netstandard approach.
netstandard, and the best practice advice around it, coupled to semver make an awful lot of sense to me in a world of multiple runtimes and a more granular approach to framework delivery - but aren't we on a bit of a hiding to nothing if the core packages released by Microsoft don't play by these guidelines?
And so a reciprocal question, I'm genuinely curious, is there a reason .Net Core and related packages aren't targeting the minimum netstandard version that they can?

netstandard, and the best practice advice around it, coupled to semver make an awful lot of sense to me in a world of multiple runtimes and a more granular approach to framework delivery - but aren't we on a bit of a hiding to nothing if the core packages released by Microsoft don't play by these guidelines?

The best practice still makes sense in general. You generally want to target the lowest netstandard you can. We made an executive decision to reset the baseline for our packages given we were shipping a major version (and removing TFMs is a breaking change). NET Standard 2.0 has lots of benefits like cleaning up the package dependency graph (faster install times etc). It also simplifies the compatibility matrix we had to test since we did the reset.
I don't expect this will be a common occurrence. .NET Standard 2.0 was a big change and we wanted to align with it.

I guess the concern is that improvements come along all the time but runtimes move at different cadences. If major version bumps result in runtimes being left behind  by package management following this approach then I'm not sure what we've achieved with .NET Standard.
As you suggest hopefully this won't happen often and therefore won't turn out to be the case.
I've bumped my packages along to .NET Standard 2.0 as it's the cleanest solution available to me given package purpose (primarily distributed services, Azure), audience (small), and the discussion above.
Thanks for the info and back and forth.

I agree with this issue.
Bumping the version of this package to 2.0 makes sense in the context that going to .NET Standard 2.0, because that is a breaking change.  But, this seems to conflict with the referenced guidance but also seems to introduce potential versioning issues as well as violating the principle of least surprise.  It's certainly adds needless friction to developers in the wild.
Versioning examples:

What if a change needed in the .NET Standard 1.1 supported version of the library (Abstractions 1.2)? That would make a new version (say 1.3) have a version smaller than and older version.
What if a change like a above (a change required for the latest ,NET Standard 1.1 supported version) is in fact a breaking change?  Does that them become 3.0 because the "breaking change" in 2.0 would in fact be an aggregate breaking change? 😕

Example friction:
I'm creating a class library targeting .NET Standard 1.2 because I need to support existing code that doesn't yet support .NET Standard/Core 2.0. That library would like to support a logging abstraction, so I attempt to add the package to my class library.  The NuGet package manager in Visual Studio proceeds to try to install Abstractions 2.0 and, of course, barfs.  As a dev I now need to know that maybe a prior version would in fact support the .NET Standard that I need, then go looking for past versions that do that 🤞 .  This assumes that .NET Standard versions prior to 2.0 will be supported for a least a while in the future.
This strategy doesn't make long-term sense for any level of support for .NET Standards <2.0.

I also agree... I have packages and code that can't be bumped to 2.0... so I'm stuck now with M.E.L.Abstractions 1.1.2.
I can foresee several consequences of this breaking change in the long run:

Packages that do require to stay at the lowest possible net.standard version, to remove M.E.L.Abstractions altoghether.
Third party logging providers, to be forced to provide updates for both M.E.L.Abstracions 2.0, and for 1.1.2 ( for those that want to stick with a lower version )

In both cases, bumping the version defeats the original purpose of M.E.L.Abstracions to be a foundation for an universal logging system.

As the general issue remains and it is causing others similar concerns and difficulties it doesn't seem appropriate for this to be closed by me and so am reopening.

So, could it be possible to bump Abstractions back to net.standard 1.1 ? or it is already out of reach?

authors: JamesRandall davidfowl peteraritchie vpenades

repo: aspnet/Logging


text:
Unable to disable Url Resolution logic from _ViewImports.cshtml.

If a user wants to disable URL resolution (~/) they can do:
@removeTagHelper "*, Microsoft.AspNet.Mvc.Razor"

If done on a single page, everything works well. However, you're unable to add this @removeTagHelper in a _ViewImports.cstml to get the same effect.

@DamianEdwards
Why doesn't this work and what is the fix?

It doesn't work due to the order in which we apply InheritedChunks vs DefaultInheritedChunks within the MvcRazorHost/ChunkInheritanceUtility.
There's a default @addTagHelper "*, Microsoft.AspNet.Mvc.Razor" applied to every page; if a user does the corresponding @removeTagHelper in a _ViewImport.cshtml the @removeTagHelper is run before the @addTagHelper due to the order of our chunk merging. Therefore, nothing gets removed.

How do we fix it?

@DamianEdwards Change the order in which we apply default chunks and inherited chunks. It's a relatively easy change.

Ok cool. Let's fix it in beta8

Fixed in f045c6792b7d62697cd748d45fe38205b1aab136

authors: DamianEdwards NTaylorMullen danroth27 pranavkm

repo: aspnet/Mvc


text:
Authorize Doesnt work

Authorize attribute doesn't work
I have parent controller like this
 [Authorize(Roles = "Administrator")]
    public class AdminController : Controller
    {
        protected string AreaName { get; set; }
        protected AdminController()
        {
            AreaName = "Areas/Administrator";
        }
    }

What exactly doesn't work? Does the attribute work if you put it on the specific controller (e.g. one that derives from AdminController)?

doesn't check user is authorized and if user is in role. AdminController is Parent Controller;
public class Dashboard : AdminController{
}
and admincontroller has anttribute  [Authorize(Roles = "Administrator")]

@blowdart

@HaoK @kichalla  does authorize inherit?

Authorize should be combining all of the attributes into one policy (a sort of union of all of the attributes), which results in an AND of all the requirements...  if that makes sense to anyone but me :)

We have tested inheritance and Authorize works for us as expected.
What authentication method are you using? What creates your identity?

ASPNET.Identity
Method: Cookie
@blowdart

OK, in that case, assuming you're using the default templates, something strange is going on. Can you post a repo of the stripped down project please so we can see the problem in action?

@gvx111 Could you share a repro?

which repro? @kichalla

@gvx111 we are not able to repro the inheritance issue that you are mentioning so checking if you can share a repro project

It's framework 10 Projects. I can share class:
 [Authorize(Roles = "Administrator")]
    public class AdminController : Controller
    {
        protected string AreaName { get; set; }
        protected Guid CurrentSiteId { get; set; }
        protected string SiteName { get; set; }

        protected AdminController(IActionContextAccessor context, IShellSettingsManager manager)
        {
            ActionContext = context.ActionContext;
            AreaName = RouteData.Values["area"].ToString();
            SiteName = context.ActionContext.RouteData.Values.ContainsKey("siteid")
                ? context.ActionContext.RouteData.Values["siteid"].ToString().ToLower()
                : "";
            CurrentSiteId = (manager.LoadSettings().Any(e => e.Name.ToLower() == SiteName) ? Guid.Parse(manager.LoadSettings().First(e => e.Name.ToLower() == SiteName).SiteId) : Guid.Empty);

        }

        public override void OnActionExecuting(ActionExecutingContext context)
        {
            base.OnActionExecuting(context);
            if (!context.HttpContext.User.Identity.IsAuthenticated)
            {
                context.Result = new RedirectToRouteResult(new RouteValueDictionary(new { action = "Index", controller = "Login" }));
            }
        }

        protected IActionResult RedirectToLocal(string returnUrl)
        {
            if (Url.IsLocalUrl(returnUrl))
            {
                return Redirect(returnUrl);
            }
            else
            {
                return RedirectToAction("Index", "Dashboard");
            }
        }
and
 public class DashboardController : AdminController
    {
        private IShellSettingsManager _shellSettingsManager;

        public DashboardController(IActionContextAccessor httpcontext, IShellSettingsManager shellSettingsManager) : base(httpcontext, shellSettingsManager)
        {
            _shellSettingsManager = shellSettingsManager;
        }

    }

@gvx111 Ok, I am not exactly clear what you are mentioning here, but following is what I have tried now and it does check if the user is in role

Create a new Web Application project in VS 2015 (I tested this with Beta8 tooling)
Replace the code in Controller\AccountController.cs's Register action with the following(you may need to resolve namespaces)...here I am just using the Register action to create a user in administrator role if the user being registered has a user name admin@admin.com

[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task Register(RegisterViewModel model)
{
EnsureDatabaseCreated(_applicationDbContext);
if (ModelState.IsValid)
{
ApplicationUser user;
    if (model.Email.ToLowerInvariant() == "admin@admin.com")
    {
        const string adminRole = "Administrator";
        var userManager = HttpContext.RequestServices.GetRequiredService<UserManager<ApplicationUser>>();
        var roleManager = HttpContext.RequestServices.GetRequiredService<RoleManager<IdentityRole>>();
        if (!await roleManager.RoleExistsAsync(adminRole))
        {
            await roleManager.CreateAsync(new IdentityRole(adminRole));
        }

        user = await userManager.FindByNameAsync(model.Email);
        if (user == null)
        {
            user = new ApplicationUser { UserName = model.Email };
            var result = await userManager.CreateAsync(user, model.Password);
            await userManager.AddToRoleAsync(user, adminRole);
            await userManager.AddClaimAsync(user, new Claim("ManageStore", "Allowed"));
            return RedirectToAction(nameof(HomeController.Index), "Home");
        }
    }
    else
    {
        user = new ApplicationUser { UserName = model.Email, Email = model.Email };
        var result = await _userManager.CreateAsync(user, model.Password);
        if (result.Succeeded)
        {
            // For more information on how to enable account confirmation and password reset please visit http://go.microsoft.com/fwlink/?LinkID=532713
            // Send an email with this link
            //var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);
            //var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: HttpContext.Request.Scheme);
            //await _emailSender.SendEmailAsync(model.Email, "Confirm your account",
            //    "Please confirm your account by clicking this link: link");
            await _signInManager.SignInAsync(user, isPersistent: false);
            return RedirectToAction(nameof(HomeController.Index), "Home");
        }
        AddErrors(result);
    }
}

// If we got this far, something failed, redisplay form
return View(model);

}
- Create following controllers

[Authorize(Roles = "Administrator")]
public class AdminController : Controller
{
}
public class DashboardController : AdminController
{
public IActionResult Index()
{
return Content("Hello!", contentType: "text/plain");
}
}
- Create the admin user using `admin@admin.com` username and you should be able to hit `http://localhost:<port>/dashboard/index` successfully and get a `Hello!` message.
- Create another user, for example:`test@test.com` username and you should be seeing access denied error when accessing `http://localhost:<port>/dashboard/index`message.

can you give me your skype or mail address? I will show details of my code.
my email: givi.bibi@Yahoo.com
@kichalla

Sure kiranchalla@hotmail.com

Closing this as we cannot repro it. If you still see the issue, please send us a repro project.

authors: Eilon HaoK blowdart danroth27 gvx111 kichalla


text:
difficult to track the error when an I have errors serializing action result

Hi,
I'm writing a sample application and I wrote this action to send the client some data.
        public IEnumerable<Attivita> GetLatest(int last) {
            var atts = db.Attivita
                .Include(att => att.Cliente).Include(att => att.Commessa).Include(att => att.Fattura).Include(att => att.Locazione)
                .Include(att => att.Pagamento).Include(att => att.Tipo).Include(att => att.Progetto)
                .OrderByDescending(att => att.Data).ThenByDescending(att => att.AttivitaNo)
                .Take(last).ToList();

            return atts;
}

I tried the action but I started to receive 502 (Bad Gateway) error and an empty result: Just giving a look was clear the problem, and I solved creating a model class to send the data avoiding the usual nested serialization issues, but this is not the real problem.
Trying to debug the action I don't have any exception, the simple answer is this http response code and no details. Looking in the debug window I found the real message error
Microsoft.AspNet.Server.Kestrel: Error: An unhandled exception was thrown by the application.
Newtonsoft.Json.JsonSerializationException: Self referencing loop detected for property 'Cliente' with type 'MyLibrary.Model.Cliente'. Path '[0].Cliente.Locazioni[0]'.
   in Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.CheckForCircularReference(JsonWriter writer, Object value, JsonProperty property, JsonContract contract, JsonContainerContract containerContract, JsonProperty containerProperty)
   in Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.CalculatePropertyValues(JsonWriter writer, Object value, JsonContainerContract contract, JsonProperty member, JsonProperty property, JsonContract& memberContract, Object& memberValue)
   in Newtonsoft.Json.Serialization.JsonSerializerInternalWriter.SerializeObject(JsonWriter writer, Object value, JsonObjectContract contract, JsonProperty member, JsonContainerContract collectionContract, JsonProperty containerProperty)

In the Configure method I added
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
                app.UseDatabaseErrorPage();
            }

but this doesn't help.
The answer, in this situation, is a bit hard to understand, and I don't understand how to write clients that can handle these situation. Am I missing something?

I gave another look to this issue, and I see than the reason is slighly different from what I tought at the beginning: I tought that the problem was the ef lazy loading of ef, that was fetching the data, but ef 7 actually I think doesn't support lazy loading, so the problem is that I a referencing loop in the model is just detected.
If this is the reason, this is a problem: when I add a relationship between entities in ef, I always add navigation properties to both the sides of the relation, so if I have a order entity that refers a customer object, I always have a list of orders in the customer entity.
This was the only way to avoid the problem is create a vm class specular to the ef entity jsut for serialization, that is annoying.

There isn't much we can do if there is an exception when writing out the body of the response, but you can see errors like these by looking at the logging output. By default we log to the console and to the debug output window.

FYI, I found the solution.
I write because it may be useful to someone else who had the same problem: The referencing loop detection is a Json.Net feature that may be configured is the serializerSettings.
At the moment, in the controllers who I have this problem I added this:
 public override void OnActionExecuting(ActionExecutingContext context)
        {
            base.OnActionExecuting(context);

            var lstFormatters = this.BindingContext.OutputFormatters.ToList();
            foreach (var formatter in lstFormatters)
            {
                Microsoft.AspNet.Mvc.Formatters.JsonOutputFormatter jsonFormatter = formatter as Microsoft.AspNet.Mvc.Formatters.JsonOutputFormatter;
                if (jsonFormatter != null) {
                    jsonFormatter.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
                }
            }
        }

this way I change the settings to every call to the controller: I'm sure I can do this application level in the startup, but at the moment it's fine to me.
About the exception when writing out the response I understand: my problem is not under development but in production: generally speaking I don't have idea when I can have problems in this phase, but I don't see an easy way to monitor and handle this situation, checking the error type and deciding if to send, for example sending an email  for immediate check.


text:
XmlSerializerOutputFormatter throws InvalidCastException on async method

Is this a Bug or Feature request?:
Bug, regression
Steps to reproduce or link to a repro project:

Create an Asp.Net Core api project
Update package to use 2.1.0-rc1-final

<Project Sdk="Microsoft.NET.Sdk.Web">

  <PropertyGroup>
    <TargetFramework>netcoreapp2.1</TargetFramework>
  </PropertyGroup>

  <ItemGroup>
    <Folder Include="wwwroot\" />
  </ItemGroup>

  <ItemGroup>
    <PackageReference Include="Microsoft.AspNetCore.All" Version="2.1.0-rc1-final" />
  </ItemGroup>

  <ItemGroup>
    <DotNetCliToolReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Tools" Version="2.0.4" />
  </ItemGroup>

</Project>

Add XmlSerializerOutputFormatter in MVC option

public void ConfigureServices(IServiceCollection services)
        {
            services.AddMvc(options =>
            {
                options.OutputFormatters.Add(new XmlSerializerOutputFormatter());
            });
        }

Update a ValuesController method to use async

 public async Task<IEnumerable<string>> Get()
        {
            return await Task.FromResult(new string[] { "value1", "value2" });
        }

run the project
send a request using Accept: application/xml

GET /api/values HTTP/1.1
Host: localhost:61519
Accept: application/xml

Description of the problem:
An InvalidCastException is thrown

InvalidCastException: Unable to cast object of type 'System.String[]' to type 'System.Threading.Tasks.Task1[System.Collections.Generic.IEnumerable1[System.String]]'.

Version of Microsoft.AspNetCore.Mvc or Microsoft.AspNetCore.App or Microsoft.AspNetCore.All:
Microsoft.AspNetCore.All Version="2.1.0-rc1-final"

@aguacongas, thanks for contacting us.
@dougbu, can you please investigate this? Thanks!

@dougbu If I apply the workaround, will that work with the fix ?

Yes, if you apply the workaround, you'll still be fine after picking up @pranavkm's fix.

authors: aguacongas dougbu mkArtakMSFT


text:
Handle subtype with suffix being a subtype without a suffix

For https://github.com/aspnet/Mvc/issues/8156

The CI checks should succeed now but please wait for most of them…

I think there is still functional tests that need to be fixed 😢

authors: dougbu jkotalik


text:
Flaky test: GetImportSourceDocuments_WithSuppressExceptions_UnreadableItem_DoesNotThrow

This test fails occasionally with the following error:
System.NullReferenceException : Object reference not set to an instance of an object.
   at System.Collections.Generic.Dictionary`2.FindEntry(TKey key)
   at System.Collections.Generic.Dictionary`2.TryGetValue(TKey key, TValue& value)
   at Castle.DynamicProxy.Generators.BaseProxyGenerator.ObtainProxyType(CacheKey cacheKey, Func`3 factory)
   at Castle.DynamicProxy.ProxyGenerator.CreateClassProxy(Type classToProxy, Type[] additionalInterfacesToProxy, ProxyGenerationOptions options, Object[] constructorArguments, IInterceptor[] interceptors)
   at Moq.Proxy.CastleProxyFactory.CreateProxy(Type mockType, ICallInterceptor interceptor, Type[] interfaces, Object[] arguments)
   at Moq.Mock`1.<InitializeInstance>b__20_0()
   at Moq.Mock`1.OnGetObject()
   at Moq.Mock`1.get_Object()
   at Microsoft.AspNetCore.Razor.Language.DefaultRazorProjectEngineTest.GetImportSourceDocuments_WithSuppressExceptions_UnreadableItem_DoesNotThrow() in /_/test/Microsoft.AspNetCore.Razor.Language.Test/DefaultRazorProjectEngineTest.cs:line 53

Future instances of this failure can be seen here.

Waiting for Moq to fix this.

@NTaylorMullen, I think Moq is updated now. Can you please check?

Given the flakiness of this test the only way I can verify that this is "fixed" is to use ILSpy or some other reflector to verify that the binaries we're currently consuming have the fix in them. Is that what you meant by check?

No, just confirm that we did update the Moq dependency and close this for now.

@ryanbrandenburg I see that in Universe we updated Moq to 4.10 nine days ago, how often do those changes flow to the underlying repos? I ask because Razor is still at 4.9

Normally the deps are updated once a week. Moq would have been brought to 4.10 here, but it was decided that while we moved things into a Mondo World it was more trouble than it's worth to have these dependency PR's getting created. If you find yourself in need of new deps before you're in the Mondo-repo you need only do run.ps1 -update upgrade deps and commit the results along with whatever it is that needs them. Alternatively you could ask Nate to bring Razor into Mondo in the next batch 😛.

Ahhh, gotcha, thanks @ryanbrandenburg !

repo: aspnet/Razor


text:
Create new notification for SignOut

RedirectToIdentityProvider has a dual purpose: Redirect to IDP for signin or signout.
How about we have another notification for signout.  We may want to rename RedirectToIdentityProvider.

Could be done as part of the notifications cleanup work.
Also need to fix this in the cookies middleware.

authors: Eilon brentschmaltz

repo: aspnet/Security


text:
Add WebSocket and EventSource polyfills to options

#2048

@dotnet-bot test Windows Release x64 Build

@dotnet-bot test Windows Release x64 Build

repo: aspnet/SignalR


text:
Add tests for produced linux installers

Test scripts for linux installers were omitted in https://github.com/aspnet/Universe/pull/603.

Dup of https://github.com/aspnet/Universe/issues/706

repo: aspnet/Universe


text:
use abp zero Development project has  performance  problem

After develop several MPA webp projects, there are a few performance issues
The  page opens very slowly
The pop-up box loads the page very slowly

Hi,
Thank you for such a feedback. But "page is very slow" is too generic problem. Why do you think it's because of the framework. Do you have metrics that show it?

authors: apchenjun hikalkan

repo: aspnetboilerplate/module-zero


text:
Fix broken table size in report dashboard

Before:

After:

Thanks!

authors: ilyasovd phillbaker

repo: assaf/vanity


text:
feat(client): allow support of blocking notification

Closes #8 support of blocking notification in amqp.
Missing some tests. I was not able to block rabbit server by limiting resources to do the testing.

Hello @sebastienfr, thanks for contribution!
I have few comments on this:

please remove .editorconfig file, it doesn't really belong to this feature.
chan *amqp.Blocking — no need for pointer here, original amqp lib exposed amqp.Blocking, not pointer to it.
You've forgot to initialize (*Client).blocking channel. Some buffering will be nice to have.
method (*Client).reportBlocking used only once and without checking return, it will be better to inline its body and remove method.

like this:
case blocking := <-chanBlocking:
    select {
    case c.blocking <- blocking:
    default:
    }
}

Thanks for your careful review. Here are the changes.
I was able to test it by running a rabbitmq in a docker container with allocating only 300m of memory to my docker-machine and it works fine.

@sebastienfr awesome! Looks good.
@pavel-d please merge this.

repo: assembla/cony


text:
Add containsExactly/containsExactlyInAnyOrder String assertion

Check List:

Fixes #1063
Unit tests : YES
Javadoc with a code example (API only) : YES

Something needed to be discussed
While I'm implementing the assertContainsExactly assertion, I have reused the IterableDiff in package org.assertj.core.internal like it is done in Iterables#assertContainsExactly.
But I find something unexpected, if you write an iterable assertion like this
    List<String> myList = Arrays.asList("$","$","#");
    Assertions.assertThat(myList)
              .containsExactly("#", "#", "$");

AssertionError is this
java.lang.AssertionError:
Actual and expected have the same elements but not in the same order, at index 0 actual element was:
  <"$">
whereas expected element was:
  <"#">

method differencesFound() in IterableDiff will return false when calling IterableDiff.diff(Arrays.asList("#","#","$"),Arrays.asList("$","$","#"),StandardComparisonStrategy.instance()).differencesFound()
It looks like this may lead to give a wrong assertion message

Actual and expected have the same elements but not in the same order

in fact they don't have the same elements?
For now I'm following the same impl in containsExactly Iterable assertion when implementing containsExactly String assertion.
So the question is
shall we change the IterableDiff or work this out in some other ways?

I agree the error message is wrong, there is a bug in IterableDiff as it does not deal correctly with duplicate elements.

Hi! After issue #1140 is fixed, I did some changes and make the containsExactly/containsExactlyInAnyOrder String Assertion work implemented with IterableDiff.
In addition, I rework the Impl of containsExactlyInAnyOrder Array/Iterable Assertion with IterableDiff.

@joel-costigliola any plan for this?

for 3.10!

@joel-costigliola I'm really sorry for the late reply, I have made some changes according to your feedback.
The algorithm is not yet finished, but I think it will be difficult to handle the string in words because we don't give a clear definition of the bound of words.
Imagine you write an assertion like
assertThat("Practice makes perfect!").containsExactly("Practisse ", "made ", "perffect!"); or
assertThat("Practicemakesperfect!").containsExactly("perfect!", "makes ", "Practice");, what will be the output of the assertion error?
Maybe we should still use the size check and if size is different we throw a shouldHaveSameSize exception, and check the char one by one but (something different here from the previous impl) regard the chars as a string if they are next to each other, this way would show something meaningful when the minor typos appear but can do nothing about missing or unexpected elements(I just think it only makes sense to compare when the size is same).
for example, a typo scenario here:
assertThat("Practice madesperfect !").containsExactly("Practice ", "makes ", "perfect!");

shows something like:
java.lang.AssertionError:
Expected: <java.lang.AssertionError:
Expecting:
  <"Practice madesperfect !">
to contain exactly and in order:
  <["Practice ", "makes ", "perfect!"]>
but some elements were not found:
  <["k"," perfect!"]>
and others were not expected:
  <["d", "perfect !"]>

as for the different size scenario
assertThat("Practice makes perfect!").containsExactly("Practice ", "makes ", "!");

we handle like this:
java.lang.AssertionError:
Expected: <java.lang.AssertionError:
Expecting:
  <"Practice makes perfect!">
to contain exactly and in order:
  <["Practice ", "makes ", "!"]>
but actual and expected don't have same numbers of characters.

WDYK?

I need to think about this, I'll try to give you my opinion by the end of the week.
I wanted to thank for your work, don't worry about delays, we all have important things to do and not enough to do them all!

I think if there are missing elements (even there is only character diff), the whole expected elements should be reported as missing and not only reporting the diff, on your example:
assertThat("Practice madesperfect !").containsExactly("Practice ", "makes ", "perfect!");

should return an error like:
Expecting:
  <"Practice madesperfect !">
to contain exactly and in order:
  <["Practice ", "makes ", "perfect!"]>
but some elements were not found:
  <["makes"," perfect!"]>

"makes" is reported as missing although there is only a one char diff.

Another type of error you pointed out is when all the expected elements are found but actual is bigger:
assertThat("Practice makes perfect!").containsExactly("Practice ", "makes ", "!");

would ideally report an error like:
Expecting:
  <"Practice makes perfect!">
to contain exactly and in order:
  <["Practice ", "makes ", "!"]>
but the following elements were not expected:
  <["perfect"]>

if that is not possible, I'm happy with the size check.

Closing due to lack of interest and potential complexity of the assertion but happy to reopen it if someones is interested.

authors: BillyYccc joel-costigliola

repo: assertj/assertj-core


text:
Improved runtime of containsExactly

Check List:

Fixes Improve the performance of containsExactly from quadratic to linear complexity #2548
Unit tests : NO
Javadoc with a code example (on API only) : NO
PR meets the contributing guidelines

With these edits, the the assertContainsExactly() function will run in O(n) time if the actual and expected iterable are equivalent. However, if they are not equivalent, the code will run in O(n^2) time.
Also, I was told to rebase my changes or something, so I tried doing some research to figure that out but wasn't sure if I did it right. Hope I did it correctly, but if not, I could use a tutorial or a walkthrough on that!

Okay! I'll review the changes and resolve them this weekend (Midterms killing me 💀)

@joel-costigliola revised!

Integrated thanks @nith2001 and @sarajuhosova!


text:
Mettre en place les design tokens Synapse

https://www.figma.com/file/Y1qJ3Z9V6CWiJ65CFZbdm5/[CNAM]-UI-Kit-V3.0?type=design&node-id=266%3A626&mode=design&t=C0wNdDuG6olZ0GAK-1
A voir si on intègre ces nouveaux tokens directement dans le projet

Epic : tokens
Deadline : début octobre

authors: DavidFyon valentinbecquet

repo: assurance-maladie-digital/design-system


text:
Clarify in README whether this plugin actually works with Spring AOP

There is a section in the README comparing Spring AOP vs AspectJ, but it doesn't indicate whether it's possible to use this plugin in conjunction with Spring AOP. Can the README be updated to state clearly whether this works with Spring AOP?

Thanks for the suggestion.
A reference can be added at the beginning of that section to point to the metrics-spring project which is supposed to be used in Spring based applications to integration Metrics and Spring AOP. I wonder whether that section is really bringing value here though.
Let me know what you think.

Well, I feel like an idiot now. I didn't even see that there was a specific integration with Spring for DropWizard Metrics.
I think the Spring AOP vs AspectJ section might even be somewhat confusing in its current form. It might be worth making clear that this integration is for use only with AspectJ and that the metrics-spring project should be used with projects using Spring to do AOP.

No worries. Thanks for the feedback.
I'll rework that section to add pointers to metrics-spring, metrics-cdi, metrics-guice and make it clear in what context each one is to be used.

authors: astefanutti erikthered

repo: astefanutti/metrics-aspectj


text:
timeout may happen in addNewChannel()

if a simple GetVarAction has timeout, it will try it again, and don't skip the rest of the addNewChannel(), because of an exception. Or if it has no more time (SLEEP_TIME_BEFORE_GET_VAR interval was not enough) to complete GetVar, it will skip it simple.
more details: https://github.com/asterisk-java/asterisk-java/issues/302

Thanks for the patch :)

authors: bsutton endredy

repo: asterisk-java/asterisk-java


text:
Prevents my DE from loading when internet is unavailable.

I'm on Mint 17.3 Cinnamon
For some reason when I don't have internet Cinnamon won't load. I ended up having to uninstall.

Google-drive-ocamlfuse should be made to fail gracefully when offline. There's more info about this at http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=846367 , but basically the mount point is "busy", and makes my file manager, your desktop environment hang.

I'm having a similar issue. I'm using the new Mint 18 on KDE. Every time I disconnect from the Internet, I can navigate in dolphin no problem, except when I try to view /home/%User%/. My entire home folder hangs, and I can't access any documents. I tried to do an ls, and came up with the same result. As long as I have an Internet connection, I can access my home folder, but I'm running a lab that forces me to disconnect from the Internet to do properly.

authors: Schisco94 leetwanker matiasw

repo: astrada/google-drive-ocamlfuse


text:
fuse: failed to open /dev/fuse: Operation not permitted

debian.
According to this page the installation was successful，but the last step failed。
google-drive-ocamlfuse -label googledrive  /googledrive
fuse: failed to open /dev/fuse: Operation not permitted

Have you tried mounting with -o allow_other?

Are you mounting in an lxc container?

Are you mounting in an lxc container?

OpenVZ  Server.Debian GNU/Linux 7.9 (wheezy).
Can't mounting？
Thanks

I did manage to make to make google-drive-ocamlfuse work in an LXC container. But you need to configure AppArmor and OpenVZ to allow access to /dev/fuse.

authors: astrada rkkoszewski taozitaozi