Correct code and settings with both Publisher and Subscriber with Rebus - rebus

Are the code and comments below from 1 - 7 all correct?
//7 below is not needed for both publisher and subscriber
// .Routing(r => r.TypeBased().MapAssemblyOf<string>(Consts.Publisher))
Subscriber1
Configure.With(activator)
.Logging(l => l.ColoredConsole(minLevel: LogLevel.Warn))
.Transport(t => t.UseAzureServiceBus(Consts.ServiceBusConnectionString, Consts.Subscriber1))
//7 below is not needed for both publisher and subscriber
// .Routing(r => r.TypeBased().MapAssemblyOf<string>(Consts.Publisher))
.Options(o =>
{
//1 can be used for both publisher and subscriber
o.Register<ITopicNameConvention>(c => new SimpleTopicNameConvention());
//2 only used by consumer
o.Decorate<IErrorHandler>(c => new MyErrorHandler(c.Get<IErrorHandler>()));
//3 only used by consumer
o.SimpleRetryStrategy(maxDeliveryAttempts: 2,
errorQueueAddress: "poison");
//4 only used by consumer
o.SetNumberOfWorkers(5);
o.SetMaxParallelism(30);
//5 only used by consumer
o.SetBackoffTimes(
TimeSpan.FromMilliseconds(100),
TimeSpan.FromMilliseconds(200),
TimeSpan.FromSeconds(1));
//6 only used by consumer
o.Register<IBackoffStrategy>(c =>
{
var strategy = new MyBackoffStrategy();
return strategy;
});
}).Start();

Related

Statement using EF Core for multiple table with same FK

I am not sure why I am receiving null values for users in PurchaseOrderHistory in the code below. I think it has to do with PurchaseOrder also containing a userID. What I don't understand is that if the UserID is the same for PurchaseOrder and PurchaseOrderHistory then it will appear. I have attached snips for clarification.
var purchaseOrder = await _context.PurchaseOrder
.Include(p => p.Division)
.Include(p => p.PaymentType)
.Include(p => p.Status)
.Include(p => p.Vendor)
.Include(p => p.ItemServiceLine)
.Include(p => p.PurchaseOrderHistory)
.Include(p => p.User)
.FirstOrDefaultAsync(m => m.ID == id);
PurchaseOrder user snip
PurchaseOrderHistory user snip
What I don't understand is that if the UserID is the same for PurchaseOrder and PurchaseOrderHistory then it will appear.
If the Change Tracker already has a User entity whose UserID matches the PurchaseOrderHistory.UserID it will "fix up" the navigation property.
You include PurchaseOrder's User, not PurchaseOrderHistory's. If both user ids are the same, relationship fixup will also populate PurchaseOrderHistory's User because it's attached to the context.
What you intended to do is:
var purchaseOrder = await _context.PurchaseOrder
.Include(p => p.Division)
.Include(p => p.PaymentType)
.Include(p => p.Status)
.Include(p => p.Vendor)
.Include(p => p.ItemServiceLine)
.Include(p => p.User)
.Include(p => p.PurchaseOrderHistory)
.ThenInclude(poh => poh.User)
.FirstOrDefaultAsync(m => m.ID == id);

Cakephp 3 - Query Fixture in IntegrationTestTrait

