Devexpress XAF (Blazor) Popup window to edit property - devexpress

I have an XAF application. Most of my Business Objects are based on a baseclass "MyBaseClass" which contains Createdby, ModifiedBy, ... Comments. The Comments field is AllowEdit=false. I only want users to be able to modify the comment thru an action which would allow them to create an entry to which I would prepend their UserName and timestamp.
I don't know how to pop up a window to edit a property (string) within the current object and view.
There are plenty of examples of how to CreateListView but in this case what I wish to edit in the popup is not a separate BO but just a string. Maybe that is my problem(???)
I have the Action Controller and I am not sure how to create the DetailView when I get into the _Execute()

In Winforms XAF I add an action in a view controller.
In the action's execute event I call something like
private void actOpenDetailView_Execute(object sender, SimpleActionExecuteEventArgs e)
{
var application = Controller.Application
var viewId = application.FindDetailViewId(typeof(MyBusinessObject));
application.CreateObjectSpace(typeof(MyBusinessObject));
var detailView = application.CreateDetailView(newObjectSpace, jh, true);
e.ShowViewParameters.CreatedView = detailView;
e.ShowViewParameters.TargetWindow = TargetWindow.NewWindow;
}
I haven't tried that in Blazor.

Related

Relational Query - 2 degrees away

I have three models:
Timesheets
Employee
Manager
I am looking for all timesheets that need to be approved by a manager (many timesheets per employee, one manager per employee).
I have tried creating datasources and prefetching both Employee and Employee.Manager, but I so far no success as of yet.
Is there a trick to this? Do I need to load the query and then do another load? Or create an intermediary datasource that holds both the Timesheet and Employee data or something else?
You can do it by applying a query filter to the datasource onDataLoad event or another event. For example, you could bind the value of a dropdown with Managers to:
#datasource.query.filters.Employee.Manager._equals
- assuming that the datasource of the widget is set to Timesheets.
If you are linking to the page from another page, you could also call a script instead of using a preset action. On the link click, invoke the script below, passing it the desired manager object from the linking page.
function loadPageTimesheets(manager){
app.showPage(app.pages.Timesheets);
app.pages.Timesheets.datasource.query.filters.Employee.Manager._equals = manager;
app.pages.Timesheets.datasource.load();
}
I would recommend to redesign your app a little bit to use full power of App Maker. You can go with Directory Model (Manager -> Employees) plus one table with data (Timesheets). In this case your timesheets query can look similar to this:
// Server side script
function getTimesheets(query) {
var managerEmail = query.parameters.ManagerEmail;
var dirQuery = app.models.Directory.newQuery();
dirQuery.filters.PrimaryEmail._equals = managerEmail;
dirQuery.prefetch.DirectReports._add();
var people = dirQuery.run();
if (people.length === 0) {
return [];
}
var manager = people[0];
// Subordinates lookup can look fancier if you need recursively
// include everybody down the hierarchy chart. In this case
// it also will make sense to update prefetch above to include
// reports of reports of reports...
var subortinatesEmails = manager.DirectReports.map(function(employee) {
return employee.PrimaryEmail;
});
var tsQuery = app.models.Timesheet.newQuery();
tsQuery.filters.EmployeeEmail._in = subortinatesEmails;
return tsQuery.run();
}

ASP dynamic usercontrols in a gridview do not update

I have a got Gridview, that gets its data by:
internal void updateGrid()
{
List<String> data = dt.getAlldata(UserID(), ListID());
gridViewer.DataSource = data;
gridViewer.DataBind();
}
After a button click the database is updated and the new data is shown. Everything works fine.
Now I have to replace the string with an Usercontrol:
internal void updateGrid()
{
List<String> data = dt.getAlldata(UserID(), ListID());
gridViewer.DataSource = data;
gridViewer.DataBind();
for (int i = 0; i < gridViewer..Rows.Count; i++)
{
UCControl dum = (UCControl)LoadControl("~/UCControl.ascx");
dum.SetData(gridViewer.Rows[i].Cells[0].Text, false);
gridViewer.Rows[i].Cells[0].Controls.Clear();
gridViewer.Rows[i].Cells[0].Controls.Add(dum);
}
}
After first Page_Load(), everything is shown correctly. But when I click my buttons, the Usercontrols do not repaint. The data is set correctly inside, but it does not update.
Because this Control reacts by javascript on UserInputs on the client side, every Usercontrol has got his own Id that is set by
this.ID = "UCControl" + data[0];
data[0] is unique, but known during the whole process.
Can somebody tell me why the UserControl does not repaint? Or better: How do I tell the Usercontrols to update?
From your code I would say that once the data is bound then you can't go in immediately after and start to change it. You would need to hook into one of the databinding events.
If you were using a list viem ItemDataBound would be a good candidate to hook into. But the GridView has a more limited set of events and doesn't offer that level of control - so you are a bit stuck on that score.
In my experience using dynamic controls in asp.net (LoadControl) is just a bit fraught. I think a better option would be to publicly expose a property in your user control and bind to that.
This question gives a good description of how to achieve this
asp.net user controls binds inside gridview
Hope that helps

