How can I use Format Arguments in BusinessException? - asp.net-core

I have noticed the abp localization provide a Format Arguments mechanism to help generate realtime local string by this way, and I want to know how can I do the same thing in calling a BusinessException while all its overloads are not suitable for this purpose.

Please see the documentation: https://docs.abp.io/en/abp/latest/Exception-Handling#exception-localization
It is possible to set an exception code and data related to the exception. Then ABP automatically localizes the exception message by also using the data arguments you've provided.
Example exception:
throw new BusinessException("App:010046")
.WithData("UserName", "john");
And the related localization entry in the json file:
"App:010046": "Username should be unique. '{UserName}' is already taken!"
It is not using {0}, {1}... but using parameter names instead.

Related

Entity Framework: .Add & .SaveChanges() is not adding entity to database

When I am adding an entry
var objectEntity = new ObjectStaging();
objectEntity .CreatedBy = ClaimsPrincipal.Current.Identity.Name;
objectEntity .ModifiedBy = ClaimsPrincipal.Current.Identity.Name;
objectEntity .Set(ObjectInfo);
database.ObjectStaging.Add(objectEntity);
database.SaveChanges();
For some reason, my objectEntity is not being added to my database given the following code. When using the debugger, it moves through database.ObjectStaging.Add(objectEntity); but does not continue after calling SaveChanges(). Is there a way to know why it is failing to add the entry to the database?
Exception Thrown:
Exception thrown:
'System.Data.Entity.Validation.DbEntityValidationException' in
VCC.BrokerPortal.DAO.dll Validation failed for one or more entities.
See 'EntityValidationErrors' property for more details.
Is there a way to know what specifically did not validate?
Also, I tested the state of the entity using the following lines of code,
database.ObjectStaging.Add(objectEntity);
var state= brokerPortalDB.Entry(objectEntity).State;
state currently shows the value of 'added'.
Thank you!
I ended up looking into the exception thrown and it appears it was related to one of the properties not having proper validation. In this instance I had a [MaxLength] attribute assigned to a field and I was trying to add a value longer than that length allowed.

How to pass the background response value of the to another feature json in function value using Karate

