I am trying to implement permission based access control in ASP.NET. To implement this I have created some database tables that hold all the information about which roles are assigned what permissions and which roles are assigned to what user.
I am checking the permissions in the business access layer. Right now I have created a method which checks the permissions of the user. If the user has permissions then okay otherwise it redirects to another page.
I want to know if the following things are possible?
class User
{
[PremissionCheck(UserID,ObjectName,OperationName)]
public DataTable GetUser()
{
//coding for user
}
}
I have seen it in MVC3. Can I Create it in ASP.NET? If yes then how can I implement it?
Any permissions system requires two components -- authorization and access control. Authorization is the means to prove the user's identity. This is accomplished, usually, with some kind of user and password storage, but you can use systems like OpenID, or any number of federated identity systems (Active Directory/Kerberos/etc.) to accomplish the same thing.
Once you know who the user is, then there's access control, which is enforcing permssions against that user.
Now, in ASP.NET's case, you're not going to be able to just stick an attribute on something, because attributes do not run code. In order to get the validation code to run, you would need to write a plugin of some sort to do this validation for you. Webforms already has support for authentication and access control mechanisms; why reinvent the wheel?
I want to know if the following things are possible?
class User {
[PremissionCheck(UserID,ObjectName,OperationName)]
public DataTable GetUser()
{
//coding for user
} }
No. It´s not possible in ASP.Net webforms
However, I've implemented Role Based Access Control on a a classic 3-tier ASP.Net 3.5 web forms application, using a MasterPage, a BasePage class and a RoleBasedAccessControl database model.
Example
User "jtirado" is assigned role "HR-Assistant", can access route "mywebapp/employee.aspx?id=1452" to edit employee (id:1452) data.
Being "HR-Assistant", this user can change employee telephone number and e-mail, can view employee salary but not edit the amount.
Telephone number, email, salary are dabatase fields and are represented/rendered by a "asp.net-control" on the ASPX page. So I want to restrict access to these controls based on user's role.
MasterPage builds the options menu the user has access according to his assigned role. It's used by all my internal pages.
protected void Page_Load(object sender, System.EventArgs e)
{
if (!Page.IsPostBack)
{
CargaItemMenu(MnuPrincipal, Convert.ToInt32(Session["IdPais"]), Convert.ToInt32(Session["IdRol"]), Convert.ToInt32(Session["IdUsuario"]));
Session.Add("MenuDinamico", MnuPrincipal);
if (MnuPrincipal.Items.Count < 1)
{
MenuItem menuItems = new MenuItem();
menuItems.Text = "Principal";
menuItems.Value = "1";
menuItems.NavigateUrl = "";
menuItems.Selectable = true;
MnuPrincipal.Items.Add(menuItems);
}
}
}
private void CargaItemMenu(Menu ctrlmenu, int v_IdPais, int v_IdRol, int v_IdUsuario)
{
oBEOpcionRol = new SEGU.Entities.ENOpcionRol();
oBLOpcionRol = new SEGU.BusinessLogic.BLOpcionRol();
List<ParametroGenerico> ArrayParam;
ArrayParam = CargarParamentrosOpcionRol(v_IdPais, v_IdRol, v_IdUsuario);
List<SEGU.Entities.ENOpcionRol> ListaMenuItems = oBLOpcionRol.ListaxIdPaisxIdRolxIdUsuario(ArrayParam);
foreach (SEGU.Entities.ENOpcionRol objOpcionRol in ListaMenuItems)
{
if (objOpcionRol.IdOpcion.IdOpcion.Equals(objOpcionRol.IdOpcion.IdMenu))
{
MenuItem mnuMenuItem = new MenuItem();
mnuMenuItem.Value = objOpcionRol.IdOpcion.IdOpcion.ToString();
mnuMenuItem.Text = objOpcionRol.IdOpcion.Nombre.ToString();
if (objOpcionRol.IdOpcion.RutaFormulario != "")
{
mnuMenuItem.NavigateUrl = objOpcionRol.IdOpcion.RutaFormulario.ToString();// +"?IdOpcion=" + Convert.ToString(objOpcionRol.IdOpcion.IdOpcion);
}
if (objOpcionRol.IdOpcion.PageNew == "1")
{
mnuMenuItem.Target = "_blank";
}
//mnuMenuItem.Target = "iframePrincipal"
if (objOpcionRol.IdOpcion.Imagen.Trim() != "")
{
mnuMenuItem.ImageUrl = "Seguridad/ImagenesMenus/" + objOpcionRol.IdOpcion.Imagen.Trim();
}
if ((mnuMenuItem.NavigateUrl.Trim().Length > 0))
{
mnuMenuItem.Selectable = true;
}
else
{
mnuMenuItem.Selectable = false;
}
ctrlmenu.Items.Add(mnuMenuItem);
AddMenuItem(mnuMenuItem, ListaMenuItems);
}
}
}
private void AddMenuItem(MenuItem mnuMenuItem, List<SEGU.Entities.ENOpcionRol> listaOpcionRol)
{
foreach (SEGU.Entities.ENOpcionRol objOpcionRol in listaOpcionRol)
{
if (objOpcionRol.IdOpcion.IdMenu.ToString().Equals(mnuMenuItem.Value) && !objOpcionRol.IdOpcion.IdOpcion.Equals(objOpcionRol.IdOpcion.IdMenu))
{
MenuItem mnuNewMenuItem = new MenuItem();
mnuNewMenuItem.Value = objOpcionRol.IdOpcion.IdOpcion.ToString();
mnuNewMenuItem.Text = objOpcionRol.IdOpcion.Nombre.ToString();
if (objOpcionRol.IdOpcion.RutaFormulario != "")
{
mnuNewMenuItem.NavigateUrl = objOpcionRol.IdOpcion.RutaFormulario.ToString();// +"?IdOpcion=" + Convert.ToString(objOpcionRol.IdOpcion.IdOpcion);
}
if (objOpcionRol.IdOpcion.PageNew == "1")
{
mnuNewMenuItem.Target = "_blank";
}
mnuMenuItem.ChildItems.Add(mnuNewMenuItem);
//mnuNewMenuItem.Target = "iframePrincipal"
if (objOpcionRol.IdOpcion.Imagen.Trim() != "")
{
mnuNewMenuItem.ImageUrl = "Seguridad/ImagenesMenus/" + objOpcionRol.IdOpcion.Imagen.Trim();
}
if ((mnuNewMenuItem.NavigateUrl.Trim().Length > 0))
{
mnuNewMenuItem.Selectable = true;
}
else
{
mnuNewMenuItem.Selectable = false;
}
AddMenuItem(mnuNewMenuItem, listaOpcionRol);
}
}
}
BasePage class checks if the user has access to the required page. All pages requiring authorization inherit from this BasePage class.
public class PaginaBase : System.Web.UI.Page
{
SEGU.BusinessLogic.BLOpcionRol oBLOpcionRol;
protected void Page_InitComplete(object sender, System.EventArgs e) {
string Url = this.Page.AppRelativeVirtualPath;
oBLOpcionRol = new SEGU.BusinessLogic.BLOpcionRol();
int b = oBLOpcionRol.AutentificarUrl(Convert.ToInt32(System.Web.HttpContext.Current.Session["IdPais"]), Convert.ToInt32(System.Web.HttpContext.Current.Session["IdUsuario"]), Convert.ToInt32(System.Web.HttpContext.Current.Session["IdRol"]), Url);
System.Web.HttpContext.Current.Session["IdOpcion"] = b;
if( b <= 0 ){
System.Web.HttpContext.Current.Response.Redirect("~/Seguridad/Acceso.aspx");
return;
}
}
.
.
}
Finally, on Customers.aspx Page_Load event I call a function (oBLPermisoOpcionRol.ValidarPermisos) which checks which receives the Page instance as parameters and iterate its controls (ex: DdlClientType, TxtLastName,ChkIsActive) to check which ones the user can edit, enabling, disabling or hiding them.
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
SetNodosMenu(TrvMenu, "");
if (this.TrvMenu.Nodes.Count < 1)
{
PrimerNodos(this.TrvMenu);
}
ListarModuloxAnulado(GvModulo, Convert.ToString(RblAnuladoModuloBusqueda.SelectedValue), Convert.ToInt32(0), Convert.ToInt32(DdlNroPaginaModulo.SelectedValue));
oBLPermisoOpcionRol = new SEGU.BusinessLogic.BLPermisoOpcionRol();
oBLPermisoOpcionRol.ValidarPermisos(Page, Convert.ToInt32(Session["IdRol"]), Convert.ToInt32(Session["IdOpcion"]));
}
}
public void ValidarPermisos(System.Web.UI.Page v_Page, int v_IdRol, int v_IdOpcion)
{
BusinessLogic.BLPermisoOpcionRol oBLPermisoOpcionRol = new BusinessLogic.BLPermisoOpcionRol();
List<ParametroGenerico> ArrayParam ;
ArrayParam = CargarParametros(v_IdRol, v_IdOpcion);
List<SEGU.Entities.ENPermisoOpcionRol> Lista = oBLPermisoOpcionRol.ListaxIdRolxIdOpcion(ArrayParam);
for(int Fila= 0; Fila< Lista.Count; Fila++){
bool v_Anulado= true;
if (Lista[Fila].Anulado == "1") {
v_Anulado = true;
}else if (Lista[Fila].Anulado == "0") {
v_Anulado = false;
}
bool v_ControlVisibleDisabled = true;
if (Lista[Fila].VisbleDisabled == "1") // Control Disabled
{
v_ControlVisibleDisabled = true;
}
else if (Lista[Fila].VisbleDisabled == "0") // Control Visible
{
v_ControlVisibleDisabled = false;
}
SetControls(v_Page, Lista[Fila].IdPermiso.Control, v_Anulado, v_ControlVisibleDisabled);
}
}
public void SetControls(System.Web.UI.Control parentControl, string v_Control, bool permitir, bool v_Permitir_ControlVisibleDisabled)
{
foreach(System.Web.UI.Control c in parentControl.Controls){
if( (c) is Button ){
if( ((Button)c).ID == v_Control ){
if( permitir == true ){
if (v_Permitir_ControlVisibleDisabled == true)
{
((Button)c).Enabled = false;
}else if (v_Permitir_ControlVisibleDisabled == false)
{
((Button)c).Visible = false;
}
}else{
((Button)c).Visible = true;
}
}
}else if( (c) is CheckBox ){
if( ((CheckBox)c).ID == v_Control ){
if( permitir == true ){
if (v_Permitir_ControlVisibleDisabled == true)
{
((CheckBox)c).Enabled = false;
}else if (v_Permitir_ControlVisibleDisabled == false)
{
((CheckBox)c).Visible = false;
}
}else{
((CheckBox)c).Visible = true;
}
}
}else if( (c) is Label ){
if( ((Label)c).ID == v_Control ){
if( permitir == true ){
if (v_Permitir_ControlVisibleDisabled == true)
{
((Label)c).Enabled = false;
}else if (v_Permitir_ControlVisibleDisabled == false)
{
((Label)c).Visible = false;
}
}else{
((Label)c).Visible = true;
}
}
}else if( (c) is TextBox ){
if( ((TextBox)c).ID == v_Control ){
if( permitir == true ){
if (v_Permitir_ControlVisibleDisabled == true)
{
((TextBox)c).Enabled = false;
}
else if (v_Permitir_ControlVisibleDisabled == false)
{
((TextBox)c).Visible = false;
}
}else{
((TextBox)c).Visible = true;
}
}
}else if( (c) is GridView ){
if( ((GridView)c).ID == v_Control ){
if( permitir == true ){
if (v_Permitir_ControlVisibleDisabled == true)
{
((GridView)c).Enabled = false;
}else if (v_Permitir_ControlVisibleDisabled == false)
{
((GridView)c).Visible = false;
}
}else{
((GridView)c).Visible = true;
}
}
}else if( (c) is ImageButton ){
if( ((ImageButton)c).ID == v_Control ){
if (permitir == true)
{
if (v_Permitir_ControlVisibleDisabled == true)
{
((ImageButton)c).Enabled = false;
}
else if (v_Permitir_ControlVisibleDisabled == false)
{
((ImageButton)c).Visible = false;
}
}
else
{
((ImageButton)c).Visible = true;
}
}
}else if( (c) is HyperLink ){
if( ((HyperLink)c).ID == v_Control ){
if( permitir == true ){
if (v_Permitir_ControlVisibleDisabled == true)
{
((HyperLink)c).Enabled = false;
}
else if (v_Permitir_ControlVisibleDisabled == false)
{
((HyperLink)c).Visible = false;
}
}else{
((HyperLink)c).Visible = true;
}
}
}else if( (c) is DropDownList ){
if( ((DropDownList)c).ID == v_Control ){
if( permitir == true ){
if (v_Permitir_ControlVisibleDisabled == true)
{
((DropDownList)c).Enabled = false;
}
else if (v_Permitir_ControlVisibleDisabled == false)
{
((DropDownList)c).Visible = false;
}
}else{
((DropDownList)c).Visible = true;
}
}
}else if( (c) is ListBox ){
if( ((ListBox)c).ID == v_Control ){
if( permitir == true ){
if (v_Permitir_ControlVisibleDisabled == true)
{
((ListBox)c).Enabled = false;
}
else if (v_Permitir_ControlVisibleDisabled == false)
{
((ListBox)c).Visible = false;
}
}else{
((ListBox)c).Visible= true;
}
}
}else if( (c) is DataList ){
if( ((DataList)c).ID == v_Control ){
if( permitir == true ){
if (v_Permitir_ControlVisibleDisabled == true)
{
((DataList)c).Enabled = false;
}
else if (v_Permitir_ControlVisibleDisabled == false)
{
((DataList)c).Visible = false;
}
}else{
((DataList)c).Visible = true;
}
}
}else if( (c) is CheckBoxList ){
if( ((CheckBoxList)c).ID == v_Control ){
if( permitir == true ){
if (v_Permitir_ControlVisibleDisabled == true)
{
((CheckBoxList)c).Enabled = false;
}
else if (v_Permitir_ControlVisibleDisabled == false)
{
((CheckBoxList)c).Visible = false;
}
}else{
((CheckBoxList)c).Visible = true;
}
}
}else if( (c) is RadioButton ){
if( ((RadioButton)c).ID == v_Control ){
if( permitir == true ){
if (v_Permitir_ControlVisibleDisabled == true)
{
((RadioButton)c).Enabled= false;
}
else if (v_Permitir_ControlVisibleDisabled == false)
{
((RadioButton)c).Visible = false;
}
}else{
((RadioButton)c).Visible = true;
}
}
}else if( (c) is RadioButtonList ){
if( ((RadioButtonList)c).ID == v_Control ){
if( permitir == true ){
if (v_Permitir_ControlVisibleDisabled == true)
{
((RadioButtonList)c).Enabled = false;
}
else if (v_Permitir_ControlVisibleDisabled == false)
{
((RadioButtonList)c).Visible = false;
}
}else{
((RadioButtonList)c).Visible = true;
}
}
}else if( (c) is Image ){
if( ((Image)c).ID == v_Control ){
if( permitir == true ){
((Image)c).Visible = false;
}else{
((Image)c).Visible = true;
}
}
}else if( (c) is Panel ){
if( ((Panel)c).ID == v_Control ){
if (permitir == true)
{
if (v_Permitir_ControlVisibleDisabled == true)
{
((Panel)c).Enabled = false;
}
else if (v_Permitir_ControlVisibleDisabled == false)
{
((Panel)c).Visible = false;
}
}
else
{
((Panel)c).Visible = true;
}
}
}else if( (c) is Table ){
if( ((Table)c).ID == v_Control ){
if( permitir == true ){
if (v_Permitir_ControlVisibleDisabled == true)
{
((Table)c).Enabled = false;
}
else if (v_Permitir_ControlVisibleDisabled == false)
{
((Table)c).Visible = false;
}
}else{
((Table)c).Visible= true;
}
}
}else if( (c) is LinkButton ){
if( ((LinkButton)c).ID == v_Control ){
if( permitir == true ){
if (v_Permitir_ControlVisibleDisabled == true)
{
((LinkButton)c).Enabled = false;
}
else if (v_Permitir_ControlVisibleDisabled == false)
{
((LinkButton)c).Visible = false;
}
}else{
((LinkButton)c).Visible = true;
}
}
}else if( (c) is System.Web.UI.HtmlControls.HtmlInputButton ){
if( ((System.Web.UI.HtmlControls.HtmlInputButton)c).ID == v_Control ){
if( permitir == true ){
((System.Web.UI.HtmlControls.HtmlInputButton)c).Visible = false;
((System.Web.UI.HtmlControls.HtmlInputButton)c).Attributes.Add("disabled", "disabled");
}else{
((System.Web.UI.HtmlControls.HtmlInputButton)c).Visible = true;
((System.Web.UI.HtmlControls.HtmlInputButton)c).Attributes.Remove("disabled");
}
}
}else if( (c) is System.Web.UI.HtmlControls.HtmlAnchor ){
if( ((System.Web.UI.HtmlControls.HtmlAnchor)c).ID == v_Control ){
if( permitir == true ){
((System.Web.UI.HtmlControls.HtmlAnchor)c).Visible = false;
// CType(c, System.Web.UI.HtmlControls.HtmlAnchor).Attributes.Add("disabled", "disabled")
}else{
((System.Web.UI.HtmlControls.HtmlAnchor)c).Visible = true;
//CType(c, System.Web.UI.HtmlControls.HtmlAnchor).Attributes.Remove("disabled") '' etiqueta <a runat="server" ID="id1">
}
}
}else if( (c) is System.Web.UI.HtmlControls.HtmlGenericControl ){
if( ((System.Web.UI.HtmlControls.HtmlGenericControl)c).TagName.ToUpper() == "DIV".ToUpper() ){
if( ((System.Web.UI.HtmlControls.HtmlGenericControl)c).ID == v_Control ){
if( permitir == true ){
((System.Web.UI.HtmlControls.HtmlGenericControl)c).Visible = false;
//CType(c, System.Web.UI.HtmlControls.HtmlGenericControl).Attributes.Add("disabled", "disabled")
}else{
((System.Web.UI.HtmlControls.HtmlGenericControl)c).Visible = true;
//CType(c, System.Web.UI.HtmlControls.HtmlGenericControl).Attributes.Remove("disabled") '' etiqueta <div runat="server" ID="iddiv">
}
}
}
}
SetControls(c, v_Control, permitir, v_Permitir_ControlVisibleDisabled);
}
}
This way, I don't have to use if-then sentences to check permissions and, I can create as many roles as I want, giving them any permissions, without having to change any C# code.
You can check these posts also:
Is ASP.NET role based security a true role based access control system?
Role-based access control - should I have the permission list in the db as well or just in the code (eg enum)?
How to control access to forms fields on a ASP.Net MVC 3 view?
Related
The code below works fine, but I want no special characters to be entered including the period. In addition, the phone number like "534-055-7888", which it masks, is also shown on the admin panel in the same way. I want it to show as "5340557888" without "-" in admin panel but I couldn't.
`
add_filter( 'woocommerce_checkout_fields', 'bbloomer_checkout_phone_us_format' );
function bbloomer_checkout_phone_us_format( $fields ) {
$fields['billing']['billing_phone']['placeholder'] = '123-456-7890';
$fields['billing']['billing_phone']['maxlength'] = 12; // 123-456-7890 is 12 chars long
return $fields;
}
add_action( 'woocommerce_after_checkout_form', 'bbloomer_phone_mask_us' );
function bbloomer_phone_mask_us() {
wc_enqueue_js( "
$('#billing_phone')
.keydown(function(e) {
var key = e.which || e.charCode || e.keyCode || 0;
var phone = $(this);
if (key !== 8 && key !== 9) {
if (phone.val().length === 3) {
phone.val(phone.val() + '-'); // add dash after char #3
}
if (phone.val().length === 7) {
phone.val(phone.val() + '-'); // add dash after char #7
}
}
return (key == 8 ||
key == 9 ||
key == 46 ||
(key >= 48 && key <= 57) ||
(key >= 96 && key <= 105));
});
" );
}
`
Please help me find the errors in my PHP code:
if(isset(show_title) && $show_title = 1){
$the_title = "
<div class=\"sola_t_title\">".get_the_title()."</div>"
} else {
$the_title =;
if(isset($show_body)and $show_body == 1){
$the_body = "
div class=\"sola_t_body\">“".striptags(get_the_excerpt(),"<a><b><em><strong><i><h>")."”</div>";
} else {
$the_body = "";
}
if(isset(show_title) && $show_title = 1){
$the_title = "
<div class='sola_t_title'><a href='".get_the_permalink($post->ID)."'>".get_the_title()."</a></div>"
} else {
$the_title =;
if(isset($show_body)and $show_body == 1){
$the_body = "
div class='sola_t_body'>“".striptags(get_the_excerpt(),"<a><b><em><strong><i><h>")."”</div>";
} else {
$the_body = "";
}
So I am creating a calculator that will compute numbers.I have this code(I will not include very basic codes)
long num1, num2, answer;
boolean mySwitch = false;
boolean do_subtraction_flag = false; // when true we will apply subtraction
boolean multiply = false;
boolean divide = false;
void loop()
{
char keypressed = myKeypad.getKey();
if(keypressed != NO_KEY)
{
Serial.print(keypressed);
if(keypressed > 47 && keypressed < 58) // is between '0' and '9'
{
if(!mySwitch)
{
num1 = (num1 * 10) + (keypressed - 48);
}
else
{
num2 = (num2 * 10) + (keypressed - 48);
}
}
if(keypressed == '=')
{
if(do_subtraction_flag) // we want to subtract the numbers
{
answer = num1 - num2;
}else if(multiply){
answer = num1 * num2;
}else if(divide){
answer = num1 / num2;
}
else // we want to add the numbers
{
answer = num1 + num2;
}
Serial.println(answer);
num1 = 0;
num2 = 0;
mySwitch = false;
do_subtraction_flag = false;
multiply = false;
divide = false;
}
else if(keypressed == '+')
{
mySwitch = true;
}
else if(keypressed == '*'){
mySwitch = true;
multiply = true;
}else if(keypressed == '/'){
mySwitch = true;
divide = true;
}
else if(keypressed == '-')
{
mySwitch = true;
do_subtraction_flag = true;
}else if (keypressed == 'C'){
for (int i=0; i < 80; i++)
{
Serial.write(8); // print 80 times backspace (BS)
}
}
}
}
Im confused here because I want to compute multiple number with multiple operands (eg., 2+1+3 or 2+1-2), but when i add another variable 'num3' what should I suppose to do with it? if i put it into the do_subtraction flag what if the user inputs 2-1+3?Is it possible to compute 3 numbers with this code?I'm getting confused here but let me know if you are also confused what I want to do
Make an array to hold the numbers and operators that you input, then loop through them when the input == '='. Have your num1 always hold the result and num2 hold the next array value.
I'm having a great deal of trouble wrapping my head around recursion. Simple recursion I can do but this is one is not easy for me. My goal here is to speed up this search algorithm. I'm guessing recursion will help. It takes 15 seconds on a simple 43 node tree with children as it is. Below is my unrolled recursion fomr of the code that works.
var nodeList = new Array();
var removeList = new Array();
var count = 0;
var foundInThisNodeTree;
var find = function ( condition )
{
}
while ( this.treeIDMap.igTree( "nodeByPath", count ).data() )
{
var foundInThisNodeTree = false;
var n;
n = this.treeIDMap.igTree( "nodeFromElement", this.treeIDMap.igTree( "nodeByPath", count ) )
if ( n.data.ITEM.indexOf( filter ) > -1 ) { foundInThisNodeTree = true; }
else {//look deeper
var i = 0;
while ( this.treeIDMap.igTree( "nodeByPath", count + "_" + i ).data() )
{
n = this.treeIDMap.igTree( "nodeFromElement", this.treeIDMap.igTree( "nodeByPath", count + "_" + i ) );
if ( n.data.ITEM.indexOf( filter ) > -1 ) { foundInThisNodeTree = true; break; }
else {//look deeper
var j = 0;
while ( this.treeIDMap.igTree( "nodeByPath", count + "_" + i + "_" + j ).data() )
{
n = this.treeIDMap.igTree( "nodeFromElement", this.treeIDMap.igTree( "nodeByPath", count + "_" + i + "_" + j ) );
if ( n.data.ITEM.indexOf( filter ) > -1 ) { foundInThisNodeTree = true; break; }
else {//look deeper
var k = 0;
while ( this.treeIDMap.igTree( "nodeByPath", count + "_" + i + "_" + j + "_" + k ).data() )
{
n = this.treeIDMap.igTree( "nodeFromElement", this.treeIDMap.igTree( "nodeByPath", count + "_" + i + "_" + j + "_" + k ) );
if ( n.data.ITEM.indexOf( filter ) > -1 ) { foundInThisNodeTree = true; break; }
k++;
}
}
j++;
}
}
i++;
}
}
if ( !foundInThisNodeTree ) this.treeIDMap.igTree("removeAt", ""+count )
else count++;
}
*** second revision suggested by Mirco Ellmann *****
var nodeList = new Array();
var removeList = new Array();
var count = 0;
var foundInThisNodeTree;
filter = filter.toLowerCase();
while ( this.treeIDMap.igTree( "nodeByPath", count ).data() )
{
var foundInThisNodeTree = false;
var n;
n = this.treeIDMap.igTree( "nodeFromElement", this.treeIDMap.igTree( "nodeByPath", count ) )
if ( n.data.ITEM.toLowerCase().indexOf( filter ) > -1 ) { foundInThisNodeTree = true; }
else {//look deeper
var i = 0;
n = this.treeIDMap.igTree( "childrenByPath", count );
while ( n[i] )
{
if ( n[i].data.ITEM.indexOf( filter ) > -1 ) { foundInThisNodeTree = true; break; }
var j = 0;
n = this.treeIDMap.igTree( "childrenByPath", count + "_" + i );
while ( n[j] )
{
if ( n[j].data.ITEM.indexOf( filter ) > -1 ) { foundInThisNodeTree = true; break; }
var k = 0;
n = this.treeIDMap.igTree( "childrenByPath", count + "_" + i + "_" + j);
while ( n[k] )
{
if ( n[k].data.ITEM.indexOf( filter ) > -1 ) { foundInThisNodeTree = true; break; }
k++;
}
j++;
}
i++;
}
}
if ( !foundInThisNodeTree ) this.treeIDMap.igTree("removeAt", ""+count )
else count++;
}
****using my branchable trees to get the data no need for any calls to tree****
var count = 0;
var foundInThisNodeTree;
filter = filter.toLowerCase();
while ( this.treeIDMap.igTree( "nodeByPath", count ).data() )
{
var foundInThisNodeTree = false;
var n;
n = this.treeIDMap.igTree( "nodeFromElement", this.treeIDMap.igTree( "nodeByPath", count ) )
if ( n.data.ITEM.toLowerCase().indexOf( filter ) > -1 ) { foundInThisNodeTree = true; }
if ( n.data.branch )//look at all childer under the root node
{
var i = 0;
n = n.data.branch;
while ( n[i] )//look at all childer under the root node
{
if ( n[i].ITEM.toLowerCase().indexOf( filter ) > -1 ) { foundInThisNodeTree = true; break; }
while ( n[i].branch )//look deeper
{
var j = 0;
n = n[i].branch;
if ( n[j].ITEM.toLowerCase().indexOf( filter ) > -1 ) { foundInThisNodeTree = true; break; }
while ( n[j].branch )//look deeper
{
var k = 0;
n = n[j].branch;
if ( n[k].ITEM.toLowerCase().indexOf( filter ) > -1 ) { foundInThisNodeTree = true; break; }
k++;
}
j++;
}
i++;
}
}
if ( !foundInThisNodeTree ) this.treeIDMap.igTree("removeAt", ""+count )
else count++;
}
instead of always use "nodeByPath" you should use "childrenByPath".
that would minimize the search calls on the igTree.
PS: USE not REPLACE ;)
You're not really doing this recursively. You're rather repeating your code for each level in the hierarchy. What you want is a helper function which takes the current node-path as a parameter and recursively calls the same method for each of its children with their id added to the path of the current node. Recursively means the code should work for any depth of tree. To me it looks like your code will only work for a set depth.
For the speed issue, there might be two issues. I didn't really read your code too closely, so I leave it to you to figure out which one is more likely.
You might be revisiting nodes. If so, obviously that would impact performance.
The framework you're using might be slow with looking up the nodes. One solution could be to find alternate methods to call on the framework which is meant for what you're doing. For instance the framework might have a hierarchical representation internally, but has to rebuild it or parse it when you pass in your full paths. Look for methods taking a source and relative path instead. If that's not the problem the framework might just be slow, and you might be better of to read all the nodes and build your own in-memory tree to use instead.
ok, I found a way to use the data provider and use a normal Json search. Still if anyone can speed this up I'd be grateful. I just when from 15 seconds to 1. This one has the recursion I need.
findInObject = function( obj, prop, val )
{
if ( obj !== null && obj.hasOwnProperty( prop ) && obj[prop].toLowerCase().indexOf(val) > -1 )
{
return obj;
} else
{
for ( var s in obj )
{
if ( obj.hasOwnProperty( s ) && typeof obj[s] == 'object' && obj[s] !== null )
{
var result = findInObject( obj[s], prop, val );
if ( result !== null )
{
return result;
}
}
}
}
return null;
}
for ( var i = 0; i < this.treeData.length; i++)
{
if ( findInObject( this.treeData[i], "ITEM", filter ) ) foundNodes.push( this.treeData[i] )//does the node have a match?
}
this.treeIDMap.igTree( { dataSource: foundNodes } );
this.treeIDMap.igTree( "dataBind" );
};
I have a several datagrids (with data being retrieved from some map service).
I want to place these data grids within seperate tabs of a tab navigator. All works fine apart from the first tab which always ends up without any datagrid in it.
I have tried creation policy="all" and stuff but the first tab always is empty. Does anybody have any ideas as to why the first tab is always empty.
Any workarounds.
Thanks
var box:HBox=new HBox();
var dg:DataGrid = new DataGrid();
dg.dataProvider = newAC;
box.label=title.text;
box.addChild(dg);
tabNaviId.addChild(box);
tabNaviId.selectedIndex=2;
resultsArea.addChild(tabNaviId);
dg is datagrid that is being filled up. The above code is in a loop, in each loop i am creating an Hbox+datagrid. then i am adding the Hbox to the navigator and final adding the navigator to resultsArea (which is a canvas).
The above code works great apart from first time.
The end result i get is, having a tab navigator with first tab without any datagrid but the remaining tabs all have the datagrids. Any ideas as to why this is happening.
Call to a function called createDatagrid is made:
dgCollection.addItem(parentApplication.resultsPanel.createDatagrid( token.name.toString() + " (" + recAC.length + " selected)", recAC, false, callsToMake ));
In another Mxml component this function exists
public function createDatagrid(titleText:String, recACAll:ArrayCollection, showContent:Boolean, callsToMake:Number):DataGrid
{
var dg:DataGrid = new DataGrid();
var newAC:ArrayCollection = new ArrayCollection();
var newDGCols:Array = new Array();
for( var i:Number = 0; i < recACAll.length; i ++)
{
var contentStr:String = recACAll[i][CONTENT_FIELD];
var featureGeo:Geometry = recACAll[i][GEOMETRY_FIELD];
var iconPath:String = recACAll[i][ICON_FIELD];
var linkStr:String = recACAll[i][LINK_FIELD];
var linkNameStr:String = recACAll[i][LINK_NAME_FIELD];
var featurePoint:MapPoint = recACAll[i][POINT_FIELD];
var titleStr:String = recACAll[i][TITLE_FIELD];
if( contentStr.length > 0)
{
var rows:Array = contentStr.split("\n");
var tmpObj:Object = new Object();
if(!showContent)
{
for( var j:Number = 0; j < rows.length; j++)
{
var tmpStr:String = rows[j] as String;
var header:String = tmpStr.substring(0,tmpStr.indexOf(":"));
var val:String = tmpStr.substring(tmpStr.indexOf(":") + 2);
if(header.length > 0)
{
tmpObj[header] = val;
if(newDGCols.length < rows.length - 1)
{
newDGCols.push( new DataGridColumn(header));
}
}
}
}
else
{
if(newDGCols.length == 0)
{
newDGCols.push(new DataGridColumn(CONTENT_FIELD));
newDGCols.push(new DataGridColumn(GEOMETRY_FIELD));
newDGCols.push(new DataGridColumn(ICON_FIELD));
newDGCols.push(new DataGridColumn(LINK_FIELD));
newDGCols.push(new DataGridColumn(LINK_NAME_FIELD));
newDGCols.push(new DataGridColumn(POINT_FIELD));
newDGCols.push(new DataGridColumn(TITLE_FIELD));
}
}
tmpObj[CONTENT_FIELD] = contentStr;
tmpObj[GEOMETRY_FIELD] = featureGeo;
tmpObj[ICON_FIELD] = iconPath;
tmpObj[LINK_FIELD] = linkStr;
tmpObj[LINK_NAME_FIELD] = linkNameStr;
tmpObj[POINT_FIELD] = featurePoint;
tmpObj[TITLE_FIELD] = titleStr;
newAC.addItem(tmpObj);
}
if( showHidePic.source == minSourceI )
{
showHidePic.source = minSource;
}
else if( showHidePic.source == maxSourceI )
{
showHidePic.source = maxSource;
}
curResults = curResults + recACAll.length;
if (curResults == 1)
{
showInfoWindow(tmpObj);
if(showContent)
{
parentApplication.maps.map.extent = featureGeo.extent;
}
}
else
{
showInfoWindow(null);
// Added to avoid the overview button problem (needs checking)
this.removeEventListener(MouseEvent.MOUSE_OVER, handleMouseOver, false);
this.removeEventListener(MouseEvent.MOUSE_MOVE,handleMouseOver,false);
this.removeEventListener(MouseEvent.MOUSE_OUT,handleMouseOut,false);
this.removeEventListener(MouseEvent.MOUSE_DOWN,handleMouseDrag,false);
this.removeEventListener(MouseEvent.MOUSE_UP,handleMouseDragStop,false);
this.parent.removeEventListener(MouseEvent.MOUSE_MOVE,handleParentMove,false);
this.parent.removeEventListener(MouseEvent.MOUSE_UP,handleMouseDragStop2,false);
maximizePanel();
}
}
dg.dataProvider = newAC;
dg.columns = newDGCols;
dg.rowCount = newAC.length;
var totalDGCWidth:Number = 0;
for( var m:Number = 0; m < dg.columns.length; m++)
{
var dgc2:DataGridColumn = dg.columns[m];
/*if(dgc2.headerText.toUpperCase()==LINK_FIELD.toUpperCase()){
//dgc.itemRenderer=new ClassFactory(CustomRenderer);
dgc2.itemRenderer=new ClassFactory(CustomRenderer);
}*/
var dgcWidth2:Number = dgc2.headerText.length * CHAR_LENGTH;
for( var l:Number = 0; l < newAC.length; l++)
{
var row2:Object = newAC.getItemAt(l) as Object;
var rowVal2:String = row2[dgc2.headerText];
if( rowVal2 != null)
{
var tmpLength2:Number = rowVal2.length * CHAR_LENGTH;
if(tmpLength2 < CHAR_MAX_LENGTH)
{
if(tmpLength2 > dgcWidth2)
{
dgcWidth2 = tmpLength2;
}
}
else
{
dgcWidth2 = CHAR_MAX_LENGTH
break;
}
}
}
// Added by FT:to change the item renderer for link field
if( dgc2.headerText == GEOMETRY_FIELD || dgc2.headerText == CONTENT_FIELD ||
dgc2.headerText == ICON_FIELD || dgc2.headerText == LINK_FIELD ||
dgc2.headerText == POINT_FIELD || dgc2.headerText == TITLE_FIELD ||
dgc2.headerText == LINK_NAME_FIELD)
{
if(dgc2.headerText == CONTENT_FIELD && showContent)
{
//something
}
else
{
dgcWidth2 = 0;
}
}
totalDGCWidth += dgcWidth2;
}
dg.width = totalDGCWidth;
for( var k:Number = 0; k < dg.columns.length; k++)
{
var dgc:DataGridColumn = dg.columns[k];
var dgcWidth:Number = dgc.headerText.length * CHAR_LENGTH;
for( var n:Number = 0; n < newAC.length; n++)
{
var row:Object = newAC.getItemAt(n) as Object;
var rowVal:String = row[dgc.headerText];
if(rowVal != null)
{
var tmpLength:Number = rowVal.length * CHAR_LENGTH;
if(tmpLength < CHAR_MAX_LENGTH)
{
if(tmpLength > dgcWidth)
{
dgcWidth = tmpLength;
}
}
else
{
dgcWidth = CHAR_MAX_LENGTH
break;
}
}
}
if( dgc.headerText == GEOMETRY_FIELD || dgc.headerText == CONTENT_FIELD ||
dgc.headerText == ICON_FIELD || dgc.headerText == LINK_FIELD ||
dgc.headerText == POINT_FIELD || dgc.headerText == TITLE_FIELD ||
dgc.headerText == LINK_NAME_FIELD)
{
if(dgc.headerText == CONTENT_FIELD && showContent)
{
dgc.visible = true;
}
else
{
dgc.visible = false;
dgcWidth = 0;
}
}
if( dgc.headerText == LINK_COL_NAME)
{
dgcWidth = LINK_COL_WIDTH;
}
dgc.width = dgcWidth;
}
dg.addEventListener(ListEvent.ITEM_CLICK,rowClicked);
dg.addEventListener(ListEvent.ITEM_ROLL_OVER,mouseOverRow);
dg.addEventListener(ListEvent.ITEM_ROLL_OUT,mouseOutRow);
var title:Text = new Text();
title.text = titleText;
title.setStyle("fontWeight","bold");
//resultsArea.addChild(title);
return dg;
//tabNaviId.selectedIndex=2;
}
public function populateGrid(dgCollection:ArrayCollection):void{
for( var k:Number = 0; k < dgCollection.length; k++)
{
var box:HBox=new HBox();
var dg2:DataGrid=dgCollection.getItemAt(k) as DataGrid;
box.label="some";
box.addChild(dg2);
tabNaviId.addChild(box);
}
resultsArea.addChild(tabNaviId);
}
and the tab navigator declared as
<mx:Image id="showHidePic" click="toggleResults()"/>
<mx:VBox y="20" styleName="ResultsArea" width="100%" height="100%">
<mx:HBox>
<mx:Button label="Export to Excel" click="downloadExcel()"/>
<mx:Button label="Clear" click="clear()" />
</mx:HBox>
<mx:VBox id="resultsArea" styleName="ResultsContent" paddingTop="10" paddingLeft="10" paddingRight="10" verticalScrollPolicy="off" horizontalScrollPolicy="off">
<mx:TabNavigator id="tabNaviId" width="622" height="274" creationPolicy="all">
</mx:TabNavigator>
</mx:VBox>
</mx:VBox>
Abstract, can we get the full code including the loop you mention, as well as the code where you create the TabNavigator?
It's possible that the TabNavigator already has an initial child, and all the children you're creating are being added after that.