Quantcast
Channel: DevExpress Support Center (Examples)
Viewing all 7205 articles
Browse latest View live

WPF Report Designer - How to customize the Data Source wizard

$
0
0

This example illustrates how to customize the list of data providers displayed on the Specify a Connection String page of the Data Source wizard and Report wizard (e.g., to leave only the Microsoft SQL Server option), as well as make the wizard always start with this page.

To do this, assign an object implementing the DevExpress.Xpf.Reports.UserDesigner.IWizardCustomizationService interface to the ReportDesigner.ServicesRegistry property.


WPF End-User Report Designer - How to create a custom data source wizard

$
0
0
This example demonstrates how to create a dialog that allows end-users create a new report and customize its Data Source in the WPF Report Designer.

For an example illustrating how to customize the existing wizard, please see WPF Report Designer - How to customize the Data Source wizard.


To complete this solution, I used the DevExpress MVVM Framework and IEditableObject. Here are useful links:
MVVM Framework
POCO ViewModels
IEditableObject Adapter for WPF and Windows Forms

ASP.NET: ASPxReportDesigner - How to add/edit/remove DataSourses in the web report designer (Custom DataSource wizard)

How to: Display WinUIDialogWindow and WinUIMessageBox at the View Model level

$
0
0

This Code Example demonstrates how to use the WinUIDialogWindow and WinUIMessageBox controls. The example contains two projects: one demonstrates how to use the controls in the MVVM pattern, and the other - in code behind. The first project uses special servicesWinUIDialogService and WinUIMessageBoxService. In the second project, the dialog and MessageBox are shown using the WinUIDialogWindow.ShowDialogWindow and WinUIMessageBox.Show methods.

Question Comments

Added By: Jaime López Portillo at: 1/14/2015 10:53:33 AM    

I can't seem to find any documentation regarding WinUIDialogWindow and WinUIMessageBox detailing their properties, constructors and methods, can you please provide me the full documentation link?

Added By: Andrey Marten (DevExpress Support) at: 1/14/2015 12:08:47 PM    

Hello,

To process your recent post more efficiently, I created a separate ticket on your behalf: T196769: Where the documentation for WinUIDialogWindow and WinUIMessageBox can be found. This ticket is currently in our processing queue. Our team will address it as soon as we have any updates.

Thanks,
Andrey

Added By: JRelyea at: 4/12/2015 10:21:13 AM    

I'm new to DevExpress.

Something seems to be very wrong with your example, as outlined below:

Something's not right with the following line because it constantly gets pounded and causes a sustained CPU usage at 30% (dual core 2.0gHz I7). Close the dialog window and the CPU drops back to 0%.

      bool OnRegisterCommandCanExecute(CancelEventArgs parameter) { return !string.IsNullOrEmpty(UserName); }

Do you have a working example that doesn't significantly impact a CPU? A dialog window should never consume CPU resources waiting to be closed.

Thank you

Added By: Andrey Marten (DevExpress Support) at: 4/13/2015 12:50:15 AM    


Hello,

To process your recent post more efficiently, I created a separate ticket on your behalf: T229667: WinUIDialogService - CPU usage increases if the command's CanExecute method is implemented. This ticket is currently in our processing queue. Our team will address it as soon as we have any updates.

Thanks,
Andrey

How to preserve the Legend checkbox item state when the Series collection is initialized programmatically

$
0
0

WebChartControl does not cache information about Series items and data source initialized at runtime. As a result, the Legend item checkbox state cannot be applied correctly. This example illustrates how to save the Legend state into a Session variable and restore it using the Page_Load event handler. The WebChartControl.LegendItemChecked event is used to obtain the current Legend panel state. Note that it is also required to disable the internal viewstate management using the WebChartControl.EnableViewState and WebChartControl.SaveStateOnCallbacks properties.

How to preserve the Legend checkbox item state when the Series Template approach is used to generate the Series collection

How to implement the ThemeMananger theme support in custom controls

$
0
0

This is a sample project for the K18542 (How to implement the ThemeMananger theme support in custom controls) KB article illustrating how to support themes in custom controls.

