Umbraco 7, How to change a custom property in MemberService.Saved - c#

I am struggling with changing a simple true / false flag in member properties once the Is Approved flag is set to true for the first time. I can change the property but the value is not saved / committed. I have tried both MemberService.Saved and MemberService.Saving. I am quite new to Umbraco so may have missed something obvious.
protected override void ApplicationStarted(UmbracoApplicationBase umbracoApplication, ApplicationContext applicationContext)
{
MemberService.Saved += MemberService_Saved;
}
void MemberService_Saved(IMemberService sender, Umbraco.Core.Events.SaveEventArgs<IMember> e)
{
foreach (var member in e.SavedEntities)
{
if (!member.IsNewEntity())
{
var dirtyProperties = member.Properties.Where(x => x.WasDirty()).Select(p => p.Alias);
if (dirtyProperties.Contains("umbracoMemberApproved"))
{
if (member.IsApproved && !member.GetValue<bool>("approvalEmailSent"))
{
//Send Email to Customer
//new SmtpClient().Send(mail);
var prop = member.Properties["approvalEmailSent"];
prop.Value = true;
var propValue = member.GetValue<bool>("approvalEmailSent");
//Have verified propValue is now true
sender.Save(member);
}
}
}
}
}
Strangely I can find another member, make the property change and save it fine, just not the member sent through in e.SavedEntities.
TIA

Maybe try doing this instead?
member.SetValue("approvalEmailSent", true);
sender.Save(member, false);
When in MemberService.Saved, tell the .Save method to not raise any further events, just to make sure no infinite loops will happen.

This appears to me to be some sort of bug, after much debugging I have found the following:
Even when setting the raise events flag to false on the save, it still comes back through the method again.
On the second pass through you must set the value of the property you are changing again, even though it should already be saved / committed. I did not need to save again. I believe this is a bug
The original changed by the user property's was dirty flag is no longer set the second time through. So the original check for this was stopping the property I want to change being set again.
I had to have the was dirty check so that on the second pass through I did not send the email again.
As a note even changing something unrelated in a member using the umbraco front end will cause my method to run twice.
protected override void ApplicationStarted(UmbracoApplicationBase umbracoApplication, ApplicationContext applicationContext)
{
MemberService.Saved += MemberService_Saved;
}
void MemberService_Saved(IMemberService sender, Umbraco.Core.Events.SaveEventArgs<IMember> e)
{
foreach (var member in e.SavedEntities)
{
if (!member.IsNewEntity())
{
if (member.IsApproved && !member.GetValue<bool>("approvalEmailSent"))
{
member.SetValue("approvalEmailSent", true);
var dirtyProperties = member.Properties.Where(x => x.WasDirty()).Select(p => p.Alias);
if (dirtyProperties.Contains("umbracoMemberApproved"))
{
//Email Customer
//new SmtpClient().Send(mail);
sender.Save(member, false);
}
}
}
}
}

Related

Acumatica - Require File be Attached

In Bills and Adjustments, an error message "Please upload invoice" needs to display if user tries to save without attaching/uploading a document.
I created a bool field, UsrFilesAttached, that does not persist. On Rowselected event, i get a count, set bool if 0 or not.
I tried updating AP.APRegister DAC to [PXUIRequired(typeof(Where>))]
I tried something else in the BLC but I can't find it now.
//in APInvoiceEntry
protected void APInvoice_RowSelected(PXCache cache, PXRowSelectedEventArgs e)
{
var inv = (APInvoice)e.Row;
bool attachedFiles = PXNoteAttribute.GetFileNotes(cache, cache.Current).Length != 0;
cache.SetValueExt<APRegisterExt.usrFilesAttached>(inv, attachedFiles);
}
// in DAC AP.APRegister
[PXBool]
[PXUIField(DisplayName="UsrFilesAttached")]
[PXDefault]
[PXUIRequired(typeof(Where<usrFilesAttached, Equal<False>>))]
I expect that if UsrFilesAttached is false an error will appear. I am able to save record whether UsrFilesAttached is true or false. Also, how do I add a custom error message?
This morning, I had a different thought about how to tackle this and it worked. I started over with this and it works:
protected void APInvoice_Hold_FieldUpdated(PXCache cache, PXFieldUpdatedEventArgs e)
{
var inv = (APInvoice)e.Row;
if (inv == null)
return;
bool attachedFiles = PXNoteAttribute.GetFileNotes(cache, cache.Current).Length != 0;
if (attachedFiles == false)
{
cache.RaiseExceptionHandling<APRegister.hold>(inv, null, new PXSetPropertyException("Please attach invoice", PXErrorLevel.Error));
inv.Hold = true;
}
}
It makes better sense to do the check when trying to release the hold anyway. It can probably be improved on, so please teach me if you know a cleaner way. :)