I have got the response in the background to one of the request and passing to the function for polling purpose and need to run until specific condition met. In that function, I need to pass the values to the calling feature JSON file
while (true) {
var result = karate.call('extractProgress.feature') packageid; -- package id
is response of another request
I followed the similar way as mentioned but in that not passing any parameter.
https://github.com/intuit/karate/blob/933d3803987a736cc1a38893e7039c4b5e5132fc/karate-demo/src/test/java/demo/polling/polling.feature
But i am getting the below error
feature(com.intuit.karate.testng.KarateTestngTest):
java.lang.RuntimeException: javascript evaluation failed: packageid,
ReferenceError: "packageid" is not defined in at line number 1
Input for call inside js should be given as
karate.call("<featureFile>",yourInputVaraible);
refer this on doc
https://github.com/intuit/karate#the-karate-object
It sounds wrong to me, maybe you have a typo.
Also please read the docs carefully. Only JSON is supported as a call argument.
The best way for you to get support is to follow this process, else no one can help you with the limited info you seem to be providing in your questions.
https://github.com/intuit/karate/wiki/How-to-Submit-an-Issue

Send exception for UNIQUE constraint to UI in .NET core

When a unique constraint exception occurs, how do I message the UI in .NET Core; I want to return JSON, not MVC/Razor approach.
I think you have been looking at my article Catching Bad Data in Entity Framework. In there I describe a way to catch a SQL error and turn it into a validation error for EF Core.
UPDATE
In answer to your follow on questions I can point you to the code associated with the book I am writing, Entity Framework Core in Action. In this I built a method called SaveChangesSqlCheck, which contains the code to check for sql errors. You would use this method instead of calling SaveChanges, and it will return a ValidationResult.
My book has associated git repository where I have unit tests for just about everything I show in the book. Below are links to a unit test to see how you call SaveChangesSqlCheck, and then the SaveChangesSqlCheck code itself.
Unit test: https://github.com/JonPSmith/EfCoreInAction/blob/Chapter10/Test/UnitTests/DataLayer/Ch10_CatchSqlError.cs#L59-L89
The SaveChangesSqlCheck code: https://github.com/JonPSmith/EfCoreInAction/blob/Chapter10/DataLayer/EfCode/SaveChangesSqlCheck.cs
The method that catches the Unique error: https://github.com/JonPSmith/EfCoreInAction/blob/Chapter10/DataLayer/EfCode/SqlErrorFormatters.cs
Note: you need to format the unique constraint name in a special way - see https://github.com/JonPSmith/EfCoreInAction/blob/Chapter10/Test/Chapter10Listings/EfCode/Configuration/MyUniqueConfig.cs for an example.
If you plan to use the code shown in the article then all you need to do is use JsonConvert.SerializeObject(errors) to turn that into json. I have included some code so you can see what the json output would look like.
var error = new ValidationResult("error message");
var jsonList = JsonConvert.SerializeObject(error,
new JsonSerializerSettings { Formatting = Newtonsoft.Json.Formatting.Indented });
The json output of this would be
{
"MemberNames": [],
"ErrorMessage": "error message"
}
I hope that helps.

How to read properties from .properties file in Mule

I'm trying to use Mule Credentials Vault security feature.
I've created .properties file, Security Property Placeholder and defined the key and encryption algorithm.
Now I want to use some of the properties from the file when I return HTTP response.
I have the file src/main/resources/data.properties that contains for example:
In my canvas, under Configuration XML I added:
<secure-property-placeholder:config name="Secure_Property_Placeholder" key="24681357" location="data.properties" doc:name="Secure Property Placeholder" encryptionAlgorithm="DES"/>
<set-variable variableName="card.number" value="${number}" />
In my canvas I have message flow that builds xml 'Create XML response based on User'. The value in settings is:
This doesn't work. The error I get is:
-> org.mule.module.launcher.DeploymentInitException: IllegalArgumentException: Could not resolve placeholder 'key' in string value "${key}"
-> Caused by: org.mule.api.lifecycle.InitialisationException: Invalid bean definition with name 'org.mule.autogen.bean.13' defined in null: Could not resolve placeholder 'key' in string value "${key}"; nested exception is java.lang.IllegalArgumentException: Could not resolve placeholder 'key' in string value "${key}"
-> Caused by: java.lang.IllegalArgumentException: Could not resolve placeholder 'key' in string value "${key}"
Does anyone know how can I read the properties from .properties file (credentials vault)? And then use it in my flow?
Thanks,
Keren
If you simply want to get the value for the property number and add it into the XML you can use ${number} from .properties. No need to define any other variables in Configuration XML.
<set-payload value="<user><name>Royal Bank of Canada</name><id>Royal_Bank_Of_Canada</id><cc><company>>Visa</company><number>${number}</number><secret>123</secret></cc></user>" doc:name="Set Payload"/>
However note that the property placeholder is resolved at startup so you will not be able to dynamically retrieve a property based on some user input. For this you will have to do some Java coding. This SO post gives you some hints on how this can be achieved. Based on those answers I have created a simple example on how this can be done with a very simple helper bean.
I'm afraid you just can't. The Mule Credentials Vault is an enterprise feature and therefore tipically you won't have access to the source code unless you are a MuleSoft customer.
Even if you were a customer, the api you'd use would be sort of unsupported. I suggest to manually create a custom java component levearing your code and Jasypt (not as a property placeholder but as a library).
The other option, if you are a customer (I guess you are given you are using the credentials vault) is to contact the official support so they take care of it for you.
The property placeholder is used resolve at startup so you will not be able to dynamically retrieve a property based on some user input.
Use ${propertyName} from .properties in MEL to access particular property
From Dataweave you can read it as given below
p('variablename')
where variablename is defined in property files ex: variablename = 15

How do I utilize a named instance within the ObjectFactory.Initialize call for StructureMap?

I am trying to do the following bootstrapping:
x.For(Of IErrorLogger).Use(Of ErrorLogger.SQLErrorLogger)().
Ctor(Of IErrorLogger)("backupErrorLogger").Is(ObjectFactory.GetNamedInstance(Of IErrorLogger)("Disk"))
x.For(Of IErrorLogger).Add(
Function()
Return New ErrorLogger.DiskErrorLogger(
CreateErrorFileName(ServerMapPath(GetAppSetting("ErrorLogFolder"))))
End Function).Named("Disk")
But it shows this error:
StructureMap Exception Code: 200
Could not find an Instance named "Disk" for PluginType Logging.IErrorLogger
I sort of understand why this is happening.. the question is, how do I utilize a named instance within the registry? Maybe something like lazy initialization for the ctor argument for the SQLErrorLogger? I am not sure how to make it happen.
Thanks in advance for any help you can provide.
I found the correct way to do it in the latest version (2.6.1) of StructureMap:
x.For(Of IErrorLogger).Use(Of ErrorLogger.SQLErrorLogger)().
Ctor(Of IErrorLogger)("backupErrorLogger").Is(
Function(c) c.ConstructedBy(Function() ObjectFactory.GetNamedInstance(Of IErrorLogger)("Disk"))
)
x.For(Of IErrorLogger).Add(Function() _
New ErrorLogger.DiskErrorLogger(
CreateErrorFileName(ServerMapPath(GetAppSetting("ErrorLogFolder"))))
).Named("Disk")
Notice for the Is method of Ctor, we need to provide a func(IContext), and use the IContext.ConstructedBy(Func()) to call ObjectFactory.Get... to successfully register the IErrorLogger in this case.
This is the only way to do it as far as I know. The other Icontext methods such as IsThis and Instance will only work with already registered type.
Your problem is that you are trying to access the Container before it's configured. In order to make structuremap evaluate the object resolution after the configuration you need to provide a lambda to the Is function. The lambda will be evaluated when trying to resolve the type registered.
x.[For](Of ILogger)().Add(Of SqlLogger)().Ctor(Of ILogger)("backupErrorLogger")_
.[Is](Function(context) context.GetInstance(Of ILogger)("Disk"))
x.[For](Of ILogger)().Add(Of DiskLogger)().Ctor(Of String)("errorFileName")_
.[Is](CreateErrorFileName(ServerMapPath(GetAppSetting("ErrorLogFolder"))))_
.Named("Disk")
Disclaimer: I'm not completely up-to-date with the lambda syntax in VB.NET, but I hope I got it right.
Edit:
The working C# version of this I tried myself before posting was this:
ObjectFactory.Initialize(i =>
{
i.For<ILogger>().Add<SqlLogger>()
.Ctor<ILogger>("backup").Is(
c => c.GetInstance<ILogger>("disk"))
.Named("sql");
i.For<ILogger>().Add<DiskLogger>().Named("disk");
});
var logger = ObjectFactory.GetNamedInstance<ILogger>("sql");