Powershell select different exceptions - powershell

I am creating a script that needs to handle all the exceptions available, when creating quotas for a file server.
try
{
### Create cuota ###
}
catch [System.Management.Automation.MethodInvocationException]
{
Write-Host "Exception 0x80045306"
}
catch [System.Management.Automation.MethodInvocationException]
{
Write-Host " Exception 0x80045307 "
}
In this script I have 2 exceptions that are identified with the same net code System.Management.Automation.MethodInvocationException: I need to be able to select between the two exceptions en the code and do different remediation task for each exception.
My question is who can I select the different exceptions to make the appropriate error handling of this two different exceptions with the same .net code.
Full exceptions
Exception : System.Management.Automation.MethodInvocationException: Exception calling "CreateQuota" with "1" argument(s): "Exception from HRESULT: 0x80045306" ---> System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.Runtime.InteropServices.COMException (0x80045306)
Exception from HRESULT: 0x80045306
--- End of inner exception stack trace ---
at System.RuntimeType.InvokeDispMethod(String name, BindingFlags invokeAttr, Object target, Object[] args, Boolean[] byrefModifiers, Int32 culture, String[] namedParameters)
at System.RuntimeType.InvokeMember(String name, BindingFlags bindingFlags, Binder binder, Object target, Object[] providedArgs, ParameterModifier[] modifiers, CultureInfo culture, String[] namedParams)
at System.Management.Automation.ComMethod.InvokeMethod(PSMethod method, Object[] arguments)
--- End of inner exception stack trace ---
at System.Management.Automation.ComMethod.InvokeMethod(PSMethod method, Object[] arguments)
at System.Management.Automation.ComAdapter.MethodInvoke(PSMethod method, Object[] arguments)
at System.Management.Automation.Adapter.BaseMethodInvoke(PSMethod method, Object[] arguments)
at System.Management.Automation.ParserOps.CallMethod(Token token, Object target, String methodName, Object[] paramArray, Boolean callStatic, Object valueToSet)
at System.Management.Automation.MethodCallNode.InvokeMethod(Object target, Object[] arguments, Object value)
at System.Management.Automation.MethodCallNode.Execute(Array input, Pipe outputPipe, ExecutionContext context)
at System.Management.Automation.AssignmentStatementNode.Execute(Array input, Pipe outputPipe, ExecutionContext context)
at System.Management.Automation.StatementListNode.ExecuteStatement(ParseTreeNode statement, Array input, Pipe outputPipe, ArrayList& resultList, ExecutionContext context)
Exception: System.Management.Automation.MethodInvocationException: Exception calling "Commit" with "0" argument(s): "Exception from HRESULT: 0x80045307"
System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation.
System.Runtime.InteropServices.COMException (0x80045307): Exception from HRESULT: 0x80045307
--- End of inner exception stack trace ---
at System.RuntimeType.InvokeDispMethod(String name, BindingFlags invokeAttr, Object target, Object[] args, Boolean[] byrefModifiers, Int32 culture, String[] namedParameters)
at System.RuntimeType.InvokeMember(String name, BindingFlags bindingFlags, Binder binder, Object target, Object[] providedArgs, ParameterModifier[] modifiers, CultureInfo culture, String[] namedParams)
at System.Management.Automation.ComMethod.InvokeMethod(PSMethod method, Object[] arguments)
--- End of inner exception stack trace ---
at System.Management.Automation.ComMethod.InvokeMethod(PSMethod method, Object[] arguments)
at System.Management.Automation.ComAdapter.MethodInvoke(PSMethod method, Object[] arguments)
at System.Management.Automation.Adapter.BaseMethodInvoke(PSMethod method, Object[] arguments)
at System.Management.Automation.ParserOps.CallMethod(Token token, Object target, String methodName, Object[] paramArray, Boolean callStatic, Object valueToSet)
at System.Management.Automation.MethodCallNode.InvokeMethod(Object target, Object[] arguments, Object value)
at System.Management.Automation.MethodCallNode.Execute(Array input, Pipe outputPipe, ExecutionContext context)
at System.Management.Automation.ParseTreeNode.Execute(Array input, Pipe outputPipe, ArrayList& resultList, ExecutionContext context)
at System.Management.Automation.StatementListNode.ExecuteStatement(ParseTreeNode statement, Array input, Pipe outputPipe, ArrayList& resultList, ExecutionContext context)