I am having issues querying a loaded Fixture in my TestCase for an IntegrationTestTrait. I want to verify that a record already exist inside of a Fixture, then insert a duplicate record and verify that there is still only 1 record in the database.
During my test case initialization, I set the session variable for authentication.
public function setUp() {
parent::setUp();
$this->loadFixtures(
'Students', 'Users');
// Configure Authentication
$this->session([
'Auth' => [
'User' => [
'id' => 21896,
'institution_id' => 1,
'student_id' => null,
'contact_id' => 91,
'email' => 'AuthenticatedEmail#school.edu',
'role' => 'DSP',
'is_admin' => false
]
]
]);
// Load Tables
$this->Students = TableRegistry::getTableLocator()->get('Students');
}
In my Test Case, I check to see if the Database contains a record, then submit a POST request then test to see if the record did not insert.
public function testAddStudentSuccess() {
$data = [
'institution_id' => 1,
'contact_id' => null,
'id_number' => '200XYZ',
'last_name' => 'Trimor',
'first_name' => 'Paul',
'email' => '1_test#email.com'
];
// Test Pre-condition
$query = $this->Students->find('all')->where([
'id_number' => $data['id_number']
]);
$this->assertEquals(1, $query->count());
$this->post('students/add', $data);
// Test Post-condition
$this->assertResponseSuccess();
$query = $this->Students->find('all')->where([
'id_number' => $data['id_number']
]);
$this->assertEquals(1, $query->count());
}
However, when I run the Test Case, I get the following error:
Notice Error: Undefined variable: _SESSION in/var/www/html/samusg/src/Model/Table/StudentsTable.php, line 206]
A couple things:
The last assertion works! After $this->post('students/add', $data) is submitted, the $query is populated with data.
The first assertion does not work. I debug the Fixture before the $this->post() is called and it returns empty.
In the Test Table, there is a test for $_SESSION variable, which is what line 206 referring to.
Long Story short: The Fixture is not populated with data during the start of the Test Case, but once the integration runs then the Fixture magically contains all the data. I get $_SESSION errors, but I already set the session in the setUp(), so I'm lost.
I greatly appreciate any help. Thank you
I was able to by pass this message by setting the $_SESSION super global directly on my Test:
public function setUp() {
parent::setUp();
$this->loadFixtures(
'Students', 'Users');
// Configure Authentication
$this->session([
'Auth' => [
'User' => [
'id' => 21896,
'institution_id' => 1,
'student_id' => null,
'contact_id' => 91,
'email' => 'AuthenticatedEmail#school.edu',
'role' => 'DSP',
'is_admin' => false
]
]
]);
$_SESSION = [
'Auth' => [
'User' => [
'id' => 21896,
'institution_id' => 1,
'student_id' => null,
'contact_id' => 91,
'email' => 'AuthenticatedEmail#school.edu',
'role' => 'DSP',
'is_admin' => false
]
]
];

How to ignore mapping with condition

As I'm having a single DTO, we use DTOs for GET, PUT and POST http method in our Web API.
To make simple we have ActivityDO:
public ActivityDTO
{
public int Id;
public string Name;
public string CategoryName;
public DateTime DateCreated;
public DateTime DateModified;
}
The challenge is when you only have a single DTO for handling multiple conditions i.e. post/get/put method, the mapping as follow:
private MapperConfiguration configuration = new MapperConfiguration(cfg => {
cfg.CreateMap<ActivityDTO, Activity>()
.ForMember(dst => dst.UserId, opt => opt.MapFrom(src => HttpContext.Current.User.Identity.GetUserId()))
.ForMember(dst => dst.CategoryId, opt => opt.MapFrom(src => GetCategoryId(HttpContext.Current.User.Identity.GetUserId(), src.CategoryName)))
.ForMember(dst => dst.DateCreated, opt => opt.MapFrom(src => DateTime.UtcNow))
.ForMember(dst => dst.DateModified, opt => opt.MapFrom(src => DateTime.UtcNow));
});
I want to IGNORE the mapping for DateCreated if we do the update and we can do the condition if the id <= 0, the rest is allowed to mapping for DateCreated.
Is this possible? Would rather to have a seperate DTOs between GET/POST (Add) VS PUT (Update)? Is there any better solution to handle this DateCreated VS DateModified thingy?
I'm appreciated your feedback/comment.
This is the way to add conditions.
Is that what you are looking for?
private MapperConfiguration configuration = new MapperConfiguration(cfg => {
cfg.CreateMap<ActivityDTO, Activity>()
.ForMember(dst => dst.UserId, opt => opt.MapFrom(src => HttpContext.Current.User.Identity.GetUserId()))
.ForMember(dst => dst.CategoryId, opt => opt.MapFrom(src => GetCategoryId(HttpContext.Current.User.Identity.GetUserId(), src.CategoryName)))
.ForMember(dst => dst.DateCreated, opt => opt.MapFrom(src => src.Condition(src.DateCreated != null)))
.ForMember(dst => dst.DateModified, opt => opt.MapFrom(src => DateTime.UtcNow));
});
I used src.DateCreated != null but you can specify any condition using the src.Condition() and the variable will only be mapped when the condition is met.
Also
You can use AutoMapper's PreCondition
var configuration = new MapperConfiguration(cfg => {
cfg.CreateMap<Foo,Bar>()
.ForMember(dest => dest.baz, opt => {
opt.PreCondition(src => (src.baz >= 0));
opt.MapFrom(src => {
});
});
});

Nhibernate QueryOver how can I make this query use async?

For this new website I want to use async methods in NHibernate. I have this simple query using QueryOver API but I can't get this one to work with async.
It is a simple query with some where clauses that list all businesses. I want 20 of them each time I execute this.
Query:
BusinessListItem bli = null;
BusinessCategory bc = null;
Category c = null;
BusinessImage bi = null;
Image i = null;
var q = Session.QueryOver<Business>()
.JoinAlias(x => x.Categories, () => bc)
.JoinAlias(() => bc.Category, () => c)
.JoinAlias(x => x.Images, () => bi, JoinType.LeftOuterJoin)
.JoinAlias(() => bi.Image, () => i, JoinType.LeftOuterJoin)
.Where(() => bc.IsMain);
if (!string.IsNullOrEmpty(_name))
q.WhereRestrictionOn(x => x.Name).IsLike($"%{_name}%");
if (!string.IsNullOrEmpty(_streetName))
q.WhereRestrictionOn(x => x.StreetName).IsLike($"%{_streetName}%");
if (_categoryId != null)
q.Where(() => c.Id == _categoryId.Value);
if (_subCategoryIds != null)
q.WhereRestrictionOn(() => c.Id).IsIn(_subCategoryIds);
return q.Select(
Projections.Property<Business>(x => x.Id).WithAlias(() => bli.Id),
Projections.Property<Business>(x => x.Name).WithAlias(() => bli.Name),
Projections.Property("c.Name").WithAlias(() => bli.CategoryName),
Projections.Property("bi.Image").WithAlias(() => bli.Image)
)
.TransformUsing(Transformers.AliasToBean<BusinessListItem>())
.List<BusinessListItem>()
.OrderBy(x => x.Name)
.Skip(_skipCount)
.Take(20)
.ToList();
I know the method .ListAsync() exists but I cannot get it working together with the Skip, Take and OrderBy method.
Any help is much appreciated!
The solution to this question is :
var result = await q.Select(
Projections.Distinct(
Projections.Property<Business>(x => x.Id).WithAlias(() => bli.Id)
)
.TransformUsing(Transformers.AliasToBean<BusinessListItem>())
.OrderBy(x => x.Name).Asc
.Skip(_skipCount)
.Take(_takeCount)
.ListAsync<BusinessListItem>();
return result.ToList();
Thx to #DavidOsborne

symfony 1.4 conditional validation of shipping address

how can i validate the bill address depending on bill_ceck post parameter?
i reviewed the post validation (http://symfony.com/legacy/doc/cookbook/1_2/en/conditional-validator) but it seem to me like an AND validation not an OR.
class OrderAddForm extends BaseOprOrderHeaderForm {
public function configure() {
$this->setWidgets(array(
'email' => new sfWidgetFormInputText(),
'name' => new sfWidgetFormInputText(),
//....
'city' => new sfWidgetFormInputText(),
'street' => new sfWidgetFormInputText(),
//....
'bill_check' => new sfWidgetFormInputCheckbox(),
'bill_name' => new sfWidgetFormInputText(),
'bill_city' => new sfWidgetFormInputText(),
'bill_street' => new sfWidgetFormInputText(),
//....
));
$this->widgetSchema['bill_check']->setOption('value_attribute_value', 1);
$this->setValidators(array(
'email' => new sfValidatorEmail(),
'name' => new sfValidatorString(),
//...
'city' => new sfValidatorString(),
'street' => new sfValidatorString(),
//...
'bill_check' => new sfValidatorBoolean(),
));
if (/** the most convetional solution to check 'bill_check' state */) {
$this->validatorSchema['bill_name'] = new sfValidatorString();
$this->validatorSchema['bill_city'] = new sfValidatorString();
$this->validatorSchema['bill_street'] = new sfValidatorString();
//....
}
$this->widgetSchema->setNameFormat('orderAddForm[%s]');
}
}
thanks,
oliver
You could use a postValidator
public function configure() {
// your current code
$this->validatorSchema->setPostValidator(
new sfValidatorCallback(array('callback' => array($this, 'checkOtherStuff')))
);
}
public function checkOtherStuff($validator, $values)
{
// $values is an array of POSTed values
if ($values['bill_check'] == 'something in here')
{
if ($values['bill_city'] == '' || $values['bill_street'] == '') {
throw new sfValidatorError($validator, 'You must complete all fields');
}
}
// bill_check is correct, return the clean values
return $values;
}
Blog article on the subject here

Resources