How to create a kentico form that does not store the response - forms

Is there any way in Kentico to have a user submit a form and then email the response but not actually save the answer to the related table?

As mentioned the emails from Kentico rely on the record being written to the DB before they trigger. Furthermore (unless I'm just unlucky) the only values you have access to are those stored in the table. I had thought that maybe you could mark the offending fields as Field without database representation, but sadly, the fields you may want will all be null - so best not to go down that route.
I took a slightly different approach to #trevor-j-fayas in that I used the BizFormItemEvents.Insert.Before event so that there is no trace of any log. It's a short hop from there to make use of an email template to make things look good. So my code looked as follows:
using CMS;
using CMS.DataEngine;
using CMS.EmailEngine;
using System;
[assembly: RegisterModule(typeof(FormGlobalEvents))]
public class FormGlobalEvents : Module
{
public FormGlobalEvents() : base("FormGlobalEvents")
{
}
protected override void OnInit()
{
CMS.OnlineForms.BizFormItemEvents.Insert.Before += Insert_Before;
}
private void Insert_Before(object sender, CMS.OnlineForms.BizFormItemEventArgs e)
{
var email = new EmailMessage();
email.From = e.Item.GetStringValue("ContactEmail", "null#foo.com");
email.Recipients = "no-reply#foo.com";
email.Subject = "Test from event handler (before save)";
email.PlainTextBody = "test" + DateTime.Now.ToLongTimeString();
EmailSender.SendEmail(email);
e.Cancel();
}
}
To me, it seems cleaner to not insert the record in the first place than delete it, but obviously that autoresponder etc. will only kick in automatically if you do save the record, so the choice is yours and ultimately depends on your preference.

Well, there's a couple different options, but the easiest is to simply delete the record after it's inserted. Use the Global Event Hooks to capture the BizFormItemEvent insert after, if it's your form, then delete it. Below is for Kentico 10:
using CMS;
using CMS.DataEngine;
using CMS.Forums;
using CMS.Helpers;
using CMS.IO;
using System.Net;
using System.Web;
// Registers the custom module into the system
[assembly: RegisterModule(typeof(CustomLoaderModule))]
public class CustomLoaderModule : Module
{
// Module class constructor, the system registers the module under the name "CustomForums"
public CustomLoaderModule()
: base("CustomLoaderModule")
{
}
// Contains initialization code that is executed when the application starts
protected override void OnInit()
{
base.OnInit();
CMS.OnlineForms.BizFormItemEvents.Insert.After += BizFormItem_Insert_After;
}
private void BizFormItem_Insert_After(object sender, CMS.OnlineForms.BizFormItemEventArgs e)
{
switch(e.Item.BizFormInfo.FormName)
{
case "YourFormNameHere":
e.Item.Delete();
break;
}
}
}
The other option would be to clone and modify the Online Form Web part to take the information, manually call the email and cancel the insert, but that's a lot of work when this is quicker.

Yes and no. The record is stored before the email notifications and autoresponders are sent out. Your best bet for this is to create a custom global event handler for the form submission(s) using the BizFormItemEvents.Insert.Before. This will call the event before the actual record is stored in the database. You can then cancel out of the event (which will not store the record) and send your email manually.
Handling global events
BizFormItemEvents Events

Related

Umbraco - when editor create content send email notification to admin

Is it possible?
I am an admin. I want to be notified by email when editor (or writer or whom ever with the access) creates some content (e.g. enters some News in News document type).
And how?
I use Umbraco 7.5
You need to code into Umbraco ContentService events.
The following should get you started. It will be triggered whenever an item is published.
Be careful what you wish for though. You may get a barrage of useless emails if somebody publishes a parent node along with all of its child nodes.
There are other events that you can hook into so please refer to documentation at https://our.umbraco.com/Documentation/Reference/Events/ContentService-Events-v7.
using Umbraco.Core;
using Umbraco.Core.Events;
using Umbraco.Core.Models;
using Umbraco.Core.Publishing;
using Umbraco.Core.Services;
namespace My.Namespace
{
public class MyEventHandler : ApplicationEventHandler
{
protected override void ApplicationStarted(UmbracoApplicationBase umbracoApplication, ApplicationContext applicationContext)
{
ContentService.Published += ContentServicePublished;
}
private void ContentServicePublished(IPublishingStrategy sender, PublishEventArgs<IContent> args)
{
foreach (var node in args.PublishedEntities)
{
// Your code to send email here
}
}
}
}
You can either write your own custom code by creating some event handlers, which is what #wingyip has recommended, or you can use built-in Umbraco notification functionality.
For the second built-in option, please see all the steps here on this post.

enverse-how to customize user id in customized revision listner

i am using jpa with hibernate envers of micro service.
i tried
public class MyRevisionEntityListener implements RevisionListener {
#Override
public void newRevision(Object revisionEntity) {
// If you use spring security, you could use SpringSecurityContextHolder.
final UserContext userContext = UserContextHolder.getUserContext();
MyRevisionEntity mre = MyRevisionEntity.class.cast( revisionEntity );
mre.setUserName( userContext.getUserName() );
}
}
it saves username better.but i want to save user name as"by system" when updates the record by another micro service and when user updates should save the user name as above.how to customize above code as my requirement
It would seem the most logical based on your supplied code might be to simply add a boolean flag to your UserContext thread local variable and simply check that inside the listener.
By default this flag would be false but for your special microservice or business use case, you could alter that state temporarily, run your process, and clear that state after you've finished, very much like a web filter chain works in web applications.

Explicit transaction for entire request duration with automatic commit/rollback on errors (EF6, Web API2, NInject)

I'm starting a new Web API application, and I'm unsure how to handle transactions (and subsequent rollbacks in case of exceptions).
My overall goal is so have a single database connection per request, and have the entire thing wrapped in an explicit transaction.
I'll need an explicit transaction since I will be executing stored procedures aswell, and need to rollback any results from those if my application should throw any exceptions.
My plan was to re-use an approach I've used in MVC applications in the past which in rough terms was simply binding my database context to requestscope using ninject and then handling rollback/commit in the ondeactivation event.
Let's say I have a controller with two methods.
public class MyController : ApiController {
public MyController(IRepo repo) {
}
}
public string SimpleAddElement() {
_repo.Add(new MyModel());
}
public string ThisCouldBlowUp() {
// read from context
var foo = _repo.ReadFromDB();
// execute stored prodecure which changes some content
var res = _repo.StoredProcOperation();
// throw an exception due to bug/failsafe condition
if (res == 42)
throw Exception("Argh, an error occured");
}
}
My repo skeleton
public class Repo : IRepo {
public Repo(IMyDbContext context) {
}
}
From here, my plan was to simply bind the repositories using
kernel.Bind<IRepo>().To<Repo>();
and provide a single database context per request using
kernel.bind<IMyDbContext>().To<CreateCtx>()
.InRequestScope()
.OnDeactivate(FinalizeTransaction);
private IMyDbContext CreateCtx(IMyDbContext ctx) {
var ctx = new DbContext();
ctx.Database.BeginTransaction();
}
private void FinalizeTransaction(IMyDbContext ctx) {
if (true /* no errors logged on current HttpRequest.AllErrors */)
ctx.Commit();
else
ctx.Rollback();
}
Now, if I invoke SimpleAddElement from my browser FinalizeTransaction never gets invoked... So either I'm doing something wrong suddently, or missing something related to WebAPI pipeline
So how should I go about implementing a transactional "single DB session per request"-module?
What is best practise ?
If possible, I'd like the solution to support ASP vNext aswell
I suppose one potential solution could dropping the "ondeactivation" handler and implementing an HTTP module which will commit in Endrequest and rollback in Error... but there's just something about that I dont like.
You are missing an abstraction in your code. You execute business logic inside your controller, which is the wrong place. If you extract this logic to the business layer and hide it behind an abstraction, it will be trivial to wrap all business layer operations inside a transaction. Take a look at this article for some examples of this.