Keep DbContext open for DataGridView

I have a DataGridView and the DataGridView's DataSource is a BindingList I got from the Entity Framework (V6) via context.Person.Local.ToBindingList().
After I set the DataSource to this BindingList, I dispose the context, because I read that keeping the context open would be bad practice.
So, if I wanted to add a new row, I would click on the "add" button that comes with the BindingNavigator that got created when I dragged the "people" object data source to my Windows Form.
Every time I click the "add" button, I get an exception that tells me that the context has been disposed.
Do I need to keep the context open all the time when using DataGridView? Oh and: the DataSource might change during runtime depending on the selection of a ListBox Item.
Also, when the context has been disposed and I edited one row from the DataGridView, how could I find out (after multiple changes) which row has changed?
I tried to do:
foreach(DataGridViewRow row in peopleDataGridView.Rows)
{
People item = (People)row.DataBoundItem;
if (item != null)
{
db.People.Attach(item);
}
}
db.SaveChanges();
...but SaveChanges() did not recognize any changes. However, if I force every attached item to a "modified" state, it works. But I do not want to change 100 items to "modified", if only one got actually modified.
Any ideas?
EDIT 1
Oh well, so I changed my code to keep the context open all the time (or at least as long as the form gets displayed).
Now, I ran into a different problem (people may have many jobs):
private void listBox1_SelectedValueChanged(object sender, EventArgs e)
{
People p = (People)listBox1.SelectedItem;
if(p != null)
{
//jobBindingSource.Clear(); this caused another error at runtime...
db.Entry(p).Collection(b => b.Job).Load();
jobBindingSource.DataSource = db.Job.Local.ToBindingList();
}
}
The DataGridView that is bound to this jobBindingSource instance shows the correct jobs for a person, but in addition to the jobs from the previously selected person. I tried to Clear() the entries, but if I do this and click on the same person twice, the datagridview starts to sometimes show no entries at all. A strange behaviour.
What am I doing wrong now?
EDIT 2
Okay... I found a solution myself. But I refuse to accept that this is the correct way to do it:
private void listBox1_SelectedValueChanged(object sender, EventArgs e)
{
People p = (People)listBox1.SelectedItem;
if(p != null)
{
db.Dispose();
db = new PeopleJobsEntities();
db.People.Attach(p);
db.Entry(p).Collection(person => person.Job).Load();
jobBindingSource.DataSource = db.Job.Local.ToBindingList();
}
}
Only if I dispose the context and open it anew, the whole thing works. The reason is that if I clear the local cache (of db.Job.Local), its entries will not be reloaded again even if I use the Load() method. Is there some way to force the reloading of entities?
While I try not to keep the DBContext open for a long period of time, with datagrids you don't have much choice. I set my grid's DataSource property to IQueryable<T> and then all the edits, deletes and additions are taken care of by the grid and context itself. You just have to call dbContext.SubmitChanges() whenever you want to persist the changes. You can save each time a user leaves a row by saving on the RowLeave or the RowValidated event. Or you can save when you close the form. But also make sure you call dbContext.Dispose() when you close the form as well.
To find out which rows change you can view the ChangeSet that is returned by doing the following:
var changes = dbContext.GetChangeSet();
dbContext.SubmitChanges();
Be sure if your item is not null.
Check your connection string.
And, try this :
db.People.Add(item);
Instead of :
db.People.Attach(item);
Ok, thanks to #jaredbaszler I came up with this solution that works fine for me.
I decided to keep the DbContext alive all the time. To clear the local cache, I detached every entity inside in a loop. I think this is a very disgusting way to do it. There must be a better way...
This is what I have:
PeopleJobsEntities db;
public FormTest()
{
InitializeComponent();
db = new PeopleJobsEntities();
db.Database.Log = Console.Write;
db.People.Load();
List<People> peoplelist = db.People.Local.ToList();
listBox1.DataSource = peoplelist;
}
private void FormTest_FormClosing(object sender, FormClosingEventArgs e)
{
if (db != null)
db.Dispose();
}
private void listBox1_SelectedValueChanged(object sender, EventArgs e)
{
People p = (People)listBox1.SelectedItem;
if(p != null)
{
List<Job> oldlist = db.Job.Local.ToList();
foreach (Job j in oldlist)
{
db.Entry(j).State = EntityState.Detached;
}
db.Entry(p).Collection(b => b.Job).Load();
jobBindingSource.DataSource = db.Job.Local.ToBindingList();
}
}
private void jobBindingNavigatorSaveItem_Click(object sender, EventArgs e)
{
foreach(DataGridViewRow row in jobDataGridView.Rows)
{
if(row != null && row.DataBoundItem != null)
{
Job j = (Job)row.DataBoundItem;
if(db.Entry(j).State == EntityState.Added)
{
if(j.People.Count == 0)
{
People people = (People)listBox1.SelectedItem;
if (people != null)
j.People.Add(people);
}
}
}
}
db.SaveChanges();
}
Editing entries works
Adding new entries works
Deleting entries works