Question Comments

Added By: Adam Caviness at: 1/11/2017 12:29:53 PM    This example throws a XamlParseException exception upon loading the app stating that:
'ThemeResourcesThemeKeyExtension_Background' resource not found.

Visual Studio reports an error in CustomControl3_Resources.xaml that:

The local property "ResourceKey" can only be applied to types that are derived from "ThemeKeyExtensionInternalBase`1". Thanks.
Added By: Adam Caviness at: 1/11/2017 12:34:56 PM    If you change the base class of ThemeResourcesThemeKeyExtension to ThemeKeyExtensionInternalBase<ThemeResourcesThemeKeys> the error in CustomControl3_Resources.xaml goes away but you still get the runtime error:

'ThemeResourcesThemeKeyExtension_Background' resource not found.

How to implement an editor with a dynamic autocomplete list

$
0
0

This example demonstrates how to create a custom LookUpEdit class descendant that allows you to provide autocomplete items based on typed text. The items can be provided via the GetAutoCompleteList event.

Question Comments

Added By: Brian Winkleman at: 1/21/2015 9:44:28 AM    

How would i then add this control as a xtraBar to a BarManager?

Added By: Alexey Z (DevExpress Support) at: 1/21/2015 11:21:54 PM    Hello,

In order not to mix several questions within one thread, I will extract your question to a new ticket. Let us continue our discussion there How to add a LookUpEdit descendant to BarEditItem.Added By: Onyx DevExpress at: 7/26/2016 5:45:21 PM    Behavior is slightly different between 16.1 vs 15.s and prior ones in the examples.
In 16.1 a value type that's not in the list will be kept while in prior version it reverts to whatever it likes from the list.

Example: I type Support and it makes it Supportyahio
I remove the yahio
with 16.1 it leaves it Support but with 15.2 and prior it reverts to Supportyahio

I can't find anything in the release notes. Is this a new feature?  I like the way it works in 16.1 but will it stay this way? Added By: Stas (DevExpress Support) at: 7/27/2016 6:02:28 AM    

Hello,

I've created a separate ticket on your behalf (The behavior of the E3132 example in version 16.1 is slightly different than in version 15.x). It has been placed in our processing queue and will be answered shortly.

Added By: SamDev at: 10/24/2016 7:31:25 PM    This control with a bit of customization (painting capabilities to show more than what is being typed in the box in the dropdown) would be a hit control. I think everyone using Winforms feels left out. Problem is with custom development of this which is possible is the fact that it may not work in the future.

Example usage scenario that no other winforms control handles well:

1. Type a generic search (example in our application they want to search for anything in there application clients, appointment descriptions etc)
2. Dropdown will have an event handler of possible hits associated with a unique id that the event handler allows to pass in


Example dropdown

---------------------
John                     <------Typed text
---------------------
John (client) - id 0                         <------ Results that are not sitting in a table in a database
We will meet with John (appointment)

---------------------

3. User selects the value and the key returned in the callback function is set as the value.  Of course the developer utilizing control will have to know what keys are associated with search result and keep track of which ones they posted as a result in the call back that is provided with devexpress. So as the user types the call back is called.  This control is actually very simple to implement but we don't want to do it as we are using straight devexpress controls so they can be upgrade proof.


example callback

searchresult_populate(string typedtextofuserintextbox)
{
  // Allow user of control to populate with endless variation of data vs a concrete dataset (think no tables exist)
  Dictionary<key,valuestoshow> valuestoshow =  GenerateADictionaryFromSearchByWebAPI(typedtextofuserintextbox) or GetDataSearchedFromFile(typedtextofuserintextbox)
  return valuestoshow;
}

I think this is going to be the best and most flexible editor and will reduce a lot of variations of dropdowns. Allowing painting of results (highlighting typed text).

A perfect example is from a great website called google.  Simple and returns infinite array of information from potentially limitless data sources.  Its up to the developer to choose. Tired of hacking this out and using gridlookupedit. I want to do a simple select and populate it whichever way and not have to be so tightly bound to a database. Jquery has this control and many other frameworks even your devexpreme autocomplete widget.