Two big question marks about CQRS

I'm a C# developer but I read nearly every tutorial about cqrs out there, doesn't matter if the language was Java, because I want to learn the structure and base of cqrs.
But now I think, the fact that I read so much tutorials is the problem because there are differences in the tutorials and now I'm confused and don't know which technique I have to use.
Two main questions are running wild in my head and maybe some of you can bring some clarity in there.
On the command side, where should I place the logic to call my ORM for example?
Some tutorials do that in the command handler (what is more logic to me) and some do it in the event handlers which will be fired by the command handler which in that case do only validation logic.
For the event store and to undo thinks, which data do I have to save into the db, some tutorials save the aggregate and some save the event model.
I hope that someone can explain me what pattern to use and why, maybe both in different scenarios, I don't know.
An practical example would be great. (Only pseudo code)
Maybe a User registration, RegisterTheUser command:
Things to do:
Check if the username is already in use
Add user to db
Send confirmation mail (In command or in the UserIsRegistered event?)
Fire event ConfirmationMailSended or only UserIsRegistered event?
Kind regards
EDIT:
Here is my current implementation (Simple)
public class RegisterTheUser : ICommand
{
public String Login { get; set; }
public String Password { get; set; }
}
public class RegisterTheUserHandler : IHandleCommand<RegisterTheUser, AccountAggregate>
{
public void Handle(AccountAggregate agg, RegisterTheUser command)
{
if (agg.IsLoginAlreadyInUse(command.Login))
throw new LoginIsAlreadyInUse();
agg.AddUserAccount(command);
CommandBus.Execute<SendMail>(x => { });
EventBus.Raise<UserIsRegistred>(x => { x.Id = agg.UserAccount.Id; });
}
}
public class UserIsRegistred : IEvent
{
public Guid Id { get; set; }
}
public class AccountAggregate : AggregateBase
{
public AccountAggregate(IUnitOfWork uow)
{
UnitOfWork = uow;
}
private IUnitOfWork UnitOfWork { get; set; }
public UserAccount UserAccount { get; set; }
public void AddUserAccount(RegisterTheUser command)
{
UserAccount = new UserAccount
{
Id = Guid.NewGuid(),
IsAdmin = false,
Login = command.Login,
Password = Crypto.Sha512Encrypt(command.Password)
};
UnitOfWork.UserAccountRepository.Add(UserAccount);
UnitOfWork.Commit();
}
public Boolean IsLoginAlreadyInUse(String login)
{
var result = UnitOfWork.UserAccountRepository.SingleOrDefault(x => x.Login == login);
return (result != null);
}
}
So a number of questions, but I'll take a stab at answering.
On the command side, where should I place the logic to call my ORM for
example?
Having this logic either in the command handler or in your event handler, to me, really depends on the type of system you're building. If you have a fairly simple system, you can probably have your persistence logic in your event handlers, which receive events raised by your domain. The thinking here is that your commands handled by the command handler will already have the information needed and your command handler ends up being not much more than a router. If you need more complexity in your command handler, such as dealing with sagas, long running transactions, or some additional layer of validation, then your command handler will use your persistence layer here to pull out data (and perhaps write data) and then route the command to the proper domain or issue more commands or raise events. So I believe it really depends on the level of complexity you're dealing with.
I tend to favor simplicity over complexity when starting out, and would probably look at having that logic in the event handler to begin with. Move to the command handler if your system is more complex.
For the event store and to undo thinks, which data do I have to save
into the db, some tutorials save the aggregate and some save the event
model
I'm not exactly sure what you're asking here, but if you're asking what should be stored in your event store, then I think a simple solution is the aggregate id, the aggregate type, the event with data (serialized) and the event type. Off the top of my head, that's probably the bare bones of what you'd need: based on the aggregate id you're working with, get all the events for that aggregate (in order raised) and then replay them to rebuild the aggregate. I don't think you need to save the aggregate unless there's some compelling reason to (which is always possible).
As for your request for a practical example and the steps you laid out, that's probably a question in and of itself, but my thoughts on that are:
Check if the user name is already in use
Depending on your application, you may want to do this from the read side in your controller (or whichever layer is raising commands) before you issue a command. Validate at that point, but you'd probably want to validate again before persisting it. You could do that in your event handler where it would probably catch an exception because you're violating a unique index in your database.
Add user to DB
Again, my thought is keep it simple and handle it in your event handler, since your domain is raising a UserIsRegistered event.
Send confirmation email
Your domain could raise the UserIsRegistered event and a second event handler (EmailHandler) would also subscribe to that event and send out the email.
ConfirmationMailSent event could be raised by the event handler, added to the event queue and handled accordingly. I guess I'm not sure what you want to happen here.
But, hopefully this helps a bit.