Reload Data every time I navigate to Page

I have this Windows Phone Page where I load data through the standard ViewModel scope.
public Profile()
{
InitializeComponent();
App.PersonalizedViewModel.favorites.Clear();
DataContext = App.PersonalizedViewModel;
this.Loaded += new RoutedEventHandler(MainPage_Loaded);
}
private void MainPage_Loaded(object sender, RoutedEventArgs e)
{
if (!App.PersonalizedViewModel.IsDataLoaded)
{
App.PersonalizedViewModel.LoadData();
}
}
This works fine. However when I navigate to this page from some other page the data is still the same. I mean the LoadData() method should recheck updated data right? Please suggest.
EDIT:
My PersonalizedViewModelClass:
public class PersonalizationViewModel: INotifyPropertyChanged
{
public PersonalizationViewModel()
{
this.favorites = new ObservableCollection<ItemViewModel>();
this.Bar = new ObservableCollection<Bars>();
}
public ObservableCollection<ItemViewModel> favorites { get; private set; }
public ObservableCollection<Bars> Bar { get; private set; }
private string _sampleProperty = "Sample Runtime Property Value";
public string SampleProperty
{
get
{
return _sampleProperty;
}
set
{
if (value != _sampleProperty)
{
_sampleProperty = value;
NotifyPropertyChanged("SampleProperty");
}
}
}
public bool IsDataLoaded
{
get;
private set;
}
/// <summary>
/// Creates and adds a few ItemViewModel objects into the Items collection.
/// </summary>
public async void LoadData()
{
favorites.Clear();
try
{
var query = ParseObject.GetQuery("Favorite")
.WhereEqualTo("user", ParseUser.CurrentUser.Username);
IEnumerable<ParseObject> results = await query.FindAsync();
this.favorites.Clear();
foreach (ParseObject result in results)
{
string venue = result.Get<string>("venue");
string address = result.Get<string>("address");
string likes = result.Get<string>("likes");
string price = result.Get<string>("price");
string contact = result.Get<string>("contact");
this.favorites.Add(new ItemViewModel { LineOne=venue, LineTwo=address, LineThree=likes, Rating="", Hours="", Contact=contact, Price=price, Latitude="", Longitude="" });
}
if (favorites.Count == 0)
{
// emailPanorama.DefaultItem = emailPanorama.Items[1];
MessageBox.Show("You do not have any saved cafes. Long press a cafe in main menu to save it.");
}
}
catch (Exception exc)
{
MessageBox.Show("Data could not be fetched!", "Error", MessageBoxButton.OK);
}
}
public event PropertyChangedEventHandler PropertyChanged;
private void NotifyPropertyChanged(String propertyName)
{
PropertyChangedEventHandler handler = PropertyChanged;
if (null != handler)
{
handler(this, new PropertyChangedEventArgs(propertyName));
}
}
}
Implementation of PersonalizedViewModel:
protected async override void OnNavigatedTo(NavigationEventArgs e)
{
base.OnNavigatedTo(e);
await App.PersonalizedViewModel.LoadData();
user_tb.Text = ParseUser.CurrentUser.Username;
if (NavigationContext.QueryString.ContainsKey("item"))
{
var index = NavigationContext.QueryString["item"];
var indexParsed = int.Parse(index);
mypivot.SelectedIndex = indexParsed;
}
if (NavigationService.BackStack.Any())
{
var length = NavigationService.BackStack.Count() - 1;
var i = 0;
while (i < length)
{
NavigationService.RemoveBackEntry();
i++;
}
}
}
I don't see the problem, however, I think you need to narrow in on the problem.
First off, you are calling LoadData from 2 places. 1 from MainPage_Load and 1 from OnNavigatedTo. In MainPage_Load it is conditional and in OnNavigatedTo it is always being called. I suggest that you get to a single path through the code instead of 2 so that you don't get different experiences. I personally recommend (without knowing all the details) that you call load data from OnNavigatedTo instead of MainPage_Load. If you want to do it conditionally that is fine but if you are loading the data from memory, it really is unnecessary as you won't improve performance anymore than a few milliseconds. Also, if you are not loading from memory, you may not want to load it conditionally because the underlying data may have changed. In either case, the choice to load data or not should be moved out of the view and into the data layer (but that is for another post).
Once you have a single path chosen (i.e. calling LoadData from MainPage_Load or OnNavigatedTo) you should use your debugger. Put a break point in LoadData method and if it is being called appropriately, then your problem is more specific than your posted question. Here are some questions to think about (you may want to start from the last question and work your way backward)
Questions:
Is LoadData being called appropriately?
Does ParseObject have the correct data?
Is the ParseUser...UserName set properly?
Is the foreach being executed the proper # of times (i.e. does the result of your query have the right # of items?)
Couple Code Tips completely unrelated to this problem:
Single Path through code. Don't call LoadData from more than one place.
Don't call favorites.clear() twice in the same method. (it is called twice in LoadData)
Consistent naming. favorites is lowercase but Bar is upper case.
User proper data types. On your ItemViewModel you have Hours, Latitude, and Longitude. You have them as strings. These clearly are not strings. Also, you should not set them to empty. Empty means they have been set to a value. Emtpy is a valid value. Null means not set. To keep your objects clean and accurate you want to be accurate in how you set things and then deal appropriately with the impact. If you really really want them to be initialized to empty strings, then at least do it in the constructor of ItemViewModel so that every caller doesn't have to know how to initialize every property. I guarantee this is leading to buggy code if you continue using this practice.
Please take the comments as constructive criticism not criticism. I know many people don't like to hear these things but the teams I lead write bugs until they start following these types of guidelines.
Good luck,
Tom
Instead of defining this
App.PersonalizedViewModel.favorites.Clear();
DataContext = App.PersonalizedViewModel;
this.Loaded += new RoutedEventHandler(MainPage_Loaded);
into constructor i.e. Profile I would suggest remove this code from Constructor and add it into your OnNavigatedTo. so the data will load after navigation
Your OnNavigatedTo Method looks like follows
protected async override void OnNavigatedTo(NavigationEventArgs e)
{
base.OnNavigatedTo(e);
App.PersonalizedViewModel.favorites.Clear();
DataContext = App.PersonalizedViewModel;
this.Loaded += new RoutedEventHandler(MainPage_Loaded);
}
Might be your problem will solve.
Edit
Try this query
var results = (from find in ParseObject.GetQuery("Favorite").WhereEqualTo("user", ParseUser.CurrentUser.Username) select find);
Tried this:
var query = from favorite in ParseObject.GetQuery("Favorite")
where favorite.Get<string>("user") == ParseUser.CurrentUser.Username
select favorite;
IEnumerable<ParseObject> results = await query.FindAsync();
I had a similar Problem.All u want to do here is generate a new instance of the Page.U can do this in two Ways.
One Way is by forcing a GUID along with Page Navigation URI that will create a New Instance of the Page and your Load Data() will work.
NavigationService.Navigate(new Uri(String.Format("/MainPage.xaml?item={0}", Guid.NewGuid().ToString()), UriKind.RelativeOrAbsolute));
The Second Way to implement that Part of your Page in a User Control .Like create a User Control for Load Data() and put it in constructor.It will generate a new Instance everytime you load the Page.
If the problem persists in the front end,you can try this.
1.have you mentioned the below attribute in your xaml page?
<UserControl Loaded="MainPage_Loaded">
So that every time the page loads the data will get loaded on to the page.
2.The data must exist, if you have no problem in the code behind as it is a WPF application and not a web page.
Hope you find it useful.
Two changes required..
Remove the this.Loaded from OnNavigatedTo. That may not be required.
Second move the LoadData to OnNavigatedTo method
protected async override void OnNavigatedTo(NavigationEventArgs e)
{
base.OnNavigatedTo(e);
App.PersonalizedViewModel.favorites.Clear();
DataContext = App.PersonalizedViewModel;
// this.Loaded += new RoutedEventHandler(MainPage_Loaded);
if (!App.PersonalizedViewModel.IsDataLoaded)
{
App.PersonalizedViewModel.LoadData();
}
}
For the purpose of debugging, you can remove the line if (!App.PersonalizedViewModel.IsDataLoaded) and try.