catch blocks can distinguish exceptions by class:
try {
...
} catch [System.Net.WebException], [System.IO.IOException] {
# handle WebException and IOException
} catch [System.Management.Automation.MethodInvocationException] {
# handle MethodInvocationException
} catch {
# handle all other exceptions
}
They can't distinguish between different exceptions of the same class. You need to differentiate yourself inside the catch block, for instance by HRESULT:
try {
...
} catch [System.Management.Automation.MethodInvocationException] {
switch ($_.Exception.HResult) {
0x80045306 { ... }
0x80045307 { ... }
default { "Unknown HResult: $_" }
}
}
If the exception is nested in another exception you need to unroll it first:
try {
...
} catch [OuterException] {
$e = $_.Exception.InnerException
switch ($e.HResult) {
...
}
}
See here for more information about try..catch.

You can try something like this:
try {
1/0
}
catch{
$et = $_.Exception.gettype().Name
switch (et) {
'RuntimeException' : { 'runtime' }
}
}

Related

POST results in a HTTP 415 Unsupported Media Type response

I created an API which recovers the deck created by a user and store it in the database but the API gives me a 415 error.
Ising react I would like to use the api to communicate the front-end and the back-end
Thank you for your help :)
[Route("api/[controller]")]
[ApiController]
public class DeckController : Controller
{
private readonly ILogger<DeckController> _logger;
private readonly mtgContext _context;
public DeckController(ILogger<DeckController> logger, mtgContext context)
{
_logger = logger;
_context = context;
}
[HttpPost]
public OkObjectResult Add([FromBody] Deck deck)
{
try
{
Deck D = new Deck();
D.Name = deck.Name;
D.CreateAt = deck.CreateAt;
D.User = new User();
_context.Deck.Add(D);
_context.SaveChanges();
}
catch (Exception ex)
{
Console.Write(ex.Message);
}
return Ok(new
{
Success = true,
returnCode = "200"
});
}
}
const [name, setName] = useState("");
const deck = useSelector(state => state.cardList.decklist);
function addDeck() {
fetch(`/api/Deck`, {
method: 'POST',
body: JSON.stringify({ Name: name, CreateAt: "2007-07-15", JoinCards: deck })
})
}
POST results in a HTTP 415 Unsupported Media Type response
When I tested with your code, I did reproduce the problem.
Through debug, it is found that in the fetch method, the contentType needs to be added to the application/json format to pass the json data, but there is a problem with your writing.
To sove it, just to change the content of headers in fecth as follow:
headers: { 'Content-Type': "application/json" }
I update the information and I give it to you hoping that it helps you find the origin of the problem.
[Route ("api/[controller]")]
[ApiController]
public class DeckController : Controller {
private readonly mtgContext _context;
public DeckController (mtgContext context) {
_context = context;
}
[HttpPost]
public void Add ([FromBody] JsonObject deck) {
}
}
function addDeck() {
const test = JSON.stringify({ Name: name, CreateAt: Date.now(), cardList: deck });
console.log(typeof(test));
fetch(`/api/Deck`, {
method: 'POST',
body: test,
headers: { contentType: 'application/json' }
})
}
System.NotSupportedException: Deserialization of reference types without parameterless constructor is not supported. Type 'System.JsonObject'
at System.Text.Json.ThrowHelper.ThrowNotSupportedException_DeserializeCreateObjectDelegateIsNull(Type invalidType)
at System.Text.Json.JsonSerializer.HandleStartObject(JsonSerializerOptions options, ReadStack& state)
at System.Text.Json.JsonSerializer.ReadCore(JsonSerializerOptions options, Utf8JsonReader& reader, ReadStack& readStack)
at System.Text.Json.JsonSerializer.ReadCore(JsonReaderState& readerState, Boolean isFinalBlock, ReadOnlySpan`1 buffer, JsonSerializerOptions options, ReadStack& readStack)
at System.Text.Json.JsonSerializer.ReadAsync[TValue](Stream utf8Json, Type returnType, JsonSerializerOptions options, CancellationToken cancellationToken)
at Microsoft.AspNetCore.Mvc.Formatters.SystemTextJsonInputFormatter.ReadRequestBodyAsync(InputFormatterContext context, Encoding encoding)
at Microsoft.AspNetCore.Mvc.Formatters.SystemTextJsonInputFormatter.ReadRequestBodyAsync(InputFormatterContext context, Encoding encoding)
at Microsoft.AspNetCore.Mvc.ModelBinding.Binders.BodyModelBinder.BindModelAsync(ModelBindingContext bindingContext)
at Microsoft.AspNetCore.Mvc.ModelBinding.ParameterBinder.BindModelAsync(ActionContext actionContext, IModelBinder modelBinder, IValueProvider valueProvider, ParameterDescriptor parameter, ModelMetadata metadata, Object value)
at Microsoft.AspNetCore.Mvc.Controllers.ControllerBinderDelegateProvider.<>c__DisplayClass0_0.<<CreateBinderDelegate>g__Bind|0>d.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at Microsoft.AspNetCore.Mvc.Infrastructure.ControllerActionInvoker.<InvokeInnerFilterAsync>g__Awaited|13_0(ControllerActionInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeNextResourceFilter>g__Awaited|24_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResourceExecutedContextSealed context)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.InvokeFilterPipelineAsync()
--- End of stack trace from previous location where exception was thrown ---
at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
at Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)
at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)

how to use multi DBContextPool?

In EFCore 2.0 Add new feature, DbContext pooling.
i know how to use it in single context,
however, sometimes need multi context in project,
public class BContext : DbContext
{
public BContext(DbContextOptions<BContext> options) : base(options) { }
}
public class AContext : DbContext
{
public AContext(DbContextOptions<AContext> options) : base(options) { }
}
ConfigureServices
services.AddDbContextPool<AContext>(options =>
{
options.UseInMemoryDatabase("AContext.InMemory");
});
services.AddDbContextPool<BContext>(options =>
{
options.UseInMemoryDatabase("BContext.InMemory");
});
Controller
public class HomeController : Controller
{
private readonly AContext aContext;
public HomeController(AContext aContext)
{
this.aContext = aContext;
}
public IActionResult Index()
{
return View();
}
}
When i use any context, exception throw.
System.ArgumentException: Expression of type 'Microsoft.EntityFrameworkCore.DbContextOptions`1[MultiContext.Contexts.BContext]' cannot be used for constructor parameter of type 'Microsoft.EntityFrameworkCore.DbContextOptions`1[MultiContext.Contexts.AContext]'
Parameter name: arguments[0]
at System.Dynamic.Utils.ExpressionUtils.ValidateOneArgument(MethodBase method, ExpressionType nodeKind, Expression arguments, ParameterInfo pi, String methodParamName, String argumentParamName, Int32 index)
at System.Dynamic.Utils.ExpressionUtils.ValidateArgumentTypes(MethodBase method, ExpressionType nodeKind, ReadOnlyCollection`1& arguments, String methodParamName)
at System.Linq.Expressions.Expression.New(ConstructorInfo constructor, IEnumerable`1 arguments)
at System.Linq.Expressions.Expression.New(ConstructorInfo constructor, Expression[] arguments)
at Microsoft.EntityFrameworkCore.Internal.DbContextPool`1.CreateActivator(DbContextOptions options)
at Microsoft.EntityFrameworkCore.Internal.DbContextPool`1..ctor(DbContextOptions options)
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitConstructor(ConstructorCallSite constructorCallSite, ServiceProvider provider)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSite(IServiceCallSite callSite, TArgument argument)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitScoped(ScopedCallSite scopedCallSite, ServiceProvider provider)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitSingleton(SingletonCallSite singletonCallSite, ServiceProvider provider)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSite(IServiceCallSite callSite, TArgument argument)
at Microsoft.Extensions.DependencyInjection.ServiceProvider.<>c__DisplayClass22_0.b__0(ServiceProvider provider)
at Microsoft.Extensions.DependencyInjection.ServiceProvider.GetService(Type serviceType)
at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetService[T](IServiceProvider provider)
at Microsoft.Extensions.DependencyInjection.EntityFrameworkServiceCollectionExtensions.<>c__2`1.b__2_1(IServiceProvider p)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitFactory(FactoryCallSite factoryCallSite, ServiceProvider provider)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSite(IServiceCallSite callSite, TArgument argument)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteRuntimeResolver.VisitScoped(ScopedCallSite scopedCallSite, ServiceProvider provider)
at Microsoft.Extensions.DependencyInjection.ServiceLookup.CallSiteVisitor`2.VisitCallSite(IServiceCallSite callSite, TArgument argument)
at Microsoft.Extensions.DependencyInjection.ServiceProvider.<>c__DisplayClass22_0.b__0(ServiceProvider provider)
at Microsoft.Extensions.DependencyInjection.ServiceProvider.GetService(Type serviceType)
at Microsoft.Extensions.Internal.ActivatorUtilities.GetService(IServiceProvider sp, Type type, Type requiredBy, Boolean isDefaultParameterRequired)
at lambda_method(Closure , IServiceProvider , Object[] )
at Microsoft.AspNetCore.Mvc.Controllers.ControllerActivatorProvider.<>c__DisplayClass4_0.b__0(ControllerContext controllerContext)
at Microsoft.AspNetCore.Mvc.Controllers.ControllerFactoryProvider.<>c__DisplayClass5_0.g__CreateController0(ControllerContext controllerContext)
at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.d__14.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.d__22.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Rethrow(ResourceExecutedContext context)
at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.d__17.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.d__15.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.AspNetCore.Builder.RouterMiddleware.d__4.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.d__7.MoveNext()
Ok. i've found problem. You need to download EF Core, then change constructor for
DbContextPool< TContext>
original
public DbContextPool([NotNull] DbContextOptions options)
and change to
public DbContextPool([NotNull] DbContextOptions<TContext> options)
otherwise DI will use last added options :)
Or you can register your own factory of DbContextPool
services.AddDbContextPool<AContext>(options =>
{
options.UseInMemoryDatabase("AContext.InMemory");
});
services.AddDbContextPool<BContext>(options =>
{
options.UseInMemoryDatabase("BContext.InMemory");
});
collection.AddSingleton(svcs => new DbContextPool<AContext>(svcs.GetService<DbContextOptions<AContext>>()));
collection.AddSingleton(svcs => new DbContextPool<BContext>(svcs.GetService<DbContextOptions<BContext>>()));

Asp.net core rc1, dbcontext connection is closed in IStringLocalizer GetString method

Asp.net core rc1, dbcontext connection is closed in IStringLocalizer GetString method. Happening only when VS2015 is on Debug mode and only once at start up.
I am using Autofac DI, but same issue (without autofac) using the buildin DI.
When I am running the App in debug mode and only at start up, producing the following error. When I refresh the browser all fine, no errors. If I run the App without debugging, no errors, everything runs normally.
Something's wrong with the debugging threat and the DI? Any ideas?
Error on browser:
A database operation failed while processing the request.
InvalidOperationException: ExecuteReader requires an open and
available Connection. The connection's current state is closed.
Output window:
Microsoft.Data.Entity.Storage.Internal.RelationalCommandBuilderFactory: Information: Executed DbCommand (55ms) [Parameters=[#___cultureName_0='?', #__name_1='?'], CommandType='Text', CommandTimeout='30']
SELECT TOP(1) [l].[CultureId], [l].[Name], [l].[Value]
FROM [UIResources] AS [l]
WHERE ([l].[CultureId] = #___cultureName_0) AND ([l].[Name] = #__name_1)
Microsoft.Data.Entity.Query.Internal.QueryCompiler: Error: An exception occurred in the database while iterating the results of a query.
System.NullReferenceException: Not Specified object reference to an instance object.
σε System.Data.SqlClient.SqlConnection.TryOpenInner(TaskCompletionSource`1 retry)
σε System.Data.SqlClient.SqlConnection.TryOpen(TaskCompletionSource`1 retry)
σε System.Data.SqlClient.SqlConnection.Open()
σε Microsoft.Data.Entity.Storage.RelationalConnection.Open()
σε Microsoft.Data.Entity.Query.Internal.QueryingEnumerable.Enumerator.MoveNext()
σε System.Linq.Enumerable.WhereSelectEnumerableIterator`2.MoveNext()
σε System.Linq.Enumerable.FirstOrDefault[TSource](IEnumerable`1 source)
σε lambda_method(Closure , QueryContext )
σε Microsoft.Data.Entity.Query.Internal.QueryCompiler.<>c__DisplayClass18_1`1.<CompileQuery>b__1(QueryContext qc)
Microsoft.Data.Entity.Query.Internal.QueryCompiler: Error: An exception occurred in the database while iterating the results of a query.
System.InvalidOperationException: ExecuteReader requires an open and available Connection. The connection's current state is closed.
at System.Data.SqlClient.SqlCommand.ValidateCommand(String method, Boolean async)
at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method, TaskCompletionSource`1 completion, Int32 timeout, Task& task, Boolean asyncWrite)
at System.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method)
at System.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior, String method)
at Microsoft.Data.Entity.Storage.Internal.RelationalCommand.<>c__DisplayClass17_0.<ExecuteReader>b__0(DbCommand cmd, IRelationalConnection con)
at Microsoft.Data.Entity.Storage.Internal.RelationalCommand.Execute[T](IRelationalConnection connection, Func`3 action, String executeMethod, Boolean openConnection, Boolean closeConnection)
at Microsoft.Data.Entity.Storage.Internal.RelationalCommand.ExecuteReader(IRelationalConnection connection, Boolean manageConnection)
at Microsoft.Data.Entity.Query.Internal.QueryingEnumerable.Enumerator.MoveNext()
at System.Linq.Enumerable.WhereSelectEnumerableIterator`2.MoveNext()
at System.Linq.Enumerable.FirstOrDefault[TSource](IEnumerable`1 source)
at lambda_method(Closure , QueryContext )
at Microsoft.Data.Entity.Query.Internal.QueryCompiler.<>c__DisplayClass18_1`1.<CompileQuery>b__1(QueryContext qc)
Exception thrown: 'System.NullReferenceException' in EntityFramework.Core.dll
Exception thrown: 'System.InvalidOperationException' in EntityFramework.Core.dll
This is my startup:
public IServiceProvider ConfigureServices(IServiceCollection services)
{
// Add framework services.
services.AddEntityFramework()
.AddSqlServer()
.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer(Configuration["Data:DefaultConnection:ConnectionString"]));
services.AddIdentity<ApplicationUser, ApplicationRole>()
.AddEntityFrameworkStores<ApplicationDbContext>()
.AddDefaultTokenProviders();
services.AddMvc().AddViewLocalization();
services.AddMvc().AddDataAnnotationsLocalization();
services.AddLocalization();
// Create the Autofac container builder.
var builder = new ContainerBuilder();
// Populate the services from the collection.
// This have to come First.
builder.Populate(services);
// Register dependencies.
builder.RegisterType<AuthMessageSender>().As<IEmailSender>().InstancePerLifetimeScope();
builder.RegisterType<AuthMessageSender>().As<ISmsSender>().InstancePerLifetimeScope();
builder.RegisterType<DataInitializer>().As<IDataInitializer>().InstancePerLifetimeScope();
builder.RegisterType<CultureHelper>().As<ICultureHelper>().InstancePerLifetimeScope();
builder.RegisterType<RouteRequestCultureProvider>().InstancePerLifetimeScope();
builder.RegisterType<CultureActionFilter>().InstancePerLifetimeScope();
builder.RegisterType<DbStringLocalizerFactory>().As<IStringLocalizerFactory>().InstancePerLifetimeScope();
// DbStringLocalizer registers with InstancePerDependency,
// because localization requires a new instance of IStringLocalizer created in the IStringLocalizerFactory.
builder.RegisterType<DbStringLocalizer>().As<IStringLocalizer>().InstancePerDependency();
// Build the container.
var container = builder.Build();
// Return the IServiceProvider resolved from the container.
return container.Resolve<IServiceProvider>();
}
This is Localization implementation:
public class DbStringLocalizerFactory : IStringLocalizerFactory
{
private IServiceProvider _serviceProvider;
public DbStringLocalizerFactory(IServiceProvider serviceProvider)
{
_serviceProvider = serviceProvider;
}
public IStringLocalizer Create(Type resourceSource)
{
return _serviceProvider.GetService<IStringLocalizer>();
}
public IStringLocalizer Create(string baseName, string location)
{
return _serviceProvider.GetService<IStringLocalizer>();
}
}
public class DbStringLocalizer : IStringLocalizer
{
private ApplicationDbContext _db;
private string _cultureName;
public DbStringLocalizer(ApplicationDbContext db)
: this(db, CultureInfo.CurrentCulture)
{
}
public DbStringLocalizer(ApplicationDbContext db, CultureInfo cultureInfo)
{
_db = db;
_cultureName = cultureInfo.Name;
}
public LocalizedString this[string name]
{
get
{
var value = GetString(name);
return new LocalizedString(name, value ?? name, resourceNotFound: value == null);
}
}
public LocalizedString this[string name, params object[] arguments]
{
get
{
var format = GetString(name);
var value = string.Format(format ?? name, arguments);
return new LocalizedString(name, value, resourceNotFound: format == null);
}
}
private string GetString(string name)
{
//try
//{
var query = _db.UIResources.Where(l => l.CultureId == _cultureName);
var value = query.FirstOrDefault(l => l.Name == name);
return value?.Value;
//}
//catch
//{
// return null;
//}
}
public IEnumerable<LocalizedString> GetAllStrings(bool includeAncestorCultures)
{
return _db.UIResources.Where(l => l.CultureId == _cultureName)
.Select(l => new LocalizedString(l.Name, l.Value, true));
}
public IStringLocalizer WithCulture(CultureInfo culture)
{
return new DbStringLocalizer(_db, culture);
}
}
The IDataInitializer registration as scoped service in
builder.RegisterType<DataInitializer>().As<IDataInitializer>().InstancePerLifetimeScope();
seems odd, as a data initializer is expected to be called only once, when the application starts to ensure the database is created and filled with data required to run the application or after an update.
I suspect you dispose the scoped db context somewhere inside your DataInitializer class, so it becomes unavailable during your request because your IoC container will always return the same instance for the duration of the request.

Resharper command line inspection throws exceptions

We use TeamCity as CI server and want to activate code ispection (.Net). If I configure the code inspection I got a lot of errors from inspector. The same if I try to do code inspection with resharper comman line tools.
We have the following project / solution structure
/
- Solutions/
- Solution1/
- Solution1.sln
- BuildOutput/
- Solution2/
- Solution2.sln
- BuildOutput
...
- Projects/
- Project1/
...
- Project2/
...
The projects are configured to allways build in the solution BuildOutput directory.
If I execute code inspection like this from the solution directory:
C:\Tools\RSCL\inspectcode.exe "Solution1.sln"
I got the following output with errors on the command line:
JetBrains Inspect Code 9.0 Update 1
Running in 64-bit mode, .NET runtime 4.0.30319.34014 under Microsoft Windows NT 6.2.9200.0
C:\Tools\RSCL\inspectcode.exe : Paths relative to drive roots are not supported. Parametername: component Der tats„chliche Wert war \BuildOutput\Debug.
In Zeile:1 Zeichen:1
+ C:\Tools\RSCL\inspectcode.exe "Solution1.sln"
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (Paths relative ...ldOutput\Debug.:String) [], RemoteException
+ FullyQualifiedErrorId : NativeCommandError
--- EXCEPTION #1/2 [ArgumentOutOfRangeException]
Message = "Paths relative to drive roots are not supported."
ExceptionPath = Root.InnerException
ClassName = System.ArgumentOutOfRangeException
HResult = COR_E_ARGUMENTOUTOFRANGE=80131502
Source = JetBrains.Platform.Util
ParamName = component
ActualValue = \BuildOutput\Debug
StackTraceString = "
bei JetBrains.Util.FileSystemPath.Combine(String component)
bei JetBrains.ProjectModel.Impl.CachedProjectItemValue`2.GetValue()
bei JetBrains.ProjectModel.ProjectImpl.<.ctor>b__5(ProjectImpl element)
bei JetBrains.ProjectModel.ProjectImpl.GetOutputFilePath()
bei JetBrains.ProjectModel.Build.OutputAssemblies.UpdateOutputAssemblyMvid(IProject project)
bei JetBrains.ProjectModel.Build.OutputAssemblies.AfterProjectOpenedInternal(IProject project)
bei JetBrains.DataFlow.Viewable.<>c__DisplayClass1d`1.<View>b__1b(Lifetime valueLifetime, TValue value)
bei JetBrains.DataFlow.ViewableCollection`1.Add(TValue item)
bei JetBrains.DataFlow.Lifetime.AddBracket(Action FOpening, Action FClosing)
bei JetBrains.ProjectModel.ProjectManagerBase.OpenProjectInstance(Pair`2 projectInstanceWithLifetime)
bei JetBrains.ProjectModel.ProjectManagerBase.<>c__DisplayClass8.<EnqueueOpenProjectInstance>b__6()
bei JetBrains.Util.Logging.Logger.Catch(Action action)
"
--- Outer ---
--- EXCEPTION #2/2 [LoggerException]
Message = "
Paths relative to drive roots are not supported.
Parametername: component
Der tats„chliche Wert war \BuildOutput\Debug.
"
ExceptionPath = Root
ClassName = JetBrains.Util.LoggerException
InnerException = "Exception #1 at Root.InnerException"
HResult = COR_E_APPLICATION=80131600
StackTraceString = "
bei JetBrains.ProjectModel.Tasks.SolutionLoadTasksSchedulerBase.ExecuteOneTask(SolutionLoadTask task)
bei JetBrains.ProjectModel.Tasks.SolutionLoadTasksSchedulerBase.DispatchTasks(Boolean background)
bei JetBrains.ProjectModel.SolutionManagerBase.CreateSolutionInstance(SolutionElement solutionElement, SolutionInstance solutionInstance)
bei JetBrains.ProjectModel.MsBuild.Internal.MsBuildSolutionManager.<>c__DisplayClass4.<>c__DisplayClass6.<.ctor>b__1()
bei JetBrains.Threading.ReentrancyGuard.Execute(String name, Action action)
bei JetBrains.Threading.ReentrancyGuard.ExecuteOrQueue(String name, Action action)
bei JetBrains.ProjectModel.MsBuild.Internal.MsBuildSolutionManager.<>c__DisplayClass4.<.ctor>b__0(Lifetime msBuildSolutionLifetime, MsBuildSolution msBuildSolution)
bei JetBrains.DataFlow.Lifetimes.Define(Lifetime lifetime, String id, Action`2 FAtomic, ILogger logger)
bei JetBrains.DataFlow.SequentialLifetimes.DefineNext(Action`2 FNext)
bei JetBrains.DataFlow.Signal`1.NotifySinks(TValue payload)
bei JetBrains.DataFlow.Signal`1.Fire(TValue value, Object cookie)
bei JetBrains.DataFlow.Property`1.FireChange(TValue old, TValue new, Object cookie)
bei JetBrains.DataFlow.Property`1.SetValue(TValue value, Object cookie)
bei JetBrains.ProjectModel.MsBuild.MsBuildSolutionHost.OpenSolution(FileSystemPath location, IMsBuildSolutionUserProfile userProfile)
bei JetBrains.CommandLine.InspectCode.Unattended.InspectCodeProductMain.OpenSolution(FileSystemPath solutionFilePath, ILogger logger, MsBuildSolutionHost solutionHost, SolutionsManager solutionsManager,
IInspectCodeSettings settings)
bei JetBrains.CommandLine.InspectCode.Unattended.InspectCodeProductMain.Main(IThreading invocator, IShellLocks shellLocks, ILogger logger, IInspectCodeSettings settings, MsBuildSolutionHost solutionHost,
SolutionsManager solutionsManager, PlatformMana
ger platformManager, ISdkManager sdkManager, IProductCommandLineArguments argumentsRaw, IssuesTypesWriter issuesTypesWriter)
bei System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor)
bei System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj, Object[] parameters, Object[] arguments)
bei System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
bei JetBrains.Application.Environment.RunsPublicStaticIntMain.<>c__DisplayClass7.<.ctor>b__0()
bei JetBrains.Util.Logging.Logger.Catch(Action action)
bei JetBrains.Threading.JetDispatcher.Closure.Execute()
bei JetBrains.Threading.JetDispatcher.ProcessQueue()
bei System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs)
bei MS.Internal.Threading.ExceptionFilterHelper.TryCatchWhen(Object source, Delegate method, Object args, Int32 numArgs, Delegate catchHandler)
bei System.Windows.Threading.DispatcherOperation.InvokeImpl()
bei System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
bei System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
bei System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
bei System.Windows.Threading.DispatcherOperation.Invoke()
bei System.Windows.Threading.Dispatcher.ProcessQueue()
bei System.Windows.Threading.Dispatcher.WndProcHook(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
bei MS.Win32.HwndWrapper.WndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
bei MS.Win32.HwndSubclass.DispatcherCallbackOperation(Object o)
bei System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs)
bei MS.Internal.Threading.ExceptionFilterHelper.TryCatchWhen(Object source, Delegate method, Object args, Int32 numArgs, Delegate catchHandler)
bei System.Windows.Threading.Dispatcher.LegacyInvokeImpl(DispatcherPriority priority, TimeSpan timeout, Delegate method, Object args, Int32 numArgs)
bei MS.Win32.HwndSubclass.SubclassWndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam)
bei MS.Win32.UnsafeNativeMethods.DispatchMessage(MSG& msg)
bei MS.Win32.UnsafeNativeMethods.DispatchMessage(MSG& msg)
bei System.Windows.Threading.Dispatcher.PushFrameImpl(DispatcherFrame frame)
bei JetBrains.DataFlow.Lifetimes.Using(Action`1 ?)
bei JetBrains.Application.Environment.IJetHostEx.RunHostMessageLoop(IComponentContainer containerEnv)
bei JetBrains.Application.Environment.HostParameters.JetHostParametersCaller.RunMainLoop(ComponentContainer containerEnv)
bei JetBrains.Application.Environment.JetEnvironment.InternalRun(JetHostParametersCaller host, ComponentContainer containerEnv)
bei JetBrains.Application.Environment.JetEnvironment.CreateAndRun(Full hostparams)
bei JetBrains.CommandLine.InspectCode.InspectCodeProgram.Main(Assembly assembly, HostInfo hostInfo, String[] args)
bei JetBrains.CommandLine.InspectCode.InspectCodeProgram.Main(String[] args)
"
Paths relative to drive roots are not supported. Parametername: component Der tats„chliche Wert war \BuildOutput\Debug.
--- EXCEPTION #1/2 [ArgumentOutOfRangeException]
...
I don't understand what is going wrong. The Solutions are all buildable and code inspection from VS works well on the same solutions.
I figured it out. Mine was failing because my .csproj did not define the SolutionDir. The relative path error is a red herring so to speak.
Make sure this is in the csproj
<SolutionDir Condition="$(SolutionDir) == '' Or $(SolutionDir) == '*Undefined*'">..\..\</SolutionDir>