Flash AS3 - Developing for Facebook API locally?

I need to develop a pretty complicated Flash site based on the Facebook API, and if there's a way I can develop locally rather than having to upload it all the time I would be forever grateful.
I saw a post mentioning setting something to localhost but they never specified what exactly ( is it possible to use facebook API locally? )
Much appreciated.
Encapsulation is your friend in this case. When I use external / 3rd party APIs, I like to make a wrapper class of my own for the data. Let's say you only care about 'fbID' and 'userName'. Make a class of your own to hold this data once it is retrieved (private vars with getters, and 1 or more setters). Some skeleton code:
class MyUserClass{
//declare vars here (_fbID, _userName)
public function setData(userID:String, userName:String):void{
//set the values here.
}
//getters here (get fbID, get userName)
}
You can use 2 setter functions if you want to, but the point is that you will be able to call them with any data you want. When your entire application fetches this info from your class, and not the api directly you can work offline. When in offline mode, you can plug in some compatible 'fake' data to see it work.
Now you need to take this to the next level by making a wrapper type for every call you make to facebook. What I mean by this is that since you know what to expect from fb, you can pretend you actually got it, and proceed from there. Asking for a list of friend IDs? make a fake list that is reasonable, and have your application use it. Better still, generate as many fake offline users as you want, and make your server calls delay a random 'lag' time before returning the fake data to the event listener. This will also help test against possible race conditions.
One way to do this is by creating and extending a class to execute the api calls. Enjoy.
import flash.events.EventDispatcher;
import flash.events.Event;
import flash.events.TimerEvent;
import flash.utils.Timer;
class MyApiCaller extends EventDispatcher{
//set up vars to hold call result data
protected var _someData:String;
//make sure to declare some event types for the callbacks
public static const SERVERCALL1_COMPLETE:String = "servercall1_complete";
function MyApiCaller(){
//init things....
}
public function doServerCall1(...args:*):void {
//create the ulrLoader etc...
//set up event listener to onServerCall1Complete
}
public function onServerCall1Complete(event:Event):void {
//parse results, save to vars
//fire event to notify the caller
dispatchEvent(new Event(SERVERCALL1_COMPLETE));
}
//getter to be used when the waiting object gets the SERVERCALL1_COMPLETE event
public function get someData():String {return _someData;}
}
class MyFakeApiCaller extends MyApiCaller{
//set up any additional types (random user data etc..) that would not be found in the base class
//no need to redeclare the event types
function MyFakeApiCaller(){
//init things....
}
override public function doServerCall1(...args:*):void {
//wait a random amount of time via Timer, set up event listener to onServerCall1Complete
}
override public function onServerCall1Complete(event:Event):void {
//event is a TimerEvent in this case
//generate data / choose random data
//save to vars: _someData = ...
//fire event to notify the caller
dispatchEvent(new Event(MyApiCaller.SERVERCALL1_COMPLETE));
}
//getter from base class will be used as usual
}
https://github.com/facebook/php-sdk plus http://www.apachefriends.org/en/xampp.html I believe is your best bet.