Modifying Quartz.NET job details after they've been scheduled

I have a Quartz.NET application where I need the administrators to be able to modify the job details - mostly information in each jobs datamap, but also things like the triggers - here is my code I'm using
protected void ButtonSubmit_Click(object sender, EventArgs e)
{
JobDetail jobDetail = sched.GetJobDetail(hdnID.Value, hdnGroupID.Value);
jobDetail.JobDataMap["idname"] = txtName.Text;
jobDetail.JobDataMap["initialPath"] = TextBox1.Text;
jobDetail.JobDataMap["targetPath"] = TextBox2.Text;
jobDetail.JobDataMap["regex"] = TextBox3.Text;
jobDetail.JobDataMap["overrideemails"] = txtEmails.Text;
jobDetail.JobDataMap["flush"] = chkflush.Checked;
jobDetail.JobDataMap["impUsername"] = txtImpUsername.Text;
jobDetail.JobDataMap["impDomain"] = txtImpDomain.Text;
jobDetail.JobDataMap["impPassword"] = txtImpPassword.Text;
Trigger[] triggers = sched.GetTriggersOfJob(hdnID.Value, hdnGroupID.Value);
if (ddlScheduleType.SelectedIndex == 0)
{
foreach (SimpleTrigger trigger in triggers.OfType<SimpleTrigger>())
{
if (ddlInterval.SelectedIndex == 0)
{
trigger.RepeatInterval = TimeSpan.Parse("00:00:01");
}
else if (ddlInterval.SelectedIndex == 1)
{
trigger.RepeatInterval = TimeSpan.Parse("00:01:00");
}
else if (ddlInterval.SelectedIndex == 2)
{
trigger.RepeatInterval = TimeSpan.Parse("00:00:01");
}
}
}
else
{
foreach (CronTrigger trigger in triggers.OfType<CronTrigger>())
{
trigger.CronExpressionString = txtCron.Text;
}
}
}
(I know what I'm doing with the foreach loops is stupid, but there is only ever one trigger with a job and it's a snippet of code I recieved here).
Problem is, the page posts back fine and the new values still stay in the textboxes. But when I go view the job again, nothing changes at all. What am I doing wrong? It's confusing as there are no errors at all.
Note the hiddenfields are also correctly set.
Thanks
The ButtonSubmit_Click event is certainly working as I've debugged the program and the program goes through that.
The instance you get by calling sched.GetTriggersOfJob and sched.GetJobDetail are clones of the real triggers / jobs.
Your changes to those objects are not used by the scheduler until you reschedule the changed trigger or add a the changed job with the changed trigger.
I think you should be able to use RescheduleJob if you only change the triggers and you could remove the original trigger and add a new one.