Setting values when a user updates a record using Entity Framework 4 and VB.NET in ASP.NET application

this is my first post, hopefully I'm following the rules!
After a few weeks of banging my head against brick walls and endless hours of internet searches, I have decided I need to make my own post and hopefully find the answers and guidance from all you experts.
I am building an ASP.NET application (in Visual Studio 2010) which uses an SQL 2008 database and Entity Framework 4 to join the two parts together. I designed the database as a database project first, then built the Entity Model as a class project which is then referenced in the main ASP.NET project. I believe this is called Database First in Entity Framwork terms?
I'm fairly new to Web Apps (I mainly develop WinForms apps) and this is my first attempt at using Entity Framwork.
I can just about understand C# so any code samples or snippets you might supply would be preferred in VB if possible.
To give some background on where I am so far. I built a regsitration page called register.aspx and created a wizard style form using ASP:Wizard with ASP:TextBox, ASP:DropdownList and ASP:CheckBoxList it's all laid out inside a HTML table and uses CSS for some of the formatting. Once the user gets the the last page in the wizard and presses "Finish" I execute some code in the VB code behind file as follows:
Protected Sub wizardRegister_FinishButtonClick(sender As Object, e As System.Web.UI.WebControls.WizardNavigationEventArgs) Handles wizardRegister.FinishButtonClick
Dim context As New CPMModel.CPMEntities
Dim person As New CPMModel.Person
Dim employee As New CPMModel.Employee
Dim newID As Guid = Guid.NewGuid
With person
.ID = newID
.UserID = txbx_UserName.Text
.Title = ddl_Title.SelectedValue
.FirstName = txbx_FirstName.Text
.MiddleInitial = txbx_MiddleInitial.Text
.FamilyName = txbx_FamilyName.Text
.Gender = ddl_Gender.SelectedValue
.DOB = txbx_DOB.Text
.RegistrationDate = Date.Now
.RegistrationMethod = "W"
.ContactMethodID = New Guid(ddl_ContactMethodList.SelectedValue)
.UserName = txbx_UserName.Text
If Not (My.Settings.AuthenticationUsingAD) Then
.Password = txbx_Password.Text ' [todo] write call to salted password hash function
End If
.IsRedundant = False
.IsLocked = False
End With
context.AddToPeople(person)
With employee
.ID = newID
.PayrollNumber = txbx_PayrollNumber.Text
.JobTitle = txbx_JobTitle.Text
.DepartmentID = ddl_DepartmentList.SelectedValue
.OfficeNumber = txbx_OfficeNumber.Text
.HomeNumber = txbx_HomeNumber.Text
.MobileNumber = txbx_MobileNumber.Text
.BleepNumber = txbx_BleepNumber.Text
.OfficeEmail = txbx_OfficeEmail.Text
.HomeEmail = txbx_HomeEmail.Text
.IsRedundant = False
.RedundantDate = Nothing
'--------------------------
.FiledBy = Threading.Thread.CurrentPrincipal.Identity.Name
.FiledLocation = My.Computer.Name
.FiledDateTimeStamp = Date.Now
'----------------------------
End With
context.AddToEmployees(employee)
context.SaveChanges()
End Sub
The above works fine, seemed to be a sensible way of doing it (remember I'm new to Entity Framework) and gave me the results I extpected.
I have another page called manage.aspx on this page is a tab control, each tab page contains a asp:DetailsView which is bound to an asp:EntityDataSource, I have enabled Update on all the Entity Data Sources and on some I have also enabled Insert, none of the have delete enabled.
If I build and run the app at this stage everything works fine, you can press the "edit" link make changes and then press "update" and sure enough those updates are displayed on the screen instantly and the database does have the correct values in.
Here's the problem, I need to intercept the update in the above code (the bold bit) notice there is a column in my database called FiledBy, FiledLocation, and FiledDateTimeStamp. I don't want to show these columns to the user viewing the ASP.NET page but I want to update them when the user presses update (if there were any changes made). I have tried converting the ASP:DetailsView into a template and then coding the HTML side with things like;
<## Eval(User.Name) #>
I did manage to get it to put the correct values in the textboxes when in edit mode but I had the following problems;
It didn't save to the database
I have to show the textboxes which I don't want to do
I have read on several other posts on here and other websites that you can override the SaveChanges part of the Entity Framwork model one example of this is in the code below;
public override int SaveChanges()
{
var entities = ChangeTracker.Entries<YourEntityType>()
.Where(e => e.State == EntityState.Added)
.Select(e => e.Entity);
var currentDate = DateTime.Now;
foreach(var entity in entities)
{
entity.Date = currentDate;
}
return base.SaveChanges();
}
The problem is, that whilst I understand the idea, and can just about transalate it to VB I have no idea how to implement this. Where do I put the code? How do I call the code? etc.
I would ideally like to find a solution that meets the following requirements:
Doesn't get overwritten if I was to regenerate / update the Entity Model
Doesn't need to be copy and pasted for every table in my model (most but not all have the audit columns in)
Can be used for other columns, for example, if a user make a selection in a check list I may want to write some value into another (not exposed to the user) column.
Am I taking the right approach to displaying data in may webpages I certainly find the DataView and GridView limiting, I did think about creating a form like the registration form in table tags but have no Idea how to populate the textboxes etc with values from the database nor how to implement paging as many of the tables have one to many relationships, although saving changes would be easy if I did populate textboxes on a table.
Thank you all in advance to anyone who offers there support.
Kevin.
Ok so I have now got closer, but still not got it working correctly. I've used the following code to edit the value in the DetailsView on the Databound event. If writes the correct timestamp into the read only textbox but does not right this value back to the database when you press the Update button on the DetailsView control.
Protected Sub dv_Employee_DataBound(sender As Object, e As EventArgs) Handles dv_Employee.DataBound
If dv_Employee.CurrentMode = DetailsViewMode.Edit Then
For Each row In dv_Employee.Rows
If row.Cells(0).Text = "FiledDateTimeStamp" Then
row.Cells(1).Text = Date.Now()
End If
Next
End If
End Sub
I like the idea of overriding the save changes method. Your context should be a partial class, so you just need to define another class marked as partial with the same name in the same namespace and add the override to it.
Namespace CPMModel
Partial Public Class CPMEntities
...Your override here
End Class
Since this is an override of the default SaveChanges method you do not need to make any changes in how it is called. You will need to find a way to gain access to entity level properties.
Since this is the method that commits changes for all entities you will not be able to access the properties like you do in your example, since the entity class does not define an of your concrete properties. So you need to create partial classes for your entities and have them all implement an interface that defines the properties you would like to interact with.
Create interface:
Interface IDate
Property Date() as DateTime
End Interface
Create partial class for each of your entities that implements the IDate interface. (The same rules apply for these partial classes they must be marked partial, have the same name as the class they extend and live in the same namespace) Then in your SaveChanges override
public override int SaveChanges()
{
var entities = ChangeTracker.Entries<Entity>()
.Where(e => e.State == EntityState.Added)
.Select(e => e.Entity);
var currentDate = DateTime.Now;
foreach(var entity in entities)
{
***Now cast entity to type of IDate and set your value ***
entity.Date = currentDate;
}
return base.SaveChanges();
}
I don't write in Vb so I left the syntax in C#.
That should fulfill all of your requirements.
Ok, so this isn't exactly how I imagined it would work but it has infact met my needs. Kind of!
What I did was Write a Protected Sub in the code behind file of the aspx file.
Protected Sub CustomEntityUpdate_Employee(sender As Object, e As
EntityDataSourceChangingEventArgs)
Dim emp As CPMModel.Employee = e.Entity
' Check if the entity state is modified and update auditing columns
If emp.EntityState = EntityState.Modified Then
emp.FiledDateTimeStamp = Date.Now()
emp.FiledBy = Threading.Thread.CurrentPrincipal.Identity.Name
emp.FiledLocation = My.Computer.Name
End If
End Sub
Then in the aspx page I edited the Entity datasource code to call the above sub routine
#nUpdating="CustomEntityUpdate_Employee"
<asp:EntityDataSource
ID="eds_Employee"
runat="server"
ConnectionString="name=CPMEntities"
DefaultContainerName="CPMEntities"
EnableFlattening="False"
EnableUpdate="True"
EntitySetName="Employees"
AutoGenerateWhereClause="True"
Where=""
EntityTypeFilter="Employee"
**OnUpdating="CustomEntityUpdate_Employee">**
<WhereParameters>
<asp:SessionParameter
Name="ID"
SessionField="UserID" />
</WhereParameters>
</asp:EntityDataSource>
The Protected Sub, checks if the entity has been modified and if it has updates the entity auditing columns with the values I wanted.
It works but it will certainly make for a lot more code, I ideally would like a way to package this up perhaps into a class and just call the sub from the various aspx pages via the OnUpdating event and have the class figure out which entity was making the call and handle all the logic there.

Adding TextBocex, CheckBoxes on Request C#

I will be starting a project soon at my company and the client would like to have the option in the portal to add textboxes or checkboxes as an administrator,,, so for instance initially I may have something like
Name [textBox]
Phone [textBox]
So the client would like to log in as an admin and be able to add
Name [textBox]
Phone [textBox]
Receive Brochure [checkBox] //added by client.
Forget about the portal and the admin part.. what I would like to know is what would be the best way to design this (the user to be able to add elements)
Any ideas would be much appreciated
Regards
You could create an additional aspx-form in which the User (or the Admin) is able to define and create his/her own forms, you supply the Variable names and they choose to add the controls, save it in a specific scheme in the Database, e.g.
UserForm:
UserID FormID
Form:
FormID FormName
FormElement:
FormID VariableName ControlType Index
Of course this could also be done by an administrator and be visible by everyone.
To view the specific forms you could add yet another aspx-page containing the following code:
protected void Page_Load(object sender, EventArgs e)
{
//you saved the FormName or ID to Session when you accessed it
string formName = Session["FormName"].ToString();
//this handles getting the elements for this Form from DB
List<FormElement> elementList = FormElement.GetForForm(formName);
this.renderForm(elementList);
}
private void renderForm(List<FormElement> eList)
{
foreach(FormElement fe in eList)
{
//Labels left, Controls right, of course this is just a design decision
if(fe.Index%2==1)
{
Label lbl = new Label();
lbl.Text = fe.Variable;
lbl.ID = fe.ControlType + fe.Variable;
divLeft.Controls.Add(lbl);
}
else
{
dynamic ctrl = null;
switch (fe.ControlType)
{
case "TextBox":
ctrl = new TextBox();
break;
case "CheckBox":
ctrl = new CheckBox();
break;
default:
break;
}
ctrl.ID = fe.ControlType + fe.Variable;
divRight.Controls.Add(ctrl);
}
}
}
Later on after the User hitting submit you'd be able to receive the values entered into those Controls by accessing divRight.FindControl(fe.ControlType + fe.Variable) since that should be unique per Form.
This approach assumes you're using .NET 4.0 (because of dynamic), but of course you can do this just fine without it, it'll just be more code.
Please let me know if this is what you searched for or if it was helpful.
Thanks,
Dennis
From what I have done in the past where I had to create a dynamic survey based on a client needs. I had a database that contained the following tables:
Survey - stores list of client surveys.
Controls - listed the type of controls that would be needed. For example, textbox, checkbox etc.
Survey Controls - links all the controls required for a survey.
User values - stores the values entered in a controll based on the survey used.
I then added some logic to dynamically create the controls based on a survey selected by reading the values from my database.

Flex - Issue with binding in script blocks

I am working on the multifile uploader, and want to set the upload directory based on a selected questionID (which is the directory name) in my datagrid.
The code can be found here http://pastie.org/784185
Something like this:
I have set myQuestionID (the directory to upload to) so it is bindable (lines 136-137):
[Bindable] public var myQuestionID:int;
In my datagrid I use a change handler (line 539):
change="setQuestionID();"
We set the variable in the setQuestionID function (lines 400-407):
[Bindable (event="questionChange")]
private function setQuestionID():void
{
myQuestionID = questionsDG.selectedItem.QuestionID;
dispatchEvent(new Event("questionChange"));
}
And then try to use it in my uploader script (lines 448-475):
// initUploader is called when account info loads
public function getSessionInfoResult(event:ResultEvent):void{
// Get jsessionid & questionid (final directory) for CF uploader
myToken = roAccount.getSessionToken.lastResult;
// BUG: myQuestion is null in actionscript, but okay in form.
var postVariables:URLVariables = new URLVariables();
postVariables.jsessionid = myToken;
postVariables.questionid = myQuestionID;
multiFileUpload = new MultiFileUpload(
filesDG,
browseBTN,
clearButton,
delButton,
upload_btn,
progressbar,
uploadDestination,
postVariables,
350000,
filesToFilter
);
multiFileUpload.addEventListener(Event.COMPLETE,uploadsfinished);
}
I can see in my MXML that the value binded (line 639):
<mx:Label text="{myDirectory}"/>
and it updates when I click a row in my datagrid. However, if I try to access this myQuestionID value inside any action script it will show as null (0). I know my uploader is working as I can hardcode myDirectory to a known directory and it will upload okay.
I'm really stumped.
The reason questionid = null is that getSessionInfoResult() is called by your init code before the bound value of myQuestionID is set.
So your file uploader (multiFileUpload) is already instantiated with myQuestionID = null.
You need to instantiate/pass the value into the multiFileUpload component after it is set.
Use dataGrid change event to set myDirectory everytime the selection has changed by user. this will update the value of myDirectory properly.
By making someID as Bindable would mostly solve your problem if you dont want to use change event on DG

Resources