Added By: SamDev at: 10/24/2016 7:34:58 PM    Winforms needs this badly.
https://js.devexpress.com/Demos/WidgetsGallery/#demo/editors-autocomplete-overview
Added By: Stas (DevExpress Support) at: 10/25/2016 6:18:04 AM    

Hello,

To avoid any misunderstanding, let's continue discussion of this question in the An editor with a dynamic autocomplete list ticket.

Added By: Vladimir Sorokin at: 12/29/2016 11:32:37 AM    Great example, but in case I set SearchMode.OnlyInPopup it stop working!
Can you advise how it can be fixed?

And one more question - how is it possible to implement async loading of AutoCompleteListEventArgs?Added By: Stas (DevExpress Support) at: 12/29/2016 1:40:37 PM    

Hello Vladimir,
To answer other questions, I've created separates tickets in order not to mix different issues in one thread and avoid possible misunderstanding. Please refer to them for further discussion.
If in the E3132 example, SearchMode is set to OnlyInPopup, the example doesn't work correctly
Is it possible to implement asynchronous loading of AutoCompleteListEventArgs in the E3132 example?

Added By: Yuriy Kokin at: 1/12/2017 1:37:57 AM    Great example, but in case I set SearchMode.OnlyInPopup it stop working!
Can you advise how it can be fixed?

And one more question - how is it possible to implement async loading of AutoCompleteListEventArgs?

SpellChecker - An example of use

$
0
0

This example illustrates how to load multiple Dictionaries to check spelling of a multi-language text in a simple text box control. Also, you will see how to add a Custom Dictionary so that the end-user can add custom words to it. 

Question Comments

Added By: Muhammad _ 1 at: 4/8/2016 4:45:04 AM    yes but did i need to add or download any dictionary as given below you pointing to any path
"\..\..\Dictionaries\es_ES\es_ES.aff";
Added By: Yulia (DevExpress Support) at: 4/8/2016 5:59:54 AM    

Hello Muhammad,

Dictionaries used in this Code Example are copied within the sample project, so you can find dictionary files in the corresponding folder.


How to show a progress bar while a report is being generated

$
0
0

The following example demonstrates how to use the ProgressReflector class. The code below invokes a form with the ProgressBarControl and shows the state of document generation while it is being created, then after it has been created the Progress Bar form is hidden and the created document is displayed in the print preview.


The ProgressReflector class is intended to be used only with the documents created with the XtraReports Suite.

DXSpellCheker - How to load dictionaries

$
0
0
This example illustrates how to load multiple dictionaries to check spelling in a multi-language text contained in a Text Edit  control. A custom dictionary enables the end-user to exclude certain words from spell check. 

How to use DevExpress themes in a WPF Application

$
0
0

This example demonstrates all common ways of using themes in your application.

DevExpress provides multiple themes that can be applied to all DevExpress WPF controls and some standard controls (GroupBox, ScrollViewer, Scroll, RadioButton, Button, ListBox, Slider, TabControl, Separator, ToggleButton, RepeatButton, Label, ListBoxItem, TabItem, ToolTip, etc.). All built-in themes are described in the following article: DevExpress WPF Themes.

The easiest way to apply a particular theme to the application is to specify the static ThemeManager.ApplicationThemeName property.

To set a theme for a specific element, use the ThemeManager.ThemeName attached property:

 

[XAML]
xmlns:dx=http://schemas.devexpress.com/winfx/2008/xaml/core<TextBoxName="textBox1"dx:ThemeManager.ThemeName="MetropolisLight"Width="120"Height="23"/>

 

In this case, the theme will be applied to the element and all its child elements.

Keep in mind these simple rules when applying DevExpress themes:

1. The ThemeManager.ApplicationThemeName property has lower priority than the ThemeManager.ThemeName property set locally.

2. The ThemeManager.ThemeName property value set for a parent element may be changed for its child if you explicitly specify the ThemeManager.ThemeName property for it.