Why is the boolean variable always resetting to false;

I have a boolean variable declared at the top of a class and when a radio button is selected on a page, the variable gets set to true, but when the page is reloaded, the variable gets reset back to false. One way I have handled this was by using the static keyword, but I am not sure if this is the best way to handle this. Here is the class where I tried doing things in the Page_Load event, but it is still resets the variables to false.
public class SendEmail
{
bool AllSelected;
protected void Page_Load(object sender, EventArgs e)
{
if(!Page.IsPostBack)
{
AllSelected = false;
}
}
protected void rbAll_SelectedIndexChanged(object sender, EventArgs e)
{
if(rbAll.SelectedValue == "All")
AllSelected = true;
}
public Send()
{
if(AllSelected)
{
//Send Email. Never runs because AllSelected is always false;
}
}
}
When the page gets reloaded, a new instance of your page class is created so any values from the last server interaction are lost. Put the value into viewstate if you want it to persist across postbacks:
bool AllSelected
{
get
{
object o = ViewState["AllSelected"];
if(o == null) return false;
return (bool)o;
}
set
{
ViewState["AllSelected"] = value;
}
}
The ViewState collection is written in a hidden element into the form in the client's browser, and posted back and restored the next time they click a button or do any other "postback" type action.
Every time asp.net serves a page, it creates a new instance of the page class. This means that AllSelected will always be auto initialized to false.
My suggestion, unless there is something I don't see here, is to just call Send() from your SelectedIndexChanged method.
You need your variable to be stored. I'd suggest storing it in ViewState or if you want to stay away from ViewState, hide it in a form element on the page.
Also, I'm not seeing where Send is being called.
Your boolean is an instance variable, so it will get the default value (which is false for bools) every time you create a new instance of your class.
Remember, every request to your page uses a brand new instance of your page class. This includes postbacks.
Not to jump down on you or anything...but why not just check if
rbAll.SelectedValue == "All"
in your send function?
No storage...no populating the ViewState or Session with data that isn't needed...
I don't really know if this is going to be handy in asp.net but I create a new bool in property.settings so that it remembers the bool whenever I close or restart the application. But I think this is more for winforms.

Categories