Entity framework raw SQL - string date format isn't correct?

I have a keyless table (which isn't my handywork) and I am trying to use raw sql to insert the row of data. I did try mapping a stored procedure but I had the same problem with the date.
internal bool InsertSession(Guid UserID, DateTime LastActivityDate, string SessionID)
{
string s = "INSERT INTO aspnet_Custom_UserSessionActivity VALUES (" + "'" + UserID.ToString() + "'" + " ," + LastActivityDate.ToString("yyyy-MM-dd HH:mm:ss") + "," + "'" + SessionID.ToString() + "')";
try
{
using (ALFDataContext)
{
ALFDataContext.Database.ExecuteSqlCommand(s);
ALFDataContext.SaveChanges();
return true;
}
}
catch (Exception ex)
{
return false;
}
}
This is what string s contains:
INSERT INTO aspnet_Custom_UserSessionActivity VALUES ('f4da4c0b-d94e-4f9c-84ef-c82fa442bbc1' ,2014-02-04 09:48:43,'wj4gesi3bdqytflifnzyqx2c')
and this is the error:
Incorrect syntax near '09'.
at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
at System.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
at System.Data.SqlClient.SqlCommand.RunExecuteNonQueryTds(String methodName, Boolean async, Int32 timeout)
at System.Data.SqlClient.SqlCommand.InternalExecuteNonQuery(TaskCompletionSource`1 completion, String methodName, Boolean sendToPipe, Int32 timeout, Boolean asyncWrite)
at System.Data.SqlClient.SqlCommand.ExecuteNonQuery()
at System.Data.Objects.ObjectContext.ExecuteStoreCommand(String commandText, Object[] parameters)
at System.Data.Entity.Internal.InternalContext.ExecuteSqlCommand(String sql, Object[] parameters)
at System.Data.Entity.Database.ExecuteSqlCommand(String sql, Object[] parameters)
at MembershipProvider.DataAccess.Repository.InsertSession(Guid UserID, DateTime LastActivityDate, String SessionID) in c:\Users\nickgowdy\Documents\Visual Studio 2012\Projects\ALF source code\ALF\branches\Nick's Branch\MembershipProvider\DataAccess\Repository.cs:line 149
I am assuming my date format is wrong but I can't see the bug.
Does anyone have suggestions for fixing this?
DO NOT, under any circumstances, use string concatenation to insert parameters into a query!
By building a dynamic SQL query, you've just opened yourself up to SQL Injection.
Avoiding SQL Injection with Entity Framework is extremely simple:
internal bool InsertSession(Guid UserID, DateTime LastActivityDate, string SessionID)
{
try
{
using (ALFDataContext)
{
string s = "INSERT INTO aspnet_Custom_UserSessionActivity VALUES ({0}, {1}, {2})";
ALFDataContext.Database.ExecuteSqlCommand(s, UserID, LastActivityDate, SessionID);
// No need to call SaveChanges here.
return true;
}
}
catch (Exception ex)
{
return false;
}
}
The ExecuteSqlCommand method will automatically create a parameterized query, and replace the {0}, {1} and {2} tokens in the string with the correct parameter names.