In some cases, you may need to retrieve a list of all available DevExpress themes. The static Theme.Themes property contains this information.

 
See Also:
KA18580 - How to modify DX themes in WPF
K18542 - How to implement the ThemeMananger theme support in custom controls
T207471 - How to use the ThemeResource extension to load resources from DevExpress themes dynamically

Question Comments

Added By: Adam Caviness at: 1/13/2017 7:50:14 AM    I realize this is an older example but it should be mentioned you have deprecated ThemeManager.ApplicationThemeName in favor of ApplicationThemeHelper.ApplicationThemeName.  It might be a good idea to also explain the philosophy as to why There are two classes for managing Themes (ie: ApplicationThemeHelper is for applying Themes application wide and never on a specific DependencyObject.  ThemeManager is DependencyObject specific and even offers DependencyProperties for use in XAML).

How to change connection to the database at runtime

$
0
0

Scenario

This example illustrates how to connect your application to another database after the application is already started. This can be required for a multi-tenant application where you need to associate a user or company with their own database of the same structure. You can choose a required database and user during the login procedure and also later in the application UI by using the specialized SingleChoiceAction (available for Admin only). The created databases will have the same structure, but can have a different predefined data set.



Steps to implement

1. Using the XAF Solution Wizard, create a new XAF app named RuntimeDbChooser and that uses XPO for data access and the Security module with the Authentication = Standard and UI-level mode options.
2. Copy code that creates predefined security users for each database from the RuntimeDbChooser.Module\DatabaseUpdate\Updater.xx file into YourSolutionName.Module/DatabaseUpdate/Updater.xx;
3. Copy and include the RuntimeDbChooser.Module\BusinessObjects\CustomLogonParameters.xx file into the YourSolutionName.Module/BusinessObjects folder; *
4. Copy and include the RuntimeDbChooser.Module.Web\WebChangeDatabaseController.xx and RuntimeDbChooser.Module.Web\WebCustomAuthentication.xx files into the YourSolutionName.Module.Web project;
5. Copy and include the RuntimeDbChooser.Module.Win\WinChangeDatabaseController.xx and RuntimeDbChooser.Module.Win\WinCustomAuthentication.xx files into the YourSolutionName.Module.Win project;
6. Copy and include the RuntimeDbChooser.Wxx\WxxApplicationEx.xx files into the YourSolutionName.Wxx project;
7. Replace the line that instantiates your WinApplication descendant in the YourSolutionName.Win/Program.xx file with the CreateApplication method call as shown in the RuntimeDbChooser.Win/Program.xx file.
8. In the Application Designer invoked for the YourSolutionName.Web/WebApplication.xx file, select the Authentication Standard component and set its LogonParametersType property to RuntimeDbChooser.Module.BusinessObjects.CustomLogonParametersForStandardAuthentication

You can learn more on the approaches used in points 2-4 from the eXpressApp Framework > Task-Based Help > How to: Use Custom Logon Parameters and Authentication article.
____
*
In this example, the available database names are hard-coded in the MSSqlServerChangeDatabaseHelper class and supplied to the DatabaseName  property editor using the PredefinedValues model option. To populate the PredefinedValues list with names that will be known only at runtime, use the approach described in these articles (Win and Web specific):
How to: Supply Predefined Values for the String Property Editor Dynamically (WinForms)
How to: Supply Predefined Values for the String Property Editor Dynamically (ASP.NET)

A custom editor described in these articles can be assigned to the DatabaseName property using the Model Editor.

Question Comments

Added By: Mario Blatarić at: 11/5/2012 11:23:09 AM    

Let me give you "some reasons" why this isn't such a specific scenario.
 - accountant company doing accounting for several different companies (it's business requirement that data for each company is in separate database)
 - building maintenance company - again - business requirements demands each building to live in separate database (because of financial data)
 - document managment companies doing document management for multiple companies - again, each company must live in seperate database
 - local community combined with utility company - same people do both things and want to keep things separated

If you like, I can go on. No, you can't go to this companies / communities and say "But, it's better if we put all this to one database" because they will reply "Thank you, we'll find someone who can do it with multiple databases".
The point is, there are many reason why one piece of software should be connecting to multiple databases, so it's not such a specific scenario really. It would be nice to have this functionality out of the box instead of implementing this hard to understand piece of code.
Also, since application is distributed to many different clients, it would be nice that end-user could setup application on first startup (add/create required databases with connection info).

Added By: Mario Blatarić at: 3/14/2013 9:51:50 AM    

This example doesn't work.
Go to WinChangeDatabaseController.cs and set breakpoint in changeDatabaseAction_Execute. This code never executes since created SingleChoiceAction is not visible on logon form, instead some default editor is created with PredefinedValues and it's behaviour is not modified.
Can you fix this code please?

Added By: Dennis (DevExpress Support) at: 3/28/2013 4:52:33 AM    

@Mario: I have answered you in www.devexpress.com/issue=Q484359
This example worked correctly in my tests. In any event, I have just updated it to .NET Framework 4.0, just for more convenience.

Added By: Mario Blatarić at: 3/28/2013 6:17:17 AM    

Thanks Dennis. I understand now how this works.

Added By: lekan odejimi at: 1/29/2014 1:28:06 AM    

Hi Dennis, each time i try to logon i keep on getting this error: "Make sure your user name is correct and retype the password in the correct case." What do you suggest?

Added By: Grégoire Perruchoud at: 3/20/2014 9:52:00 AM    

Hi,

Great piece of code !

I noticed a weakness. In Web/Win controllers, preselection of correct item is done via following code :
if (Application.ConnectionString.Contains((string)item.Data))

This fails in case database name's string is contains elsewhere in ConnectionString. It also fails in case we have multiple databases with names containing each other, for example "customers" and "customers_geneva".

We should store the current database name in a static property somewhere and make a strong comparison.

Added By: Achmad Mulyadi at: 8/15/2015 12:11:19 AM    

Hi Dennis,

From the code below,

public const string Databases = "ChangeDatabase_DB1;ChangeDatabase_DB2";

Is there anyway I can pass a dynamic attribute value? I know this attribute requires a fixed value in compile time, but I don't think it is practical to put the database name or maybe a server address in a hard coded way. For example, it would be very practical if we can read this value from the app.config file, and pass it to the ModelDefault attribute.

Added By: Dennis (DevExpress Support) at: 8/17/2015 8:12:50 AM    @Achmad: Sure, please check out a possible solution at How to make example E1344 work with runtime defined databases. I hope this meets your needs.Added By: Robert Sanford at: 12/21/2015 3:36:59 PM    

Hi Dennis,
Would it be possible to post a complete XAF solution that incorporates this logic please along with tutorial? I have a single database XAF app that now has multiple database requirement - the various sql server databases would be defined in web.config. Thanks

Added By: Dennis (DevExpress Support) at: 12/22/2015 1:26:06 AM    

@Robert: Thanks for your suggestion. We will take it into account for the future.
In the meantime, would you please submit a separate ticket and describe your business requirements in greater detail? It is possible that you can use other approaches to meet them. For instance, I feel that How to connect different ORM data models to several databases within a single application can be suitable here.

Added By: Robert Sanford at: 12/22/2015 3:43:08 PM    

Dennis, yes I will do that, thanks. Basically, I need to take an existing XAF VB.NET solution - one model, one database - and expand this to several databases, allow user to authenticate to their database based on user/account ID. Each SQL server (SQL Azure database) will be identical. Thanks

Added By: Dennis (DevExpress Support) at: 12/23/2015 1:04:34 AM    @Robert: Thanks, I will answer your new Convert existing XAF solution to allow access multiple idential databases authenticated by UserID ticket.Added By: Alexandre BOYER at: 1/15/2017 1:59:47 PM    Great work. But the Password is removed from the ConnectionString, so it is not possible to connect to the selected database even when i add "Persist Security Info=true"

I'm using SQL Server. Any advice ?

How to render the Pie Chart with margins between slices by defining CustomPie2DModel

$
0
0

This example demonstrates how to define CustomPie2DModel that displays pie slices with additional margins. The default Pie Models render a chart in the following way: the model templates contains a simple ellipse and the Model object has the Clip Property applied. This clip allows displaying only a slice of the ellipse in the chart control. 
The custom model template demonstrated here uses a custom rendering approach. Each slice is represented by a Path object. The path's Data property is bound to the Clip property of the parent model. 

Note that it is also possible to display the point slices with margins using the PieSeries.ExplodedDistance property. 

How to prevent altering the legacy database schema when creating an XAF application

$
0
0

Scenario
This example shows how to prevent altering the legacy database schema when creating an XAF application. Sometimes our customers want to connect their XAF applications to legacy databases, but they often have strong restrictions, which disallow making any changes in the legacy database schema, i.e. adding new tables, new columns. This is bad, because XAF creates the ModuleInfo table to use an application's version for internal purposes. XPO itself can add the XPObjectType table to correctly manage table hierarchies when one persistent object inherits another one. Usually, legacy databases contain plain tables that can be mapped to one persistent object. So, the XPObjectType table is not necessary in such scenarios.
However, one problem still remains: it is the additional ModuleInfo table added by XAF itself. The idea is to move the ModuleInfo and XPObjectType tables into a temporary database.

For this task we introduced a custom IDataStore implementation, which works as a proxy. This proxy receives all the requests from the application's Session objects to a data store, and redirects them to actual XPO data store objects based upon a table name that has been passed.

Steps to implement

1. In YourSolutionName.Module project create a custom IDataStore implementation as shown in the WinWebSolution.Module\XpoDataStoreProxy.xx file;

2. In YourSolutionName.Module project create a custom IXpoDataStoreProvider implementation as shown in the WinWebSolution.Module\XpoDataStoreProxyProvider.xx file;


3.
In YourSolutionName.Module project locate the ModuleBase descendant and modify it as shown in the WinWebSolution.Module\Module.xx file;

4. Define connection strings under the <connectionStrings> element in the configuration files of your WinForms and ASP.NET executable projects as shown in the WinWebSolution.Win\App.config and WinWebSolution.Win\Web.config files.

IMPORTANT NOTES
1. The approach shown here is intended for plain database tables (no inheritance between your persistent objects). If the classes you added violate this requirement, the exception will occur as expected, because it's impossible to perform a query between two different databases by default.
2. One of the limitations is that an object stored in one database cannot refer to an object stored in another database via a persistent property. Besides the fact that a criteria operator based on such a reference property cannot be evaluated, referenced objects are automatically loaded by XPO without involving the IDataStore.SelectData method. So, these queries cannot be redirected. As a solution, you can implement a non-persistent reference property and use the SessionThatPointsToAnotherDatabase.GetObjectByKey method to load a referenced object manually.
3. As an alternative to the demonstrated proxy solution you can consider joining data from several databases into a database view and then mapping persistent classes to that view: How to: Map a Database View to a Persistent Class.

See also:
How to implement XPO data models connected to different databases within a single application
How to: Use both Entity Framework and XPO in a Single Application

Question Comments

Added By: David Crumb at: 6/30/2016 4:58:07 PM    How can you control which part of the applications use the LegacyDatabaseConnectionString and the TempDatabaseConnectionString

For example, although the below code works, it STILL tries to create a Note table within the LegacyDatabase.

In my situation, my legacy database is READ ONLY.  I want to pull data only from my Legacy Database.  Everything else, I want it to go to the TempDatabase.

Any insight appreciated,

--Dave

Added By: Dennis (DevExpress Support) at: 7/1/2016 10:30:01 AM    @Dave: This is controlled by the following code in the XpoDataStoreProxy class:
[C#]
privatestring[]tempDatabaseTables=newstring[]{"ModuleInfo","XPObjectType"};privateboolIsTempDatabaseTable(stringtableName){if(!string.IsNullOrEmpty(tableName)){foreach(stringcurrentTableNameintempDatabaseTables){if(tableName.EndsWith(currentTableName)){returntrue;}}}returnfalse;}
According to the example's implementation and description, it is correct that the Note table is created in the legacy database as per the screenshot above. It is possible that you forgot to remove the             this.AdditionalExportedTypes.Add(typeof(DevExpress.Persistent.BaseImpl.Note)); line when using this example implementation in your real project.Added By: Genesis Supsup 1 at: 1/16/2017 8:30:20 AM    
[C#]
e.ObjectSpaceProvider=newXPObjectSpaceProvider(provider);
Based from the code above, will this also work:

[C#]
e.ObjectSpaceProvider=newSecuredObjectSpaceProvider(provider);

Will this cause trouble later?

A simple example of master-detail grids with editing capabilities

$
0
0

A sample is created as explained in the Master-Detail Relationship help topic. In addition, UPDATE commands are generated in SqlDataSource objects attached to the grids and the Enable Editing checkbox is selected in a smart-tag in the designer to create a command column with the Edit link. The sample requires Northwind demo database on a local MS SQL Server (or SQL Express).

Question Comments

Added By: Jay Johnson at: 1/16/2017 3:48:40 PM    I understand why the live demo doesn't do the updates, but this post would be a lot more useful if the code behind was at least viewable..Added By: Jay Johnson at: 1/16/2017 4:07:54 PM    I downloaded the example.  The functional update code for inserts isn't there either. 
I would think that handing the insert would be the meat of the example..? 
Is that available elsewhere?   In vb.net web forms?

How to hide navigation items based on the current user

$
0
0

Our Security System allows hiding navigation items for certain users by configuring their Navigation permissions. These permissions can be configured in two modes:


1. Using Type Permissions. This mode was used prior to version 16.2. It allows hiding all navigation items based on the type of objects shown by them.
2. Using Navigation Permissions for individual navigation items. This mode was introduced in version 16.2 and is used in new projects by default. To enable it in old projects upgraded to version 16.2, set the SecurityStrategy.SupportNavigationPermissionsForTypes property to false. If you are using EF, you will need to upgrade your database as described in the How to: Add Navigation Permissions to an Entity Framework Application Created with XAF 16.1 article.

Refer to the Security System Overview topic for additional information of how to assign these permissions.

If your XAF version is less than 16.2 and you need to grant permissions for individual navigation items (e.g., to a DashboardView or to a certain ListView model), use the solution described below to extend the Security System's functionality. In this example, the HiddenNavigationItems property allowing you to hide navigation items by their ID will be added to the role class.
The approach with overriding the ShowNavigationItemController.SynchItemWithSecurity method shown in this example can be also appropriate for tasks that are not related to the Security System directly. You can hide or customize any navigation item in this manner. Note that, starting with version 16.2, it is necessary to use the ShowNavigationItemController.NavigationItemCreated event or ShowNavigationItemController.OnNavigationItemCreated method instead.

 

Steps to implement:

1. Implement a custom permission type - NavigationItemPermission - that can be used to check access permissions for a certain navigation item by its ID.
2. Implement a custom permission request - NavigationItemPermissionRequest - that will be sent to check whether the current user has access to a certain navigation item.
3. Implement a custom permission request processor - NavigationItemPermissionRequestProcessor - that determines whether the current user has permissions for the received permission request.
4. Implement a custom role with the HiddenNavigationItems property. Extend it with the GetPermissions method to create NavigationPermission instances based on the value of the HiddenNavigationItems property.
5. Specify the custom role in the Security System's RoleType property in the Application Designer, as described in the How to: Implement Custom Security Objects (Users, Roles, Operation Permissions) topic.
6. Register your permission request processor in the application by handling the SecurityStrategy.CustomizeRequestProcessors event in the Program.cs and Global.asax.cs files.
7. Implement a ShowNavigationItemController's descendant - CustomShowNavigationItemController - and override its SynchItemWithSecurity method to deactivate navigation items prohibited by the CustomSecurityRole.HiddenNavigationItems property.

After implementing these steps in your project, you will be able to assign a role with the HiddenNavigationItems property to the required users to restrict their access to certain navigation items.

Note: The example is based on the PermissionPolicyRole and PermissionPolicyUser classes. These classes are used by the Security System when selecting the Allow/Deny permissions policy in the Solution Wizard. If your project was created using an earlier XAF version (prior to 16.1) and the SecuritySystemRole and SecuritySystemUser classes are used in it, change the version number in the combo box below to see an example for these classes.

Question Comments

Added By: Maurice Picton at: 6/10/2014 7:52:32 AM    

Can someone post the HideNavigationItemsExample that is mentioned below in the code?
I'm having trouble implementing this solution.

Added By: Maurice Picton at: 6/10/2014 8:00:46 AM    

In the steps to implement, none of the entities you describe are in any of the documentation and I can't locate them in visual studio.

Added By: Anatol (DevExpress Support) at: 6/10/2014 8:07:44 AM    These classes are implemented in this example. You can see their code below, under the comments. To download the complete example, use the Downloads - Example link at the right edge of this page.Added By: Randy Jean at: 2/13/2015 11:15:42 AM    

Is there a way to make this be least restriction has precedence.  For instance, if I have a users role that hides navigation items and a direct role that does not hide, can the director role take precedence over the user role somehow?

Added By: Randy Jean at: 2/13/2015 11:33:21 AM    

think I may have come up with a way to make this work.  If I add a wildcard * to my HiddenNavigationItem then modify the IsGranted like so:

       public override bool IsGranted(NavigationItemPermissionRequest permissionRequest) {
           foreach (NavigationItemPermission permission in permissions.GetPermissions<NavigationItemPermission>()) {
               if (permission.HiddenNavigationItem == permissionRequest.NavigationItem) {
                   return false;
               } else if (permission.HiddenNavigationItem.Replace("*","") == permissionRequest.NavigationItem) {
                   return true;
               }
           }
           return true;
       }

This seems to do what I want.  So I can have user with the restrictions but then override in Director with the wildcard character like this: AddressGroup*, Person_Varied*

Do you see any issues with this?

Added By: Anatol (DevExpress Support) at: 2/16/2015 6:16:18 AM    

I am not sure that this approach will work in all cases, since the GetPermissions method returns permissions from all user roles, and with your implementation the first permission always wins. So, it is better to set a boolean variable based on the permission's HiddenNavigationItem property and return this value after processing all NavigationItemPermission permissions.

Added By: Genesis Supsup 1 at: 8/7/2016 12:48:08 PM    This example doesn't seem to work anymore on when using  PermissionPolicyRoleBase in version 16.1+ ... any workaround?Added By: Anatol (DevExpress Support) at: 8/9/2016 1:15:00 PM    I have updated the example - now it uses the PermissionPolicyRole and PermissionPolicyUser classes. The PermissionPolicyRole class does not have the GetPermissionsCore method, so it was necessary to add this method to the CustomSecurityRole class and call it in the SecurityStrategy.CustomizeRequestProcessors event handler to collect permissions of the current user manually.Added By: Konstantin B (DevExpress) at: 12/20/2016 6:19:11 AM    With the version 16.2, you can grant or deny access for specific navigation items and groups in the Navigation Permissions tab of the PermissionPolicyRole Detail View (see Security - Restrict access to certain navigation items).

Added By: MohammedFarooq at: 12/21/2016 10:00:45 AM    Hi Anatol,

I have applied this approach since long time V15+ and everything was working fine but now i upgraded to V16.2.3 and this logic is not working anymore. Could you please help me as it has affected my production apps.Added By: Alexey (DevExpress Support) at: 12/21/2016 10:47:15 AM    

Hello Mohammed,

I've created a separate ticket on your behalf (T465421: E380 not working ).

How to display best and worst monthly sales for each year

How to calculate a contribution of individual quarter sales to a year sales

How to evaluate a customer acquisition by grouping customers by the quarter/year of their first purchase

$
0
0

This example shows how to evaluate a customer acquisition by grouping customers by the quarter/year of their first purchase to compare sales contributions. To learn more, see examples from the Intermediate Level Aggregations topic.

How to divide customers' count by the number of orders they made

Viewing all 7205 articles
Browse latest View live


<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>